Page MenuHomePhorge

No OneTemporary

This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/Gemfile b/Gemfile
index 34a728167..be5e34df3 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,91 +1,93 @@
source ENV['GEM_SOURCE'] || "https://rubygems.org"
def location_for(place, fake_version = nil)
if place =~ /^(git[:@][^#]*)#(.*)/
[fake_version, { :git => $1, :branch => $2, :require => false }].compact
elsif place =~ /^file:\/\/(.*)/
['>= 0', { :path => File.expand_path($1), :require => false }]
else
[place, { :require => false }]
end
end
# C Ruby (MRI) or Rubinius, but NOT Windows
platforms :ruby do
gem 'pry', :group => :development
gem 'yard', :group => :development
gem 'redcarpet', '~> 2.0', :group => :development
gem "racc", "1.4.9", :group => :development
# To enable the augeas feature, use this gem.
# Note that it is a native gem, so the augeas headers/libs
# are neeed.
#gem 'ruby-augeas', :group => :development
end
gem "puppet", :path => File.dirname(__FILE__), :require => false
gem "facter", *location_for(ENV['FACTER_LOCATION'] || ['> 1.6', '< 3'])
gem "hiera", *location_for(ENV['HIERA_LOCATION'] || '~> 1.0')
gem "rake", "10.1.1", :require => false
group(:development, :test) do
- gem "rspec", "~> 2.14.0", :require => false
+ gem "rspec", "~> 3.1", :require => false
+ gem "rspec-its", "~> 1.1", :require => false
+ gem "rspec-collection_matchers", "~> 1.1", :require => false
# Mocha is not compatible across minor version changes; because of this only
# versions matching ~> 0.10.5 are supported. All other versions are unsupported
# and can be expected to fail.
gem "mocha", "~> 0.10.5", :require => false
gem "yarjuf", "~> 1.0"
# json-schema does not support windows, so omit it from the platforms list
# json-schema uses multi_json, but chokes with multi_json 1.7.9, so prefer 1.7.7
gem "multi_json", "1.7.7", :require => false, :platforms => [:ruby, :jruby]
gem "json-schema", "2.1.1", :require => false, :platforms => [:ruby, :jruby]
gem "rubocop", "~> 0.26.1", :platforms => [:ruby]
gem 'rdoc', "~> 4.1", :platforms => [:ruby]
end
group(:development) do
if RUBY_PLATFORM != 'java'
gem 'ruby-prof', :require => false
end
end
group(:extra) do
gem "rack", "~> 1.4", :require => false
gem "net-ssh", '~> 2.1', :require => false
gem "puppetlabs_spec_helper", :require => false
gem "tzinfo", :require => false
case RUBY_PLATFORM
when 'java'
gem "msgpack-jruby", :require => false
else
gem "msgpack", :require => false
end
end
require 'yaml'
data = YAML.load_file(File.join(File.dirname(__FILE__), 'ext', 'project_data.yaml'))
bundle_platforms = data['bundle_platforms']
x64_platform = Gem::Platform.local.cpu == 'x64'
data['gem_platform_dependencies'].each_pair do |gem_platform, info|
next if gem_platform == 'x86-mingw32' && x64_platform
next if gem_platform == 'x64-mingw32' && !x64_platform
if bundle_deps = info['gem_runtime_dependencies']
bundle_platform = bundle_platforms[gem_platform] or raise "Missing bundle_platform"
platform(bundle_platform.intern) do
bundle_deps.each_pair do |name, version|
gem(name, version, :require => false)
end
end
end
end
if File.exists? "#{__FILE__}.local"
eval(File.read("#{__FILE__}.local"), binding)
end
# vim:filetype=ruby
diff --git a/lib/puppet/transaction.rb b/lib/puppet/transaction.rb
index 40e17e901..f7cb128c7 100644
--- a/lib/puppet/transaction.rb
+++ b/lib/puppet/transaction.rb
@@ -1,363 +1,371 @@
require 'puppet'
require 'puppet/util/tagging'
require 'puppet/application'
require 'digest/sha1'
require 'set'
# the class that actually walks our resource/property tree, collects the changes,
# and performs them
#
# @api private
class Puppet::Transaction
require 'puppet/transaction/additional_resource_generator'
require 'puppet/transaction/event'
require 'puppet/transaction/event_manager'
require 'puppet/transaction/resource_harness'
require 'puppet/resource/status'
attr_accessor :catalog, :ignoreschedules, :for_network_device
# The report, once generated.
attr_reader :report
# Routes and stores any events and subscriptions.
attr_reader :event_manager
# Handles most of the actual interacting with resources
attr_reader :resource_harness
attr_reader :prefetched_providers
include Puppet::Util
include Puppet::Util::Tagging
def initialize(catalog, report, prioritizer)
@catalog = catalog
@report = report || Puppet::Transaction::Report.new("apply", catalog.version, catalog.environment)
@prioritizer = prioritizer
@report.add_times(:config_retrieval, @catalog.retrieval_duration || 0)
@event_manager = Puppet::Transaction::EventManager.new(self)
@resource_harness = Puppet::Transaction::ResourceHarness.new(self)
@prefetched_providers = Hash.new { |h,k| h[k] = {} }
end
# Invoke the pre_run_check hook in every resource in the catalog.
# This should (only) be called by Transaction#evaluate before applying
# the catalog.
#
# @see Puppet::Transaction#evaluate
# @see Puppet::Type#pre_run_check
# @raise [Puppet::Error] If any pre-run checks failed.
# @return [void]
def perform_pre_run_checks
prerun_errors = {}
@catalog.vertices.each do |res|
begin
res.pre_run_check
rescue Puppet::Error => detail
prerun_errors[res] = detail
end
end
unless prerun_errors.empty?
prerun_errors.each do |res, detail|
res.log_exception(detail)
end
raise Puppet::Error, "Some pre-run checks failed"
end
end
# This method does all the actual work of running a transaction. It
# collects all of the changes, executes them, and responds to any
# necessary events.
def evaluate(&block)
block ||= method(:eval_resource)
generator = AdditionalResourceGenerator.new(@catalog, relationship_graph, @prioritizer)
@catalog.vertices.each { |resource| generator.generate_additional_resources(resource) }
perform_pre_run_checks
Puppet.info "Applying configuration version '#{catalog.version}'" if catalog.version
continue_while = lambda { !stop_processing? }
post_evalable_providers = Set.new
pre_process = lambda do |resource|
prov_class = resource.provider.class
post_evalable_providers << prov_class if prov_class.respond_to?(:post_resource_eval)
prefetch_if_necessary(resource)
# If we generated resources, we don't know what they are now
# blocking, so we opt to recompute it, rather than try to track every
# change that would affect the number.
relationship_graph.clear_blockers if generator.eval_generate(resource)
end
providerless_types = []
overly_deferred_resource_handler = lambda do |resource|
# We don't automatically assign unsuitable providers, so if there
# is one, it must have been selected by the user.
return if missing_tags?(resource)
if resource.provider
resource.err "Provider #{resource.provider.class.name} is not functional on this host"
else
providerless_types << resource.type
end
resource_status(resource).failed = true
end
canceled_resource_handler = lambda do |resource|
resource_status(resource).skipped = true
resource.debug "Transaction canceled, skipping"
end
teardown = lambda do
# Just once per type. No need to punish the user.
providerless_types.uniq.each do |type|
Puppet.err "Could not find a suitable provider for #{type}"
end
post_evalable_providers.each do |provider|
begin
provider.post_resource_eval
rescue => detail
Puppet.log_exception(detail, "post_resource_eval failed for provider #{provider}")
end
end
end
relationship_graph.traverse(:while => continue_while,
:pre_process => pre_process,
:overly_deferred_resource_handler => overly_deferred_resource_handler,
:canceled_resource_handler => canceled_resource_handler,
:teardown => teardown) do |resource|
if resource.is_a?(Puppet::Type::Component)
Puppet.warning "Somehow left a component in the relationship graph"
else
resource.info "Starting to evaluate the resource" if Puppet[:evaltrace] and @catalog.host_config?
seconds = thinmark { block.call(resource) }
resource.info "Evaluated in %0.2f seconds" % seconds if Puppet[:evaltrace] and @catalog.host_config?
end
end
Puppet.debug "Finishing transaction #{object_id}"
end
# Wraps application run state check to flag need to interrupt processing
def stop_processing?
Puppet::Application.stop_requested? && catalog.host_config?
end
# Are there any failed resources in this transaction?
def any_failed?
report.resource_statuses.values.detect { |status| status.failed? }
end
# Find all of the changed resources.
def changed?
report.resource_statuses.values.find_all { |status| status.changed }.collect { |status| catalog.resource(status.resource) }
end
def relationship_graph
catalog.relationship_graph(@prioritizer)
end
def resource_status(resource)
report.resource_statuses[resource.to_s] || add_resource_status(Puppet::Resource::Status.new(resource))
end
# The tags we should be checking.
def tags
self.tags = Puppet[:tags] unless defined?(@tags)
super
end
def prefetch_if_necessary(resource)
provider_class = resource.provider.class
return unless provider_class.respond_to?(:prefetch) and !prefetched_providers[resource.type][provider_class.name]
resources = resources_by_provider(resource.type, provider_class.name)
if provider_class == resource.class.defaultprovider
providerless_resources = resources_by_provider(resource.type, nil)
providerless_resources.values.each {|res| res.provider = provider_class.name}
resources.merge! providerless_resources
end
prefetch(provider_class, resources)
end
private
# Apply all changes for a resource
def apply(resource, ancestor = nil)
status = resource_harness.evaluate(resource)
add_resource_status(status)
event_manager.queue_events(ancestor || resource, status.events) unless status.failed?
rescue => detail
resource.err "Could not evaluate: #{detail}"
end
# Evaluate a single resource.
def eval_resource(resource, ancestor = nil)
if skip?(resource)
resource_status(resource).skipped = true
resource.debug("Resource is being skipped, unscheduling all events")
event_manager.dequeue_all_events_for_resource(resource)
else
resource_status(resource).scheduled = true
apply(resource, ancestor)
event_manager.process_events(resource)
end
end
def failed?(resource)
s = resource_status(resource) and s.failed?
end
# Does this resource have any failed dependencies?
def failed_dependencies?(resource)
# First make sure there are no failed dependencies. To do this,
# we check for failures in any of the vertexes above us. It's not
# enough to check the immediate dependencies, which is why we use
# a tree from the reversed graph.
found_failed = false
# When we introduced the :whit into the graph, to reduce the combinatorial
# explosion of edges, we also ended up reporting failures for containers
# like class and stage. This is undesirable; while just skipping the
# output isn't perfect, it is RC-safe. --daniel 2011-06-07
suppress_report = (resource.class == Puppet::Type.type(:whit))
relationship_graph.dependencies(resource).each do |dep|
next unless failed?(dep)
found_failed = true
# See above. --daniel 2011-06-06
unless suppress_report then
resource.notice "Dependency #{dep} has failures: #{resource_status(dep).failed}"
end
end
found_failed
end
# A general method for recursively generating new resources from a
# resource.
def generate_additional_resources(resource)
return unless resource.respond_to?(:generate)
begin
made = resource.generate
rescue => detail
resource.log_exception(detail, "Failed to generate additional resources using 'generate': #{detail}")
end
return unless made
made = [made] unless made.is_a?(Array)
made.uniq.each do |res|
begin
res.tag(*resource.tags)
@catalog.add_resource(res)
res.finish
add_conditional_directed_dependency(resource, res)
generate_additional_resources(res)
rescue Puppet::Resource::Catalog::DuplicateResourceError
res.info "Duplicate generated resource; skipping"
end
end
end
# Should we ignore tags?
def ignore_tags?
! @catalog.host_config?
end
def resources_by_provider(type_name, provider_name)
unless @resources_by_provider
@resources_by_provider = Hash.new { |h, k| h[k] = Hash.new { |h1, k1| h1[k1] = {} } }
@catalog.vertices.each do |resource|
if resource.class.attrclass(:provider)
prov = resource.provider && resource.provider.class.name
@resources_by_provider[resource.type][prov][resource.name] = resource
end
end
end
@resources_by_provider[type_name][provider_name] || {}
end
# Prefetch any providers that support it, yo. We don't support prefetching
# types, just providers.
def prefetch(provider_class, resources)
type_name = provider_class.resource_type.name
return if @prefetched_providers[type_name][provider_class.name]
Puppet.debug "Prefetching #{provider_class.name} resources for #{type_name}"
begin
provider_class.prefetch(resources)
rescue LoadError, Puppet::MissingCommand => detail
Puppet.log_exception(detail, "Could not prefetch #{type_name} provider '#{provider_class.name}': #{detail}")
end
@prefetched_providers[type_name][provider_class.name] = true
end
def add_resource_status(status)
report.add_resource_status(status)
end
# Is the resource currently scheduled?
def scheduled?(resource)
self.ignoreschedules or resource_harness.scheduled?(resource)
end
# Should this resource be skipped?
def skip?(resource)
if missing_tags?(resource)
resource.debug "Not tagged with #{tags.join(", ")}"
elsif ! scheduled?(resource)
resource.debug "Not scheduled"
elsif failed_dependencies?(resource)
# When we introduced the :whit into the graph, to reduce the combinatorial
# explosion of edges, we also ended up reporting failures for containers
# like class and stage. This is undesirable; while just skipping the
# output isn't perfect, it is RC-safe. --daniel 2011-06-07
unless resource.class == Puppet::Type.type(:whit) then
resource.warning "Skipping because of failed dependencies"
end
elsif resource.virtual?
resource.debug "Skipping because virtual"
elsif !host_and_device_resource?(resource) && resource.appliable_to_host? && for_network_device
resource.debug "Skipping host resources because running on a device"
elsif !host_and_device_resource?(resource) && resource.appliable_to_device? && !for_network_device
resource.debug "Skipping device resources because running on a posix host"
else
return false
end
true
end
def host_and_device_resource?(resource)
resource.appliable_to_host? && resource.appliable_to_device?
end
# Is this resource tagged appropriately?
def missing_tags?(resource)
return false if ignore_tags?
return false if tags.empty?
not resource.tagged?(*tags)
end
+
+ # These two methods are only made public to enable the existing spec tests to run
+ # under rspec 3 (apparently rspec 2 didn't enforce access controls?). Please do not
+ # treat these as part of a public API.
+ # Possible future improvement: rewrite to not require access to private methods.
+ public :skip?
+ public :missing_tags?
+
end
require 'puppet/transaction/report'
diff --git a/lib/puppet/transaction/resource_harness.rb b/lib/puppet/transaction/resource_harness.rb
index b9caaf247..5968d79fb 100644
--- a/lib/puppet/transaction/resource_harness.rb
+++ b/lib/puppet/transaction/resource_harness.rb
@@ -1,250 +1,256 @@
require 'puppet/resource/status'
class Puppet::Transaction::ResourceHarness
NO_ACTION = Object.new
extend Forwardable
def_delegators :@transaction, :relationship_graph
attr_reader :transaction
def initialize(transaction)
@transaction = transaction
end
def evaluate(resource)
status = Puppet::Resource::Status.new(resource)
begin
context = ResourceApplicationContext.from_resource(resource, status)
perform_changes(resource, context)
if status.changed? && ! resource.noop?
cache(resource, :synced, Time.now)
resource.flush if resource.respond_to?(:flush)
end
rescue => detail
status.failed_because(detail)
ensure
status.evaluation_time = Time.now - status.time
end
status
end
def scheduled?(resource)
return true if Puppet[:ignoreschedules]
return true unless schedule = schedule(resource)
# We use 'checked' here instead of 'synced' because otherwise we'll
# end up checking most resources most times, because they will generally
# have been synced a long time ago (e.g., a file only gets updated
# once a month on the server and its schedule is daily; the last sync time
# will have been a month ago, so we'd end up checking every run).
schedule.match?(cached(resource, :checked).to_i)
end
def schedule(resource)
unless resource.catalog
resource.warning "Cannot schedule without a schedule-containing catalog"
return nil
end
return nil unless name = resource[:schedule]
resource.catalog.resource(:schedule, name) || resource.fail("Could not find schedule #{name}")
end
# Used mostly for scheduling and auditing at this point.
def cached(resource, name)
Puppet::Util::Storage.cache(resource)[name]
end
# Used mostly for scheduling and auditing at this point.
def cache(resource, name, value)
Puppet::Util::Storage.cache(resource)[name] = value
end
private
def perform_changes(resource, context)
cache(resource, :checked, Time.now)
return [] if ! allow_changes?(resource)
# Record the current state in state.yml.
context.audited_params.each do |param|
cache(resource, param, context.current_values[param])
end
ensure_param = resource.parameter(:ensure)
if ensure_param && ensure_param.should
ensure_event = sync_if_needed(ensure_param, context)
else
ensure_event = NO_ACTION
end
if ensure_event == NO_ACTION
if context.resource_present?
resource.properties.each do |param|
sync_if_needed(param, context)
end
else
resource.debug("Nothing to manage: no ensure and the resource doesn't exist")
end
end
capture_audit_events(resource, context)
end
def allow_changes?(resource)
if resource.purging? and resource.deleting? and deps = relationship_graph.dependents(resource) \
and ! deps.empty? and deps.detect { |d| ! d.deleting? }
deplabel = deps.collect { |r| r.ref }.join(",")
plurality = deps.length > 1 ? "":"s"
resource.warning "#{deplabel} still depend#{plurality} on me -- not purging"
false
else
true
end
end
+ # allow_changes? is only made public to enable the existing spec tests to run
+ # under rspec 3 (apparently rspec 2 didn't enforce access controls?). Please do not
+ # treat this as part of a public API.
+ # Possible future improvement: rewrite to not require access to private methods.
+ public :allow_changes?
+
def sync_if_needed(param, context)
historical_value = context.historical_values[param.name]
current_value = context.current_values[param.name]
do_audit = context.audited_params.include?(param.name)
begin
if param.should && !param.safe_insync?(current_value)
event = create_change_event(param, current_value, historical_value)
if do_audit
event = audit_event(event, param)
end
brief_audit_message = audit_message(param, do_audit, historical_value, current_value)
if param.noop
noop(event, param, current_value, brief_audit_message)
else
sync(event, param, current_value, brief_audit_message)
end
event
else
NO_ACTION
end
rescue => detail
# Execution will continue on StandardErrors, just store the event
Puppet.log_exception(detail)
event = create_change_event(param, current_value, historical_value)
event.status = "failure"
event.message = "change from #{param.is_to_s(current_value)} to #{param.should_to_s(param.should)} failed: #{detail}"
event
rescue Exception => detail
# Execution will halt on Exceptions, they get raised to the application
event = create_change_event(param, current_value, historical_value)
event.status = "failure"
event.message = "change from #{param.is_to_s(current_value)} to #{param.should_to_s(param.should)} failed: #{detail}"
raise
ensure
if event
context.record(event)
event.send_log
context.synced_params << param.name
end
end
end
def create_change_event(property, current_value, historical_value)
event = property.event
event.previous_value = current_value
event.desired_value = property.should
event.historical_value = historical_value
event
end
# This method is an ugly hack because, given a Time object with nanosecond
# resolution, roundtripped through YAML serialization, the Time object will
# be truncated to microseconds.
# For audit purposes, this code special cases this comparison, and compares
# the two objects by their second and microsecond components. tv_sec is the
# number of seconds since the epoch, and tv_usec is only the microsecond
# portion of time.
def are_audited_values_equal(a, b)
a == b || (a.is_a?(Time) && b.is_a?(Time) && a.tv_sec == b.tv_sec && a.tv_usec == b.tv_usec)
end
private :are_audited_values_equal
def audit_event(event, property)
event.audited = true
event.status = "audit"
if !are_audited_values_equal(event.historical_value, event.previous_value)
event.message = "audit change: previously recorded value #{property.is_to_s(event.historical_value)} has been changed to #{property.is_to_s(event.previous_value)}"
end
event
end
def audit_message(param, do_audit, historical_value, current_value)
if do_audit && historical_value && !are_audited_values_equal(historical_value, current_value)
" (previously recorded value was #{param.is_to_s(historical_value)})"
else
""
end
end
def noop(event, param, current_value, audit_message)
event.message = "current_value #{param.is_to_s(current_value)}, should be #{param.should_to_s(param.should)} (noop)#{audit_message}"
event.status = "noop"
end
def sync(event, param, current_value, audit_message)
param.sync
event.message = "#{param.change_to_s(current_value, param.should)}#{audit_message}"
event.status = "success"
end
def capture_audit_events(resource, context)
context.audited_params.each do |param_name|
if context.historical_values.include?(param_name)
if !are_audited_values_equal(context.historical_values[param_name], context.current_values[param_name]) && !context.synced_params.include?(param_name)
parameter = resource.parameter(param_name)
event = audit_event(create_change_event(parameter,
context.current_values[param_name],
context.historical_values[param_name]),
parameter)
event.send_log
context.record(event)
end
else
resource.property(param_name).notice "audit change: newly-recorded value #{context.current_values[param_name]}"
end
end
end
# @api private
ResourceApplicationContext = Struct.new(:resource,
:current_values,
:historical_values,
:audited_params,
:synced_params,
:status) do
def self.from_resource(resource, status)
ResourceApplicationContext.new(resource,
resource.retrieve_resource.to_hash,
Puppet::Util::Storage.cache(resource).dup,
(resource[:audit] || []).map { |p| p.to_sym },
[],
status)
end
def resource_present?
resource.present?(current_values)
end
def record(event)
status << event
end
end
end
diff --git a/spec/integration/agent/logging_spec.rb b/spec/integration/agent/logging_spec.rb
index c686397c8..b8a768d30 100755
--- a/spec/integration/agent/logging_spec.rb
+++ b/spec/integration/agent/logging_spec.rb
@@ -1,178 +1,178 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet'
require 'puppet/daemon'
require 'puppet/application/agent'
# The command line flags affecting #20900 and #20919:
#
# --onetime
# --daemonize
# --no-daemonize
# --logdest
# --verbose
# --debug
# (no flags) (-)
#
# d and nd are mutally exclusive
#
# Combinations without logdest, verbose or debug:
#
# --onetime --daemonize
# --onetime --no-daemonize
# --onetime
# --daemonize
# --no-daemonize
# -
#
# 6 cases X [--logdest=console, --logdest=syslog, --logdest=/some/file, <nothing added>]
# = 24 cases to test
#
# X [--verbose, --debug, <nothing added>]
# = 72 cases to test
#
# Expectations of behavior are defined in the expected_loggers, expected_level methods,
# so adapting to a change in logging behavior should hopefully be mostly a matter of
# adjusting the logic in those methods to define new behavior.
#
# Note that this test does not have anything to say about what happens to logging after
# daemonizing.
describe 'agent logging' do
ONETIME = '--onetime'
DAEMONIZE = '--daemonize'
NO_DAEMONIZE = '--no-daemonize'
LOGDEST_FILE = '--logdest=/dev/null/foo'
LOGDEST_SYSLOG = '--logdest=syslog'
LOGDEST_CONSOLE = '--logdest=console'
VERBOSE = '--verbose'
DEBUG = '--debug'
DEFAULT_LOG_LEVEL = :notice
INFO_LEVEL = :info
DEBUG_LEVEL = :debug
CONSOLE = :console
SYSLOG = :syslog
EVENTLOG = :eventlog
FILE = :file
ONETIME_DAEMONIZE_ARGS = [
[ONETIME],
[ONETIME, DAEMONIZE],
[ONETIME, NO_DAEMONIZE],
[DAEMONIZE],
[NO_DAEMONIZE],
[],
]
LOG_DEST_ARGS = [LOGDEST_FILE, LOGDEST_SYSLOG, LOGDEST_CONSOLE, nil]
LOG_LEVEL_ARGS = [VERBOSE, DEBUG, nil]
shared_examples "an agent" do |argv, expected|
before(:each) do
# Don't actually run the agent, bypassing cert checks, forking and the puppet run itself
Puppet::Application::Agent.any_instance.stubs(:run_command)
end
def double_of_bin_puppet_agent_call(argv)
argv.unshift('agent')
command_line = Puppet::Util::CommandLine.new('puppet', argv)
command_line.execute
end
if Puppet.features.microsoft_windows? && argv.include?(DAEMONIZE)
it "should exit on a platform which cannot daemonize if the --daemonize flag is set" do
expect { double_of_bin_puppet_agent_call(argv) }.to raise_error(SystemExit)
end
else
it "when evoked with #{argv}, logs to #{expected[:loggers].inspect} at level #{expected[:level]}" do
# This logger is created by the Puppet::Settings object which creates and
# applies a catalog to ensure that configuration files and users are in
# place.
#
# It's not something we are specifically testing here since it occurs
# regardless of user flags.
Puppet::Util::Log.expects(:newdestination).with(instance_of(Puppet::Transaction::Report)).at_least_once
expected[:loggers].each do |logclass|
Puppet::Util::Log.expects(:newdestination).with(logclass).at_least_once
end
double_of_bin_puppet_agent_call(argv)
- Puppet::Util::Log.level.should == expected[:level]
+ expect(Puppet::Util::Log.level).to eq(expected[:level])
end
end
end
def self.no_log_dest_set_in(argv)
([LOGDEST_SYSLOG, LOGDEST_CONSOLE, LOGDEST_FILE] & argv).empty?
end
def self.verbose_or_debug_set_in_argv(argv)
!([VERBOSE, DEBUG] & argv).empty?
end
def self.log_dest_is_set_to(argv, log_dest)
argv.include?(log_dest)
end
# @param argv Array of commandline flags
# @return Set<Symbol> of expected loggers
def self.expected_loggers(argv)
loggers = Set.new
loggers << CONSOLE if verbose_or_debug_set_in_argv(argv)
loggers << 'console' if log_dest_is_set_to(argv, LOGDEST_CONSOLE)
loggers << '/dev/null/foo' if log_dest_is_set_to(argv, LOGDEST_FILE)
if Puppet.features.microsoft_windows?
# an explicit call to --logdest syslog on windows is swallowed silently with no
# logger created (see #suitable() of the syslog Puppet::Util::Log::Destination subclass)
# however Puppet::Util::Log.newdestination('syslog') does get called...so we have
# to set an expectation
loggers << 'syslog' if log_dest_is_set_to(argv, LOGDEST_SYSLOG)
loggers << EVENTLOG if no_log_dest_set_in(argv)
else
# posix
loggers << 'syslog' if log_dest_is_set_to(argv, LOGDEST_SYSLOG)
loggers << SYSLOG if no_log_dest_set_in(argv)
end
return loggers
end
# @param argv Array of commandline flags
# @return Symbol of the expected log level
def self.expected_level(argv)
case
when argv.include?(VERBOSE) then INFO_LEVEL
when argv.include?(DEBUG) then DEBUG_LEVEL
else DEFAULT_LOG_LEVEL
end
end
# @param argv Array of commandline flags
# @return Hash of expected loggers and the expected log level
def self.with_expectations_based_on(argv)
{
:loggers => expected_loggers(argv),
:level => expected_level(argv),
}
end
# For running a single spec (by line number): rspec -l150 spec/integration/agent/logging_spec.rb
# debug_argv = []
# it_should_behave_like( "an agent", [debug_argv], with_expectations_based_on([debug_argv]))
ONETIME_DAEMONIZE_ARGS.each do |onetime_daemonize_args|
LOG_LEVEL_ARGS.each do |log_level_args|
LOG_DEST_ARGS.each do |log_dest_args|
argv = (onetime_daemonize_args + [log_level_args, log_dest_args]).flatten.compact
describe "for #{argv}" do
it_should_behave_like( "an agent", argv, with_expectations_based_on(argv))
end
end
end
end
end
diff --git a/spec/integration/application/apply_spec.rb b/spec/integration/application/apply_spec.rb
index 3ce1277d3..4d9552f99 100755
--- a/spec/integration/application/apply_spec.rb
+++ b/spec/integration/application/apply_spec.rb
@@ -1,115 +1,115 @@
require 'spec_helper'
require 'puppet_spec/files'
describe "apply" do
include PuppetSpec::Files
before :each do
Puppet[:reports] = "none"
end
describe "when applying provided catalogs" do
it "can apply catalogs provided in a file in pson" do
file_to_create = tmpfile("pson_catalog")
catalog = Puppet::Resource::Catalog.new('mine', Puppet.lookup(:environments).get(Puppet[:environment]))
resource = Puppet::Resource.new(:file, file_to_create, :parameters => {:content => "my stuff"})
catalog.add_resource resource
manifest = file_containing("manifest", catalog.to_pson)
puppet = Puppet::Application[:apply]
puppet.options[:catalog] = manifest
puppet.apply
- expect(Puppet::FileSystem.exist?(file_to_create)).to be_true
+ expect(Puppet::FileSystem.exist?(file_to_create)).to be_truthy
expect(File.read(file_to_create)).to eq("my stuff")
end
end
it "applies a given file even when a directory environment is specified" do
manifest = file_containing("manifest.pp", "notice('it was applied')")
special = Puppet::Node::Environment.create(:special, [])
Puppet.override(:current_environment => special) do
Puppet[:environment] = 'special'
puppet = Puppet::Application[:apply]
puppet.stubs(:command_line).returns(stub('command_line', :args => [manifest]))
expect { puppet.run_command }.to exit_with(0)
end
expect(@logs.map(&:to_s)).to include('it was applied')
end
it "applies a given file even when an ENC is configured", :if => !Puppet.features.microsoft_windows? do
manifest = file_containing("manifest.pp", "notice('specific manifest applied')")
site_manifest = file_containing("site_manifest.pp", "notice('the site manifest was applied instead')")
enc = file_containing("enc_script", "#!/bin/sh\necho 'classes: []'")
File.chmod(0755, enc)
special = Puppet::Node::Environment.create(:special, [])
Puppet.override(:current_environment => special) do
Puppet[:environment] = 'special'
Puppet[:node_terminus] = 'exec'
Puppet[:external_nodes] = enc
Puppet[:manifest] = site_manifest
puppet = Puppet::Application[:apply]
puppet.stubs(:command_line).returns(stub('command_line', :args => [manifest]))
expect { puppet.run_command }.to exit_with(0)
end
expect(@logs.map(&:to_s)).to include('specific manifest applied')
end
context "with a module" do
let(:modulepath) { tmpdir('modulepath') }
let(:execute) { 'include amod' }
let(:args) { ['-e', execute, '--modulepath', modulepath] }
before(:each) do
dir_contained_in(modulepath, {
"amod" => {
"manifests" => {
"init.pp" => "class amod{ notice('amod class included') }"
}
}
})
Puppet[:environmentpath] = dir_containing("environments", { Puppet[:environment] => {} })
end
def init_cli_args_and_apply_app(args, execute)
Puppet.initialize_settings(args)
puppet = Puppet::Application.find(:apply).new(stub('command_line', :subcommand_name => :apply, :args => args))
puppet.options[:code] = execute
return puppet
end
it "looks in --modulepath even when the default directory environment exists" do
apply = init_cli_args_and_apply_app(args, execute)
expect do
expect { apply.run }.to exit_with(0)
end.to have_printed('amod class included')
end
it "looks in --modulepath even when given a specific directory --environment" do
args << '--environment' << 'production'
apply = init_cli_args_and_apply_app(args, execute)
expect do
expect { apply.run }.to exit_with(0)
end.to have_printed('amod class included')
end
it "looks in --modulepath when given multiple paths in --modulepath" do
args = ['-e', execute, '--modulepath', [tmpdir('notmodulepath'), modulepath].join(File::PATH_SEPARATOR)]
apply = init_cli_args_and_apply_app(args, execute)
expect do
expect { apply.run }.to exit_with(0)
end.to have_printed('amod class included')
end
end
end
diff --git a/spec/integration/application/doc_spec.rb b/spec/integration/application/doc_spec.rb
index 463bb2dc0..9fe5d419a 100755
--- a/spec/integration/application/doc_spec.rb
+++ b/spec/integration/application/doc_spec.rb
@@ -1,15 +1,15 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/application/doc'
describe Puppet::Application::Doc do
include PuppetSpec::Files
it "should respect the -o option" do
puppetdoc = Puppet::Application[:doc]
puppetdoc.command_line.stubs(:args).returns(['foo', '-o', 'bar'])
puppetdoc.parse_options
- puppetdoc.options[:outputdir].should == 'bar'
+ expect(puppetdoc.options[:outputdir]).to eq('bar')
end
end
diff --git a/spec/integration/configurer_spec.rb b/spec/integration/configurer_spec.rb
index be1f34ca3..5bd8df520 100755
--- a/spec/integration/configurer_spec.rb
+++ b/spec/integration/configurer_spec.rb
@@ -1,67 +1,67 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/configurer'
describe Puppet::Configurer do
include PuppetSpec::Files
describe "when running" do
before(:each) do
@catalog = Puppet::Resource::Catalog.new("testing", Puppet.lookup(:environments).get(Puppet[:environment]))
@catalog.add_resource(Puppet::Type.type(:notify).new(:title => "testing"))
# Make sure we don't try to persist the local state after the transaction ran,
# because it will fail during test (the state file is in a not-existing directory)
# and we need the transaction to be successful to be able to produce a summary report
@catalog.host_config = false
@configurer = Puppet::Configurer.new
end
it "should send a transaction report with valid data" do
@configurer.stubs(:save_last_run_summary)
Puppet::Transaction::Report.indirection.expects(:save).with do |report, x|
report.time.class == Time and report.logs.length > 0
end
Puppet[:report] = true
@configurer.run :catalog => @catalog
end
it "should save a correct last run summary" do
report = Puppet::Transaction::Report.new("apply")
Puppet::Transaction::Report.indirection.stubs(:save)
Puppet[:lastrunfile] = tmpfile("lastrunfile")
Puppet.settings.setting(:lastrunfile).mode = 0666
Puppet[:report] = true
# We only record integer seconds in the timestamp, and truncate
# backwards, so don't use a more accurate timestamp in the test.
# --daniel 2011-03-07
t1 = Time.now.tv_sec
@configurer.run :catalog => @catalog, :report => report
t2 = Time.now.tv_sec
# sticky bit only applies to directories in windows
file_mode = Puppet.features.microsoft_windows? ? '666' : '100666'
- Puppet::FileSystem.stat(Puppet[:lastrunfile]).mode.to_s(8).should == file_mode
+ expect(Puppet::FileSystem.stat(Puppet[:lastrunfile]).mode.to_s(8)).to eq(file_mode)
summary = nil
File.open(Puppet[:lastrunfile], "r") do |fd|
summary = YAML.load(fd.read)
end
- summary.should be_a(Hash)
+ expect(summary).to be_a(Hash)
%w{time changes events resources}.each do |key|
- summary.should be_key(key)
+ expect(summary).to be_key(key)
end
- summary["time"].should be_key("notify")
- summary["time"]["last_run"].should be_between(t1, t2)
+ expect(summary["time"]).to be_key("notify")
+ expect(summary["time"]["last_run"]).to be_between(t1, t2)
end
end
end
diff --git a/spec/integration/defaults_spec.rb b/spec/integration/defaults_spec.rb
index 8cd2b5796..3e478eec0 100755
--- a/spec/integration/defaults_spec.rb
+++ b/spec/integration/defaults_spec.rb
@@ -1,234 +1,234 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/defaults'
describe "Puppet defaults" do
describe "when default_manifest is set" do
it "returns ./manifests by default" do
expect(Puppet[:default_manifest]).to eq('./manifests')
end
end
describe "when disable_per_environment_manifest is set" do
it "returns false by default" do
expect(Puppet[:disable_per_environment_manifest]).to eq(false)
end
it "errors when set to true and default_manifest is not an absolute path" do
expect {
Puppet[:default_manifest] = './some/relative/manifest.pp'
Puppet[:disable_per_environment_manifest] = true
}.to raise_error Puppet::Settings::ValidationError, /'default_manifest' setting must be.*absolute/
end
end
describe "when setting the :factpath" do
it "should add the :factpath to Facter's search paths" do
Facter.expects(:search).with("/my/fact/path")
Puppet.settings[:factpath] = "/my/fact/path"
end
end
describe "when setting the :certname" do
it "should fail if the certname is not downcased" do
expect { Puppet.settings[:certname] = "Host.Domain.Com" }.to raise_error(ArgumentError)
end
end
describe "when setting :node_name_value" do
it "should default to the value of :certname" do
Puppet.settings[:certname] = 'blargle'
- Puppet.settings[:node_name_value].should == 'blargle'
+ expect(Puppet.settings[:node_name_value]).to eq('blargle')
end
end
describe "when setting the :node_name_fact" do
it "should fail when also setting :node_name_value" do
- lambda do
+ expect do
Puppet.settings[:node_name_value] = "some value"
Puppet.settings[:node_name_fact] = "some_fact"
- end.should raise_error("Cannot specify both the node_name_value and node_name_fact settings")
+ end.to raise_error("Cannot specify both the node_name_value and node_name_fact settings")
end
it "should not fail when using the default for :node_name_value" do
- lambda do
+ expect do
Puppet.settings[:node_name_fact] = "some_fact"
- end.should_not raise_error
+ end.not_to raise_error
end
end
it "should have a clientyamldir setting" do
- Puppet.settings[:clientyamldir].should_not be_nil
+ expect(Puppet.settings[:clientyamldir]).not_to be_nil
end
it "should have different values for the yamldir and clientyamldir" do
- Puppet.settings[:yamldir].should_not == Puppet.settings[:clientyamldir]
+ expect(Puppet.settings[:yamldir]).not_to eq(Puppet.settings[:clientyamldir])
end
it "should have a client_datadir setting" do
- Puppet.settings[:client_datadir].should_not be_nil
+ expect(Puppet.settings[:client_datadir]).not_to be_nil
end
it "should have different values for the server_datadir and client_datadir" do
- Puppet.settings[:server_datadir].should_not == Puppet.settings[:client_datadir]
+ expect(Puppet.settings[:server_datadir]).not_to eq(Puppet.settings[:client_datadir])
end
# See #1232
it "should not specify a user or group for the clientyamldir" do
- Puppet.settings.setting(:clientyamldir).owner.should be_nil
- Puppet.settings.setting(:clientyamldir).group.should be_nil
+ expect(Puppet.settings.setting(:clientyamldir).owner).to be_nil
+ expect(Puppet.settings.setting(:clientyamldir).group).to be_nil
end
it "should use the service user and group for the yamldir" do
Puppet.settings.stubs(:service_user_available?).returns true
Puppet.settings.stubs(:service_group_available?).returns true
- Puppet.settings.setting(:yamldir).owner.should == Puppet.settings[:user]
- Puppet.settings.setting(:yamldir).group.should == Puppet.settings[:group]
+ expect(Puppet.settings.setting(:yamldir).owner).to eq(Puppet.settings[:user])
+ expect(Puppet.settings.setting(:yamldir).group).to eq(Puppet.settings[:group])
end
it "should specify that the host private key should be owned by the service user" do
Puppet.settings.stubs(:service_user_available?).returns true
- Puppet.settings.setting(:hostprivkey).owner.should == Puppet.settings[:user]
+ expect(Puppet.settings.setting(:hostprivkey).owner).to eq(Puppet.settings[:user])
end
it "should specify that the host certificate should be owned by the service user" do
Puppet.settings.stubs(:service_user_available?).returns true
- Puppet.settings.setting(:hostcert).owner.should == Puppet.settings[:user]
+ expect(Puppet.settings.setting(:hostcert).owner).to eq(Puppet.settings[:user])
end
[:modulepath, :factpath].each do |setting|
it "should configure '#{setting}' not to be a file setting, so multi-directory settings are acceptable" do
- Puppet.settings.setting(setting).should be_instance_of(Puppet::Settings::PathSetting)
+ expect(Puppet.settings.setting(setting)).to be_instance_of(Puppet::Settings::PathSetting)
end
end
describe "on a Unix-like platform it", :if => Puppet.features.posix? do
it "should add /usr/sbin and /sbin to the path if they're not there" do
Puppet::Util.withenv("PATH" => "/usr/bin#{File::PATH_SEPARATOR}/usr/local/bin") do
Puppet.settings[:path] = "none" # this causes it to ignore the setting
- ENV["PATH"].split(File::PATH_SEPARATOR).should be_include("/usr/sbin")
- ENV["PATH"].split(File::PATH_SEPARATOR).should be_include("/sbin")
+ expect(ENV["PATH"].split(File::PATH_SEPARATOR)).to be_include("/usr/sbin")
+ expect(ENV["PATH"].split(File::PATH_SEPARATOR)).to be_include("/sbin")
end
end
end
describe "on a Windows-like platform it", :if => Puppet.features.microsoft_windows? do
it "should not add anything" do
path = "c:\\windows\\system32#{File::PATH_SEPARATOR}c:\\windows"
Puppet::Util.withenv("PATH" => path) do
Puppet.settings[:path] = "none" # this causes it to ignore the setting
- ENV["PATH"].should == path
+ expect(ENV["PATH"]).to eq(path)
end
end
end
it "should default to pson for the preferred serialization format" do
- Puppet.settings.value(:preferred_serialization_format).should == "pson"
+ expect(Puppet.settings.value(:preferred_serialization_format)).to eq("pson")
end
it "should have a setting for determining the configuration version and should default to an empty string" do
- Puppet.settings[:config_version].should == ""
+ expect(Puppet.settings[:config_version]).to eq("")
end
describe "when enabling reports" do
it "should use the default server value when report server is unspecified" do
Puppet.settings[:server] = "server"
- Puppet.settings[:report_server].should == "server"
+ expect(Puppet.settings[:report_server]).to eq("server")
end
it "should use the default masterport value when report port is unspecified" do
Puppet.settings[:masterport] = "1234"
- Puppet.settings[:report_port].should == "1234"
+ expect(Puppet.settings[:report_port]).to eq("1234")
end
it "should use report_port when set" do
Puppet.settings[:masterport] = "1234"
Puppet.settings[:report_port] = "5678"
- Puppet.settings[:report_port].should == "5678"
+ expect(Puppet.settings[:report_port]).to eq("5678")
end
end
it "should have a :caname setting that defaults to the cert name" do
Puppet.settings[:certname] = "foo"
- Puppet.settings[:ca_name].should == "Puppet CA: foo"
+ expect(Puppet.settings[:ca_name]).to eq("Puppet CA: foo")
end
it "should have a 'prerun_command' that defaults to the empty string" do
- Puppet.settings[:prerun_command].should == ""
+ expect(Puppet.settings[:prerun_command]).to eq("")
end
it "should have a 'postrun_command' that defaults to the empty string" do
- Puppet.settings[:postrun_command].should == ""
+ expect(Puppet.settings[:postrun_command]).to eq("")
end
it "should have a 'certificate_revocation' setting that defaults to true" do
- Puppet.settings[:certificate_revocation].should be_true
+ expect(Puppet.settings[:certificate_revocation]).to be_truthy
end
describe "reportdir" do
subject { Puppet.settings[:reportdir] }
- it { should == "#{Puppet[:vardir]}/reports" }
+ it { is_expected.to eq("#{Puppet[:vardir]}/reports") }
end
describe "reporturl" do
subject { Puppet.settings[:reporturl] }
- it { should == "http://localhost:3000/reports/upload" }
+ it { is_expected.to eq("http://localhost:3000/reports/upload") }
end
describe "when configuring color" do
subject { Puppet.settings[:color] }
- it { should == "ansi" }
+ it { is_expected.to eq("ansi") }
end
describe "daemonize" do
it "should default to true", :unless => Puppet.features.microsoft_windows? do
- Puppet.settings[:daemonize].should == true
+ expect(Puppet.settings[:daemonize]).to eq(true)
end
describe "on Windows", :if => Puppet.features.microsoft_windows? do
it "should default to false" do
- Puppet.settings[:daemonize].should == false
+ expect(Puppet.settings[:daemonize]).to eq(false)
end
it "should raise an error if set to true" do
expect { Puppet.settings[:daemonize] = true }.to raise_error(/Cannot daemonize on Windows/)
end
end
end
describe "diff" do
it "should default to 'diff' on POSIX", :unless => Puppet.features.microsoft_windows? do
- Puppet.settings[:diff].should == 'diff'
+ expect(Puppet.settings[:diff]).to eq('diff')
end
it "should default to '' on Windows", :if => Puppet.features.microsoft_windows? do
- Puppet.settings[:diff].should == ''
+ expect(Puppet.settings[:diff]).to eq('')
end
end
describe "when configuring hiera" do
it "should have a hiera_config setting" do
- Puppet.settings[:hiera_config].should_not be_nil
+ expect(Puppet.settings[:hiera_config]).not_to be_nil
end
end
describe "when configuring the data_binding terminus" do
it "should have a data_binding_terminus setting" do
- Puppet.settings[:data_binding_terminus].should_not be_nil
+ expect(Puppet.settings[:data_binding_terminus]).not_to be_nil
end
it "should be set to hiera by default" do
- Puppet.settings[:data_binding_terminus].should == :hiera
+ expect(Puppet.settings[:data_binding_terminus]).to eq(:hiera)
end
end
describe "agent_catalog_run_lockfile" do
it "(#2888) is not a file setting so it is absent from the Settings catalog" do
- Puppet.settings.setting(:agent_catalog_run_lockfile).should_not be_a_kind_of Puppet::Settings::FileSetting
- Puppet.settings.setting(:agent_catalog_run_lockfile).should be_a Puppet::Settings::StringSetting
+ expect(Puppet.settings.setting(:agent_catalog_run_lockfile)).not_to be_a_kind_of Puppet::Settings::FileSetting
+ expect(Puppet.settings.setting(:agent_catalog_run_lockfile)).to be_a Puppet::Settings::StringSetting
end
end
end
diff --git a/spec/integration/environments/default_manifest_spec.rb b/spec/integration/environments/default_manifest_spec.rb
index c1eb38ad6..3641d5c07 100644
--- a/spec/integration/environments/default_manifest_spec.rb
+++ b/spec/integration/environments/default_manifest_spec.rb
@@ -1,215 +1,215 @@
require 'spec_helper'
module EnvironmentsDefaultManifestsSpec
describe "default manifests" do
context "puppet with default_manifest settings" do
let(:confdir) { Puppet[:confdir] }
let(:environmentpath) { File.expand_path("envdir", confdir) }
context "relative default" do
let(:testingdir) { File.join(environmentpath, "testing") }
before(:each) do
FileUtils.mkdir_p(testingdir)
end
it "reads manifest from ./manifest of a basic directory environment" do
manifestsdir = File.join(testingdir, "manifests")
FileUtils.mkdir_p(manifestsdir)
File.open(File.join(manifestsdir, "site.pp"), "w") do |f|
f.puts("notify { 'ManifestFromRelativeDefault': }")
end
File.open(File.join(confdir, "puppet.conf"), "w") do |f|
f.puts("environmentpath=#{environmentpath}")
end
expect(a_catalog_compiled_for_environment('testing')).to(
include_resource('Notify[ManifestFromRelativeDefault]')
)
end
end
context "set absolute" do
let(:testingdir) { File.join(environmentpath, "testing") }
before(:each) do
FileUtils.mkdir_p(testingdir)
end
it "reads manifest from an absolute default_manifest" do
manifestsdir = File.expand_path("manifests", confdir)
FileUtils.mkdir_p(manifestsdir)
File.open(File.join(confdir, "puppet.conf"), "w") do |f|
f.puts(<<-EOF)
environmentpath=#{environmentpath}
default_manifest=#{manifestsdir}
EOF
end
File.open(File.join(manifestsdir, "site.pp"), "w") do |f|
f.puts("notify { 'ManifestFromAbsoluteDefaultManifest': }")
end
expect(a_catalog_compiled_for_environment('testing')).to(
include_resource('Notify[ManifestFromAbsoluteDefaultManifest]')
)
end
it "reads manifest from directory environment manifest when environment.conf manifest set" do
default_manifestsdir = File.expand_path("manifests", confdir)
File.open(File.join(confdir, "puppet.conf"), "w") do |f|
f.puts(<<-EOF)
environmentpath=#{environmentpath}
default_manifest=#{default_manifestsdir}
EOF
end
manifestsdir = File.join(testingdir, "special_manifests")
FileUtils.mkdir_p(manifestsdir)
File.open(File.join(manifestsdir, "site.pp"), "w") do |f|
f.puts("notify { 'ManifestFromEnvironmentConfManifest': }")
end
File.open(File.join(testingdir, "environment.conf"), "w") do |f|
f.puts("manifest=./special_manifests")
end
expect(a_catalog_compiled_for_environment('testing')).to(
include_resource('Notify[ManifestFromEnvironmentConfManifest]')
)
expect(Puppet[:default_manifest]).to eq(default_manifestsdir)
end
it "ignores manifests in the local ./manifests if default_manifest specifies another directory" do
default_manifestsdir = File.expand_path("manifests", confdir)
FileUtils.mkdir_p(default_manifestsdir)
File.open(File.join(confdir, "puppet.conf"), "w") do |f|
f.puts(<<-EOF)
environmentpath=#{environmentpath}
default_manifest=#{default_manifestsdir}
EOF
end
File.open(File.join(default_manifestsdir, "site.pp"), "w") do |f|
f.puts("notify { 'ManifestFromAbsoluteDefaultManifest': }")
end
implicit_manifestsdir = File.join(testingdir, "manifests")
FileUtils.mkdir_p(implicit_manifestsdir)
File.open(File.join(implicit_manifestsdir, "site.pp"), "w") do |f|
f.puts("notify { 'ManifestFromImplicitRelativeEnvironmentManifestDirectory': }")
end
expect(a_catalog_compiled_for_environment('testing')).to(
include_resource('Notify[ManifestFromAbsoluteDefaultManifest]')
)
end
end
context "with disable_per_environment_manifest true" do
let(:manifestsdir) { File.expand_path("manifests", confdir) }
let(:testingdir) { File.join(environmentpath, "testing") }
before(:each) do
FileUtils.mkdir_p(testingdir)
end
before(:each) do
FileUtils.mkdir_p(manifestsdir)
File.open(File.join(confdir, "puppet.conf"), "w") do |f|
f.puts(<<-EOF)
environmentpath=#{environmentpath}
default_manifest=#{manifestsdir}
disable_per_environment_manifest=true
EOF
end
File.open(File.join(manifestsdir, "site.pp"), "w") do |f|
f.puts("notify { 'ManifestFromAbsoluteDefaultManifest': }")
end
end
it "reads manifest from the default manifest setting" do
expect(a_catalog_compiled_for_environment('testing')).to(
include_resource('Notify[ManifestFromAbsoluteDefaultManifest]')
)
end
it "refuses to compile if environment.conf specifies a different manifest" do
File.open(File.join(testingdir, "environment.conf"), "w") do |f|
f.puts("manifest=./special_manifests")
end
expect { a_catalog_compiled_for_environment('testing') }.to(
raise_error(Puppet::Error, /disable_per_environment_manifest.*environment.conf.*manifest.*conflict/)
)
end
it "reads manifest from default_manifest setting when environment.conf has manifest set if setting equals default_manifest setting" do
File.open(File.join(testingdir, "environment.conf"), "w") do |f|
f.puts("manifest=#{manifestsdir}")
end
expect(a_catalog_compiled_for_environment('testing')).to(
include_resource('Notify[ManifestFromAbsoluteDefaultManifest]')
)
end
it "logs errors if environment.conf specifies a different manifest" do
File.open(File.join(testingdir, "environment.conf"), "w") do |f|
f.puts("manifest=./special_manifests")
end
Puppet.initialize_settings
expect(Puppet[:environmentpath]).to eq(environmentpath)
environment = Puppet.lookup(:environments).get('testing')
expect(environment.manifest).to eq(manifestsdir)
expect(@logs.first.to_s).to match(%r{disable_per_environment_manifest.*is true, but.*environment.*at #{testingdir}.*has.*environment.conf.*manifest.*#{testingdir}/special_manifests})
end
it "raises an error if default_manifest is not absolute" do
File.open(File.join(confdir, "puppet.conf"), "w") do |f|
f.puts(<<-EOF)
environmentpath=#{environmentpath}
default_manifest=./relative
disable_per_environment_manifest=true
EOF
end
expect { Puppet.initialize_settings }.to raise_error(Puppet::Settings::ValidationError, /default_manifest.*must be.*absolute.*when.*disable_per_environment_manifest.*true/)
end
end
end
RSpec::Matchers.define :include_resource do |expected|
match do |actual|
actual.resources.map(&:ref).include?(expected)
end
- def failure_message_for_should
+ def failure_message
"expected #{@actual.resources.map(&:ref)} to include #{expected}"
end
- def failure_message_for_should_not
+ def failure_message_when_negated
"expected #{@actual.resources.map(&:ref)} not to include #{expected}"
end
end
def a_catalog_compiled_for_environment(envname)
Puppet.initialize_settings
expect(Puppet[:environmentpath]).to eq(environmentpath)
node = Puppet::Node.new('testnode', :environment => 'testing')
expect(node.environment).to eq(Puppet.lookup(:environments).get('testing'))
Puppet::Parser::Compiler.compile(node)
end
end
end
diff --git a/spec/integration/faces/ca_spec.rb b/spec/integration/faces/ca_spec.rb
index 7b244d162..889585963 100755
--- a/spec/integration/faces/ca_spec.rb
+++ b/spec/integration/faces/ca_spec.rb
@@ -1,354 +1,354 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/face'
describe Puppet::Face[:ca, '0.1.0'], :unless => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
before :each do
Puppet.run_mode.stubs(:master?).returns(true)
Puppet[:ca] = true
Puppet[:ssldir] = tmpdir("face-ca-ssldir")
Puppet::SSL::Host.ca_location = :only
Puppet[:certificate_revocation] = true
# This is way more intimate than I want to be with the implementation, but
# there doesn't seem any other way to test this. --daniel 2011-07-18
Puppet::SSL::CertificateAuthority.stubs(:instance).returns(
# ...and this actually does the directory creation, etc.
Puppet::SSL::CertificateAuthority.new
)
end
def given_certificate_requests_for(*names)
names.each do |name|
Puppet::SSL::Host.new(name).generate_certificate_request
end
end
def given_certificates_for(*names)
names.each do |name|
Puppet::SSL::Host.new(name).generate
end
end
context "#verify" do
it "should report if there is no certificate" do
- subject.verify('random-host').should == {
+ expect(subject.verify('random-host')).to eq({
:host => 'random-host', :valid => false,
:error => 'Could not find a certificate for random-host'
- }
+ })
end
it "should report that it cannot find a certificate when there is only a request" do
given_certificate_requests_for('random-host')
- subject.verify('random-host').should == {
+ expect(subject.verify('random-host')).to eq({
:host => 'random-host', :valid => false,
:error => 'Could not find a certificate for random-host'
- }
+ })
end
it "should verify a signed certificate" do
given_certificates_for('random-host')
- subject.verify('random-host').should == {
+ expect(subject.verify('random-host')).to eq({
:host => 'random-host', :valid => true
- }
+ })
end
it "should not verify a revoked certificate" do
given_certificates_for('random-host')
subject.revoke('random-host')
- subject.verify('random-host').should == {
+ expect(subject.verify('random-host')).to eq({
:host => 'random-host', :valid => false,
:error => 'certificate revoked'
- }
+ })
end
it "should verify a revoked certificate if CRL use was turned off" do
given_certificates_for('random-host')
subject.revoke('random-host')
Puppet[:certificate_revocation] = false
- subject.verify('random-host').should == {
+ expect(subject.verify('random-host')).to eq({
:host => 'random-host', :valid => true
- }
+ })
end
end
context "#fingerprint" do
let(:fingerprint_re) { /^\([0-9A-Z]+\) [0-9A-F:]+$/ }
it "should be nil if there is no certificate" do
- subject.fingerprint('random-host').should be_nil
+ expect(subject.fingerprint('random-host')).to be_nil
end
it "should fingerprint a CSR" do
given_certificate_requests_for('random-host')
- subject.fingerprint('random-host').should =~ fingerprint_re
+ expect(subject.fingerprint('random-host')).to match(fingerprint_re)
end
it "should fingerprint a certificate" do
given_certificates_for('random-host')
- subject.fingerprint('random-host').should =~ fingerprint_re
+ expect(subject.fingerprint('random-host')).to match(fingerprint_re)
end
%w{md5 MD5 sha1 SHA1 RIPEMD160 sha256 sha512}.each do |digest|
it "should fingerprint with #{digest.inspect}" do
given_certificates_for('random-host')
- subject.fingerprint('random-host', :digest => digest).should =~ fingerprint_re
+ expect(subject.fingerprint('random-host', :digest => digest)).to match(fingerprint_re)
end
end
end
context "#print" do
it "should be nil if there is no certificate" do
- subject.print('random-host').should be_nil
+ expect(subject.print('random-host')).to be_nil
end
it "should return nothing if there is only a CSR" do
given_certificate_requests_for('random-host')
- subject.print('random-host').should be_nil
+ expect(subject.print('random-host')).to be_nil
end
it "should return the certificate content if there is a cert" do
given_certificates_for('random-host')
text = subject.print('random-host')
- text.should be_an_instance_of String
- text.should =~ /^Certificate:/
- text.should =~ /Issuer: CN=Puppet CA: /
- text.should =~ /Subject: CN=random-host$/
+ expect(text).to be_an_instance_of String
+ expect(text).to match(/^Certificate:/)
+ expect(text).to match(/Issuer: CN=Puppet CA: /)
+ expect(text).to match(/Subject: CN=random-host$/)
end
end
context "#sign" do
it "should report that there is no CSR" do
- subject.sign('random-host').should == 'Could not find certificate request for random-host'
+ expect(subject.sign('random-host')).to eq('Could not find certificate request for random-host')
end
it "should report that there is no CSR when even when there is a certificate" do
given_certificates_for('random-host')
- subject.sign('random-host').should == 'Could not find certificate request for random-host'
+ expect(subject.sign('random-host')).to eq('Could not find certificate request for random-host')
end
it "should sign a CSR if one exists" do
given_certificate_requests_for('random-host')
- subject.sign('random-host').should be_an_instance_of Puppet::SSL::Certificate
+ expect(subject.sign('random-host')).to be_an_instance_of Puppet::SSL::Certificate
list = subject.list(:signed => true)
- list.length.should == 1
- list.first.name.should == 'random-host'
+ expect(list.length).to eq(1)
+ expect(list.first.name).to eq('random-host')
end
describe "when the CSR specifies DNS alt names" do
let(:host) { Puppet::SSL::Host.new('someone') }
before :each do
host.generate_certificate_request(:dns_alt_names => 'some,alt,names')
end
it "should sign the CSR if DNS alt names are allowed" do
subject.sign('someone', :allow_dns_alt_names => true)
- host.certificate.should be_a(Puppet::SSL::Certificate)
+ expect(host.certificate).to be_a(Puppet::SSL::Certificate)
end
it "should refuse to sign the CSR if DNS alt names are not allowed" do
certname = 'someone'
expect do
subject.sign(certname)
end.to raise_error(Puppet::SSL::CertificateAuthority::CertificateSigningError, /CSR '#{certname}' contains subject alternative names \(.*\), which are disallowed. Use `puppet cert --allow-dns-alt-names sign #{certname}` to sign this request./i)
- host.certificate.should be_nil
+ expect(host.certificate).to be_nil
end
end
end
context "#generate" do
it "should generate a certificate if requested" do
- subject.list(:all => true).should == []
+ expect(subject.list(:all => true)).to eq([])
subject.generate('random-host')
list = subject.list(:signed => true)
- list.length.should == 1
- list.first.name.should == 'random-host'
+ expect(list.length).to eq(1)
+ expect(list.first.name).to eq('random-host')
end
it "should report if a CSR with that name already exists" do
given_certificate_requests_for('random-host')
- subject.generate('random-host').should =~ /already has a certificate request/
+ expect(subject.generate('random-host')).to match(/already has a certificate request/)
end
it "should report if the certificate with that name already exists" do
given_certificates_for('random-host')
- subject.generate('random-host').should =~ /already has a certificate/
+ expect(subject.generate('random-host')).to match(/already has a certificate/)
end
it "should include the specified DNS alt names" do
subject.generate('some-host', :dns_alt_names => 'some,alt,names')
host = subject.list(:signed => true).first
- host.name.should == 'some-host'
- host.certificate.subject_alt_names.should =~ %w[DNS:some DNS:alt DNS:names DNS:some-host]
+ expect(host.name).to eq('some-host')
+ expect(host.certificate.subject_alt_names).to match_array(%w[DNS:some DNS:alt DNS:names DNS:some-host])
- subject.list(:pending => true).should be_empty
+ expect(subject.list(:pending => true)).to be_empty
end
end
context "#revoke" do
it "should let the user know what went wrong when there is nothing to revoke" do
- subject.revoke('nonesuch').should == 'Nothing was revoked'
+ expect(subject.revoke('nonesuch')).to eq('Nothing was revoked')
end
it "should revoke a certificate" do
given_certificates_for('random-host')
subject.revoke('random-host')
found = subject.list(:all => true, :subject => 'random-host')
- subject.get_action(:list).when_rendering(:console).call(found, {}).
- should =~ /^- random-host \(\w+\) [:0-9A-F]+ \(certificate revoked\)/
+ expect(subject.get_action(:list).when_rendering(:console).call(found, {})).
+ to match(/^- random-host \(\w+\) [:0-9A-F]+ \(certificate revoked\)/)
end
end
context "#destroy" do
it "should let the user know if nothing was deleted" do
- subject.destroy('nonesuch').should == "Nothing was deleted"
+ expect(subject.destroy('nonesuch')).to eq("Nothing was deleted")
end
it "should destroy a CSR, if we have one" do
given_certificate_requests_for('random-host')
subject.destroy('random-host')
- subject.list(:pending => true, :subject => 'random-host').should == []
+ expect(subject.list(:pending => true, :subject => 'random-host')).to eq([])
end
it "should destroy a certificate, if we have one" do
given_certificates_for('random-host')
subject.destroy('random-host')
- subject.list(:signed => true, :subject => 'random-host').should == []
+ expect(subject.list(:signed => true, :subject => 'random-host')).to eq([])
end
it "should tell the user something was deleted" do
given_certificates_for('random-host')
- subject.list(:signed => true, :subject => 'random-host').should_not == []
+ expect(subject.list(:signed => true, :subject => 'random-host')).not_to eq([])
- subject.destroy('random-host').
- should == "Deleted for random-host: Puppet::SSL::Certificate"
+ expect(subject.destroy('random-host')).
+ to eq("Deleted for random-host: Puppet::SSL::Certificate")
end
end
context "#list" do
context "with no hosts in CA" do
[
{},
{ :pending => true },
{ :signed => true },
{ :all => true },
].each do |type|
it "should return nothing for #{type.inspect}" do
- subject.list(type).should == []
+ expect(subject.list(type)).to eq([])
end
it "should return nothing when a matcher is passed" do
- subject.list(type.merge :subject => '.').should == []
+ expect(subject.list(type.merge :subject => '.')).to eq([])
end
context "when_rendering :console" do
it "should return nothing for #{type.inspect}" do
- subject.get_action(:list).when_rendering(:console).call(subject.list(type), {}).should == ""
+ expect(subject.get_action(:list).when_rendering(:console).call(subject.list(type), {})).to eq("")
end
end
end
end
context "with some hosts" do
csr_names = (1..3).map {|n| "csr-#{n}" }
crt_names = (1..3).map {|n| "crt-#{n}" }
all_names = csr_names + crt_names
{
{} => csr_names,
{ :pending => true } => csr_names,
{ :signed => true } => crt_names,
{ :all => true } => all_names,
{ :pending => true, :signed => true } => all_names,
}.each do |input, expect|
it "should map #{input.inspect} to #{expect.inspect}" do
given_certificate_requests_for(*csr_names)
given_certificates_for(*crt_names)
- subject.list(input).map(&:name).should =~ expect
+ expect(subject.list(input).map(&:name)).to match_array(expect)
end
['', '.', '2', 'none'].each do |pattern|
filtered = expect.select {|x| Regexp.new(pattern).match(x) }
it "should filter all hosts matching #{pattern.inspect} to #{filtered.inspect}" do
given_certificate_requests_for(*csr_names)
given_certificates_for(*crt_names)
- subject.list(input.merge :subject => pattern).map(&:name).should =~ filtered
+ expect(subject.list(input.merge :subject => pattern).map(&:name)).to match_array(filtered)
end
end
end
context "when_rendering :console" do
{ [["csr1.local"], []] => [/^ csr1.local /],
[[], ["crt1.local"]] => [/^\+ crt1.local /],
[["csr2"], ["crt2"]] => [/^ csr2 /, /^\+ crt2 /]
}.each do |input, pattern|
it "should render #{input.inspect} to match #{pattern.inspect}" do
given_certificate_requests_for(*input[0])
given_certificates_for(*input[1])
text = subject.get_action(:list).when_rendering(:console).call(subject.list(:all => true), {})
pattern.each do |item|
- text.should =~ item
+ expect(text).to match(item)
end
end
end
end
end
end
actions = %w{destroy list revoke generate sign print verify fingerprint}
actions.each do |action|
- it { should be_action action }
+ it { is_expected.to be_action action }
it "should fail #{action} when not a CA" do
Puppet[:ca] = false
expect {
case subject.method(action).arity
when -1 then subject.send(action)
when -2 then subject.send(action, 'dummy')
else
raise "#{action} has arity #{subject.method(action).arity}"
end
}.to raise_error(/Not a CA/)
end
end
end
diff --git a/spec/integration/faces/documentation_spec.rb b/spec/integration/faces/documentation_spec.rb
index 803d61599..a92a3587b 100755
--- a/spec/integration/faces/documentation_spec.rb
+++ b/spec/integration/faces/documentation_spec.rb
@@ -1,58 +1,58 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/face'
describe "documentation of faces" do
it "should generate global help" do
help = nil
expect { help = Puppet::Face[:help, :current].help }.not_to raise_error
- help.should be_an_instance_of String
- help.length.should be > 200
+ expect(help).to be_an_instance_of String
+ expect(help.length).to be > 200
end
########################################################################
# Can we actually generate documentation for the face, and the actions it
# has? This avoids situations where the ERB template turns out to have a
# bug in it, triggered in something the user might do.
context "face help messages" do
Puppet::Face.faces.sort.each do |face_name|
# REVISIT: We should walk all versions of the face here...
let :help do Puppet::Face[:help, :current] end
context "generating help" do
it "for #{face_name}" do
expect {
text = help.help(face_name)
- text.should be_an_instance_of String
- text.length.should be > 100
+ expect(text).to be_an_instance_of String
+ expect(text.length).to be > 100
}.not_to raise_error
end
Puppet::Face[face_name, :current].actions.sort.each do |action_name|
it "for #{face_name}.#{action_name}" do
expect {
text = help.help(face_name, action_name)
- text.should be_an_instance_of String
- text.length.should be > 100
+ expect(text).to be_an_instance_of String
+ expect(text.length).to be > 100
}.not_to raise_error
end
end
end
########################################################################
# Ensure that we have authorship and copyright information in *our* faces;
# if you apply this to third party faces you might well be disappointed.
context "licensing of Puppet Labs face '#{face_name}'" do
subject { Puppet::Face[face_name, :current] }
its :license do should =~ /Apache\s*2/ end
its :copyright do should =~ /Puppet Labs/ end
# REVISIT: This is less that ideal, I think, but right now I am more
# comfortable watching us ship with some copyright than without any; we
# can redress that when it becomes appropriate. --daniel 2011-04-27
its :copyright do should =~ /20\d{2}/ end
end
end
end
end
diff --git a/spec/integration/file_serving/fileset_spec.rb b/spec/integration/file_serving/fileset_spec.rb
index 283f80d9c..8a3f9a26b 100755
--- a/spec/integration/file_serving/fileset_spec.rb
+++ b/spec/integration/file_serving/fileset_spec.rb
@@ -1,13 +1,13 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_serving/fileset'
describe Puppet::FileServing::Fileset do
it "should be able to recurse on a single file" do
@path = Tempfile.new("fileset_integration")
fileset = Puppet::FileServing::Fileset.new(@path.path)
- lambda { fileset.files }.should_not raise_error
+ expect { fileset.files }.not_to raise_error
end
end
diff --git a/spec/integration/file_serving/terminus_helper_spec.rb b/spec/integration/file_serving/terminus_helper_spec.rb
index 2451531b6..d75b85e14 100755
--- a/spec/integration/file_serving/terminus_helper_spec.rb
+++ b/spec/integration/file_serving/terminus_helper_spec.rb
@@ -1,21 +1,21 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_serving/terminus_helper'
class TerminusHelperIntegrationTester
include Puppet::FileServing::TerminusHelper
def model
Puppet::FileServing::Metadata
end
end
describe Puppet::FileServing::TerminusHelper do
it "should be able to recurse on a single file" do
@path = Tempfile.new("fileset_integration")
request = Puppet::Indirector::Request.new(:metadata, :find, @path.path, nil, :recurse => true)
tester = TerminusHelperIntegrationTester.new
- lambda { tester.path2instances(request, @path.path) }.should_not raise_error
+ expect { tester.path2instances(request, @path.path) }.not_to raise_error
end
end
diff --git a/spec/integration/indirector/catalog/compiler_spec.rb b/spec/integration/indirector/catalog/compiler_spec.rb
index b3e7be245..0ec4e861a 100755
--- a/spec/integration/indirector/catalog/compiler_spec.rb
+++ b/spec/integration/indirector/catalog/compiler_spec.rb
@@ -1,76 +1,76 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/resource/catalog'
Puppet::Resource::Catalog.indirection.terminus(:compiler)
describe Puppet::Resource::Catalog::Compiler do
before do
Facter.stubs(:value).returns "something"
@catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
@catalog.add_resource(@one = Puppet::Resource.new(:file, "/one"))
@catalog.add_resource(@two = Puppet::Resource.new(:file, "/two"))
end
it "should remove virtual resources when filtering" do
@one.virtual = true
- Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs.should == [ @two.ref ]
+ expect(Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs).to eq([ @two.ref ])
end
it "should not remove exported resources when filtering" do
@one.exported = true
- Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs.sort.should == [ @one.ref, @two.ref ]
+ expect(Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs.sort).to eq([ @one.ref, @two.ref ])
end
it "should remove virtual exported resources when filtering" do
@one.exported = true
@one.virtual = true
- Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs.should == [ @two.ref ]
+ expect(Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs).to eq([ @two.ref ])
end
it "should filter out virtual resources when finding a catalog" do
Puppet[:node_terminus] = :memory
Puppet::Node.indirection.save(Puppet::Node.new("mynode"))
Puppet::Resource::Catalog.indirection.terminus.stubs(:extract_facts_from_request)
Puppet::Resource::Catalog.indirection.terminus.stubs(:compile).returns(@catalog)
@one.virtual = true
- Puppet::Resource::Catalog.indirection.find("mynode").resource_refs.should == [ @two.ref ]
+ expect(Puppet::Resource::Catalog.indirection.find("mynode").resource_refs).to eq([ @two.ref ])
end
it "should not filter out exported resources when finding a catalog" do
Puppet[:node_terminus] = :memory
Puppet::Node.indirection.save(Puppet::Node.new("mynode"))
Puppet::Resource::Catalog.indirection.terminus.stubs(:extract_facts_from_request)
Puppet::Resource::Catalog.indirection.terminus.stubs(:compile).returns(@catalog)
@one.exported = true
- Puppet::Resource::Catalog.indirection.find("mynode").resource_refs.sort.should == [ @one.ref, @two.ref ]
+ expect(Puppet::Resource::Catalog.indirection.find("mynode").resource_refs.sort).to eq([ @one.ref, @two.ref ])
end
it "should filter out virtual exported resources when finding a catalog" do
Puppet[:node_terminus] = :memory
Puppet::Node.indirection.save(Puppet::Node.new("mynode"))
Puppet::Resource::Catalog.indirection.terminus.stubs(:extract_facts_from_request)
Puppet::Resource::Catalog.indirection.terminus.stubs(:compile).returns(@catalog)
@one.exported = true
@one.virtual = true
- Puppet::Resource::Catalog.indirection.find("mynode").resource_refs.should == [ @two.ref ]
+ expect(Puppet::Resource::Catalog.indirection.find("mynode").resource_refs).to eq([ @two.ref ])
end
it "filters out virtual exported resources using the agent's production environment" do
Puppet[:node_terminus] = :memory
Puppet::Node.indirection.save(Puppet::Node.new("mynode"))
Puppet::Parser::Resource::Catalog.any_instance.expects(:to_resource).with do |catalog|
expect(Puppet.lookup(:current_environment).name).to eq(:production)
end
Puppet::Resource::Catalog.indirection.find("mynode")
end
end
diff --git a/spec/integration/indirector/direct_file_server_spec.rb b/spec/integration/indirector/direct_file_server_spec.rb
index be0e7b65d..9533b46bc 100755
--- a/spec/integration/indirector/direct_file_server_spec.rb
+++ b/spec/integration/indirector/direct_file_server_spec.rb
@@ -1,64 +1,68 @@
require 'spec_helper'
require 'matchers/include'
require 'puppet/indirector/file_content/file'
describe Puppet::Indirector::DirectFileServer, " when interacting with the filesystem and the model" do
include PuppetSpec::Files
before do
# We just test a subclass, since it's close enough.
@terminus = Puppet::Indirector::FileContent::File.new
@filepath = make_absolute("/path/to/my/file")
end
it "should return an instance of the model" do
- pending("porting to Windows", :if => Puppet.features.microsoft_windows?) do
+ if Puppet.features.microsoft_windows?
+ skip("porting to Windows")
+ else
Puppet::FileSystem.expects(:exist?).with(@filepath).returns(true)
- @terminus.find(@terminus.indirection.request(:find, "file://host#{@filepath}", nil)).should be_instance_of(Puppet::FileServing::Content)
+ expect(@terminus.find(@terminus.indirection.request(:find, "file://host#{@filepath}", nil))).to be_instance_of(Puppet::FileServing::Content)
end
end
it "should return an instance capable of returning its content" do
- pending("porting to Windows", :if => Puppet.features.microsoft_windows?) do
+ if Puppet.features.microsoft_windows?
+ skip("porting to Windows")
+ else
filename = file_containing("testfile", "my content")
instance = @terminus.find(@terminus.indirection.request(:find, "file://host#{filename}", nil))
- instance.content.should == "my content"
+ expect(instance.content).to eq("my content")
end
end
end
describe Puppet::Indirector::DirectFileServer, " when interacting with FileServing::Fileset and the model" do
include PuppetSpec::Files
include Matchers::Include
matcher :file_with_content do |name, content|
match do |actual|
actual.full_path == name && actual.content == content
end
end
matcher :directory_named do |name|
match do |actual|
actual.full_path == name
end
end
it "should return an instance for every file in the fileset" do
path = tmpdir('direct_file_server_testing')
File.open(File.join(path, "one"), "w") { |f| f.print "one content" }
File.open(File.join(path, "two"), "w") { |f| f.print "two content" }
terminus = Puppet::Indirector::FileContent::File.new
request = terminus.indirection.request(:search, "file:///#{path}", nil, :recurse => true)
expect(terminus.search(request)).to include_in_any_order(
file_with_content(File.join(path, "one"), "one content"),
file_with_content(File.join(path, "two"), "two content"),
directory_named(path))
end
end
diff --git a/spec/integration/indirector/facts/facter_spec.rb b/spec/integration/indirector/facts/facter_spec.rb
index b552431f9..98ea19af3 100644
--- a/spec/integration/indirector/facts/facter_spec.rb
+++ b/spec/integration/indirector/facts/facter_spec.rb
@@ -1,22 +1,22 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/compiler'
describe Puppet::Node::Facts::Facter do
include PuppetSpec::Compiler
it "preserves case in fact values" do
Facter.add(:downcase_test) do
setcode do
"AaBbCc"
end
end
Facter.stubs(:reset)
cat = compile_to_catalog('notify { $downcase_test: }',
Puppet::Node.indirection.find('foo'))
- cat.resource("Notify[AaBbCc]").should be
+ expect(cat.resource("Notify[AaBbCc]")).to be
end
end
diff --git a/spec/integration/indirector/file_content/file_server_spec.rb b/spec/integration/indirector/file_content/file_server_spec.rb
index f2b72b697..ada4a7202 100755
--- a/spec/integration/indirector/file_content/file_server_spec.rb
+++ b/spec/integration/indirector/file_content/file_server_spec.rb
@@ -1,91 +1,91 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/file_content/file_server'
require 'shared_behaviours/file_server_terminus'
require 'puppet_spec/files'
describe Puppet::Indirector::FileContent::FileServer, " when finding files" do
it_should_behave_like "Puppet::Indirector::FileServerTerminus"
include PuppetSpec::Files
before do
@terminus = Puppet::Indirector::FileContent::FileServer.new
@test_class = Puppet::FileServing::Content
Puppet::FileServing::Configuration.instance_variable_set(:@configuration, nil)
end
it "should find plugin file content in the environment specified in the request" do
path = tmpfile("file_content_with_env")
Dir.mkdir(path)
modpath = File.join(path, "mod")
FileUtils.mkdir_p(File.join(modpath, "lib"))
file = File.join(modpath, "lib", "file.rb")
File.open(file, "wb") { |f| f.write "1\r\n" }
Puppet.settings[:modulepath] = "/no/such/file"
env = Puppet::Node::Environment.create(:foo, [path])
result = Puppet::FileServing::Content.indirection.search("plugins", :environment => env, :recurse => true)
- result.should_not be_nil
- result.length.should == 2
- result.map {|x| x.should be_instance_of(Puppet::FileServing::Content) }
- result.find {|x| x.relative_path == 'file.rb' }.content.should == "1\r\n"
+ expect(result).not_to be_nil
+ expect(result.length).to eq(2)
+ result.map {|x| expect(x).to be_instance_of(Puppet::FileServing::Content) }
+ expect(result.find {|x| x.relative_path == 'file.rb' }.content).to eq("1\r\n")
end
it "should find file content in modules" do
path = tmpfile("file_content")
Dir.mkdir(path)
modpath = File.join(path, "mymod")
FileUtils.mkdir_p(File.join(modpath, "files"))
file = File.join(modpath, "files", "myfile")
File.open(file, "wb") { |f| f.write "1\r\n" }
env = Puppet::Node::Environment.create(:foo, [path])
result = Puppet::FileServing::Content.indirection.find("modules/mymod/myfile", :environment => env)
- result.should_not be_nil
- result.should be_instance_of(Puppet::FileServing::Content)
- result.content.should == "1\r\n"
+ expect(result).not_to be_nil
+ expect(result).to be_instance_of(Puppet::FileServing::Content)
+ expect(result.content).to eq("1\r\n")
end
it "should find file content in files when node name expansions are used" do
Puppet::FileSystem.stubs(:exist?).returns true
Puppet::FileSystem.stubs(:exist?).with(Puppet[:fileserverconfig]).returns(true)
path = tmpfile("file_server_testing")
Dir.mkdir(path)
subdir = File.join(path, "mynode")
Dir.mkdir(subdir)
File.open(File.join(subdir, "myfile"), "wb") { |f| f.write "1\r\n" }
# Use a real mount, so the integration is a bit deeper.
mount1 = Puppet::FileServing::Configuration::Mount::File.new("one")
mount1.stubs(:allowed?).returns true
mount1.path = File.join(path, "%h")
parser = stub 'parser', :changed? => false
parser.stubs(:parse).returns("one" => mount1)
Puppet::FileServing::Configuration::Parser.stubs(:new).returns(parser)
path = File.join(path, "myfile")
env = Puppet::Node::Environment.create(:foo, [])
result = Puppet::FileServing::Content.indirection.find("one/myfile", :environment => env, :node => "mynode")
- result.should_not be_nil
- result.should be_instance_of(Puppet::FileServing::Content)
- result.content.should == "1\r\n"
+ expect(result).not_to be_nil
+ expect(result).to be_instance_of(Puppet::FileServing::Content)
+ expect(result.content).to eq("1\r\n")
end
end
diff --git a/spec/integration/network/authconfig_spec.rb b/spec/integration/network/authconfig_spec.rb
index 71e25a9ab..fb171af87 100644
--- a/spec/integration/network/authconfig_spec.rb
+++ b/spec/integration/network/authconfig_spec.rb
@@ -1,257 +1,257 @@
require 'spec_helper'
require 'puppet/network/authconfig'
require 'puppet/network/auth_config_parser'
RSpec::Matchers.define :allow do |params|
match do |auth|
begin
auth.check_authorization(*params)
true
rescue Puppet::Network::AuthorizationError
false
end
end
- failure_message_for_should do |instance|
+ failure_message do |instance|
"expected #{params[2][:node]}/#{params[2][:ip]} to be allowed"
end
- failure_message_for_should_not do |instance|
+ failure_message_when_negated do |instance|
"expected #{params[2][:node]}/#{params[2][:ip]} to be forbidden"
end
end
describe Puppet::Network::AuthConfig do
include PuppetSpec::Files
def add_rule(rule)
parser = Puppet::Network::AuthConfigParser.new(
"path /test\n#{rule}\n"
)
@auth = parser.parse
end
def add_regex_rule(regex, rule)
parser = Puppet::Network::AuthConfigParser.new(
"path ~ #{regex}\n#{rule}\n"
)
@auth = parser.parse
end
def add_raw_stanza(stanza)
parser = Puppet::Network::AuthConfigParser.new(
stanza
)
@auth = parser.parse
end
def request(args = {})
args = {
:key => 'key',
:node => 'host.domain.com',
:ip => '10.1.1.1',
:authenticated => true
}.merge(args)
[:find, "/test/#{args[:key]}", args]
end
describe "allow" do
it "should not match IP addresses" do
add_rule("allow 10.1.1.1")
- @auth.should_not allow(request)
+ expect(@auth).not_to allow(request)
end
it "should not accept CIDR IPv4 address" do
expect {
add_rule("allow 10.0.0.0/8")
}.to raise_error Puppet::ConfigurationError, /Invalid pattern 10\.0\.0\.0\/8/
end
it "should not match wildcard IPv4 address" do
expect {
add_rule("allow 10.1.1.*")
}.to raise_error Puppet::ConfigurationError, /Invalid pattern 10\.1\.1\.*/
end
it "should not match IPv6 address" do
expect {
add_rule("allow 2001:DB8::8:800:200C:417A")
}.to raise_error Puppet::ConfigurationError, /Invalid pattern 2001/
end
it "should support hostname" do
add_rule("allow host.domain.com")
- @auth.should allow(request)
+ expect(@auth).to allow(request)
end
it "should support wildcard host" do
add_rule("allow *.domain.com")
- @auth.should allow(request)
+ expect(@auth).to allow(request)
end
it 'should warn about missing path before allow_ip in stanza' do
expect {
add_raw_stanza("allow_ip 10.0.0.1\n")
}.to raise_error Puppet::ConfigurationError, /Missing or invalid 'path' before right directive at line.*/
end
it 'should warn about missing path before allow in stanza' do
expect {
add_raw_stanza("allow host.domain.com\n")
}.to raise_error Puppet::ConfigurationError, /Missing or invalid 'path' before right directive at line.*/
end
it "should support hostname backreferences" do
add_regex_rule('^/test/([^/]+)$', "allow $1.domain.com")
- @auth.should allow(request(:key => 'host'))
+ expect(@auth).to allow(request(:key => 'host'))
end
it "should support opaque strings" do
add_rule("allow this-is-opaque@or-not")
- @auth.should allow(request(:node => 'this-is-opaque@or-not'))
+ expect(@auth).to allow(request(:node => 'this-is-opaque@or-not'))
end
it "should support opaque strings and backreferences" do
add_regex_rule('^/test/([^/]+)$', "allow $1")
- @auth.should allow(request(:key => 'this-is-opaque@or-not', :node => 'this-is-opaque@or-not'))
+ expect(@auth).to allow(request(:key => 'this-is-opaque@or-not', :node => 'this-is-opaque@or-not'))
end
it "should support hostname ending with '.'" do
pending('bug #7589')
add_rule("allow host.domain.com.")
- @auth.should allow(request(:node => 'host.domain.com.'))
+ expect(@auth).to allow(request(:node => 'host.domain.com.'))
end
it "should support hostname ending with '.' and backreferences" do
pending('bug #7589')
add_regex_rule('^/test/([^/]+)$',"allow $1")
- @auth.should allow(request(:node => 'host.domain.com.'))
+ expect(@auth).to allow(request(:node => 'host.domain.com.'))
end
it "should support trailing whitespace" do
add_rule('allow host.domain.com ')
- @auth.should allow(request)
+ expect(@auth).to allow(request)
end
it "should support inlined comments" do
add_rule('allow host.domain.com # will it work?')
- @auth.should allow(request)
+ expect(@auth).to allow(request)
end
it "should deny non-matching host" do
add_rule("allow inexistent")
- @auth.should_not allow(request)
+ expect(@auth).not_to allow(request)
end
end
describe "allow_ip" do
it "should not warn when matches against IP addresses fail" do
add_rule("allow_ip 10.1.1.2")
- @auth.should_not allow(request)
+ expect(@auth).not_to allow(request)
- @logs.should_not be_any {|log| log.level == :warning and log.message =~ /Authentication based on IP address is deprecated/}
+ expect(@logs).not_to be_any {|log| log.level == :warning and log.message =~ /Authentication based on IP address is deprecated/}
end
it "should support IPv4 address" do
add_rule("allow_ip 10.1.1.1")
- @auth.should allow(request)
+ expect(@auth).to allow(request)
end
it "should support CIDR IPv4 address" do
add_rule("allow_ip 10.0.0.0/8")
- @auth.should allow(request)
+ expect(@auth).to allow(request)
end
it "should support wildcard IPv4 address" do
add_rule("allow_ip 10.1.1.*")
- @auth.should allow(request)
+ expect(@auth).to allow(request)
end
it "should support IPv6 address" do
add_rule("allow_ip 2001:DB8::8:800:200C:417A")
- @auth.should allow(request(:ip => '2001:DB8::8:800:200C:417A'))
+ expect(@auth).to allow(request(:ip => '2001:DB8::8:800:200C:417A'))
end
it "should support hostname" do
expect {
add_rule("allow_ip host.domain.com")
}.to raise_error Puppet::ConfigurationError, /Invalid IP pattern host.domain.com/
end
end
describe "deny" do
it "should deny denied hosts" do
add_rule <<-EOALLOWRULE
deny host.domain.com
allow *.domain.com
EOALLOWRULE
- @auth.should_not allow(request)
+ expect(@auth).not_to allow(request)
end
it "denies denied hosts after allowing them" do
add_rule <<-EOALLOWRULE
allow *.domain.com
deny host.domain.com
EOALLOWRULE
- @auth.should_not allow(request)
+ expect(@auth).not_to allow(request)
end
it "should not deny based on IP" do
add_rule <<-EOALLOWRULE
deny 10.1.1.1
allow host.domain.com
EOALLOWRULE
- @auth.should allow(request)
+ expect(@auth).to allow(request)
end
it "should not deny based on IP (ordering #2)" do
add_rule <<-EOALLOWRULE
allow host.domain.com
deny 10.1.1.1
EOALLOWRULE
- @auth.should allow(request)
+ expect(@auth).to allow(request)
end
end
describe "deny_ip" do
it "should deny based on IP" do
add_rule <<-EOALLOWRULE
deny_ip 10.1.1.1
allow host.domain.com
EOALLOWRULE
- @auth.should_not allow(request)
+ expect(@auth).not_to allow(request)
end
it "should deny based on IP (ordering #2)" do
add_rule <<-EOALLOWRULE
allow host.domain.com
deny_ip 10.1.1.1
EOALLOWRULE
- @auth.should_not allow(request)
+ expect(@auth).not_to allow(request)
end
end
end
diff --git a/spec/integration/network/formats_spec.rb b/spec/integration/network/formats_spec.rb
index 686961338..5c38177cd 100755
--- a/spec/integration/network/formats_spec.rb
+++ b/spec/integration/network/formats_spec.rb
@@ -1,91 +1,91 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/formats'
class PsonIntTest
attr_accessor :string
def ==(other)
other.class == self.class and string == other.string
end
def self.from_data_hash(data)
new(data[0])
end
def initialize(string)
@string = string
end
def to_pson(*args)
{
'type' => self.class.name,
'data' => [@string]
}.to_pson(*args)
end
def self.canonical_order(s)
s.gsub(/\{"data":\[(.*?)\],"type":"PsonIntTest"\}/,'{"type":"PsonIntTest","data":[\1]}')
end
end
describe Puppet::Network::FormatHandler.format(:s) do
before do
@format = Puppet::Network::FormatHandler.format(:s)
end
it "should support certificates" do
- @format.should be_supported(Puppet::SSL::Certificate)
+ expect(@format).to be_supported(Puppet::SSL::Certificate)
end
it "should not support catalogs" do
- @format.should_not be_supported(Puppet::Resource::Catalog)
+ expect(@format).not_to be_supported(Puppet::Resource::Catalog)
end
end
describe Puppet::Network::FormatHandler.format(:pson) do
before do
@pson = Puppet::Network::FormatHandler.format(:pson)
end
it "should be able to render an instance to pson" do
instance = PsonIntTest.new("foo")
- PsonIntTest.canonical_order(@pson.render(instance)).should == PsonIntTest.canonical_order('{"type":"PsonIntTest","data":["foo"]}' )
+ expect(PsonIntTest.canonical_order(@pson.render(instance))).to eq(PsonIntTest.canonical_order('{"type":"PsonIntTest","data":["foo"]}' ))
end
it "should be able to render arrays to pson" do
- @pson.render([1,2]).should == '[1,2]'
+ expect(@pson.render([1,2])).to eq('[1,2]')
end
it "should be able to render arrays containing hashes to pson" do
- @pson.render([{"one"=>1},{"two"=>2}]).should == '[{"one":1},{"two":2}]'
+ expect(@pson.render([{"one"=>1},{"two"=>2}])).to eq('[{"one":1},{"two":2}]')
end
it "should be able to render multiple instances to pson" do
one = PsonIntTest.new("one")
two = PsonIntTest.new("two")
- PsonIntTest.canonical_order(@pson.render([one,two])).should == PsonIntTest.canonical_order('[{"type":"PsonIntTest","data":["one"]},{"type":"PsonIntTest","data":["two"]}]')
+ expect(PsonIntTest.canonical_order(@pson.render([one,two]))).to eq(PsonIntTest.canonical_order('[{"type":"PsonIntTest","data":["one"]},{"type":"PsonIntTest","data":["two"]}]'))
end
it "should be able to intern pson into an instance" do
- @pson.intern(PsonIntTest, '{"type":"PsonIntTest","data":["foo"]}').should == PsonIntTest.new("foo")
+ expect(@pson.intern(PsonIntTest, '{"type":"PsonIntTest","data":["foo"]}')).to eq(PsonIntTest.new("foo"))
end
it "should be able to intern pson with no class information into an instance" do
- @pson.intern(PsonIntTest, '["foo"]').should == PsonIntTest.new("foo")
+ expect(@pson.intern(PsonIntTest, '["foo"]')).to eq(PsonIntTest.new("foo"))
end
it "should be able to intern multiple instances from pson" do
- @pson.intern_multiple(PsonIntTest, '[{"type": "PsonIntTest", "data": ["one"]},{"type": "PsonIntTest", "data": ["two"]}]').should == [
+ expect(@pson.intern_multiple(PsonIntTest, '[{"type": "PsonIntTest", "data": ["one"]},{"type": "PsonIntTest", "data": ["two"]}]')).to eq([
PsonIntTest.new("one"), PsonIntTest.new("two")
- ]
+ ])
end
it "should be able to intern multiple instances from pson with no class information" do
- @pson.intern_multiple(PsonIntTest, '[["one"],["two"]]').should == [
+ expect(@pson.intern_multiple(PsonIntTest, '[["one"],["two"]]')).to eq([
PsonIntTest.new("one"), PsonIntTest.new("two")
- ]
+ ])
end
end
diff --git a/spec/integration/node/environment_spec.rb b/spec/integration/node/environment_spec.rb
index 013b86acd..7f748d9f1 100755
--- a/spec/integration/node/environment_spec.rb
+++ b/spec/integration/node/environment_spec.rb
@@ -1,122 +1,122 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_spec/scope'
require 'matchers/resource'
describe Puppet::Node::Environment do
include PuppetSpec::Files
include Matchers::Resource
def a_module_in(name, dir)
Dir.mkdir(dir)
moddir = File.join(dir, name)
Dir.mkdir(moddir)
moddir
end
it "should be able to return each module from its environment with the environment, name, and path set correctly" do
base = tmpfile("env_modules")
Dir.mkdir(base)
dirs = []
mods = {}
%w{1 2}.each do |num|
dir = File.join(base, "dir#{num}")
dirs << dir
mods["mod#{num}"] = a_module_in("mod#{num}", dir)
end
environment = Puppet::Node::Environment.create(:foo, dirs)
environment.modules.each do |mod|
- mod.environment.should == environment
- mod.path.should == mods[mod.name]
+ expect(mod.environment).to eq(environment)
+ expect(mod.path).to eq(mods[mod.name])
end
end
it "should not yield the same module from different module paths" do
base = tmpfile("env_modules")
Dir.mkdir(base)
dirs = []
%w{1 2}.each do |num|
dir = File.join(base, "dir#{num}")
dirs << dir
a_module_in("mod", dir)
end
environment = Puppet::Node::Environment.create(:foo, dirs)
mods = environment.modules
- mods.length.should == 1
- mods[0].path.should == File.join(base, "dir1", "mod")
+ expect(mods.length).to eq(1)
+ expect(mods[0].path).to eq(File.join(base, "dir1", "mod"))
end
shared_examples_for "the environment's initial import" do |settings|
it "a manifest referring to a directory invokes parsing of all its files in sorted order" do
settings.each do |name, value|
Puppet[name] = value
end
# fixture has three files 00_a.pp, 01_b.pp, and 02_c.pp. The 'b' file
# depends on 'a' being evaluated first. The 'c' file is empty (to ensure
# empty things do not break the directory import).
#
dirname = my_fixture('sitedir')
# Set the manifest to the directory to make it parse and combine them when compiling
node = Puppet::Node.new('testnode',
:environment => Puppet::Node::Environment.create(:testing, [], dirname))
catalog = Puppet::Parser::Compiler.compile(node)
expect(catalog).to have_resource('Class[A]')
expect(catalog).to have_resource('Class[B]')
expect(catalog).to have_resource('Notify[variables]').with_parameter(:message, "a: 10, b: 10")
end
end
shared_examples_for "the environment's initial import in 4x" do |settings|
it "a manifest referring to a directory invokes recursive parsing of all its files in sorted order" do
settings.each do |name, value|
Puppet[name] = value
end
# fixture has three files 00_a.pp, 01_b.pp, and 02_c.pp. The 'b' file
# depends on 'a' being evaluated first. The 'c' file is empty (to ensure
# empty things do not break the directory import).
#
dirname = my_fixture('sitedir2')
# Set the manifest to the directory to make it parse and combine them when compiling
node = Puppet::Node.new('testnode',
:environment => Puppet::Node::Environment.create(:testing, [], dirname))
catalog = Puppet::Parser::Compiler.compile(node)
expect(catalog).to have_resource('Class[A]')
expect(catalog).to have_resource('Class[B]')
expect(catalog).to have_resource('Notify[variables]').with_parameter(:message, "a: 10, b: 10 c: 20")
end
end
describe 'using 4x parser' do
it_behaves_like "the environment's initial import",
# fixture uses variables that are set in a particular order (this ensures
# that files are parsed and combined in the right order or an error will
# be raised if 'b' is evaluated before 'a').
:strict_variables => true
end
describe 'using 4x parser' do
it_behaves_like "the environment's initial import in 4x",
# fixture uses variables that are set in a particular order (this ensures
# that files are parsed and combined in the right order or an error will
# be raised if 'b' is evaluated before 'a').
:strict_variables => true
end
end
diff --git a/spec/integration/node/facts_spec.rb b/spec/integration/node/facts_spec.rb
index cf465b797..298597460 100755
--- a/spec/integration/node/facts_spec.rb
+++ b/spec/integration/node/facts_spec.rb
@@ -1,41 +1,41 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Node::Facts do
describe "when using the indirector" do
it "should expire any cached node instances when it is saved" do
Puppet::Node::Facts.indirection.stubs(:terminus_class).returns :yaml
- Puppet::Node::Facts.indirection.terminus(:yaml).should equal(Puppet::Node::Facts.indirection.terminus(:yaml))
+ expect(Puppet::Node::Facts.indirection.terminus(:yaml)).to equal(Puppet::Node::Facts.indirection.terminus(:yaml))
terminus = Puppet::Node::Facts.indirection.terminus(:yaml)
terminus.stubs :save
Puppet::Node.indirection.expects(:expire).with("me", optionally(instance_of(Hash)))
facts = Puppet::Node::Facts.new("me")
Puppet::Node::Facts.indirection.save(facts)
end
it "should be able to delegate to the :yaml terminus" do
Puppet::Node::Facts.indirection.stubs(:terminus_class).returns :yaml
# Load now, before we stub the exists? method.
terminus = Puppet::Node::Facts.indirection.terminus(:yaml)
terminus.expects(:path).with("me").returns "/my/yaml/file"
Puppet::FileSystem.expects(:exist?).with("/my/yaml/file").returns false
- Puppet::Node::Facts.indirection.find("me").should be_nil
+ expect(Puppet::Node::Facts.indirection.find("me")).to be_nil
end
it "should be able to delegate to the :facter terminus" do
Puppet::Node::Facts.indirection.stubs(:terminus_class).returns :facter
Facter.expects(:to_hash).returns "facter_hash"
facts = Puppet::Node::Facts.new("me")
Puppet::Node::Facts.expects(:new).with("me", "facter_hash").returns facts
- Puppet::Node::Facts.indirection.find("me").should equal(facts)
+ expect(Puppet::Node::Facts.indirection.find("me")).to equal(facts)
end
end
end
diff --git a/spec/integration/node_spec.rb b/spec/integration/node_spec.rb
index 8337c2a66..ab3fefd89 100755
--- a/spec/integration/node_spec.rb
+++ b/spec/integration/node_spec.rb
@@ -1,82 +1,82 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/node'
describe Puppet::Node do
describe "when delegating indirection calls" do
before do
Puppet::Node.indirection.reset_terminus_class
Puppet::Node.indirection.cache_class = nil
@name = "me"
@node = Puppet::Node.new(@name)
end
it "should be able to use the yaml terminus" do
Puppet::Node.indirection.stubs(:terminus_class).returns :yaml
# Load now, before we stub the exists? method.
terminus = Puppet::Node.indirection.terminus(:yaml)
terminus.expects(:path).with(@name).returns "/my/yaml/file"
Puppet::FileSystem.expects(:exist?).with("/my/yaml/file").returns false
- Puppet::Node.indirection.find(@name).should be_nil
+ expect(Puppet::Node.indirection.find(@name)).to be_nil
end
it "should have an ldap terminus" do
- Puppet::Node.indirection.terminus(:ldap).should_not be_nil
+ expect(Puppet::Node.indirection.terminus(:ldap)).not_to be_nil
end
it "should be able to use the plain terminus" do
Puppet::Node.indirection.stubs(:terminus_class).returns :plain
# Load now, before we stub the exists? method.
Puppet::Node.indirection.terminus(:plain)
Puppet::Node.expects(:new).with(@name).returns @node
- Puppet::Node.indirection.find(@name).should equal(@node)
+ expect(Puppet::Node.indirection.find(@name)).to equal(@node)
end
describe "and using the memory terminus" do
before do
@name = "me"
@terminus = Puppet::Node.indirection.terminus(:memory)
Puppet::Node.indirection.stubs(:terminus).returns @terminus
@node = Puppet::Node.new(@name)
end
after do
@terminus.instance_variable_set(:@instances, {})
end
it "should find no nodes by default" do
- Puppet::Node.indirection.find(@name).should be_nil
+ expect(Puppet::Node.indirection.find(@name)).to be_nil
end
it "should be able to find nodes that were previously saved" do
Puppet::Node.indirection.save(@node)
- Puppet::Node.indirection.find(@name).should equal(@node)
+ expect(Puppet::Node.indirection.find(@name)).to equal(@node)
end
it "should replace existing saved nodes when a new node with the same name is saved" do
Puppet::Node.indirection.save(@node)
two = Puppet::Node.new(@name)
Puppet::Node.indirection.save(two)
- Puppet::Node.indirection.find(@name).should equal(two)
+ expect(Puppet::Node.indirection.find(@name)).to equal(two)
end
it "should be able to remove previously saved nodes" do
Puppet::Node.indirection.save(@node)
Puppet::Node.indirection.destroy(@node.name)
- Puppet::Node.indirection.find(@name).should be_nil
+ expect(Puppet::Node.indirection.find(@name)).to be_nil
end
it "should fail when asked to destroy a node that does not exist" do
- proc { Puppet::Node.indirection.destroy(@node) }.should raise_error(ArgumentError)
+ expect { Puppet::Node.indirection.destroy(@node) }.to raise_error(ArgumentError)
end
end
end
end
diff --git a/spec/integration/parser/collection_spec.rb b/spec/integration/parser/collection_spec.rb
index d889ff62f..1d5195914 100755
--- a/spec/integration/parser/collection_spec.rb
+++ b/spec/integration/parser/collection_spec.rb
@@ -1,300 +1,300 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/compiler'
describe 'collectors' do
include PuppetSpec::Compiler
def expect_the_message_to_be(expected_messages, code, node = Puppet::Node.new('the node'))
catalog = compile_to_catalog(code, node)
messages = catalog.resources.find_all { |resource| resource.type == 'Notify' }.
collect { |notify| notify[:message] }
- messages.should include(*expected_messages)
+ expect(messages).to include(*expected_messages)
end
context "virtual resource collection" do
it "matches everything when no query given" do
expect_the_message_to_be(["the other message", "the message"], <<-MANIFEST)
@notify { "testing": message => "the message" }
@notify { "other": message => "the other message" }
Notify <| |>
MANIFEST
end
it "matches regular resources " do
expect_the_message_to_be(["changed", "changed"], <<-MANIFEST)
notify { "testing": message => "the message" }
notify { "other": message => "the other message" }
Notify <| |> { message => "changed" }
MANIFEST
end
it "matches on tags" do
expect_the_message_to_be(["wanted"], <<-MANIFEST)
@notify { "testing": tag => ["one"], message => "wanted" }
@notify { "other": tag => ["two"], message => "unwanted" }
Notify <| tag == one |>
MANIFEST
end
it "matches on title" do
expect_the_message_to_be(["the message"], <<-MANIFEST)
@notify { "testing": message => "the message" }
Notify <| title == "testing" |>
MANIFEST
end
it "matches on other parameters" do
expect_the_message_to_be(["the message"], <<-MANIFEST)
@notify { "testing": message => "the message" }
@notify { "other testing": message => "the wrong message" }
Notify <| message == "the message" |>
MANIFEST
end
it "matches against elements of an array valued parameter" do
expect_the_message_to_be([["the", "message"]], <<-MANIFEST)
@notify { "testing": message => ["the", "message"] }
@notify { "other testing": message => ["not", "here"] }
Notify <| message == "message" |>
MANIFEST
end
it "matches with bare word" do
expect_the_message_to_be(["wanted"], <<-MANIFEST)
@notify { "testing": tag => ["one"], message => "wanted" }
Notify <| tag == one |>
MANIFEST
end
it "matches with single quoted string" do
expect_the_message_to_be(["wanted"], <<-MANIFEST)
@notify { "testing": tag => ["one"], message => "wanted" }
Notify <| tag == 'one' |>
MANIFEST
end
it "matches with double quoted string" do
expect_the_message_to_be(["wanted"], <<-MANIFEST)
@notify { "testing": tag => ["one"], message => "wanted" }
Notify <| tag == "one" |>
MANIFEST
end
it "matches with double quoted string with interpolated expression" do
expect_the_message_to_be(["wanted"], <<-MANIFEST)
@notify { "testing": tag => ["one"], message => "wanted" }
$x = 'one'
Notify <| tag == "$x" |>
MANIFEST
end
it "allows criteria to be combined with 'and'" do
expect_the_message_to_be(["the message"], <<-MANIFEST)
@notify { "testing": message => "the message" }
@notify { "other": message => "the message" }
Notify <| title == "testing" and message == "the message" |>
MANIFEST
end
it "allows criteria to be combined with 'or'" do
expect_the_message_to_be(["the message", "other message"], <<-MANIFEST)
@notify { "testing": message => "the message" }
@notify { "other": message => "other message" }
@notify { "yet another": message => "different message" }
Notify <| title == "testing" or message == "other message" |>
MANIFEST
end
it "allows criteria to be combined with 'or'" do
expect_the_message_to_be(["the message", "other message"], <<-MANIFEST)
@notify { "testing": message => "the message" }
@notify { "other": message => "other message" }
@notify { "yet another": message => "different message" }
Notify <| title == "testing" or message == "other message" |>
MANIFEST
end
it "allows criteria to be grouped with parens" do
expect_the_message_to_be(["the message", "different message"], <<-MANIFEST)
@notify { "testing": message => "different message", withpath => true }
@notify { "other": message => "the message" }
@notify { "yet another": message => "the message", withpath => true }
Notify <| (title == "testing" or message == "the message") and withpath == true |>
MANIFEST
end
it "does not do anything if nothing matches" do
expect_the_message_to_be([], <<-MANIFEST)
@notify { "testing": message => "different message" }
Notify <| title == "does not exist" |>
MANIFEST
end
it "excludes items with inequalities" do
expect_the_message_to_be(["good message"], <<-MANIFEST)
@notify { "testing": message => "good message" }
@notify { "the wrong one": message => "bad message" }
Notify <| title != "the wrong one" |>
MANIFEST
end
it "does not exclude resources with unequal arrays" do
expect_the_message_to_be(["message", ["not this message", "or this one"]], <<-MANIFEST)
@notify { "testing": message => "message" }
@notify { "the wrong one": message => ["not this message", "or this one"] }
Notify <| message != "not this message" |>
MANIFEST
end
it "does not exclude tags with inequalities" do
expect_the_message_to_be(["wanted message", "the way it works"], <<-MANIFEST)
@notify { "testing": tag => ["wanted"], message => "wanted message" }
@notify { "other": tag => ["why"], message => "the way it works" }
Notify <| tag != "why" |>
MANIFEST
end
it "does not collect classes" do
node = Puppet::Node.new('the node')
expect do
catalog = compile_to_catalog(<<-MANIFEST, node)
class theclass {
@notify { "testing": message => "good message" }
}
Class <| |>
MANIFEST
end.to raise_error(/Classes cannot be collected/)
end
it "does not collect resources that don't exist" do
node = Puppet::Node.new('the node')
expect do
catalog = compile_to_catalog(<<-MANIFEST, node)
class theclass {
@notify { "testing": message => "good message" }
}
SomeResource <| |>
MANIFEST
end.to raise_error(/Resource type someresource doesn't exist/)
end
context "overrides" do
it "modifies an existing array" do
expect_the_message_to_be([["original message", "extra message"]], <<-MANIFEST)
@notify { "testing": message => ["original message"] }
Notify <| |> {
message +> "extra message"
}
MANIFEST
end
it "converts a scalar to an array" do
expect_the_message_to_be([["original message", "extra message"]], <<-MANIFEST)
@notify { "testing": message => "original message" }
Notify <| |> {
message +> "extra message"
}
MANIFEST
end
it "collects with override when inside a class (#10963)" do
expect_the_message_to_be(["overridden message"], <<-MANIFEST)
@notify { "testing": message => "original message" }
include collector_test
class collector_test {
Notify <| |> {
message => "overridden message"
}
}
MANIFEST
end
it "collects with override when inside a define (#10963)" do
expect_the_message_to_be(["overridden message"], <<-MANIFEST)
@notify { "testing": message => "original message" }
collector_test { testing: }
define collector_test() {
Notify <| |> {
message => "overridden message"
}
}
MANIFEST
end
# Catches regression in implemented behavior, this is not to be taken as this is the wanted behavior
# but it has been this way for a long time.
it "collects and overrides user defined resources immediately (before queue is evaluated)" do
expect_the_message_to_be(["overridden"], <<-MANIFEST)
define foo($message) {
notify { "testing": message => $message }
}
foo { test: message => 'given' }
Foo <| |> { message => 'overridden' }
MANIFEST
end
# Catches regression in implemented behavior, this is not to be taken as this is the wanted behavior
# but it has been this way for a long time.
it "collects and overrides user defined resources immediately (virtual resources not queued)" do
expect_the_message_to_be(["overridden"], <<-MANIFEST)
define foo($message) {
@notify { "testing": message => $message }
}
foo { test: message => 'given' }
Notify <| |> # must be collected or the assertion does not find it
Foo <| |> { message => 'overridden' }
MANIFEST
end
# Catches regression in implemented behavior, this is not to be taken as this is the wanted behavior
# but it has been this way for a long time.
# Note difference from none +> case where the override takes effect
it "collects and overrides user defined resources with +>" do
expect_the_message_to_be([["given", "overridden"]], <<-MANIFEST)
define foo($message) {
notify { "$name": message => $message }
}
foo { test: message => ['given'] }
Notify <| |> { message +> ['overridden'] }
MANIFEST
end
it "collects and overrides virtual resources multiple times using multiple collects" do
expect_the_message_to_be(["overridden2"], <<-MANIFEST)
@notify { "testing": message => "original" }
Notify <| |> { message => 'overridden1' }
Notify <| |> { message => 'overridden2' }
MANIFEST
end
it "collects and overrides non virtual resources multiple times using multiple collects" do
expect_the_message_to_be(["overridden2"], <<-MANIFEST)
notify { "testing": message => "original" }
Notify <| |> { message => 'overridden1' }
Notify <| |> { message => 'overridden2' }
MANIFEST
end
end
end
end
diff --git a/spec/integration/parser/compiler_spec.rb b/spec/integration/parser/compiler_spec.rb
index 176ecb0a2..55fbe59a1 100755
--- a/spec/integration/parser/compiler_spec.rb
+++ b/spec/integration/parser/compiler_spec.rb
@@ -1,927 +1,927 @@
require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
class CompilerTestResource
attr_accessor :builtin, :virtual, :evaluated, :type, :title
def initialize(type, title)
@type = type
@title = title
end
def [](attr)
return nil if attr == :stage
:main
end
def ref
"#{type.to_s.capitalize}[#{title}]"
end
def evaluated?
@evaluated
end
def builtin_type?
@builtin
end
def virtual?
@virtual
end
def class?
false
end
def stage?
false
end
def evaluate
end
def file
"/fake/file/goes/here"
end
def line
"42"
end
end
describe Puppet::Parser::Compiler do
include PuppetSpec::Files
include Matchers::Resource
def resource(type, title)
Puppet::Parser::Resource.new(type, title, :scope => @scope)
end
let(:environment) { Puppet::Node::Environment.create(:testing, []) }
before :each do
# Push me faster, I wanna go back in time! (Specifically, freeze time
# across the test since we have a bunch of version == timestamp code
# hidden away in the implementation and we keep losing the race.)
# --daniel 2011-04-21
now = Time.now
Time.stubs(:now).returns(now)
@node = Puppet::Node.new("testnode",
:facts => Puppet::Node::Facts.new("facts", {}),
:environment => environment)
@known_resource_types = environment.known_resource_types
@compiler = Puppet::Parser::Compiler.new(@node)
@scope = Puppet::Parser::Scope.new(@compiler, :source => stub('source'))
@scope_resource = Puppet::Parser::Resource.new(:file, "/my/file", :scope => @scope)
@scope.resource = @scope_resource
end
it "should fail intelligently when a class-level compile fails" do
Puppet::Parser::Compiler.expects(:new).raises ArgumentError
- lambda { Puppet::Parser::Compiler.compile(@node) }.should raise_error(Puppet::Error)
+ expect { Puppet::Parser::Compiler.compile(@node) }.to raise_error(Puppet::Error)
end
it "should use the node's environment as its environment" do
- @compiler.environment.should equal(@node.environment)
+ expect(@compiler.environment).to equal(@node.environment)
end
it "fails if the node's environment has validation errors" do
conflicted_environment = Puppet::Node::Environment.create(:testing, [], '/some/environment.conf/manifest.pp')
conflicted_environment.stubs(:validation_errors).returns(['bad environment'])
@node.environment = conflicted_environment
expect { Puppet::Parser::Compiler.compile(@node) }.to raise_error(Puppet::Error, /Compilation has been halted because.*bad environment/)
end
it "should include the resource type collection helper" do
- Puppet::Parser::Compiler.ancestors.should be_include(Puppet::Resource::TypeCollectionHelper)
+ expect(Puppet::Parser::Compiler.ancestors).to be_include(Puppet::Resource::TypeCollectionHelper)
end
it "should be able to return a class list containing all added classes" do
@compiler.add_class ""
@compiler.add_class "one"
@compiler.add_class "two"
- @compiler.classlist.sort.should == %w{one two}.sort
+ expect(@compiler.classlist.sort).to eq(%w{one two}.sort)
end
describe "when initializing" do
it "should set its node attribute" do
- @compiler.node.should equal(@node)
+ expect(@compiler.node).to equal(@node)
end
it "should detect when ast nodes are absent" do
- @compiler.ast_nodes?.should be_false
+ expect(@compiler.ast_nodes?).to be_falsey
end
it "should detect when ast nodes are present" do
@known_resource_types.expects(:nodes?).returns true
- @compiler.ast_nodes?.should be_true
+ expect(@compiler.ast_nodes?).to be_truthy
end
it "should copy the known_resource_types version to the catalog" do
- @compiler.catalog.version.should == @known_resource_types.version
+ expect(@compiler.catalog.version).to eq(@known_resource_types.version)
end
it "should copy any node classes into the class list" do
node = Puppet::Node.new("mynode")
node.classes = %w{foo bar}
compiler = Puppet::Parser::Compiler.new(node)
- compiler.classlist.should =~ ['foo', 'bar']
+ expect(compiler.classlist).to match_array(['foo', 'bar'])
end
it "should transform node class hashes into a class list" do
node = Puppet::Node.new("mynode")
node.classes = {'foo'=>{'one'=>'p1'}, 'bar'=>{'two'=>'p2'}}
compiler = Puppet::Parser::Compiler.new(node)
- compiler.classlist.should =~ ['foo', 'bar']
+ expect(compiler.classlist).to match_array(['foo', 'bar'])
end
it "should add a 'main' stage to the catalog" do
- @compiler.catalog.resource(:stage, :main).should be_instance_of(Puppet::Parser::Resource)
+ expect(@compiler.catalog.resource(:stage, :main)).to be_instance_of(Puppet::Parser::Resource)
end
end
describe "when managing scopes" do
it "should create a top scope" do
- @compiler.topscope.should be_instance_of(Puppet::Parser::Scope)
+ expect(@compiler.topscope).to be_instance_of(Puppet::Parser::Scope)
end
it "should be able to create new scopes" do
- @compiler.newscope(@compiler.topscope).should be_instance_of(Puppet::Parser::Scope)
+ expect(@compiler.newscope(@compiler.topscope)).to be_instance_of(Puppet::Parser::Scope)
end
it "should set the parent scope of the new scope to be the passed-in parent" do
scope = mock 'scope'
newscope = @compiler.newscope(scope)
- newscope.parent.should equal(scope)
+ expect(newscope.parent).to equal(scope)
end
it "should set the parent scope of the new scope to its topscope if the parent passed in is nil" do
scope = mock 'scope'
newscope = @compiler.newscope(nil)
- newscope.parent.should equal(@compiler.topscope)
+ expect(newscope.parent).to equal(@compiler.topscope)
end
end
describe "when compiling" do
def compile_methods
[:set_node_parameters, :evaluate_main, :evaluate_ast_node, :evaluate_node_classes, :evaluate_generators, :fail_on_unevaluated,
:finish, :store, :extract, :evaluate_relationships]
end
# Stub all of the main compile methods except the ones we're specifically interested in.
def compile_stub(*except)
(compile_methods - except).each { |m| @compiler.stubs(m) }
end
it "should set node parameters as variables in the top scope" do
params = {"a" => "b", "c" => "d"}
@node.stubs(:parameters).returns(params)
compile_stub(:set_node_parameters)
@compiler.compile
- @compiler.topscope['a'].should == "b"
- @compiler.topscope['c'].should == "d"
+ expect(@compiler.topscope['a']).to eq("b")
+ expect(@compiler.topscope['c']).to eq("d")
end
it "should set the client and server versions on the catalog" do
params = {"clientversion" => "2", "serverversion" => "3"}
@node.stubs(:parameters).returns(params)
compile_stub(:set_node_parameters)
@compiler.compile
- @compiler.catalog.client_version.should == "2"
- @compiler.catalog.server_version.should == "3"
+ expect(@compiler.catalog.client_version).to eq("2")
+ expect(@compiler.catalog.server_version).to eq("3")
end
it "should evaluate the main class if it exists" do
compile_stub(:evaluate_main)
main_class = @known_resource_types.add Puppet::Resource::Type.new(:hostclass, "")
main_class.expects(:evaluate_code).with { |r| r.is_a?(Puppet::Parser::Resource) }
@compiler.topscope.expects(:source=).with(main_class)
@compiler.compile
end
it "should create a new, empty 'main' if no main class exists" do
compile_stub(:evaluate_main)
@compiler.compile
- @known_resource_types.find_hostclass("").should be_instance_of(Puppet::Resource::Type)
+ expect(@known_resource_types.find_hostclass("")).to be_instance_of(Puppet::Resource::Type)
end
it "should add an edge between the main stage and main class" do
@compiler.compile
- (stage = @compiler.catalog.resource(:stage, "main")).should be_instance_of(Puppet::Parser::Resource)
- (klass = @compiler.catalog.resource(:class, "")).should be_instance_of(Puppet::Parser::Resource)
+ expect(stage = @compiler.catalog.resource(:stage, "main")).to be_instance_of(Puppet::Parser::Resource)
+ expect(klass = @compiler.catalog.resource(:class, "")).to be_instance_of(Puppet::Parser::Resource)
- @compiler.catalog.edge?(stage, klass).should be_true
+ expect(@compiler.catalog.edge?(stage, klass)).to be_truthy
end
it "should evaluate all added collections" do
colls = []
# And when the collections fail to evaluate.
colls << mock("coll1-false")
colls << mock("coll2-false")
colls.each { |c| c.expects(:evaluate).returns(false) }
@compiler.add_collection(colls[0])
@compiler.add_collection(colls[1])
compile_stub(:evaluate_generators)
@compiler.compile
end
it "should ignore builtin resources" do
resource = resource(:file, "testing")
@compiler.add_resource(@scope, resource)
resource.expects(:evaluate).never
@compiler.compile
end
it "should evaluate unevaluated resources" do
resource = CompilerTestResource.new(:file, "testing")
@compiler.add_resource(@scope, resource)
# We have to now mark the resource as evaluated
resource.expects(:evaluate).with { |*whatever| resource.evaluated = true }
@compiler.compile
end
it "should not evaluate already-evaluated resources" do
resource = resource(:file, "testing")
resource.stubs(:evaluated?).returns true
@compiler.add_resource(@scope, resource)
resource.expects(:evaluate).never
@compiler.compile
end
it "should evaluate unevaluated resources created by evaluating other resources" do
resource = CompilerTestResource.new(:file, "testing")
@compiler.add_resource(@scope, resource)
resource2 = CompilerTestResource.new(:file, "other")
# We have to now mark the resource as evaluated
resource.expects(:evaluate).with { |*whatever| resource.evaluated = true; @compiler.add_resource(@scope, resource2) }
resource2.expects(:evaluate).with { |*whatever| resource2.evaluated = true }
@compiler.compile
end
describe "when finishing" do
before do
@compiler.send(:evaluate_main)
@catalog = @compiler.catalog
end
def add_resource(name, parent = nil)
resource = Puppet::Parser::Resource.new "file", name, :scope => @scope
@compiler.add_resource(@scope, resource)
@catalog.add_edge(parent, resource) if parent
resource
end
it "should call finish() on all resources" do
# Add a resource that does respond to :finish
resource = Puppet::Parser::Resource.new "file", "finish", :scope => @scope
resource.expects(:finish)
@compiler.add_resource(@scope, resource)
# And one that does not
dnf_resource = stub_everything "dnf", :ref => "File[dnf]", :type => "file"
@compiler.add_resource(@scope, dnf_resource)
@compiler.send(:finish)
end
it "should call finish() in add_resource order" do
resources = sequence('resources')
resource1 = add_resource("finish1")
resource1.expects(:finish).in_sequence(resources)
resource2 = add_resource("finish2")
resource2.expects(:finish).in_sequence(resources)
@compiler.send(:finish)
end
it "should add each container's metaparams to its contained resources" do
main = @catalog.resource(:class, :main)
main[:noop] = true
resource1 = add_resource("meh", main)
@compiler.send(:finish)
- resource1[:noop].should be_true
+ expect(resource1[:noop]).to be_truthy
end
it "should add metaparams recursively" do
main = @catalog.resource(:class, :main)
main[:noop] = true
resource1 = add_resource("meh", main)
resource2 = add_resource("foo", resource1)
@compiler.send(:finish)
- resource2[:noop].should be_true
+ expect(resource2[:noop]).to be_truthy
end
it "should prefer metaparams from immediate parents" do
main = @catalog.resource(:class, :main)
main[:noop] = true
resource1 = add_resource("meh", main)
resource2 = add_resource("foo", resource1)
resource1[:noop] = false
@compiler.send(:finish)
- resource2[:noop].should be_false
+ expect(resource2[:noop]).to be_falsey
end
it "should merge tags downward" do
main = @catalog.resource(:class, :main)
main.tag("one")
resource1 = add_resource("meh", main)
resource1.tag "two"
resource2 = add_resource("foo", resource1)
@compiler.send(:finish)
- resource2.tags.should be_include("one")
- resource2.tags.should be_include("two")
+ expect(resource2.tags).to be_include("one")
+ expect(resource2.tags).to be_include("two")
end
it "should work if only middle resources have metaparams set" do
main = @catalog.resource(:class, :main)
resource1 = add_resource("meh", main)
resource1[:noop] = true
resource2 = add_resource("foo", resource1)
@compiler.send(:finish)
- resource2[:noop].should be_true
+ expect(resource2[:noop]).to be_truthy
end
end
it "should return added resources in add order" do
resource1 = resource(:file, "yay")
@compiler.add_resource(@scope, resource1)
resource2 = resource(:file, "youpi")
@compiler.add_resource(@scope, resource2)
- @compiler.resources.should == [resource1, resource2]
+ expect(@compiler.resources).to eq([resource1, resource2])
end
it "should add resources that do not conflict with existing resources" do
resource = resource(:file, "yay")
@compiler.add_resource(@scope, resource)
- @compiler.catalog.should be_vertex(resource)
+ expect(@compiler.catalog).to be_vertex(resource)
end
it "should fail to add resources that conflict with existing resources" do
path = make_absolute("/foo")
file1 = resource(:file, path)
file2 = resource(:file, path)
@compiler.add_resource(@scope, file1)
- lambda { @compiler.add_resource(@scope, file2) }.should raise_error(Puppet::Resource::Catalog::DuplicateResourceError)
+ expect { @compiler.add_resource(@scope, file2) }.to raise_error(Puppet::Resource::Catalog::DuplicateResourceError)
end
it "should add an edge from the scope resource to the added resource" do
resource = resource(:file, "yay")
@compiler.add_resource(@scope, resource)
- @compiler.catalog.should be_edge(@scope.resource, resource)
+ expect(@compiler.catalog).to be_edge(@scope.resource, resource)
end
it "should not add non-class resources that don't specify a stage to the 'main' stage" do
main = @compiler.catalog.resource(:stage, :main)
resource = resource(:file, "foo")
@compiler.add_resource(@scope, resource)
- @compiler.catalog.should_not be_edge(main, resource)
+ expect(@compiler.catalog).not_to be_edge(main, resource)
end
it "should not add any parent-edges to stages" do
stage = resource(:stage, "other")
@compiler.add_resource(@scope, stage)
@scope.resource = resource(:class, "foo")
- @compiler.catalog.edge?(@scope.resource, stage).should be_false
+ expect(@compiler.catalog.edge?(@scope.resource, stage)).to be_falsey
end
it "should not attempt to add stages to other stages" do
other_stage = resource(:stage, "other")
second_stage = resource(:stage, "second")
@compiler.add_resource(@scope, other_stage)
@compiler.add_resource(@scope, second_stage)
second_stage[:stage] = "other"
- @compiler.catalog.edge?(other_stage, second_stage).should be_false
+ expect(@compiler.catalog.edge?(other_stage, second_stage)).to be_falsey
end
it "should have a method for looking up resources" do
resource = resource(:yay, "foo")
@compiler.add_resource(@scope, resource)
- @compiler.findresource("Yay[foo]").should equal(resource)
+ expect(@compiler.findresource("Yay[foo]")).to equal(resource)
end
it "should be able to look resources up by type and title" do
resource = resource(:yay, "foo")
@compiler.add_resource(@scope, resource)
- @compiler.findresource("Yay", "foo").should equal(resource)
+ expect(@compiler.findresource("Yay", "foo")).to equal(resource)
end
it "should not evaluate virtual defined resources" do
resource = resource(:file, "testing")
resource.virtual = true
@compiler.add_resource(@scope, resource)
resource.expects(:evaluate).never
@compiler.compile
end
end
describe "when evaluating collections" do
it "should evaluate each collection" do
2.times { |i|
coll = mock 'coll%s' % i
@compiler.add_collection(coll)
# This is the hard part -- we have to emulate the fact that
# collections delete themselves if they are done evaluating.
coll.expects(:evaluate).with do
@compiler.delete_collection(coll)
end
}
@compiler.compile
end
it "should not fail when there are unevaluated resource collections that do not refer to specific resources" do
coll = stub 'coll', :evaluate => false
coll.expects(:unresolved_resources).returns(nil)
@compiler.add_collection(coll)
- lambda { @compiler.compile }.should_not raise_error
+ expect { @compiler.compile }.not_to raise_error
end
it "should fail when there are unevaluated resource collections that refer to a specific resource" do
coll = stub 'coll', :evaluate => false
coll.expects(:unresolved_resources).returns(:something)
@compiler.add_collection(coll)
- lambda { @compiler.compile }.should raise_error(Puppet::ParseError, 'Failed to realize virtual resources something')
+ expect { @compiler.compile }.to raise_error(Puppet::ParseError, 'Failed to realize virtual resources something')
end
it "should fail when there are unevaluated resource collections that refer to multiple specific resources" do
coll = stub 'coll', :evaluate => false
coll.expects(:unresolved_resources).returns([:one, :two])
@compiler.add_collection(coll)
- lambda { @compiler.compile }.should raise_error(Puppet::ParseError, 'Failed to realize virtual resources one, two')
+ expect { @compiler.compile }.to raise_error(Puppet::ParseError, 'Failed to realize virtual resources one, two')
end
end
describe "when evaluating relationships" do
it "should evaluate each relationship with its catalog" do
dep = stub 'dep'
dep.expects(:evaluate).with(@compiler.catalog)
@compiler.add_relationship dep
@compiler.evaluate_relationships
end
end
describe "when told to evaluate missing classes" do
it "should fail if there's no source listed for the scope" do
scope = stub 'scope', :source => nil
- proc { @compiler.evaluate_classes(%w{one two}, scope) }.should raise_error(Puppet::DevError)
+ expect { @compiler.evaluate_classes(%w{one two}, scope) }.to raise_error(Puppet::DevError)
end
it "should raise an error if a class is not found" do
@scope.expects(:find_hostclass).with("notfound").returns(nil)
- lambda{ @compiler.evaluate_classes(%w{notfound}, @scope) }.should raise_error(Puppet::Error, /Could not find class/)
+ expect{ @compiler.evaluate_classes(%w{notfound}, @scope) }.to raise_error(Puppet::Error, /Could not find class/)
end
it "should raise an error when it can't find class" do
klasses = {'foo'=>nil}
@node.classes = klasses
@compiler.topscope.expects(:find_hostclass).with('foo').returns(nil)
- lambda{ @compiler.compile }.should raise_error(Puppet::Error, /Could not find class foo for testnode/)
+ expect{ @compiler.compile }.to raise_error(Puppet::Error, /Could not find class foo for testnode/)
end
end
describe "when evaluating found classes" do
before do
Puppet.settings[:data_binding_terminus] = "none"
@class = stub 'class', :name => "my::class"
@scope.stubs(:find_hostclass).with("myclass").returns(@class)
@resource = stub 'resource', :ref => "Class[myclass]", :type => "file"
end
around do |example|
Puppet.override(
:environments => Puppet::Environments::Static.new(environment),
:description => "Static loader for specs"
) do
example.run
end
end
it "should evaluate each class" do
@compiler.catalog.stubs(:tag)
@class.expects(:ensure_in_catalog).with(@scope)
@scope.stubs(:class_scope).with(@class)
@compiler.evaluate_classes(%w{myclass}, @scope)
end
describe "and the classes are specified as a hash with parameters" do
before do
@node.classes = {}
@ast_obj = Puppet::Parser::AST::Leaf.new(:value => 'foo')
end
# Define the given class with default parameters
def define_class(name, parameters)
@node.classes[name] = parameters
klass = Puppet::Resource::Type.new(:hostclass, name, :arguments => {'p1' => @ast_obj, 'p2' => @ast_obj})
@compiler.topscope.known_resource_types.add klass
end
def compile
@catalog = @compiler.compile
end
it "should record which classes are evaluated" do
classes = {'foo'=>{}, 'bar::foo'=>{}, 'bar'=>{}}
classes.each { |c, params| define_class(c, params) }
compile()
- classes.each { |name, p| @catalog.classes.should include(name) }
+ classes.each { |name, p| expect(@catalog.classes).to include(name) }
end
it "should provide default values for parameters that have no values specified" do
define_class('foo', {})
compile()
- @catalog.resource(:class, 'foo')['p1'].should == "foo"
+ expect(@catalog.resource(:class, 'foo')['p1']).to eq("foo")
end
it "should use any provided values" do
define_class('foo', {'p1' => 'real_value'})
compile()
- @catalog.resource(:class, 'foo')['p1'].should == "real_value"
+ expect(@catalog.resource(:class, 'foo')['p1']).to eq("real_value")
end
it "should support providing some but not all values" do
define_class('foo', {'p1' => 'real_value'})
compile()
- @catalog.resource(:class, 'Foo')['p1'].should == "real_value"
- @catalog.resource(:class, 'Foo')['p2'].should == "foo"
+ expect(@catalog.resource(:class, 'Foo')['p1']).to eq("real_value")
+ expect(@catalog.resource(:class, 'Foo')['p2']).to eq("foo")
end
it "should ensure each node class is in catalog and has appropriate tags" do
klasses = ['bar::foo']
@node.classes = klasses
ast_obj = Puppet::Parser::AST::Leaf.new(:value => 'foo')
klasses.each do |name|
klass = Puppet::Resource::Type.new(:hostclass, name, :arguments => {'p1' => ast_obj, 'p2' => ast_obj})
@compiler.topscope.known_resource_types.add klass
end
catalog = @compiler.compile
r2 = catalog.resources.detect {|r| r.title == 'Bar::Foo' }
- r2.tags.should == Puppet::Util::TagSet.new(['bar::foo', 'class', 'bar', 'foo'])
+ expect(r2.tags).to eq(Puppet::Util::TagSet.new(['bar::foo', 'class', 'bar', 'foo']))
end
end
it "should fail if required parameters are missing" do
klass = {'foo'=>{'a'=>'one'}}
@node.classes = klass
klass = Puppet::Resource::Type.new(:hostclass, 'foo', :arguments => {'a' => nil, 'b' => nil})
@compiler.topscope.known_resource_types.add klass
- lambda { @compiler.compile }.should raise_error(Puppet::ParseError, "Must pass b to Class[Foo]")
+ expect { @compiler.compile }.to raise_error(Puppet::ParseError, "Must pass b to Class[Foo]")
end
it "should fail if invalid parameters are passed" do
klass = {'foo'=>{'3'=>'one'}}
@node.classes = klass
klass = Puppet::Resource::Type.new(:hostclass, 'foo', :arguments => {})
@compiler.topscope.known_resource_types.add klass
- lambda { @compiler.compile }.should raise_error(Puppet::ParseError, "Invalid parameter: '3' on Class[Foo]")
+ expect { @compiler.compile }.to raise_error(Puppet::ParseError, "Invalid parameter: '3' on Class[Foo]")
end
it "should ensure class is in catalog without params" do
@node.classes = klasses = {'foo'=>nil}
foo = Puppet::Resource::Type.new(:hostclass, 'foo')
@compiler.topscope.known_resource_types.add foo
catalog = @compiler.compile
- catalog.classes.should include 'foo'
+ expect(catalog.classes).to include 'foo'
end
it "should not evaluate the resources created for found classes unless asked" do
@compiler.catalog.stubs(:tag)
@resource.expects(:evaluate).never
@class.expects(:ensure_in_catalog).returns(@resource)
@scope.stubs(:class_scope).with(@class)
@compiler.evaluate_classes(%w{myclass}, @scope)
end
it "should immediately evaluate the resources created for found classes when asked" do
@compiler.catalog.stubs(:tag)
@resource.expects(:evaluate)
@class.expects(:ensure_in_catalog).returns(@resource)
@scope.stubs(:class_scope).with(@class)
@compiler.evaluate_classes(%w{myclass}, @scope, false)
end
it "should skip classes that have already been evaluated" do
@compiler.catalog.stubs(:tag)
@scope.stubs(:class_scope).with(@class).returns(@scope)
@compiler.expects(:add_resource).never
@resource.expects(:evaluate).never
Puppet::Parser::Resource.expects(:new).never
@compiler.evaluate_classes(%w{myclass}, @scope, false)
end
it "should skip classes previously evaluated with different capitalization" do
@compiler.catalog.stubs(:tag)
@scope.stubs(:find_hostclass).with("MyClass").returns(@class)
@scope.stubs(:class_scope).with(@class).returns(@scope)
@compiler.expects(:add_resource).never
@resource.expects(:evaluate).never
Puppet::Parser::Resource.expects(:new).never
@compiler.evaluate_classes(%w{MyClass}, @scope, false)
end
end
describe "when evaluating AST nodes with no AST nodes present" do
it "should do nothing" do
@compiler.expects(:ast_nodes?).returns(false)
@compiler.known_resource_types.expects(:nodes).never
Puppet::Parser::Resource.expects(:new).never
@compiler.send(:evaluate_ast_node)
end
end
describe "when evaluating AST nodes with AST nodes present" do
before do
@compiler.known_resource_types.stubs(:nodes?).returns true
# Set some names for our test
@node.stubs(:names).returns(%w{a b c})
@compiler.known_resource_types.stubs(:node).with("a").returns(nil)
@compiler.known_resource_types.stubs(:node).with("b").returns(nil)
@compiler.known_resource_types.stubs(:node).with("c").returns(nil)
# It should check this last, of course.
@compiler.known_resource_types.stubs(:node).with("default").returns(nil)
end
it "should fail if the named node cannot be found" do
- proc { @compiler.send(:evaluate_ast_node) }.should raise_error(Puppet::ParseError)
+ expect { @compiler.send(:evaluate_ast_node) }.to raise_error(Puppet::ParseError)
end
it "should evaluate the first node class matching the node name" do
node_class = stub 'node', :name => "c", :evaluate_code => nil
@compiler.known_resource_types.stubs(:node).with("c").returns(node_class)
node_resource = stub 'node resource', :ref => "Node[c]", :evaluate => nil, :type => "node"
node_class.expects(:ensure_in_catalog).returns(node_resource)
@compiler.compile
end
it "should match the default node if no matching node can be found" do
node_class = stub 'node', :name => "default", :evaluate_code => nil
@compiler.known_resource_types.stubs(:node).with("default").returns(node_class)
node_resource = stub 'node resource', :ref => "Node[default]", :evaluate => nil, :type => "node"
node_class.expects(:ensure_in_catalog).returns(node_resource)
@compiler.compile
end
it "should evaluate the node resource immediately rather than using lazy evaluation" do
node_class = stub 'node', :name => "c"
@compiler.known_resource_types.stubs(:node).with("c").returns(node_class)
node_resource = stub 'node resource', :ref => "Node[c]", :type => "node"
node_class.expects(:ensure_in_catalog).returns(node_resource)
node_resource.expects(:evaluate)
@compiler.send(:evaluate_ast_node)
end
end
describe "when evaluating node classes" do
include PuppetSpec::Compiler
describe "when provided classes in array format" do
let(:node) { Puppet::Node.new('someone', :classes => ['something']) }
describe "when the class exists" do
it "should succeed if the class is already included" do
manifest = <<-MANIFEST
class something {}
include something
MANIFEST
catalog = compile_to_catalog(manifest, node)
- catalog.resource('Class', 'Something').should_not be_nil
+ expect(catalog.resource('Class', 'Something')).not_to be_nil
end
it "should evaluate the class without parameters if it's not already included" do
manifest = "class something {}"
catalog = compile_to_catalog(manifest, node)
- catalog.resource('Class', 'Something').should_not be_nil
+ expect(catalog.resource('Class', 'Something')).not_to be_nil
end
end
it "should fail if the class doesn't exist" do
expect { compile_to_catalog('', node) }.to raise_error(Puppet::Error, /Could not find class something/)
end
end
describe "when provided classes in hash format" do
describe "for classes without parameters" do
let(:node) { Puppet::Node.new('someone', :classes => {'something' => {}}) }
describe "when the class exists" do
it "should succeed if the class is already included" do
manifest = <<-MANIFEST
class something {}
include something
MANIFEST
catalog = compile_to_catalog(manifest, node)
- catalog.resource('Class', 'Something').should_not be_nil
+ expect(catalog.resource('Class', 'Something')).not_to be_nil
end
it "should evaluate the class if it's not already included" do
manifest = <<-MANIFEST
class something {}
MANIFEST
catalog = compile_to_catalog(manifest, node)
- catalog.resource('Class', 'Something').should_not be_nil
+ expect(catalog.resource('Class', 'Something')).not_to be_nil
end
end
it "should fail if the class doesn't exist" do
expect { compile_to_catalog('', node) }.to raise_error(Puppet::Error, /Could not find class something/)
end
end
describe "for classes with parameters" do
let(:node) { Puppet::Node.new('someone', :classes => {'something' => {'configuron' => 'defrabulated'}}) }
describe "when the class exists" do
it "should fail if the class is already included" do
manifest = <<-MANIFEST
class something($configuron=frabulated) {}
include something
MANIFEST
expect { compile_to_catalog(manifest, node) }.to raise_error(Puppet::Error, /Class\[Something\] is already declared/)
end
it "should evaluate the class if it's not already included" do
manifest = <<-MANIFEST
class something($configuron=frabulated) {}
MANIFEST
catalog = compile_to_catalog(manifest, node)
resource = catalog.resource('Class', 'Something')
- resource['configuron'].should == 'defrabulated'
+ expect(resource['configuron']).to eq('defrabulated')
end
end
it "should fail if the class doesn't exist" do
expect { compile_to_catalog('', node) }.to raise_error(Puppet::Error, /Could not find class something/)
end
it 'evaluates classes declared with parameters before unparameterized classes' do
node = Puppet::Node.new('someone', :classes => { 'app::web' => {}, 'app' => { 'port' => 8080 } })
manifest = <<-MANIFEST
class app($port = 80) { }
class app::web($port = $app::port) inherits app {
notify { expected: message => "$port" }
}
MANIFEST
catalog = compile_to_catalog(manifest, node)
expect(catalog).to have_resource("Class[App]").with_parameter(:port, 8080)
expect(catalog).to have_resource("Class[App::Web]")
expect(catalog).to have_resource("Notify[expected]").with_parameter(:message, "8080")
end
end
end
end
describe "when managing resource overrides" do
before do
@override = stub 'override', :ref => "File[/foo]", :type => "my"
@resource = resource(:file, "/foo")
end
it "should be able to store overrides" do
- lambda { @compiler.add_override(@override) }.should_not raise_error
+ expect { @compiler.add_override(@override) }.not_to raise_error
end
it "should apply overrides to the appropriate resources" do
@compiler.add_resource(@scope, @resource)
@resource.expects(:merge).with(@override)
@compiler.add_override(@override)
@compiler.compile
end
it "should accept overrides before the related resource has been created" do
@resource.expects(:merge).with(@override)
# First store the override
@compiler.add_override(@override)
# Then the resource
@compiler.add_resource(@scope, @resource)
# And compile, so they get resolved
@compiler.compile
end
it "should fail if the compile is finished and resource overrides have not been applied" do
@compiler.add_override(@override)
- lambda { @compiler.compile }.should raise_error Puppet::ParseError, 'Could not find resource(s) File[/foo] for overriding'
+ expect { @compiler.compile }.to raise_error Puppet::ParseError, 'Could not find resource(s) File[/foo] for overriding'
end
end
context "when converting catalog to resource" do
it "the same environment is used for compilation as for transformation to resource form" do
Puppet[:code] = <<-MANIFEST
notify { 'dummy':
}
MANIFEST
Puppet::Parser::Resource::Catalog.any_instance.expects(:to_resource).with do |catalog|
Puppet.lookup(:current_environment).name == :production
end
Puppet::Parser::Compiler.compile(Puppet::Node.new("mynode"))
end
end
end
diff --git a/spec/integration/parser/functions/require_spec.rb b/spec/integration/parser/functions/require_spec.rb
index 6731614b6..0d33456f4 100755
--- a/spec/integration/parser/functions/require_spec.rb
+++ b/spec/integration/parser/functions/require_spec.rb
@@ -1,43 +1,43 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "The require function" do
before :each do
@node = Puppet::Node.new("mynode")
@compiler = Puppet::Parser::Compiler.new(@node)
@compiler.send(:evaluate_main)
@compiler.catalog.client_version = "0.25"
@scope = @compiler.topscope
# preload our functions
Puppet::Parser::Functions.function(:include)
Puppet::Parser::Functions.function(:require)
end
it "should add a dependency between the 'required' class and our class" do
@compiler.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "requiredclass")
@scope.function_require(["requiredclass"])
- @scope.resource["require"].should_not be_nil
+ expect(@scope.resource["require"]).not_to be_nil
ref = @scope.resource["require"].shift
- ref.type.should == "Class"
- ref.title.should == "Requiredclass"
+ expect(ref.type).to eq("Class")
+ expect(ref.title).to eq("Requiredclass")
end
it "should queue relationships between the 'required' class and our classes" do
@compiler.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "requiredclass1")
@compiler.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "requiredclass2")
@scope.function_require(["requiredclass1"])
@scope.function_require(["requiredclass2"])
- @scope.resource["require"].should_not be_nil
+ expect(@scope.resource["require"]).not_to be_nil
(ref1,ref2) = @scope.resource["require"]
- ref1.type.should == "Class"
- ref1.title.should == "Requiredclass1"
- ref2.type.should == "Class"
- ref2.title.should == "Requiredclass2"
+ expect(ref1.type).to eq("Class")
+ expect(ref1.title).to eq("Requiredclass1")
+ expect(ref2.type).to eq("Class")
+ expect(ref2.title).to eq("Requiredclass2")
end
end
diff --git a/spec/integration/parser/scope_spec.rb b/spec/integration/parser/scope_spec.rb
index b3f3c3931..358f3c4a4 100644
--- a/spec/integration/parser/scope_spec.rb
+++ b/spec/integration/parser/scope_spec.rb
@@ -1,627 +1,627 @@
require 'spec_helper'
require 'puppet_spec/compiler'
describe "Two step scoping for variables" do
include PuppetSpec::Compiler
def expect_the_message_to_be(message, node = Puppet::Node.new('the node'))
catalog = compile_to_catalog(yield, node)
- catalog.resource('Notify', 'something')[:message].should == message
+ expect(catalog.resource('Notify', 'something')[:message]).to eq(message)
end
before :each do
Puppet.expects(:deprecation_warning).never
end
describe "using unsupported operators" do
it "issues an error for +=" do
expect do
catalog = compile_to_catalog(<<-MANIFEST)
$var = ["top_msg"]
node default {
$var += ["override"]
}
MANIFEST
end.to raise_error(/The operator '\+=' is no longer supported/)
end
it "issues an error for -=" do
expect do
catalog = compile_to_catalog(<<-MANIFEST)
$var = ["top_msg"]
node default {
$var -= ["top_msg"]
}
MANIFEST
end.to raise_error(/The operator '-=' is no longer supported/)
end
end
it "when using a template ignores the dynamic value of the var when using the @varname syntax" do
expect_the_message_to_be('node_msg') do <<-MANIFEST
node default {
$var = "node_msg"
include foo
}
class foo {
$var = "foo_msg"
include bar
}
class bar {
notify { 'something': message => inline_template("<%= @var %>"), }
}
MANIFEST
end
end
it "when using a template gets the var from an inherited class when using the @varname syntax" do
expect_the_message_to_be('Barbamama') do <<-MANIFEST
node default {
$var = "node_msg"
include bar_bamama
include foo
}
class bar_bamama {
$var = "Barbamama"
}
class foo {
$var = "foo_msg"
include bar
}
class bar inherits bar_bamama {
notify { 'something': message => inline_template("<%= @var %>"), }
}
MANIFEST
end
end
it "when using a template ignores the dynamic var when it is not present in an inherited class" do
expect_the_message_to_be('node_msg') do <<-MANIFEST
node default {
$var = "node_msg"
include bar_bamama
include foo
}
class bar_bamama {
}
class foo {
$var = "foo_msg"
include bar
}
class bar inherits bar_bamama {
notify { 'something': message => inline_template("<%= @var %>"), }
}
MANIFEST
end
end
describe "fully qualified variable names" do
it "keeps nodescope separate from topscope" do
expect_the_message_to_be('topscope') do <<-MANIFEST
$c = "topscope"
node default {
$c = "nodescope"
notify { 'something': message => $::c }
}
MANIFEST
end
end
end
describe "when colliding class and variable names" do
it "finds a topscope variable with the same name as a class" do
expect_the_message_to_be('topscope') do <<-MANIFEST
$c = "topscope"
class c { }
node default {
include c
notify { 'something': message => $c }
}
MANIFEST
end
end
it "finds a node scope variable with the same name as a class" do
expect_the_message_to_be('nodescope') do <<-MANIFEST
class c { }
node default {
$c = "nodescope"
include c
notify { 'something': message => $c }
}
MANIFEST
end
end
it "finds a class variable when the class collides with a nodescope variable" do
expect_the_message_to_be('class') do <<-MANIFEST
class c { $b = "class" }
node default {
$c = "nodescope"
include c
notify { 'something': message => $c::b }
}
MANIFEST
end
end
it "finds a class variable when the class collides with a topscope variable" do
expect_the_message_to_be('class') do <<-MANIFEST
$c = "topscope"
class c { $b = "class" }
node default {
include c
notify { 'something': message => $::c::b }
}
MANIFEST
end
end
end
describe "when using shadowing and inheritance" do
it "finds values in its local scope" do
expect_the_message_to_be('local_msg') do <<-MANIFEST
node default {
include baz
}
class foo {
}
class bar inherits foo {
$var = "local_msg"
notify { 'something': message => $var, }
}
class baz {
include bar
}
MANIFEST
end
end
it "finds values in its inherited scope" do
expect_the_message_to_be('foo_msg') do <<-MANIFEST
node default {
include baz
}
class foo {
$var = "foo_msg"
}
class bar inherits foo {
notify { 'something': message => $var, }
}
class baz {
include bar
}
MANIFEST
end
end
it "prefers values in its local scope over values in the inherited scope" do
expect_the_message_to_be('local_msg') do <<-MANIFEST
include bar
class foo {
$var = "inherited"
}
class bar inherits foo {
$var = "local_msg"
notify { 'something': message => $var, }
}
MANIFEST
end
end
it "finds a qualified variable by following parent scopes of the specified scope" do
expect_the_message_to_be("from node") do <<-MANIFEST
class c {
notify { 'something': message => "$a::b" }
}
class a { }
node default {
$b = "from node"
include a
include c
}
MANIFEST
end
end
it "finds values in its inherited scope when the inherited class is qualified to the top" do
expect_the_message_to_be('foo_msg') do <<-MANIFEST
node default {
include baz
}
class foo {
$var = "foo_msg"
}
class bar inherits ::foo {
notify { 'something': message => $var, }
}
class baz {
include bar
}
MANIFEST
end
end
it "prefers values in its local scope over values in the inherited scope when the inherited class is fully qualified" do
expect_the_message_to_be('local_msg') do <<-MANIFEST
include bar
class foo {
$var = "inherited"
}
class bar inherits ::foo {
$var = "local_msg"
notify { 'something': message => $var, }
}
MANIFEST
end
end
it "finds values in top scope when the inherited class is qualified to the top" do
expect_the_message_to_be('top msg') do <<-MANIFEST
$var = "top msg"
class foo {
}
class bar inherits ::foo {
notify { 'something': message => $var, }
}
include bar
MANIFEST
end
end
it "finds values in its inherited scope when the inherited class is a nested class that shadows another class at the top" do
expect_the_message_to_be('inner baz') do <<-MANIFEST
node default {
include foo::bar
}
class baz {
$var = "top baz"
}
class foo {
class baz {
$var = "inner baz"
}
class bar inherits foo::baz {
notify { 'something': message => $var, }
}
}
MANIFEST
end
end
it "finds values in its inherited scope when the inherited class is qualified to a nested class and qualified to the top" do
expect_the_message_to_be('top baz') do <<-MANIFEST
node default {
include foo::bar
}
class baz {
$var = "top baz"
}
class foo {
class baz {
$var = "inner baz"
}
class bar inherits ::baz {
notify { 'something': message => $var, }
}
}
MANIFEST
end
end
it "finds values in its inherited scope when the inherited class is qualified" do
expect_the_message_to_be('foo_msg') do <<-MANIFEST
node default {
include bar
}
class foo {
class baz {
$var = "foo_msg"
}
}
class bar inherits foo::baz {
notify { 'something': message => $var, }
}
MANIFEST
end
end
it "prefers values in its inherited scope over those in the node (with intermediate inclusion)" do
expect_the_message_to_be('foo_msg') do <<-MANIFEST
node default {
$var = "node_msg"
include baz
}
class foo {
$var = "foo_msg"
}
class bar inherits foo {
notify { 'something': message => $var, }
}
class baz {
include bar
}
MANIFEST
end
end
it "prefers values in its inherited scope over those in the node (without intermediate inclusion)" do
expect_the_message_to_be('foo_msg') do <<-MANIFEST
node default {
$var = "node_msg"
include bar
}
class foo {
$var = "foo_msg"
}
class bar inherits foo {
notify { 'something': message => $var, }
}
MANIFEST
end
end
it "prefers values in its inherited scope over those from where it is included" do
expect_the_message_to_be('foo_msg') do <<-MANIFEST
node default {
include baz
}
class foo {
$var = "foo_msg"
}
class bar inherits foo {
notify { 'something': message => $var, }
}
class baz {
$var = "baz_msg"
include bar
}
MANIFEST
end
end
it "does not used variables from classes included in the inherited scope" do
expect_the_message_to_be('node_msg') do <<-MANIFEST
node default {
$var = "node_msg"
include bar
}
class quux {
$var = "quux_msg"
}
class foo inherits quux {
}
class baz {
include foo
}
class bar inherits baz {
notify { 'something': message => $var, }
}
MANIFEST
end
end
it "does not use a variable from a scope lexically enclosing it" do
expect_the_message_to_be('node_msg') do <<-MANIFEST
node default {
$var = "node_msg"
include other::bar
}
class other {
$var = "other_msg"
class bar {
notify { 'something': message => $var, }
}
}
MANIFEST
end
end
it "finds values in its node scope" do
expect_the_message_to_be('node_msg') do <<-MANIFEST
node default {
$var = "node_msg"
include baz
}
class foo {
}
class bar inherits foo {
notify { 'something': message => $var, }
}
class baz {
include bar
}
MANIFEST
end
end
it "finds values in its top scope" do
expect_the_message_to_be('top_msg') do <<-MANIFEST
$var = "top_msg"
node default {
include baz
}
class foo {
}
class bar inherits foo {
notify { 'something': message => $var, }
}
class baz {
include bar
}
MANIFEST
end
end
it "prefers variables from the node over those in the top scope" do
expect_the_message_to_be('node_msg') do <<-MANIFEST
$var = "top_msg"
node default {
$var = "node_msg"
include foo
}
class foo {
notify { 'something': message => $var, }
}
MANIFEST
end
end
it "finds top scope variables referenced inside a defined type" do
expect_the_message_to_be('top_msg') do <<-MANIFEST
$var = "top_msg"
node default {
foo { "testing": }
}
define foo() {
notify { 'something': message => $var, }
}
MANIFEST
end
end
it "finds node scope variables referenced inside a defined type" do
expect_the_message_to_be('node_msg') do <<-MANIFEST
$var = "top_msg"
node default {
$var = "node_msg"
foo { "testing": }
}
define foo() {
notify { 'something': message => $var, }
}
MANIFEST
end
end
end
describe "in situations that used to have dynamic lookup" do
it "ignores the dynamic value of the var" do
expect_the_message_to_be('node_msg') do <<-MANIFEST
node default {
$var = "node_msg"
include foo
}
class baz {
$var = "baz_msg"
include bar
}
class foo inherits baz {
}
class bar {
notify { 'something': message => $var, }
}
MANIFEST
end
end
it "finds nil when the only set variable is in the dynamic scope" do
expect_the_message_to_be(nil) do <<-MANIFEST
node default {
include baz
}
class foo {
}
class bar inherits foo {
notify { 'something': message => $var, }
}
class baz {
$var = "baz_msg"
include bar
}
MANIFEST
end
end
it "ignores the value in the dynamic scope for a defined type" do
expect_the_message_to_be('node_msg') do <<-MANIFEST
node default {
$var = "node_msg"
include foo
}
class foo {
$var = "foo_msg"
bar { "testing": }
}
define bar() {
notify { 'something': message => $var, }
}
MANIFEST
end
end
it "when using a template ignores the dynamic value of the var when using scope.lookupvar" do
expect_the_message_to_be('node_msg') do <<-MANIFEST
node default {
$var = "node_msg"
include foo
}
class foo {
$var = "foo_msg"
include bar
}
class bar {
notify { 'something': message => inline_template("<%= scope.lookupvar('var') %>"), }
}
MANIFEST
end
end
end
describe "when using an enc" do
it "places enc parameters in top scope" do
enc_node = Puppet::Node.new("the node", { :parameters => { "var" => 'from_enc' } })
expect_the_message_to_be('from_enc', enc_node) do <<-MANIFEST
notify { 'something': message => $var, }
MANIFEST
end
end
it "does not allow the enc to specify an existing top scope var" do
enc_node = Puppet::Node.new("the_node", { :parameters => { "var" => 'from_enc' } })
expect {
compile_to_catalog("$var = 'top scope'", enc_node)
}.to raise_error(
Puppet::Error,
/Cannot reassign variable var at line 1(\:6)? on node the_node/
)
end
it "evaluates enc classes in top scope when there is no node" do
enc_node = Puppet::Node.new("the node", { :classes => ['foo'], :parameters => { "var" => 'from_enc' } })
expect_the_message_to_be('from_enc', enc_node) do <<-MANIFEST
class foo {
notify { 'something': message => $var, }
}
MANIFEST
end
end
it "overrides enc variables from a node scope var" do
enc_node = Puppet::Node.new("the_node", { :classes => ['foo'], :parameters => { 'enc_var' => 'Set from ENC.' } })
expect_the_message_to_be('ENC overridden in node', enc_node) do <<-MANIFEST
node the_node {
$enc_var = "ENC overridden in node"
}
class foo {
notify { 'something': message => $enc_var, }
}
MANIFEST
end
end
end
end
diff --git a/spec/integration/parser/undef_param_spec.rb b/spec/integration/parser/undef_param_spec.rb
index 26f937a67..59a151cc5 100644
--- a/spec/integration/parser/undef_param_spec.rb
+++ b/spec/integration/parser/undef_param_spec.rb
@@ -1,87 +1,87 @@
require 'spec_helper'
require 'puppet_spec/compiler'
describe "Parameter passing" do
include PuppetSpec::Compiler
before :each do
# DataBinding will be consulted before falling back to a default value,
# but we aren't testing that here
Puppet::DataBinding.indirection.stubs(:find)
end
def expect_the_message_to_be(message, node = Puppet::Node.new('the node'))
catalog = compile_to_catalog(yield, node)
- catalog.resource('Notify', 'something')[:message].should == message
+ expect(catalog.resource('Notify', 'something')[:message]).to eq(message)
end
def expect_puppet_error(message, node = Puppet::Node.new('the node'))
expect { compile_to_catalog(yield, node) }.to raise_error(Puppet::Error, message)
end
it "overrides the default when a value is given" do
expect_the_message_to_be('2') do <<-MANIFEST
define a($x='1') { notify { 'something': message => $x }}
a {'a': x => '2'}
MANIFEST
end
end
it "shadows an inherited variable with the default value when undef is passed" do
expect_the_message_to_be('default') do <<-MANIFEST
class a { $x = 'inherited' }
class b($x='default') inherits a { notify { 'something': message => $x }}
class { 'b': x => undef}
MANIFEST
end
end
it "uses a default value that comes from an inherited class when the parameter is undef" do
expect_the_message_to_be('inherited') do <<-MANIFEST
class a { $x = 'inherited' }
class b($y=$x) inherits a { notify { 'something': message => $y }}
class { 'b': y => undef}
MANIFEST
end
end
it "uses a default value that references another variable when the parameter is passed as undef" do
expect_the_message_to_be('a') do <<-MANIFEST
define a($a = $title) { notify { 'something': message => $a }}
a {'a': a => undef}
MANIFEST
end
end
it "uses the default when 'undef' is given'" do
expect_the_message_to_be('1') do <<-MANIFEST
define a($x='1') { notify { 'something': message => $x }}
a {'a': x => undef}
MANIFEST
end
end
it "uses the default when no parameter is provided" do
expect_the_message_to_be('1') do <<-MANIFEST
define a($x='1') { notify { 'something': message => $x }}
a {'a': }
MANIFEST
end
end
it "uses a value of undef when the default is undef and no parameter is provided" do
expect_the_message_to_be(true) do <<-MANIFEST
define a($x=undef) { notify { 'something': message => $x == undef}}
a {'a': }
MANIFEST
end
end
it "errors when no parameter is provided and there is no default" do
expect_puppet_error(/^Must pass x to A\[a\].*/) do <<-MANIFEST
define a($x) { notify { 'something': message => $x }}
a {'a': }
MANIFEST
end
end
end
diff --git a/spec/integration/provider/cron/crontab_spec.rb b/spec/integration/provider/cron/crontab_spec.rb
index e75523cac..e16a9df03 100644
--- a/spec/integration/provider/cron/crontab_spec.rb
+++ b/spec/integration/provider/cron/crontab_spec.rb
@@ -1,241 +1,241 @@
#!/usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_bucket/dipper'
require 'puppet_spec/compiler'
describe Puppet::Type.type(:cron).provider(:crontab), '(integration)', :unless => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
include PuppetSpec::Compiler
before :each do
Puppet::Type.type(:cron).stubs(:defaultprovider).returns described_class
Puppet::FileBucket::Dipper.any_instance.stubs(:backup) # Don't backup to filebucket
# I don't want to execute anything
described_class.stubs(:filetype).returns Puppet::Util::FileType::FileTypeFlat
described_class.stubs(:default_target).returns crontab_user1
# I don't want to stub Time.now to get a static header because I don't know
# where Time.now is used elsewhere, so just go with a very simple header
described_class.stubs(:header).returns "# HEADER: some simple\n# HEADER: header\n"
FileUtils.cp(my_fixture('crontab_user1'), crontab_user1)
FileUtils.cp(my_fixture('crontab_user2'), crontab_user2)
end
after :each do
described_class.clear
end
let :crontab_user1 do
tmpfile('cron_integration_specs')
end
let :crontab_user2 do
tmpfile('cron_integration_specs')
end
def expect_output(fixture_name)
- File.read(crontab_user1).should == File.read(my_fixture(fixture_name))
+ expect(File.read(crontab_user1)).to eq(File.read(my_fixture(fixture_name)))
end
describe "when managing a cron entry" do
it "should be able to purge unmanaged entries" do
apply_with_error_check(<<-MANIFEST)
cron {
'only managed entry':
ensure => 'present',
command => '/bin/true',
target => '#{crontab_user1}',
}
resources { 'cron': purge => 'true' }
MANIFEST
expect_output('purged')
end
describe "with ensure absent" do
it "should do nothing if entry already absent" do
apply_with_error_check(<<-MANIFEST)
cron {
'no_such_entry':
ensure => 'absent',
target => '#{crontab_user1}',
}
MANIFEST
expect_output('crontab_user1')
end
it "should remove the resource from crontab if present" do
apply_with_error_check(<<-MANIFEST)
cron {
'My daily failure':
ensure => 'absent',
target => '#{crontab_user1}',
}
MANIFEST
expect_output('remove_named_resource')
end
it "should remove a matching cronentry if present" do
apply_with_error_check(<<-MANIFEST)
cron {
'no_such_named_resource_in_crontab':
ensure => absent,
minute => [ '17-19', '22' ],
hour => [ '0-23/2' ],
weekday => 'Tue',
command => '/bin/unnamed_regular_command',
target => '#{crontab_user1}',
}
MANIFEST
expect_output('remove_unnamed_resource')
end
end
describe "with ensure present" do
context "and no command specified" do
it "should work if the resource is already present" do
apply_with_error_check(<<-MANIFEST)
cron {
'My daily failure':
special => 'daily',
target => '#{crontab_user1}',
}
MANIFEST
expect_output('crontab_user1')
end
it "should fail if the resource needs creating" do
manifest = <<-MANIFEST
cron {
'Entirely new resource':
special => 'daily',
target => '#{crontab_user1}',
}
MANIFEST
apply_compiled_manifest(manifest) do |res|
if res.ref == 'Cron[Entirely new resource]'
res.expects(:err).with(regexp_matches(/no command/))
else
res.expects(:err).never
end
end
end
end
it "should do nothing if entry already present" do
apply_with_error_check(<<-MANIFEST)
cron {
'My daily failure':
special => 'daily',
command => '/bin/false',
target => '#{crontab_user1}',
}
MANIFEST
expect_output('crontab_user1')
end
it "should work correctly when managing 'target' but not 'user'" do
apply_with_error_check(<<-MANIFEST)
cron {
'My daily failure':
special => 'daily',
command => '/bin/false',
target => '#{crontab_user1}',
}
MANIFEST
expect_output('crontab_user1')
end
it "should do nothing if a matching entry already present" do
apply_with_error_check(<<-MANIFEST)
cron {
'no_such_named_resource_in_crontab':
ensure => present,
minute => [ '17-19', '22' ],
hour => [ '0-23/2' ],
command => '/bin/unnamed_regular_command',
target => '#{crontab_user1}',
}
MANIFEST
expect_output('crontab_user1')
end
it "should add a new normal entry if currently absent" do
apply_with_error_check(<<-MANIFEST)
cron {
'new entry':
ensure => present,
minute => '12',
weekday => 'Tue',
command => '/bin/new',
environment => [
'MAILTO=""',
'SHELL=/bin/bash'
],
target => '#{crontab_user1}',
}
MANIFEST
expect_output('create_normal_entry')
end
it "should add a new special entry if currently absent" do
apply_with_error_check(<<-MANIFEST)
cron {
'new special entry':
ensure => present,
special => 'reboot',
command => 'echo "Booted" 1>&2',
environment => 'MAILTO=bob@company.com',
target => '#{crontab_user1}',
}
MANIFEST
expect_output('create_special_entry')
end
it "should change existing entry if out of sync" do
apply_with_error_check(<<-MANIFEST)
cron {
'Monthly job':
ensure => present,
special => 'monthly',
#minute => ['22'],
command => '/usr/bin/monthly',
environment => [],
target => '#{crontab_user1}',
}
MANIFEST
expect_output('modify_entry')
end
it "should change a special schedule to numeric if requested" do
apply_with_error_check(<<-MANIFEST)
cron {
'My daily failure':
special => 'absent',
command => '/bin/false',
target => '#{crontab_user1}',
}
MANIFEST
expect_output('unspecialized')
end
it "should not try to move an entry from one file to another" do
# force the parsedfile provider to also parse user1's crontab
apply_with_error_check(<<-MANIFEST)
cron {
'foo':
ensure => absent,
target => '#{crontab_user1}';
'My daily failure':
special => 'daily',
command => "/bin/false",
target => '#{crontab_user2}',
}
MANIFEST
- File.read(crontab_user1).should == File.read(my_fixture('moved_cronjob_input1'))
- File.read(crontab_user2).should == File.read(my_fixture('moved_cronjob_input2'))
+ expect(File.read(crontab_user1)).to eq(File.read(my_fixture('moved_cronjob_input1')))
+ expect(File.read(crontab_user2)).to eq(File.read(my_fixture('moved_cronjob_input2')))
end
end
end
end
diff --git a/spec/integration/provider/mount_spec.rb b/spec/integration/provider/mount_spec.rb
index 2757ad7fd..4c9b914f1 100755
--- a/spec/integration/provider/mount_spec.rb
+++ b/spec/integration/provider/mount_spec.rb
@@ -1,171 +1,174 @@
require 'spec_helper'
require 'puppet/file_bucket/dipper'
describe "mount provider (integration)", :unless => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
family = Facter.value(:osfamily)
def create_fake_fstab(initially_contains_entry)
File.open(@fake_fstab, 'w') do |f|
if initially_contains_entry
f.puts("/dev/disk1s1\t/Volumes/foo_disk\tmsdos\tlocal\t0\t0")
end
end
end
before :each do
@fake_fstab = tmpfile('fstab')
@current_options = "local"
@current_device = "/dev/disk1s1"
Puppet::Type.type(:mount).defaultprovider.stubs(:default_target).returns(@fake_fstab)
Facter.stubs(:value).with(:hostname).returns('some_host')
Facter.stubs(:value).with(:domain).returns('some_domain')
Facter.stubs(:value).with(:kernel).returns('Darwin')
Facter.stubs(:value).with(:operatingsystem).returns('Darwin')
Facter.stubs(:value).with(:osfamily).returns('Darwin')
Puppet::Util::ExecutionStub.set do |command, options|
case command[0]
when %r{/s?bin/mount}
if command.length == 1
if @mounted
"#{@current_device} on /Volumes/foo_disk (msdos, #{@current_options})\n"
else
''
end
else
- command.length.should == 4
- command[1].should == '-o'
+ expect(command.length).to eq(4)
+ expect(command[1]).to eq('-o')
# update is a special option, used on bsd's
# strip it out and track as a local bool here
update = false
tmp_options = command[2].split(",")
if tmp_options.include?("update")
update = true
tmp_options.delete("update")
end
@current_options = tmp_options.join(",")
if !update
- @mounted.should == false # verify that we don't try to call "mount" redundantly
+ expect(@mounted).to eq(false) # verify that we don't try to call "mount" redundantly
end
- command[3].should == '/Volumes/foo_disk'
+ expect(command[3]).to eq('/Volumes/foo_disk')
@current_device = check_fstab(true)
@mounted = true
''
end
when %r{/s?bin/umount}
- command.length.should == 2
- command[1].should == '/Volumes/foo_disk'
- @mounted.should == true # "umount" doesn't work when device not mounted (see #6632)
+ expect(command.length).to eq(2)
+ expect(command[1]).to eq('/Volumes/foo_disk')
+ expect(@mounted).to eq(true) # "umount" doesn't work when device not mounted (see #6632)
@mounted = false
''
else
fail "Unexpected command #{command.inspect} executed"
end
end
end
after :each do
Puppet::Type::Mount::ProviderParsed.clear # Work around bug #6628
end
def check_fstab(expected_to_be_present)
# Verify that the fake fstab has the expected data in it
fstab_contents = File.read(@fake_fstab).split("\n").reject { |x| x =~ /^#|^$/ }
if expected_to_be_present
- fstab_contents.length().should == 1
+ expect(fstab_contents.length()).to eq(1)
device, rest_of_line = fstab_contents[0].split(/\t/,2)
- rest_of_line.should == "/Volumes/foo_disk\tmsdos\t#{@desired_options}\t0\t0"
+ expect(rest_of_line).to eq("/Volumes/foo_disk\tmsdos\t#{@desired_options}\t0\t0")
device
else
- fstab_contents.length().should == 0
+ expect(fstab_contents.length()).to eq(0)
nil
end
end
def run_in_catalog(settings)
resource = Puppet::Type.type(:mount).new(settings.merge(:name => "/Volumes/foo_disk",
:device => "/dev/disk1s1", :fstype => "msdos"))
Puppet::FileBucket::Dipper.any_instance.stubs(:backup) # Don't backup to the filebucket
resource.expects(:err).never
catalog = Puppet::Resource::Catalog.new
catalog.host_config = false # Stop Puppet from doing a bunch of magic
catalog.add_resource resource
catalog.apply
end
[false, true].each do |initial_state|
describe "When initially #{initial_state ? 'mounted' : 'unmounted'}" do
before :each do
@mounted = initial_state
end
[false, true].each do |initial_fstab_entry|
describe "When there is #{initial_fstab_entry ? 'an' : 'no'} initial fstab entry" do
before :each do
create_fake_fstab(initial_fstab_entry)
end
[:defined, :present, :mounted, :unmounted, :absent].each do |ensure_setting|
expected_final_state = case ensure_setting
when :mounted
true
when :unmounted, :absent
false
when :defined, :present
initial_state
else
fail "Unknown ensure_setting #{ensure_setting}"
end
expected_fstab_data = (ensure_setting != :absent)
describe "When setting ensure => #{ensure_setting}" do
["local", "journaled"].each do |options_setting|
describe "When setting options => #{options_setting}" do
it "should leave the system in the #{expected_final_state ? 'mounted' : 'unmounted'} state, #{expected_fstab_data ? 'with' : 'without'} data in /etc/fstab" do
- pending("Solaris: The mock :operatingsystem value does not get changed in lib/puppet/provider/mount/parsed.rb", :if => family == "Solaris")
- @desired_options = options_setting
- run_in_catalog(:ensure=>ensure_setting, :options => options_setting)
- @mounted.should == expected_final_state
- if expected_fstab_data
- check_fstab(expected_fstab_data).should == "/dev/disk1s1"
+ if family == "Solaris"
+ skip("Solaris: The mock :operatingsystem value does not get changed in lib/puppet/provider/mount/parsed.rb")
else
- check_fstab(expected_fstab_data).should == nil
- end
- if @mounted
- if ![:defined, :present].include?(ensure_setting)
- @current_options.should == @desired_options
- elsif initial_fstab_entry
- @current_options.should == @desired_options
+ @desired_options = options_setting
+ run_in_catalog(:ensure=>ensure_setting, :options => options_setting)
+ expect(@mounted).to eq(expected_final_state)
+ if expected_fstab_data
+ expect(check_fstab(expected_fstab_data)).to eq("/dev/disk1s1")
else
- @current_options.should == 'local' #Workaround for #6645
+ expect(check_fstab(expected_fstab_data)).to eq(nil)
+ end
+ if @mounted
+ if ![:defined, :present].include?(ensure_setting)
+ expect(@current_options).to eq(@desired_options)
+ elsif initial_fstab_entry
+ expect(@current_options).to eq(@desired_options)
+ else
+ expect(@current_options).to eq('local') #Workaround for #6645
+ end
end
end
end
end
end
end
end
end
end
end
end
describe "When the wrong device is mounted" do
it "should remount the correct device" do
pending "Due to bug 6309"
@mounted = true
@current_device = "/dev/disk2s2"
create_fake_fstab(true)
@desired_options = "local"
run_in_catalog(:ensure=>:mounted, :options=>'local')
- @current_device.should=="/dev/disk1s1"
- @mounted.should==true
- @current_options.should=='local'
- check_fstab(true).should == "/dev/disk1s1"
+ expect(@current_device).to eq("/dev/disk1s1")
+ expect(@mounted).to eq(true)
+ expect(@current_options).to eq('local')
+ expect(check_fstab(true)).to eq("/dev/disk1s1")
end
end
end
diff --git a/spec/integration/provider/package_spec.rb b/spec/integration/provider/package_spec.rb
index 9a21e4558..e806a35f1 100755
--- a/spec/integration/provider/package_spec.rb
+++ b/spec/integration/provider/package_spec.rb
@@ -1,35 +1,33 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "Package provider" do
include PuppetSpec::Files
Puppet::Type.type(:package).providers.each do |name|
provider = Puppet::Type.type(:package).provider(name)
describe name, :if => provider.suitable? do
it "should fail when asked to install an invalid package" do
- pending("This test hangs forever with recent versions of RubyGems") if provider.name == :gem
-
options = {:name => "nosuch#{provider.name}", :provider => provider.name}
pkg = Puppet::Type.newpackage(options)
- lambda { pkg.provider.install }.should raise_error
+ expect { pkg.provider.install }.to raise_error
end
it "should be able to get a list of existing packages" do
# the instances method requires root priviledges on gentoo
# if the eix cache is outdated (to run eix-update) so make
# sure we dont actually run eix-update
if provider.name == :portage
provider.stubs(:update_eix).returns('Database contains 15240 packages in 155 categories')
end
provider.instances.each do |package|
- package.should be_instance_of(provider)
- package.properties[:provider].should == provider.name
+ expect(package).to be_instance_of(provider)
+ expect(package.properties[:provider]).to eq(provider.name)
end
end
end
end
end
diff --git a/spec/integration/provider/service/init_spec.rb b/spec/integration/provider/service/init_spec.rb
index c487f6d68..f21b525ef 100755
--- a/spec/integration/provider/service/init_spec.rb
+++ b/spec/integration/provider/service/init_spec.rb
@@ -1,46 +1,46 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider = Puppet::Type.type(:service).provider(:init)
describe provider do
describe "when running on FreeBSD" do
before :each do
Facter.stubs(:value).with(:operatingsystem).returns 'FreeBSD'
end
it "should set its default path to include /etc/rc.d and /usr/local/etc/rc.d" do
- provider.defpath.should == ["/etc/rc.d", "/usr/local/etc/rc.d"]
+ expect(provider.defpath).to eq(["/etc/rc.d", "/usr/local/etc/rc.d"])
end
end
describe "when running on HP-UX" do
before :each do
Facter.stubs(:value).with(:operatingsystem).returns 'HP-UX'
end
it "should set its default path to include /sbin/init.d" do
- provider.defpath.should == "/sbin/init.d"
+ expect(provider.defpath).to eq("/sbin/init.d")
end
end
describe "when running on Archlinux" do
before :each do
Facter.stubs(:value).with(:operatingsystem).returns 'Archlinux'
end
it "should set its default path to include /etc/rc.d" do
- provider.defpath.should == "/etc/rc.d"
+ expect(provider.defpath).to eq("/etc/rc.d")
end
end
describe "when not running on FreeBSD, HP-UX or Archlinux" do
before :each do
Facter.stubs(:value).with(:operatingsystem).returns 'RedHat'
end
it "should set its default path to include /etc/init.d" do
- provider.defpath.should == "/etc/init.d"
+ expect(provider.defpath).to eq("/etc/init.d")
end
end
end
diff --git a/spec/integration/provider/service/systemd_spec.rb b/spec/integration/provider/service/systemd_spec.rb
index b48eb06f3..59b9b8ccd 100644
--- a/spec/integration/provider/service/systemd_spec.rb
+++ b/spec/integration/provider/service/systemd_spec.rb
@@ -1,20 +1,20 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:service).provider(:systemd), '(integration)' do
# TODO: Unfortunately there does not seem a way to stub the executable
# checks in the systemd provider because they happen at load time.
it "should be considered suitable if /bin/systemctl is present", :if => File.executable?('/bin/systemctl') do
- described_class.should be_suitable
+ expect(described_class).to be_suitable
end
it "should be considered suitable if /usr/bin/systemctl is present", :if => File.executable?('/usr/bin/systemctl') do
- described_class.should be_suitable
+ expect(described_class).to be_suitable
end
it "should not be cosidered suitable if systemctl is absent",
:unless => (File.executable?('/bin/systemctl') or File.executable?('/usr/bin/systemctl')) do
- described_class.should_not be_suitable
+ expect(described_class).not_to be_suitable
end
end
diff --git a/spec/integration/provider/ssh_authorized_key_spec.rb b/spec/integration/provider/ssh_authorized_key_spec.rb
index 6863e1351..14af2de46 100755
--- a/spec/integration/provider/ssh_authorized_key_spec.rb
+++ b/spec/integration/provider/ssh_authorized_key_spec.rb
@@ -1,219 +1,219 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_bucket/dipper'
describe Puppet::Type.type(:ssh_authorized_key).provider(:parsed), '(integration)', :unless => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
let :fake_userfile do
tmpfile('authorized_keys.user')
end
let :fake_rootfile do
tmpfile('authorized_keys.root')
end
let :sample_rsa_keys do
[
'AAAAB3NzaC1yc2EAAAADAQABAAAAgQCi18JBZOq10X3w4f67nVhO0O3s5Y1vHH4UgMSM3ZnQwbC5hjGyYSi9UULOoQQoQynI/a0I9NL423/Xk/XJVIKCHcS8q6V2Wmjd+fLNelOjxxoW6mbIytEt9rDvwgq3Mof3/m21L3t2byvegR00a+ikKbmInPmKwjeWZpexCIsHzQ==', # 1024 bit
'AAAAB3NzaC1yc2EAAAADAQABAAAAgQDLClyvi3CsJw5Id6khZs2/+s11qOH4Gdp6iDioDsrIp0m8kSiPr71VGyQYAfPzzvHemHS7Xg0NkG1Kc8u9tRqBQfTvz7ubq0AT/g01+4P2hQ/soFkuwlUG/HVnnaYb6N0Qp5SHWvD5vBE2nFFQVpP5GrSctPtHSjzJq/i+6LYhmQ==', # 1024 bit
'AAAAB3NzaC1yc2EAAAADAQABAAABAQDLygAO6txXkh9FNV8xSsBkATeqLbHzS7sFjGI3gt0Dx6q3LjyKwbhQ1RLf28kd5G6VWiXmClU/RtiPdUz8nrGuun++2mrxzrXrvpR9dq1lygLQ2wn2cI35dN5bjRMtXy3decs6HUhFo9MoNwX250rUWfdCyNPhGIp6OOfmjdy+UeLGNxq9wDx6i4bT5tVVSqVRtsEfw9+ICXchzl85QudjneVVpP+thriPZXfXA5eaGwAo/dmoKOIhUwF96gpdLqzNtrGQuxPbV80PTbGv9ZtAtTictxaDz8muXO7he9pXmchUpxUKtMFjHkL0FAZ9tRPmv3RA30sEr2fZ8+LKvnE50w0' #2048 Bit
]
end
let :sample_dsa_keys do
[
'AAAAB3NzaC1kc3MAAACBAOPck2O8MIDSqxPSnvENt6tzRrKJ5oOhB6Nc6oEcWm+VEH1gvuxdiRqwoMgRwyEf1yUd+UAcLw3a6Jn+EtFyEBN/5WF+4Tt4xTxZ0Pfik2Wc5uqHbQ2dkmOoXiAOYPiD3JUQ1Xwm/J0CgetjitoLfzAGdCNhMqguqAuHcVJ78ZZbAAAAFQCIBKFYZ+I18I+dtgteirXh+VVEEwAAAIEAs1yvQ/wnLLrRCM660pF4kBiw3D6dJfMdCXWQpn0hZmkBQSIzZv4Wuk3giei5luxscDxNc+y3CTXtnyG4Kt1Yi2sOdvhRI3rX8tD+ejn8GHazM05l5VIo9uu4AQPIE32iV63IqgApSBbJ6vDJW91oDH0J492WdLCar4BS/KE3cRwAAACBAN0uSDyJqYLRsfYcFn4HyVf6TJxQm1IcwEt6GcJVzgjri9VtW7FqY5iBqa9B9Zdh5XXAYJ0XLsWQCcrmMHM2XGHGpA4gL9VlCJ/0QvOcXxD2uK7IXwAVUA7g4V4bw8EVnFv2Flufozhsp+4soo1xiYc5jiFVHwVlk21sMhAtKAeF' # 1024 Bit
]
end
let :sample_lines do
[
"ssh-rsa #{sample_rsa_keys[1]} root@someotherhost",
"ssh-dss #{sample_dsa_keys[0]} root@anywhere",
"ssh-rsa #{sample_rsa_keys[2]} paul",
"ssh-rsa #{sample_rsa_keys[2]} dummy"
]
end
let :dummy do
Puppet::Type.type(:ssh_authorized_key).new(
:name => 'dummy',
:target => fake_userfile,
:user => 'nobody',
:ensure => :absent
)
end
before :each do
File.stubs(:chown)
File.stubs(:chmod)
Puppet::Util::SUIDManager.stubs(:asuser).yields
end
after :each do
described_class.clear # Work around bug #6628
end
def create_fake_key(username, content)
filename = (username == :root ? fake_rootfile : fake_userfile )
File.open(filename, 'w') do |f|
content.each do |line|
f.puts line
end
end
end
def check_fake_key(username, expected_content)
filename = (username == :root ? fake_rootfile : fake_userfile )
content = File.readlines(filename).map(&:chomp).sort.reject{ |x| x =~ /^# HEADER:/ }
- content.join("\n").should == expected_content.sort.join("\n")
+ expect(content.join("\n")).to eq(expected_content.sort.join("\n"))
end
def run_in_catalog(*resources)
Puppet::FileBucket::Dipper.any_instance.stubs(:backup) # Don't backup to the filebucket
catalog = Puppet::Resource::Catalog.new
catalog.host_config = false
resources.each do |resource|
resource.expects(:err).never
catalog.add_resource(resource)
end
catalog.apply
end
it "should not complain about empty lines and comments" do
described_class.expects(:flush).never
sample = ['',sample_lines[0],' ',sample_lines[1],'# just a comment','#and another']
create_fake_key(:user,sample)
run_in_catalog(dummy)
check_fake_key(:user, sample)
end
it "should keep empty lines and comments when modifying a file" do
create_fake_key(:user, ['',sample_lines[0],' ',sample_lines[3],'# just a comment','#and another'])
run_in_catalog(dummy)
check_fake_key(:user, ['',sample_lines[0],' ','# just a comment','#and another'])
end
describe "when managing one resource" do
describe "with ensure set to absent" do
let :resource do
Puppet::Type.type(:ssh_authorized_key).new(
:name => 'root@hostname',
:type => :rsa,
:key => sample_rsa_keys[0],
:target => fake_rootfile,
:user => 'root',
:ensure => :absent
)
end
it "should not modify root's keyfile if resource is currently not present" do
create_fake_key(:root, sample_lines)
run_in_catalog(resource)
check_fake_key(:root, sample_lines)
end
it "remove the key from root's keyfile if resource is currently present" do
create_fake_key(:root, sample_lines + ["ssh-rsa #{sample_rsa_keys[0]} root@hostname"])
run_in_catalog(resource)
check_fake_key(:root, sample_lines)
end
end
describe "when ensure is present" do
let :resource do
Puppet::Type.type(:ssh_authorized_key).new(
:name => 'root@hostname',
:type => :rsa,
:key => sample_rsa_keys[0],
:target => fake_rootfile,
:user => 'root',
:ensure => :present
)
end
# just a dummy so the parsedfile provider is aware
# of the user's authorized_keys file
it "should add the key if it is not present" do
create_fake_key(:root, sample_lines)
run_in_catalog(resource)
check_fake_key(:root, sample_lines + ["ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
end
it "should modify the type if type is out of sync" do
create_fake_key(:root,sample_lines + [ "ssh-dss #{sample_rsa_keys[0]} root@hostname" ])
run_in_catalog(resource)
check_fake_key(:root, sample_lines + [ "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
end
it "should modify the key if key is out of sync" do
create_fake_key(:root,sample_lines + [ "ssh-rsa #{sample_rsa_keys[1]} root@hostname" ])
run_in_catalog(resource)
check_fake_key(:root, sample_lines + [ "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
end
it "should remove the key from old file if target is out of sync" do
create_fake_key(:user, [ sample_lines[0], "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
create_fake_key(:root, [ sample_lines[1], sample_lines[2] ])
run_in_catalog(resource, dummy)
check_fake_key(:user, [ sample_lines[0] ])
#check_fake_key(:root, [ sample_lines[1], sample_lines[2], "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
end
it "should add the key to new file if target is out of sync" do
create_fake_key(:user, [ sample_lines[0], "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
create_fake_key(:root, [ sample_lines[1], sample_lines[2] ])
run_in_catalog(resource, dummy)
#check_fake_key(:user, [ sample_lines[0] ])
check_fake_key(:root, [ sample_lines[1], sample_lines[2], "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
end
it "should modify options if options are out of sync" do
resource[:options]=[ 'from="*.domain1,host1.domain2"', 'no-port-forwarding', 'no-pty' ]
create_fake_key(:root, sample_lines + [ "from=\"*.false,*.false2\",no-port-forwarding,no-pty ssh-rsa #{sample_rsa_keys[0]} root@hostname"])
run_in_catalog(resource)
check_fake_key(:root, sample_lines + [ "from=\"*.domain1,host1.domain2\",no-port-forwarding,no-pty ssh-rsa #{sample_rsa_keys[0]} root@hostname"] )
end
end
end
describe "when managing two resource" do
let :examples do
resources = []
resources << Puppet::Type.type(:ssh_authorized_key).new(
:name => 'root@hostname',
:type => :rsa,
:key => sample_rsa_keys[0],
:target => fake_rootfile,
:user => 'root',
:ensure => :present
)
resources << Puppet::Type.type(:ssh_authorized_key).new(
:name => 'user@hostname',
:key => sample_rsa_keys[1],
:type => :rsa,
:target => fake_userfile,
:user => 'nobody',
:ensure => :present
)
resources
end
describe "and both keys are absent" do
before :each do
create_fake_key(:root, sample_lines)
create_fake_key(:user, sample_lines)
end
it "should add both keys" do
run_in_catalog(*examples)
check_fake_key(:root, sample_lines + [ "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
check_fake_key(:user, sample_lines + [ "ssh-rsa #{sample_rsa_keys[1]} user@hostname" ])
end
end
end
end
diff --git a/spec/integration/reference/providers_spec.rb b/spec/integration/reference/providers_spec.rb
index f2e999e3f..bb5a56ce9 100755
--- a/spec/integration/reference/providers_spec.rb
+++ b/spec/integration/reference/providers_spec.rb
@@ -1,16 +1,16 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/reference'
reference = Puppet::Util::Reference.reference(:providers)
describe reference do
it "should exist" do
- reference.should_not be_nil
+ expect(reference).not_to be_nil
end
it "should be able to be rendered as markdown" do
reference.to_markdown
end
end
diff --git a/spec/integration/reports_spec.rb b/spec/integration/reports_spec.rb
index 2c2c76c72..28eb8d936 100755
--- a/spec/integration/reports_spec.rb
+++ b/spec/integration/reports_spec.rb
@@ -1,14 +1,14 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/reports'
describe Puppet::Reports, " when using report types" do
before do
Puppet.settings.stubs(:use)
end
it "should load report types as modules" do
- Puppet::Reports.report(:store).should be_instance_of(Module)
+ expect(Puppet::Reports.report(:store)).to be_instance_of(Module)
end
end
diff --git a/spec/integration/resource/catalog_spec.rb b/spec/integration/resource/catalog_spec.rb
index 583792103..c117e1474 100755
--- a/spec/integration/resource/catalog_spec.rb
+++ b/spec/integration/resource/catalog_spec.rb
@@ -1,54 +1,54 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Resource::Catalog do
it "should support pson" do
- Puppet::Resource::Catalog.supported_formats.should be_include(:pson)
+ expect(Puppet::Resource::Catalog.supported_formats).to be_include(:pson)
end
describe "when using the indirector" do
before do
# This is so the tests work w/out networking.
Facter.stubs(:to_hash).returns({"hostname" => "foo.domain.com"})
Facter.stubs(:value).returns("eh")
end
it "should be able to delegate to the :yaml terminus" do
Puppet::Resource::Catalog.indirection.stubs(:terminus_class).returns :yaml
# Load now, before we stub the exists? method.
terminus = Puppet::Resource::Catalog.indirection.terminus(:yaml)
terminus.expects(:path).with("me").returns "/my/yaml/file"
Puppet::FileSystem.expects(:exist?).with("/my/yaml/file").returns false
- Puppet::Resource::Catalog.indirection.find("me").should be_nil
+ expect(Puppet::Resource::Catalog.indirection.find("me")).to be_nil
end
it "should be able to delegate to the :compiler terminus" do
Puppet::Resource::Catalog.indirection.stubs(:terminus_class).returns :compiler
# Load now, before we stub the exists? method.
compiler = Puppet::Resource::Catalog.indirection.terminus(:compiler)
node = mock 'node'
node.stub_everything
Puppet::Node.indirection.expects(:find).returns(node)
compiler.expects(:compile).with(node).returns nil
- Puppet::Resource::Catalog.indirection.find("me").should be_nil
+ expect(Puppet::Resource::Catalog.indirection.find("me")).to be_nil
end
it "should pass provided node information directly to the terminus" do
terminus = mock 'terminus'
Puppet::Resource::Catalog.indirection.stubs(:terminus).returns terminus
node = mock 'node'
terminus.stubs(:validate)
terminus.expects(:find).with { |request| request.options[:use_node] == node }
Puppet::Resource::Catalog.indirection.find("me", :use_node => node)
end
end
end
diff --git a/spec/integration/resource/type_collection_spec.rb b/spec/integration/resource/type_collection_spec.rb
index 7ce2a8bc6..c08da5560 100755
--- a/spec/integration/resource/type_collection_spec.rb
+++ b/spec/integration/resource/type_collection_spec.rb
@@ -1,79 +1,79 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/resource/type_collection'
describe Puppet::Resource::TypeCollection do
describe "when autoloading from modules" do
include PuppetSpec::Files
before do
@dir = tmpfile("autoload_testing")
FileUtils.mkdir_p @dir
environment = Puppet::Node::Environment.create(:env, [@dir])
@code = environment.known_resource_types
end
# Setup a module.
def mk_module(name, files = {})
mdir = File.join(@dir, name)
mandir = File.join(mdir, "manifests")
FileUtils.mkdir_p mandir
defs = files.delete(:define)
Dir.chdir(mandir) do
files.each do |file, classes|
File.open("#{file}.pp", "w") do |f|
classes.each { |klass|
if defs
f.puts "define #{klass} {}"
else
f.puts "class #{klass} {}"
end
}
end
end
end
end
it "should return nil when a class can't be found or loaded" do
- @code.find_hostclass('nosuchclass').should be_nil
+ expect(@code.find_hostclass('nosuchclass')).to be_nil
end
it "should load the module's init file first" do
name = "simple"
mk_module(name, :init => [name])
- @code.find_hostclass(name).name.should == name
+ expect(@code.find_hostclass(name).name).to eq(name)
end
it "should be able to load definitions from the module base file" do
name = "simpdef"
mk_module(name, :define => true, :init => [name])
- @code.find_definition(name).name.should == name
+ expect(@code.find_definition(name).name).to eq(name)
end
it "should be able to load qualified classes from the module base file" do
mk_module('both', :init => %w{both both::sub})
- @code.find_hostclass("both::sub").name.should == "both::sub"
+ expect(@code.find_hostclass("both::sub").name).to eq("both::sub")
end
it "should be able load classes from a separate file" do
mk_module('separate', :init => %w{separate}, :sub => %w{separate::sub})
- @code.find_hostclass("separate::sub").name.should == "separate::sub"
+ expect(@code.find_hostclass("separate::sub").name).to eq("separate::sub")
end
it "should not fail when loading from a separate file if there is no module file" do
mk_module('alone', :sub => %w{alone::sub})
- lambda { @code.find_hostclass("alone::sub") }.should_not raise_error
+ expect { @code.find_hostclass("alone::sub") }.not_to raise_error
end
it "should be able to load definitions from their own file" do
name = "mymod"
mk_module(name, :define => true, :mydefine => ["mymod::mydefine"])
- @code.find_definition("mymod::mydefine").name.should == "mymod::mydefine"
+ expect(@code.find_definition("mymod::mydefine").name).to eq("mymod::mydefine")
end
end
end
diff --git a/spec/integration/ssl/autosign_spec.rb b/spec/integration/ssl/autosign_spec.rb
index 2812d1fcc..68fde58f4 100644
--- a/spec/integration/ssl/autosign_spec.rb
+++ b/spec/integration/ssl/autosign_spec.rb
@@ -1,130 +1,130 @@
require 'spec_helper'
describe "autosigning" do
include PuppetSpec::Files
let(:puppet_dir) { tmpdir("ca_autosigning") }
let(:csr_attributes_content) do
{
'custom_attributes' => {
'1.3.6.1.4.1.34380.2.0' => 'hostname.domain.com',
'1.3.6.1.4.1.34380.2.1' => 'my passphrase',
'1.3.6.1.4.1.34380.2.2' => # system IPs in hex
[ 0xC0A80001, # 192.168.0.1
0xC0A80101 ], # 192.168.1.1
},
'extension_requests' => {
'pp_uuid' => 'abcdef',
'1.3.6.1.4.1.34380.1.1.2' => '1234', # pp_instance_id
'1.3.6.1.4.1.34380.1.2.1' => 'some-value', # private extension
},
}
end
let(:host) { Puppet::SSL::Host.new }
before do
Puppet.settings[:confdir] = puppet_dir
Puppet.settings[:vardir] = puppet_dir
# This is necessary so the terminus instances don't lie around.
Puppet::SSL::Key.indirection.termini.clear
end
def write_csr_attributes(yaml)
File.open(Puppet.settings[:csr_attributes], 'w') do |file|
file.puts YAML.dump(yaml)
end
end
context "when the csr_attributes file is valid, but empty" do
it "generates a CSR when the file is empty" do
Puppet::FileSystem.touch(Puppet.settings[:csr_attributes])
host.generate_certificate_request
end
it "generates a CSR when the file contains whitespace" do
File.open(Puppet.settings[:csr_attributes], 'w') do |file|
file.puts "\n\n"
end
host.generate_certificate_request
end
end
context "when the csr_attributes file doesn't contain a YAML encoded hash" do
it "raises when the file contains a string" do
write_csr_attributes('a string')
expect {
host.generate_certificate_request
}.to raise_error(Puppet::Error, /invalid CSR attributes, expected instance of Hash, received instance of String/)
end
it "raises when the file contains an empty array" do
write_csr_attributes([])
expect {
host.generate_certificate_request
}.to raise_error(Puppet::Error, /invalid CSR attributes, expected instance of Hash, received instance of Array/)
end
end
context "with extension requests from csr_attributes file" do
let(:ca) { Puppet::SSL::CertificateAuthority.new }
it "generates a CSR when the csr_attributes file is an empty hash" do
write_csr_attributes(csr_attributes_content)
host.generate_certificate_request
end
context "and subjectAltName" do
it "raises an error if you include subjectAltName in csr_attributes" do
csr_attributes_content['extension_requests']['subjectAltName'] = 'foo'
write_csr_attributes(csr_attributes_content)
expect { host.generate_certificate_request }.to raise_error(Puppet::Error, /subjectAltName.*conflicts with internally used extension request/)
end
it "properly merges subjectAltName when in settings" do
Puppet.settings[:dns_alt_names] = 'althostname.nowhere'
write_csr_attributes(csr_attributes_content)
host.generate_certificate_request
csr = Puppet::SSL::CertificateRequest.indirection.find(host.name)
expect(csr.subject_alt_names).to include('DNS:althostname.nowhere')
end
end
context "without subjectAltName" do
before do
write_csr_attributes(csr_attributes_content)
host.generate_certificate_request
end
it "pulls extension attributes from the csr_attributes file into the certificate" do
csr = Puppet::SSL::CertificateRequest.indirection.find(host.name)
expect(csr.request_extensions).to have(3).items
expect(csr.request_extensions).to include('oid' => 'pp_uuid', 'value' => 'abcdef')
expect(csr.request_extensions).to include('oid' => 'pp_instance_id', 'value' => '1234')
expect(csr.request_extensions).to include('oid' => '1.3.6.1.4.1.34380.1.2.1', 'value' => 'some-value')
end
it "copies extension requests to certificate" do
cert = ca.sign(host.name)
expect(cert.custom_extensions).to include('oid' => 'pp_uuid', 'value' => 'abcdef')
expect(cert.custom_extensions).to include('oid' => 'pp_instance_id', 'value' => '1234')
expect(cert.custom_extensions).to include('oid' => '1.3.6.1.4.1.34380.1.2.1', 'value' => 'some-value')
end
it "does not copy custom attributes to certificate" do
cert = ca.sign(host.name)
cert.custom_extensions.each do |ext|
- expect(Puppet::SSL::Oids.subtree_of?('1.3.6.1.4.1.34380.2', ext['oid'])).to be_false
+ expect(Puppet::SSL::Oids.subtree_of?('1.3.6.1.4.1.34380.2', ext['oid'])).to be_falsey
end
end
end
end
end
diff --git a/spec/integration/ssl/certificate_authority_spec.rb b/spec/integration/ssl/certificate_authority_spec.rb
index 3cf494afa..b0f83e6a3 100755
--- a/spec/integration/ssl/certificate_authority_spec.rb
+++ b/spec/integration/ssl/certificate_authority_spec.rb
@@ -1,163 +1,163 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/certificate_authority'
describe Puppet::SSL::CertificateAuthority, :unless => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
let(:ca) { @ca }
before do
dir = tmpdir("ca_integration_testing")
Puppet.settings[:confdir] = dir
Puppet.settings[:vardir] = dir
Puppet.settings[:group] = Process.gid
Puppet::SSL::Host.ca_location = :local
# this has the side-effect of creating the various directories that we need
@ca = Puppet::SSL::CertificateAuthority.new
end
it "should be able to generate a new host certificate" do
ca.generate("newhost")
- Puppet::SSL::Certificate.indirection.find("newhost").should be_instance_of(Puppet::SSL::Certificate)
+ expect(Puppet::SSL::Certificate.indirection.find("newhost")).to be_instance_of(Puppet::SSL::Certificate)
end
it "should be able to revoke a host certificate" do
ca.generate("newhost")
ca.revoke("newhost")
expect { ca.verify("newhost") }.to raise_error(Puppet::SSL::CertificateAuthority::CertificateVerificationError, "certificate revoked")
end
describe "when signing certificates" do
it "should save the signed certificate" do
host = certificate_request_for("luke.madstop.com")
ca.sign("luke.madstop.com")
- Puppet::SSL::Certificate.indirection.find("luke.madstop.com").should be_instance_of(Puppet::SSL::Certificate)
+ expect(Puppet::SSL::Certificate.indirection.find("luke.madstop.com")).to be_instance_of(Puppet::SSL::Certificate)
end
it "should be able to sign multiple certificates" do
host = certificate_request_for("luke.madstop.com")
other = certificate_request_for("other.madstop.com")
ca.sign("luke.madstop.com")
ca.sign("other.madstop.com")
- Puppet::SSL::Certificate.indirection.find("other.madstop.com").should be_instance_of(Puppet::SSL::Certificate)
- Puppet::SSL::Certificate.indirection.find("luke.madstop.com").should be_instance_of(Puppet::SSL::Certificate)
+ expect(Puppet::SSL::Certificate.indirection.find("other.madstop.com")).to be_instance_of(Puppet::SSL::Certificate)
+ expect(Puppet::SSL::Certificate.indirection.find("luke.madstop.com")).to be_instance_of(Puppet::SSL::Certificate)
end
it "should save the signed certificate to the :signeddir" do
host = certificate_request_for("luke.madstop.com")
ca.sign("luke.madstop.com")
client_cert = File.join(Puppet[:signeddir], "luke.madstop.com.pem")
- File.read(client_cert).should == Puppet::SSL::Certificate.indirection.find("luke.madstop.com").content.to_s
+ expect(File.read(client_cert)).to eq(Puppet::SSL::Certificate.indirection.find("luke.madstop.com").content.to_s)
end
it "should save valid certificates" do
host = certificate_request_for("luke.madstop.com")
ca.sign("luke.madstop.com")
unless ssl = Puppet::Util::which('openssl')
pending "No ssl available"
else
ca_cert = Puppet[:cacert]
client_cert = File.join(Puppet[:signeddir], "luke.madstop.com.pem")
output = %x{openssl verify -CAfile #{ca_cert} #{client_cert}}
- $CHILD_STATUS.should == 0
+ expect($CHILD_STATUS).to eq(0)
end
end
it "should verify proof of possession when signing certificates" do
host = certificate_request_for("luke.madstop.com")
csr = host.certificate_request
wrong_key = Puppet::SSL::Key.new(host.name)
wrong_key.generate
csr.content.public_key = wrong_key.content.public_key
# The correct key has to be removed so we can save the incorrect one
Puppet::SSL::CertificateRequest.indirection.destroy(host.name)
Puppet::SSL::CertificateRequest.indirection.save(csr)
expect {
ca.sign(host.name)
}.to raise_error(
Puppet::SSL::CertificateAuthority::CertificateSigningError,
"CSR contains a public key that does not correspond to the signing key"
)
end
end
describe "when revoking certificate" do
it "should work for one certificate" do
certificate_request_for("luke.madstop.com")
ca.sign("luke.madstop.com")
ca.revoke("luke.madstop.com")
expect { ca.verify("luke.madstop.com") }.to raise_error(
Puppet::SSL::CertificateAuthority::CertificateVerificationError,
"certificate revoked"
)
end
it "should work for several certificates" do
3.times.each do |c|
certificate_request_for("luke.madstop.com")
ca.sign("luke.madstop.com")
ca.destroy("luke.madstop.com")
end
ca.revoke("luke.madstop.com")
- ca.crl.content.revoked.map { |r| r.serial }.should == [2,3,4] # ca has serial 1
+ expect(ca.crl.content.revoked.map { |r| r.serial }).to eq([2,3,4]) # ca has serial 1
end
end
it "allows autosigning certificates concurrently", :unless => Puppet::Util::Platform.windows? do
Puppet[:autosign] = true
hosts = (0..4).collect { |i| certificate_request_for("host#{i}") }
run_in_parallel(5) do |i|
ca.autosign(Puppet::SSL::CertificateRequest.indirection.find(hosts[i].name))
end
certs = hosts.collect { |host| Puppet::SSL::Certificate.indirection.find(host.name).content }
serial_numbers = certs.collect(&:serial)
- serial_numbers.sort.should == [2, 3, 4, 5, 6] # serial 1 is the ca certificate
+ expect(serial_numbers.sort).to eq([2, 3, 4, 5, 6]) # serial 1 is the ca certificate
end
def certificate_request_for(hostname)
key = Puppet::SSL::Key.new(hostname)
key.generate
host = Puppet::SSL::Host.new(hostname)
host.key = key
host.generate_certificate_request
host
end
def run_in_parallel(number)
children = []
number.times do |i|
children << Kernel.fork do
yield i
end
end
children.each { |pid| Process.wait(pid) }
end
end
diff --git a/spec/integration/ssl/certificate_request_spec.rb b/spec/integration/ssl/certificate_request_spec.rb
index eeb29da79..b3f924027 100755
--- a/spec/integration/ssl/certificate_request_spec.rb
+++ b/spec/integration/ssl/certificate_request_spec.rb
@@ -1,48 +1,48 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/certificate_request'
describe Puppet::SSL::CertificateRequest do
include PuppetSpec::Files
before do
# Get a safe temporary file
dir = tmpdir("csr_integration_testing")
Puppet.settings[:confdir] = dir
Puppet.settings[:vardir] = dir
Puppet.settings[:group] = Process.gid
Puppet::SSL::Host.ca_location = :none
@csr = Puppet::SSL::CertificateRequest.new("luke.madstop.com")
@key = OpenSSL::PKey::RSA.new(512)
# This is necessary so the terminus instances don't lie around.
Puppet::SSL::CertificateRequest.indirection.termini.clear
end
it "should be able to generate CSRs" do
@csr.generate(@key)
end
it "should be able to save CSRs" do
Puppet::SSL::CertificateRequest.indirection.save(@csr)
end
it "should be able to find saved certificate requests via the Indirector" do
@csr.generate(@key)
Puppet::SSL::CertificateRequest.indirection.save(@csr)
- Puppet::SSL::CertificateRequest.indirection.find("luke.madstop.com").should be_instance_of(Puppet::SSL::CertificateRequest)
+ expect(Puppet::SSL::CertificateRequest.indirection.find("luke.madstop.com")).to be_instance_of(Puppet::SSL::CertificateRequest)
end
it "should save the completely CSR when saving" do
@csr.generate(@key)
Puppet::SSL::CertificateRequest.indirection.save(@csr)
- Puppet::SSL::CertificateRequest.indirection.find("luke.madstop.com").content.to_s.should == @csr.content.to_s
+ expect(Puppet::SSL::CertificateRequest.indirection.find("luke.madstop.com").content.to_s).to eq(@csr.content.to_s)
end
end
diff --git a/spec/integration/ssl/host_spec.rb b/spec/integration/ssl/host_spec.rb
index 18f0d17fc..2ff409b47 100755
--- a/spec/integration/ssl/host_spec.rb
+++ b/spec/integration/ssl/host_spec.rb
@@ -1,82 +1,82 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/host'
describe Puppet::SSL::Host do
include PuppetSpec::Files
before do
# Get a safe temporary file
dir = tmpdir("host_integration_testing")
Puppet.settings[:confdir] = dir
Puppet.settings[:vardir] = dir
Puppet.settings[:group] = Process.gid
Puppet::SSL::Host.ca_location = :local
@host = Puppet::SSL::Host.new("luke.madstop.com")
@ca = Puppet::SSL::CertificateAuthority.new
end
after {
Puppet::SSL::Host.ca_location = :none
}
it "should be considered a CA host if its name is equal to 'ca'" do
- Puppet::SSL::Host.new(Puppet::SSL::CA_NAME).should be_ca
+ expect(Puppet::SSL::Host.new(Puppet::SSL::CA_NAME)).to be_ca
end
describe "when managing its key" do
it "should be able to generate and save a key" do
@host.generate_key
end
it "should save the key such that the Indirector can find it" do
@host.generate_key
- Puppet::SSL::Key.indirection.find(@host.name).content.to_s.should == @host.key.to_s
+ expect(Puppet::SSL::Key.indirection.find(@host.name).content.to_s).to eq(@host.key.to_s)
end
it "should save the private key into the :privatekeydir" do
@host.generate_key
- File.read(File.join(Puppet.settings[:privatekeydir], "luke.madstop.com.pem")).should == @host.key.to_s
+ expect(File.read(File.join(Puppet.settings[:privatekeydir], "luke.madstop.com.pem"))).to eq(@host.key.to_s)
end
end
describe "when managing its certificate request" do
it "should be able to generate and save a certificate request" do
@host.generate_certificate_request
end
it "should save the certificate request such that the Indirector can find it" do
@host.generate_certificate_request
- Puppet::SSL::CertificateRequest.indirection.find(@host.name).content.to_s.should == @host.certificate_request.to_s
+ expect(Puppet::SSL::CertificateRequest.indirection.find(@host.name).content.to_s).to eq(@host.certificate_request.to_s)
end
it "should save the private certificate request into the :privatekeydir" do
@host.generate_certificate_request
- File.read(File.join(Puppet.settings[:requestdir], "luke.madstop.com.pem")).should == @host.certificate_request.to_s
+ expect(File.read(File.join(Puppet.settings[:requestdir], "luke.madstop.com.pem"))).to eq(@host.certificate_request.to_s)
end
end
describe "when the CA host" do
it "should never store its key in the :privatekeydir" do
Puppet.settings.use(:main, :ssl, :ca)
@ca = Puppet::SSL::Host.new(Puppet::SSL::Host.ca_name)
@ca.generate_key
- Puppet::FileSystem.exist?(File.join(Puppet[:privatekeydir], "ca.pem")).should be_false
+ expect(Puppet::FileSystem.exist?(File.join(Puppet[:privatekeydir], "ca.pem"))).to be_falsey
end
end
it "should pass the verification of its own SSL store", :unless => Puppet.features.microsoft_windows? do
@host.generate
@ca = Puppet::SSL::CertificateAuthority.new
@ca.sign(@host.name)
- @host.ssl_store.verify(@host.certificate.content).should be_true
+ expect(@host.ssl_store.verify(@host.certificate.content)).to be_truthy
end
end
diff --git a/spec/integration/transaction_spec.rb b/spec/integration/transaction_spec.rb
index 7ae28411a..26fd1cb35 100755
--- a/spec/integration/transaction_spec.rb
+++ b/spec/integration/transaction_spec.rb
@@ -1,398 +1,398 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/transaction'
describe Puppet::Transaction do
include PuppetSpec::Files
before do
Puppet::Util::Storage.stubs(:store)
end
def mk_catalog(*resources)
catalog = Puppet::Resource::Catalog.new(Puppet::Node.new("mynode"))
resources.each { |res| catalog.add_resource res }
catalog
end
def touch_path
Puppet.features.microsoft_windows? ? "#{ENV['windir']}/system32" : "/usr/bin:/bin"
end
def usr_bin_touch(path)
Puppet.features.microsoft_windows? ? "#{ENV['windir']}/system32/cmd.exe /c \"type NUL >> \"#{path}\"\"" : "/usr/bin/touch #{path}"
end
def touch(path)
Puppet.features.microsoft_windows? ? "cmd.exe /c \"type NUL >> \"#{path}\"\"" : "touch #{path}"
end
it "should not apply generated resources if the parent resource fails" do
catalog = Puppet::Resource::Catalog.new
resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar"), :backup => false
catalog.add_resource resource
child_resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar/baz"), :backup => false
resource.expects(:eval_generate).returns([child_resource])
transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::RandomPrioritizer.new)
resource.expects(:retrieve).raises "this is a failure"
resource.stubs(:err)
child_resource.expects(:retrieve).never
transaction.evaluate
end
it "should not apply virtual resources" do
catalog = Puppet::Resource::Catalog.new
resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar"), :backup => false
resource.virtual = true
catalog.add_resource resource
transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::RandomPrioritizer.new)
resource.expects(:evaluate).never
transaction.evaluate
end
it "should apply exported resources" do
catalog = Puppet::Resource::Catalog.new
path = tmpfile("exported_files")
resource = Puppet::Type.type(:file).new :path => path, :backup => false, :ensure => :file
resource.exported = true
catalog.add_resource resource
catalog.apply
- Puppet::FileSystem.exist?(path).should be_true
+ expect(Puppet::FileSystem.exist?(path)).to be_truthy
end
it "should not apply virtual exported resources" do
catalog = Puppet::Resource::Catalog.new
resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar"), :backup => false
resource.exported = true
resource.virtual = true
catalog.add_resource resource
transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::RandomPrioritizer.new)
resource.expects(:evaluate).never
transaction.evaluate
end
it "should not apply device resources on normal host" do
catalog = Puppet::Resource::Catalog.new
resource = Puppet::Type.type(:interface).new :name => "FastEthernet 0/1"
catalog.add_resource resource
transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::RandomPrioritizer.new)
transaction.for_network_device = false
transaction.expects(:apply).never.with(resource, nil)
transaction.evaluate
- transaction.resource_status(resource).should be_skipped
+ expect(transaction.resource_status(resource)).to be_skipped
end
it "should not apply host resources on device" do
catalog = Puppet::Resource::Catalog.new
resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar"), :backup => false
catalog.add_resource resource
transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::RandomPrioritizer.new)
transaction.for_network_device = true
transaction.expects(:apply).never.with(resource, nil)
transaction.evaluate
- transaction.resource_status(resource).should be_skipped
+ expect(transaction.resource_status(resource)).to be_skipped
end
it "should apply device resources on device" do
catalog = Puppet::Resource::Catalog.new
resource = Puppet::Type.type(:interface).new :name => "FastEthernet 0/1"
catalog.add_resource resource
transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::RandomPrioritizer.new)
transaction.for_network_device = true
transaction.expects(:apply).with(resource, nil)
transaction.evaluate
- transaction.resource_status(resource).should_not be_skipped
+ expect(transaction.resource_status(resource)).not_to be_skipped
end
it "should apply resources appliable on host and device on a device" do
catalog = Puppet::Resource::Catalog.new
resource = Puppet::Type.type(:schedule).new :name => "test"
catalog.add_resource resource
transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::RandomPrioritizer.new)
transaction.for_network_device = true
transaction.expects(:apply).with(resource, nil)
transaction.evaluate
- transaction.resource_status(resource).should_not be_skipped
+ expect(transaction.resource_status(resource)).not_to be_skipped
end
# Verify that one component requiring another causes the contained
# resources in the requiring component to get refreshed.
it "should propagate events from a contained resource through its container to its dependent container's contained resources" do
transaction = nil
file = Puppet::Type.type(:file).new :path => tmpfile("event_propagation"), :ensure => :present
execfile = File.join(tmpdir("exec_event"), "exectestingness2")
exec = Puppet::Type.type(:exec).new :command => touch(execfile), :path => ENV['PATH']
catalog = mk_catalog(file)
fcomp = Puppet::Type.type(:component).new(:name => "Foo[file]")
catalog.add_resource fcomp
catalog.add_edge(fcomp, file)
ecomp = Puppet::Type.type(:component).new(:name => "Foo[exec]")
catalog.add_resource ecomp
catalog.add_resource exec
catalog.add_edge(ecomp, exec)
ecomp[:subscribe] = Puppet::Resource.new(:foo, "file")
exec[:refreshonly] = true
exec.expects(:refresh)
catalog.apply
end
# Make sure that multiple subscriptions get triggered.
it "should propagate events to all dependent resources" do
path = tmpfile("path")
file1 = tmpfile("file1")
file2 = tmpfile("file2")
file = Puppet::Type.type(:file).new(
:path => path,
:ensure => "file"
)
exec1 = Puppet::Type.type(:exec).new(
:path => ENV["PATH"],
:command => touch(file1),
:refreshonly => true,
:subscribe => Puppet::Resource.new(:file, path)
)
exec2 = Puppet::Type.type(:exec).new(
:path => ENV["PATH"],
:command => touch(file2),
:refreshonly => true,
:subscribe => Puppet::Resource.new(:file, path)
)
catalog = mk_catalog(file, exec1, exec2)
catalog.apply
- Puppet::FileSystem.exist?(file1).should be_true
- Puppet::FileSystem.exist?(file2).should be_true
+ expect(Puppet::FileSystem.exist?(file1)).to be_truthy
+ expect(Puppet::FileSystem.exist?(file2)).to be_truthy
end
it "does not refresh resources that have 'noop => true'" do
path = tmpfile("path")
notify = Puppet::Type.type(:notify).new(
:name => "trigger",
:notify => Puppet::Resource.new(:exec, "noop exec")
)
noop_exec = Puppet::Type.type(:exec).new(
:name => "noop exec",
:path => ENV["PATH"],
:command => touch(path),
:noop => true
)
catalog = mk_catalog(notify, noop_exec)
catalog.apply
- Puppet::FileSystem.exist?(path).should be_false
+ expect(Puppet::FileSystem.exist?(path)).to be_falsey
end
it "should apply no resources whatsoever if a pre_run_check fails" do
path = tmpfile("path")
file = Puppet::Type.type(:file).new(
:path => path,
:ensure => "file"
)
notify = Puppet::Type.type(:notify).new(
:title => "foo"
)
notify.expects(:pre_run_check).raises(Puppet::Error, "fail for testing")
catalog = mk_catalog(file, notify)
catalog.apply
- Puppet::FileSystem.exist?(path).should_not be_true
+ expect(Puppet::FileSystem.exist?(path)).not_to be_truthy
end
it "should not let one failed refresh result in other refreshes failing" do
path = tmpfile("path")
newfile = tmpfile("file")
file = Puppet::Type.type(:file).new(
:path => path,
:ensure => "file"
)
exec1 = Puppet::Type.type(:exec).new(
:path => ENV["PATH"],
:command => touch(File.expand_path("/this/cannot/possibly/exist")),
:logoutput => true,
:refreshonly => true,
:subscribe => file,
:title => "one"
)
exec2 = Puppet::Type.type(:exec).new(
:path => ENV["PATH"],
:command => touch(newfile),
:logoutput => true,
:refreshonly => true,
:subscribe => [file, exec1],
:title => "two"
)
exec1.stubs(:err)
catalog = mk_catalog(file, exec1, exec2)
catalog.apply
- Puppet::FileSystem.exist?(newfile).should be_true
+ expect(Puppet::FileSystem.exist?(newfile)).to be_truthy
end
describe "skipping resources" do
let(:fname) { tmpfile("exec") }
let(:file) do
Puppet::Type.type(:file).new(
:name => tmpfile("file"),
:ensure => "file",
:backup => false
)
end
let(:exec) do
Puppet::Type.type(:exec).new(
:name => touch(fname),
:path => touch_path,
:subscribe => Puppet::Resource.new("file", file.name)
)
end
it "does not trigger unscheduled resources" do
catalog = mk_catalog
catalog.add_resource(*Puppet::Type.type(:schedule).mkdefaultschedules)
Puppet[:ignoreschedules] = false
exec[:schedule] = "monthly"
catalog.add_resource(file, exec)
# Run it once so further runs don't schedule the resource
catalog.apply
- expect(Puppet::FileSystem.exist?(fname)).to be_true
+ expect(Puppet::FileSystem.exist?(fname)).to be_truthy
# Now remove it, so it can get created again
Puppet::FileSystem.unlink(fname)
file[:content] = "some content"
catalog.apply
- expect(Puppet::FileSystem.exist?(fname)).to be_false
+ expect(Puppet::FileSystem.exist?(fname)).to be_falsey
end
it "does not trigger untagged resources" do
catalog = mk_catalog
Puppet[:tags] = "runonly"
file.tag("runonly")
catalog.add_resource(file, exec)
catalog.apply
- expect(Puppet::FileSystem.exist?(fname)).to be_false
+ expect(Puppet::FileSystem.exist?(fname)).to be_falsey
end
it "does not trigger resources with failed dependencies" do
catalog = mk_catalog
file[:path] = make_absolute("/foo/bar/baz")
catalog.add_resource(file, exec)
catalog.apply
- expect(Puppet::FileSystem.exist?(fname)).to be_false
+ expect(Puppet::FileSystem.exist?(fname)).to be_falsey
end
end
it "should not attempt to evaluate resources with failed dependencies" do
exec = Puppet::Type.type(:exec).new(
:command => "#{File.expand_path('/bin/mkdir')} /this/path/cannot/possibly/exist",
:title => "mkdir"
)
file1 = Puppet::Type.type(:file).new(
:title => "file1",
:path => tmpfile("file1"),
:require => exec,
:ensure => :file
)
file2 = Puppet::Type.type(:file).new(
:title => "file2",
:path => tmpfile("file2"),
:require => file1,
:ensure => :file
)
catalog = mk_catalog(exec, file1, file2)
catalog.apply
- Puppet::FileSystem.exist?(file1[:path]).should be_false
- Puppet::FileSystem.exist?(file2[:path]).should be_false
+ expect(Puppet::FileSystem.exist?(file1[:path])).to be_falsey
+ expect(Puppet::FileSystem.exist?(file2[:path])).to be_falsey
end
it "should not trigger subscribing resources on failure" do
file1 = tmpfile("file1")
file2 = tmpfile("file2")
create_file1 = Puppet::Type.type(:exec).new(
:command => usr_bin_touch(file1)
)
exec = Puppet::Type.type(:exec).new(
:command => "#{File.expand_path('/bin/mkdir')} /this/path/cannot/possibly/exist",
:title => "mkdir",
:notify => create_file1
)
create_file2 = Puppet::Type.type(:exec).new(
:command => usr_bin_touch(file2),
:subscribe => exec
)
catalog = mk_catalog(exec, create_file1, create_file2)
catalog.apply
- Puppet::FileSystem.exist?(file1).should be_false
- Puppet::FileSystem.exist?(file2).should be_false
+ expect(Puppet::FileSystem.exist?(file1)).to be_falsey
+ expect(Puppet::FileSystem.exist?(file2)).to be_falsey
end
# #801 -- resources only checked in noop should be rescheduled immediately.
it "should immediately reschedule noop resources" do
Puppet::Type.type(:schedule).mkdefaultschedules
resource = Puppet::Type.type(:notify).new(:name => "mymessage", :noop => true)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource resource
trans = catalog.apply
- trans.resource_harness.should be_scheduled(resource)
+ expect(trans.resource_harness).to be_scheduled(resource)
end
end
diff --git a/spec/integration/type/exec_spec.rb b/spec/integration/type/exec_spec.rb
index 1e39bdb9f..d76d91664 100755
--- a/spec/integration/type/exec_spec.rb
+++ b/spec/integration/type/exec_spec.rb
@@ -1,77 +1,77 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
describe Puppet::Type.type(:exec) do
include PuppetSpec::Files
let(:catalog) { Puppet::Resource::Catalog.new }
let(:path) { tmpfile('exec_provider') }
let(:command) { "ruby -e 'File.open(\"#{path}\", \"w\") { |f| f.print \"foo\" }'" }
before :each do
catalog.host_config = false
end
it "should execute the command" do
exec = described_class.new :command => command, :path => ENV['PATH']
catalog.add_resource exec
catalog.apply
- File.read(path).should == 'foo'
+ expect(File.read(path)).to eq('foo')
end
it "should not execute the command if onlyif returns non-zero" do
exec = described_class.new(
:command => command,
:onlyif => "ruby -e 'exit 44'",
:path => ENV['PATH']
)
catalog.add_resource exec
catalog.apply
- Puppet::FileSystem.exist?(path).should be_false
+ expect(Puppet::FileSystem.exist?(path)).to be_falsey
end
it "should execute the command if onlyif returns zero" do
exec = described_class.new(
:command => command,
:onlyif => "ruby -e 'exit 0'",
:path => ENV['PATH']
)
catalog.add_resource exec
catalog.apply
- File.read(path).should == 'foo'
+ expect(File.read(path)).to eq('foo')
end
it "should execute the command if unless returns non-zero" do
exec = described_class.new(
:command => command,
:unless => "ruby -e 'exit 45'",
:path => ENV['PATH']
)
catalog.add_resource exec
catalog.apply
- File.read(path).should == 'foo'
+ expect(File.read(path)).to eq('foo')
end
it "should not execute the command if unless returns zero" do
exec = described_class.new(
:command => command,
:unless => "ruby -e 'exit 0'",
:path => ENV['PATH']
)
catalog.add_resource exec
catalog.apply
- Puppet::FileSystem.exist?(path).should be_false
+ expect(Puppet::FileSystem.exist?(path)).to be_falsey
end
end
diff --git a/spec/integration/type/file_spec.rb b/spec/integration/type/file_spec.rb
index b2e9c2e99..c9a0a43ba 100755
--- a/spec/integration/type/file_spec.rb
+++ b/spec/integration/type/file_spec.rb
@@ -1,1300 +1,1300 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
if Puppet.features.microsoft_windows?
require 'puppet/util/windows'
class WindowsSecurity
extend Puppet::Util::Windows::Security
end
end
describe Puppet::Type.type(:file), :uses_checksums => true do
include PuppetSpec::Files
let(:catalog) { Puppet::Resource::Catalog.new }
let(:path) do
# we create a directory first so backups of :path that are stored in
# the same directory will also be removed after the tests
parent = tmpdir('file_spec')
File.join(parent, 'file_testing')
end
let(:dir) do
# we create a directory first so backups of :path that are stored in
# the same directory will also be removed after the tests
parent = tmpdir('file_spec')
File.join(parent, 'dir_testing')
end
if Puppet.features.posix?
def set_mode(mode, file)
File.chmod(mode, file)
end
def get_mode(file)
Puppet::FileSystem.lstat(file).mode
end
def get_owner(file)
Puppet::FileSystem.lstat(file).uid
end
def get_group(file)
Puppet::FileSystem.lstat(file).gid
end
else
class SecurityHelper
extend Puppet::Util::Windows::Security
end
def set_mode(mode, file)
SecurityHelper.set_mode(mode, file)
end
def get_mode(file)
SecurityHelper.get_mode(file)
end
def get_owner(file)
SecurityHelper.get_owner(file)
end
def get_group(file)
SecurityHelper.get_group(file)
end
def get_aces_for_path_by_sid(path, sid)
SecurityHelper.get_aces_for_path_by_sid(path, sid)
end
end
around :each do |example|
Puppet.override(:environments => Puppet::Environments::Static.new) do
example.run
end
end
before do
# stub this to not try to create state.yaml
Puppet::Util::Storage.stubs(:store)
end
it "should not attempt to manage files that do not exist if no means of creating the file is specified" do
source = tmpfile('source')
catalog.add_resource described_class.new :path => source, :mode => '0755'
status = catalog.apply.report.resource_statuses["File[#{source}]"]
- status.should_not be_failed
- status.should_not be_changed
- Puppet::FileSystem.exist?(source).should be_false
+ expect(status).not_to be_failed
+ expect(status).not_to be_changed
+ expect(Puppet::FileSystem.exist?(source)).to be_falsey
end
describe "when ensure is absent" do
it "should remove the file if present" do
FileUtils.touch(path)
catalog.add_resource(described_class.new(:path => path, :ensure => :absent, :backup => :false))
report = catalog.apply.report
- report.resource_statuses["File[#{path}]"].should_not be_failed
- Puppet::FileSystem.exist?(path).should be_false
+ expect(report.resource_statuses["File[#{path}]"]).not_to be_failed
+ expect(Puppet::FileSystem.exist?(path)).to be_falsey
end
it "should do nothing if file is not present" do
catalog.add_resource(described_class.new(:path => path, :ensure => :absent, :backup => :false))
report = catalog.apply.report
- report.resource_statuses["File[#{path}]"].should_not be_failed
- Puppet::FileSystem.exist?(path).should be_false
+ expect(report.resource_statuses["File[#{path}]"]).not_to be_failed
+ expect(Puppet::FileSystem.exist?(path)).to be_falsey
end
# issue #14599
it "should not fail if parts of path aren't directories" do
FileUtils.touch(path)
catalog.add_resource(described_class.new(:path => File.join(path,'no_such_file'), :ensure => :absent, :backup => :false))
report = catalog.apply.report
- report.resource_statuses["File[#{File.join(path,'no_such_file')}]"].should_not be_failed
+ expect(report.resource_statuses["File[#{File.join(path,'no_such_file')}]"]).not_to be_failed
end
end
describe "when setting permissions" do
it "should set the owner" do
target = tmpfile_with_contents('target', '')
owner = get_owner(target)
catalog.add_resource described_class.new(
:name => target,
:owner => owner
)
catalog.apply
- get_owner(target).should == owner
+ expect(get_owner(target)).to eq(owner)
end
it "should set the group" do
target = tmpfile_with_contents('target', '')
group = get_group(target)
catalog.add_resource described_class.new(
:name => target,
:group => group
)
catalog.apply
- get_group(target).should == group
+ expect(get_group(target)).to eq(group)
end
describe "when setting mode" do
describe "for directories" do
let(:target) { tmpdir('dir_mode') }
it "should set executable bits for newly created directories" do
catalog.add_resource described_class.new(:path => target, :ensure => :directory, :mode => '0600')
catalog.apply
- (get_mode(target) & 07777).should == 0700
+ expect(get_mode(target) & 07777).to eq(0700)
end
it "should set executable bits for existing readable directories" do
set_mode(0600, target)
catalog.add_resource described_class.new(:path => target, :ensure => :directory, :mode => '0644')
catalog.apply
- (get_mode(target) & 07777).should == 0755
+ expect(get_mode(target) & 07777).to eq(0755)
end
it "should not set executable bits for unreadable directories" do
begin
catalog.add_resource described_class.new(:path => target, :ensure => :directory, :mode => '0300')
catalog.apply
- (get_mode(target) & 07777).should == 0300
+ expect(get_mode(target) & 07777).to eq(0300)
ensure
# so we can cleanup
set_mode(0700, target)
end
end
it "should set user, group, and other executable bits" do
catalog.add_resource described_class.new(:path => target, :ensure => :directory, :mode => '0664')
catalog.apply
- (get_mode(target) & 07777).should == 0775
+ expect(get_mode(target) & 07777).to eq(0775)
end
it "should set executable bits when overwriting a non-executable file" do
target_path = tmpfile_with_contents('executable', '')
set_mode(0444, target_path)
catalog.add_resource described_class.new(:path => target_path, :ensure => :directory, :mode => '0666', :backup => false)
catalog.apply
- (get_mode(target_path) & 07777).should == 0777
- File.should be_directory(target_path)
+ expect(get_mode(target_path) & 07777).to eq(0777)
+ expect(File).to be_directory(target_path)
end
end
describe "for files" do
it "should not set executable bits" do
catalog.add_resource described_class.new(:path => path, :ensure => :file, :mode => '0666')
catalog.apply
- (get_mode(path) & 07777).should == 0666
+ expect(get_mode(path) & 07777).to eq(0666)
end
it "should not set executable bits when replacing an executable directory (#10365)" do
pending("bug #10365")
FileUtils.mkdir(path)
set_mode(0777, path)
catalog.add_resource described_class.new(:path => path, :ensure => :file, :mode => 0666, :backup => false, :force => true)
catalog.apply
- (get_mode(path) & 07777).should == 0666
+ expect(get_mode(path) & 07777).to eq(0666)
end
end
describe "for links", :if => described_class.defaultprovider.feature?(:manages_symlinks) do
let(:link) { tmpfile('link_mode') }
describe "when managing links" do
let(:link_target) { tmpfile('target') }
before :each do
FileUtils.touch(link_target)
File.chmod(0444, link_target)
Puppet::FileSystem.symlink(link_target, link)
end
it "should not set the executable bit on the link nor the target" do
catalog.add_resource described_class.new(:path => link, :ensure => :link, :mode => '0666', :target => link_target, :links => :manage)
catalog.apply
(Puppet::FileSystem.stat(link).mode & 07777) == 0666
(Puppet::FileSystem.lstat(link_target).mode & 07777) == 0444
end
it "should ignore dangling symlinks (#6856)" do
File.delete(link_target)
catalog.add_resource described_class.new(:path => link, :ensure => :link, :mode => '0666', :target => link_target, :links => :manage)
catalog.apply
- Puppet::FileSystem.exist?(link).should be_false
+ expect(Puppet::FileSystem.exist?(link)).to be_falsey
end
it "should create a link to the target if ensure is omitted" do
FileUtils.touch(link_target)
catalog.add_resource described_class.new(:path => link, :target => link_target)
catalog.apply
- Puppet::FileSystem.exist?(link).should be_true
- Puppet::FileSystem.lstat(link).ftype.should == 'link'
- Puppet::FileSystem.readlink(link).should == link_target
+ expect(Puppet::FileSystem.exist?(link)).to be_truthy
+ expect(Puppet::FileSystem.lstat(link).ftype).to eq('link')
+ expect(Puppet::FileSystem.readlink(link)).to eq(link_target)
end
end
describe "when following links" do
it "should ignore dangling symlinks (#6856)" do
target = tmpfile('dangling')
FileUtils.touch(target)
Puppet::FileSystem.symlink(target, link)
File.delete(target)
catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow)
catalog.apply
end
describe "to a directory" do
let(:link_target) { tmpdir('dir_target') }
before :each do
File.chmod(0600, link_target)
Puppet::FileSystem.symlink(link_target, link)
end
after :each do
File.chmod(0750, link_target)
end
describe "that is readable" do
it "should set the executable bits when creating the destination (#10315)" do
catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0666', :links => :follow)
catalog.apply
- File.should be_directory(path)
- (get_mode(path) & 07777).should == 0777
+ expect(File).to be_directory(path)
+ expect(get_mode(path) & 07777).to eq(0777)
end
it "should set the executable bits when overwriting the destination (#10315)" do
FileUtils.touch(path)
catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0666', :links => :follow, :backup => false)
catalog.apply
- File.should be_directory(path)
- (get_mode(path) & 07777).should == 0777
+ expect(File).to be_directory(path)
+ expect(get_mode(path) & 07777).to eq(0777)
end
end
describe "that is not readable" do
before :each do
set_mode(0300, link_target)
end
# so we can cleanup
after :each do
set_mode(0700, link_target)
end
it "should set executable bits when creating the destination (#10315)" do
catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0666', :links => :follow)
catalog.apply
- File.should be_directory(path)
- (get_mode(path) & 07777).should == 0777
+ expect(File).to be_directory(path)
+ expect(get_mode(path) & 07777).to eq(0777)
end
it "should set executable bits when overwriting the destination" do
FileUtils.touch(path)
catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0666', :links => :follow, :backup => false)
catalog.apply
- File.should be_directory(path)
- (get_mode(path) & 07777).should == 0777
+ expect(File).to be_directory(path)
+ expect(get_mode(path) & 07777).to eq(0777)
end
end
end
describe "to a file" do
let(:link_target) { tmpfile('file_target') }
before :each do
FileUtils.touch(link_target)
Puppet::FileSystem.symlink(link_target, link)
end
it "should create the file, not a symlink (#2817, #10315)" do
catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow)
catalog.apply
- File.should be_file(path)
- (get_mode(path) & 07777).should == 0600
+ expect(File).to be_file(path)
+ expect(get_mode(path) & 07777).to eq(0600)
end
it "should overwrite the file" do
FileUtils.touch(path)
catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow)
catalog.apply
- File.should be_file(path)
- (get_mode(path) & 07777).should == 0600
+ expect(File).to be_file(path)
+ expect(get_mode(path) & 07777).to eq(0600)
end
end
describe "to a link to a directory" do
let(:real_target) { tmpdir('real_target') }
let(:target) { tmpfile('target') }
before :each do
File.chmod(0666, real_target)
# link -> target -> real_target
Puppet::FileSystem.symlink(real_target, target)
Puppet::FileSystem.symlink(target, link)
end
after :each do
File.chmod(0750, real_target)
end
describe "when following all links" do
it "should create the destination and apply executable bits (#10315)" do
catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow)
catalog.apply
- File.should be_directory(path)
- (get_mode(path) & 07777).should == 0700
+ expect(File).to be_directory(path)
+ expect(get_mode(path) & 07777).to eq(0700)
end
it "should overwrite the destination and apply executable bits" do
FileUtils.mkdir(path)
catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow)
catalog.apply
- File.should be_directory(path)
- (get_mode(path) & 0111).should == 0100
+ expect(File).to be_directory(path)
+ expect(get_mode(path) & 0111).to eq(0100)
end
end
end
end
end
end
end
describe "when writing files" do
with_digest_algorithms do
it "should backup files to a filebucket when one is configured" do
filebucket = Puppet::Type.type(:filebucket).new :path => tmpfile("filebucket"), :name => "mybucket"
file = described_class.new :path => path, :backup => "mybucket", :content => "foo"
catalog.add_resource file
catalog.add_resource filebucket
File.open(file[:path], "w") { |f| f.write("bar") }
d = digest(IO.binread(file[:path]))
catalog.apply
- filebucket.bucket.getfile(d).should == "bar"
+ expect(filebucket.bucket.getfile(d)).to eq("bar")
end
it "should backup files in the local directory when a backup string is provided" do
file = described_class.new :path => path, :backup => ".bak", :content => "foo"
catalog.add_resource file
File.open(file[:path], "w") { |f| f.puts "bar" }
catalog.apply
backup = file[:path] + ".bak"
- Puppet::FileSystem.exist?(backup).should be_true
- File.read(backup).should == "bar\n"
+ expect(Puppet::FileSystem.exist?(backup)).to be_truthy
+ expect(File.read(backup)).to eq("bar\n")
end
it "should fail if no backup can be performed" do
dir = tmpdir("backups")
file = described_class.new :path => File.join(dir, "testfile"), :backup => ".bak", :content => "foo"
catalog.add_resource file
File.open(file[:path], 'w') { |f| f.puts "bar" }
# Create a directory where the backup should be so that writing to it fails
Dir.mkdir(File.join(dir, "testfile.bak"))
Puppet::Util::Log.stubs(:newmessage)
catalog.apply
- File.read(file[:path]).should == "bar\n"
+ expect(File.read(file[:path])).to eq("bar\n")
end
it "should not backup symlinks", :if => described_class.defaultprovider.feature?(:manages_symlinks) do
link = tmpfile("link")
dest1 = tmpfile("dest1")
dest2 = tmpfile("dest2")
bucket = Puppet::Type.type(:filebucket).new :path => tmpfile("filebucket"), :name => "mybucket"
file = described_class.new :path => link, :target => dest2, :ensure => :link, :backup => "mybucket"
catalog.add_resource file
catalog.add_resource bucket
File.open(dest1, "w") { |f| f.puts "whatever" }
Puppet::FileSystem.symlink(dest1, link)
d = digest(File.read(file[:path]))
catalog.apply
- Puppet::FileSystem.readlink(link).should == dest2
- Puppet::FileSystem.exist?(bucket[:path]).should be_false
+ expect(Puppet::FileSystem.readlink(link)).to eq(dest2)
+ expect(Puppet::FileSystem.exist?(bucket[:path])).to be_falsey
end
it "should backup directories to the local filesystem by copying the whole directory" do
file = described_class.new :path => path, :backup => ".bak", :content => "foo", :force => true
catalog.add_resource file
Dir.mkdir(path)
otherfile = File.join(path, "foo")
File.open(otherfile, "w") { |f| f.print "yay" }
catalog.apply
backup = "#{path}.bak"
- FileTest.should be_directory(backup)
+ expect(FileTest).to be_directory(backup)
- File.read(File.join(backup, "foo")).should == "yay"
+ expect(File.read(File.join(backup, "foo"))).to eq("yay")
end
it "should backup directories to filebuckets by backing up each file separately" do
bucket = Puppet::Type.type(:filebucket).new :path => tmpfile("filebucket"), :name => "mybucket"
file = described_class.new :path => tmpfile("bucket_backs"), :backup => "mybucket", :content => "foo", :force => true
catalog.add_resource file
catalog.add_resource bucket
Dir.mkdir(file[:path])
foofile = File.join(file[:path], "foo")
barfile = File.join(file[:path], "bar")
File.open(foofile, "w") { |f| f.print "fooyay" }
File.open(barfile, "w") { |f| f.print "baryay" }
food = digest(File.read(foofile))
bard = digest(File.read(barfile))
catalog.apply
- bucket.bucket.getfile(food).should == "fooyay"
- bucket.bucket.getfile(bard).should == "baryay"
+ expect(bucket.bucket.getfile(food)).to eq("fooyay")
+ expect(bucket.bucket.getfile(bard)).to eq("baryay")
end
end
end
describe "when recursing" do
def build_path(dir)
Dir.mkdir(dir)
File.chmod(0750, dir)
@dirs = [dir]
@files = []
%w{one two}.each do |subdir|
fdir = File.join(dir, subdir)
Dir.mkdir(fdir)
File.chmod(0750, fdir)
@dirs << fdir
%w{three}.each do |file|
ffile = File.join(fdir, file)
@files << ffile
File.open(ffile, "w") { |f| f.puts "test #{file}" }
File.chmod(0640, ffile)
end
end
end
it "should be able to recurse over a nonexistent file" do
@file = described_class.new(
:name => path,
:mode => '0644',
:recurse => true,
:backup => false
)
catalog.add_resource @file
- lambda { @file.eval_generate }.should_not raise_error
+ expect { @file.eval_generate }.not_to raise_error
end
it "should be able to recursively set properties on existing files" do
path = tmpfile("file_integration_tests")
build_path(path)
file = described_class.new(
:name => path,
:mode => '0644',
:recurse => true,
:backup => false
)
catalog.add_resource file
catalog.apply
- @dirs.should_not be_empty
+ expect(@dirs).not_to be_empty
@dirs.each do |path|
- (get_mode(path) & 007777).should == 0755
+ expect(get_mode(path) & 007777).to eq(0755)
end
- @files.should_not be_empty
+ expect(@files).not_to be_empty
@files.each do |path|
- (get_mode(path) & 007777).should == 0644
+ expect(get_mode(path) & 007777).to eq(0644)
end
end
it "should be able to recursively make links to other files", :if => described_class.defaultprovider.feature?(:manages_symlinks) do
source = tmpfile("file_link_integration_source")
build_path(source)
dest = tmpfile("file_link_integration_dest")
@file = described_class.new(:name => dest, :target => source, :recurse => true, :ensure => :link, :backup => false)
catalog.add_resource @file
catalog.apply
@dirs.each do |path|
link_path = path.sub(source, dest)
- Puppet::FileSystem.lstat(link_path).should be_directory
+ expect(Puppet::FileSystem.lstat(link_path)).to be_directory
end
@files.each do |path|
link_path = path.sub(source, dest)
- Puppet::FileSystem.lstat(link_path).ftype.should == "link"
+ expect(Puppet::FileSystem.lstat(link_path).ftype).to eq("link")
end
end
it "should be able to recursively copy files" do
source = tmpfile("file_source_integration_source")
build_path(source)
dest = tmpfile("file_source_integration_dest")
@file = described_class.new(:name => dest, :source => source, :recurse => true, :backup => false)
catalog.add_resource @file
catalog.apply
@dirs.each do |path|
newpath = path.sub(source, dest)
- Puppet::FileSystem.lstat(newpath).should be_directory
+ expect(Puppet::FileSystem.lstat(newpath)).to be_directory
end
@files.each do |path|
newpath = path.sub(source, dest)
- Puppet::FileSystem.lstat(newpath).ftype.should == "file"
+ expect(Puppet::FileSystem.lstat(newpath).ftype).to eq("file")
end
end
it "should not recursively manage files managed by a more specific explicit file" do
dir = tmpfile("recursion_vs_explicit_1")
subdir = File.join(dir, "subdir")
file = File.join(subdir, "file")
FileUtils.mkdir_p(subdir)
File.open(file, "w") { |f| f.puts "" }
base = described_class.new(:name => dir, :recurse => true, :backup => false, :mode => "755")
sub = described_class.new(:name => subdir, :recurse => true, :backup => false, :mode => "644")
catalog.add_resource base
catalog.add_resource sub
catalog.apply
- (get_mode(file) & 007777).should == 0644
+ expect(get_mode(file) & 007777).to eq(0644)
end
it "should recursively manage files even if there is an explicit file whose name is a prefix of the managed file" do
managed = File.join(path, "file")
generated = File.join(path, "file_with_a_name_starting_with_the_word_file")
FileUtils.mkdir_p(path)
FileUtils.touch(managed)
FileUtils.touch(generated)
catalog.add_resource described_class.new(:name => path, :recurse => true, :backup => false, :mode => '0700')
catalog.add_resource described_class.new(:name => managed, :recurse => true, :backup => false, :mode => "644")
catalog.apply
- (get_mode(generated) & 007777).should == 0700
+ expect(get_mode(generated) & 007777).to eq(0700)
end
describe "when recursing remote directories" do
describe "when sourceselect first" do
describe "for a directory" do
it "should recursively copy the first directory that exists" do
one = File.expand_path('thisdoesnotexist')
two = tmpdir('two')
FileUtils.mkdir_p(File.join(two, 'three'))
FileUtils.touch(File.join(two, 'three', 'four'))
catalog.add_resource Puppet::Type.newfile(
:path => path,
:ensure => :directory,
:backup => false,
:recurse => true,
:sourceselect => :first,
:source => [one, two]
)
catalog.apply
- File.should be_directory(path)
- Puppet::FileSystem.exist?(File.join(path, 'one')).should be_false
- Puppet::FileSystem.exist?(File.join(path, 'three', 'four')).should be_true
+ expect(File).to be_directory(path)
+ expect(Puppet::FileSystem.exist?(File.join(path, 'one'))).to be_falsey
+ expect(Puppet::FileSystem.exist?(File.join(path, 'three', 'four'))).to be_truthy
end
it "should recursively copy an empty directory" do
one = File.expand_path('thisdoesnotexist')
two = tmpdir('two')
three = tmpdir('three')
file_in_dir_with_contents(three, 'a', '')
catalog.add_resource Puppet::Type.newfile(
:path => path,
:ensure => :directory,
:backup => false,
:recurse => true,
:sourceselect => :first,
:source => [one, two, three]
)
catalog.apply
- File.should be_directory(path)
- Puppet::FileSystem.exist?(File.join(path, 'a')).should be_false
+ expect(File).to be_directory(path)
+ expect(Puppet::FileSystem.exist?(File.join(path, 'a'))).to be_falsey
end
it "should only recurse one level" do
one = tmpdir('one')
FileUtils.mkdir_p(File.join(one, 'a', 'b'))
FileUtils.touch(File.join(one, 'a', 'b', 'c'))
two = tmpdir('two')
FileUtils.mkdir_p(File.join(two, 'z'))
FileUtils.touch(File.join(two, 'z', 'y'))
catalog.add_resource Puppet::Type.newfile(
:path => path,
:ensure => :directory,
:backup => false,
:recurse => true,
:recurselimit => 1,
:sourceselect => :first,
:source => [one, two]
)
catalog.apply
- Puppet::FileSystem.exist?(File.join(path, 'a')).should be_true
- Puppet::FileSystem.exist?(File.join(path, 'a', 'b')).should be_false
- Puppet::FileSystem.exist?(File.join(path, 'z')).should be_false
+ expect(Puppet::FileSystem.exist?(File.join(path, 'a'))).to be_truthy
+ expect(Puppet::FileSystem.exist?(File.join(path, 'a', 'b'))).to be_falsey
+ expect(Puppet::FileSystem.exist?(File.join(path, 'z'))).to be_falsey
end
end
describe "for a file" do
it "should copy the first file that exists" do
one = File.expand_path('thisdoesnotexist')
two = tmpfile_with_contents('two', 'yay')
three = tmpfile_with_contents('three', 'no')
catalog.add_resource Puppet::Type.newfile(
:path => path,
:ensure => :file,
:backup => false,
:sourceselect => :first,
:source => [one, two, three]
)
catalog.apply
- File.read(path).should == 'yay'
+ expect(File.read(path)).to eq('yay')
end
it "should copy an empty file" do
one = File.expand_path('thisdoesnotexist')
two = tmpfile_with_contents('two', '')
three = tmpfile_with_contents('three', 'no')
catalog.add_resource Puppet::Type.newfile(
:path => path,
:ensure => :file,
:backup => false,
:sourceselect => :first,
:source => [one, two, three]
)
catalog.apply
- File.read(path).should == ''
+ expect(File.read(path)).to eq('')
end
end
end
describe "when sourceselect all" do
describe "for a directory" do
it "should recursively copy all sources from the first valid source" do
dest = tmpdir('dest')
one = tmpdir('one')
two = tmpdir('two')
three = tmpdir('three')
four = tmpdir('four')
file_in_dir_with_contents(one, 'a', one)
file_in_dir_with_contents(two, 'a', two)
file_in_dir_with_contents(two, 'b', two)
file_in_dir_with_contents(three, 'a', three)
file_in_dir_with_contents(three, 'c', three)
obj = Puppet::Type.newfile(
:path => dest,
:ensure => :directory,
:backup => false,
:recurse => true,
:sourceselect => :all,
:source => [one, two, three, four]
)
catalog.add_resource obj
catalog.apply
- File.read(File.join(dest, 'a')).should == one
- File.read(File.join(dest, 'b')).should == two
- File.read(File.join(dest, 'c')).should == three
+ expect(File.read(File.join(dest, 'a'))).to eq(one)
+ expect(File.read(File.join(dest, 'b'))).to eq(two)
+ expect(File.read(File.join(dest, 'c'))).to eq(three)
end
it "should only recurse one level from each valid source" do
one = tmpdir('one')
FileUtils.mkdir_p(File.join(one, 'a', 'b'))
FileUtils.touch(File.join(one, 'a', 'b', 'c'))
two = tmpdir('two')
FileUtils.mkdir_p(File.join(two, 'z'))
FileUtils.touch(File.join(two, 'z', 'y'))
obj = Puppet::Type.newfile(
:path => path,
:ensure => :directory,
:backup => false,
:recurse => true,
:recurselimit => 1,
:sourceselect => :all,
:source => [one, two]
)
catalog.add_resource obj
catalog.apply
- Puppet::FileSystem.exist?(File.join(path, 'a')).should be_true
- Puppet::FileSystem.exist?(File.join(path, 'a', 'b')).should be_false
- Puppet::FileSystem.exist?(File.join(path, 'z')).should be_true
- Puppet::FileSystem.exist?(File.join(path, 'z', 'y')).should be_false
+ expect(Puppet::FileSystem.exist?(File.join(path, 'a'))).to be_truthy
+ expect(Puppet::FileSystem.exist?(File.join(path, 'a', 'b'))).to be_falsey
+ expect(Puppet::FileSystem.exist?(File.join(path, 'z'))).to be_truthy
+ expect(Puppet::FileSystem.exist?(File.join(path, 'z', 'y'))).to be_falsey
end
end
end
end
end
describe "when generating resources" do
before do
source = tmpdir("generating_in_catalog_source")
s1 = file_in_dir_with_contents(source, "one", "uno")
s2 = file_in_dir_with_contents(source, "two", "dos")
@file = described_class.new(
:name => path,
:source => source,
:recurse => true,
:backup => false
)
catalog.add_resource @file
end
it "should add each generated resource to the catalog" do
catalog.apply do |trans|
- catalog.resource(:file, File.join(path, "one")).must be_a(described_class)
- catalog.resource(:file, File.join(path, "two")).must be_a(described_class)
+ expect(catalog.resource(:file, File.join(path, "one"))).to be_a(described_class)
+ expect(catalog.resource(:file, File.join(path, "two"))).to be_a(described_class)
end
end
it "should have an edge to each resource in the relationship graph" do
catalog.apply do |trans|
one = catalog.resource(:file, File.join(path, "one"))
- catalog.relationship_graph.should be_edge(@file, one)
+ expect(catalog.relationship_graph).to be_edge(@file, one)
two = catalog.resource(:file, File.join(path, "two"))
- catalog.relationship_graph.should be_edge(@file, two)
+ expect(catalog.relationship_graph).to be_edge(@file, two)
end
end
end
describe "when copying files" do
it "should be able to copy files with pound signs in their names (#285)" do
source = tmpfile_with_contents("filewith#signs", "foo")
dest = tmpfile("destwith#signs")
catalog.add_resource described_class.new(:name => dest, :source => source)
catalog.apply
- File.read(dest).should == "foo"
+ expect(File.read(dest)).to eq("foo")
end
it "should be able to copy files with spaces in their names" do
dest = tmpfile("destwith spaces")
source = tmpfile_with_contents("filewith spaces", "foo")
catalog.add_resource described_class.new(:path => dest, :source => source)
catalog.apply
- File.read(dest).should == "foo"
+ expect(File.read(dest)).to eq("foo")
end
it "should be able to copy individual files even if recurse has been specified" do
source = tmpfile_with_contents("source", "foo")
dest = tmpfile("dest")
catalog.add_resource described_class.new(:name => dest, :source => source, :recurse => true)
catalog.apply
- File.read(dest).should == "foo"
+ expect(File.read(dest)).to eq("foo")
end
end
it "should create a file with content if ensure is omitted" do
catalog.add_resource described_class.new(
:path => path,
:content => "this is some content, yo"
)
catalog.apply
- File.read(path).should == "this is some content, yo"
+ expect(File.read(path)).to eq("this is some content, yo")
end
it "should create files with content if both content and ensure are set" do
file = described_class.new(
:path => path,
:ensure => "file",
:content => "this is some content, yo"
)
catalog.add_resource file
catalog.apply
- File.read(path).should == "this is some content, yo"
+ expect(File.read(path)).to eq("this is some content, yo")
end
it "should delete files with sources but that are set for deletion" do
source = tmpfile_with_contents("source_source_with_ensure", "yay")
dest = tmpfile_with_contents("source_source_with_ensure", "boo")
file = described_class.new(
:path => dest,
:ensure => :absent,
:source => source,
:backup => false
)
catalog.add_resource file
catalog.apply
- Puppet::FileSystem.exist?(dest).should be_false
+ expect(Puppet::FileSystem.exist?(dest)).to be_falsey
end
describe "when sourcing" do
let(:source) { tmpfile_with_contents("source_default_values", "yay") }
describe "on POSIX systems", :if => Puppet.features.posix? do
it "should apply the source metadata values" do
set_mode(0770, source)
file = described_class.new(
:path => path,
:ensure => :file,
:source => source,
:source_permissions => :use,
:backup => false
)
catalog.add_resource file
catalog.apply
- get_owner(path).should == get_owner(source)
- get_group(path).should == get_group(source)
- (get_mode(path) & 07777).should == 0770
+ expect(get_owner(path)).to eq(get_owner(source))
+ expect(get_group(path)).to eq(get_group(source))
+ expect(get_mode(path) & 07777).to eq(0770)
end
end
it "should override the default metadata values" do
set_mode(0770, source)
file = described_class.new(
:path => path,
:ensure => :file,
:source => source,
:backup => false,
:mode => '0440'
)
catalog.add_resource file
catalog.apply
- (get_mode(path) & 07777).should == 0440
+ expect(get_mode(path) & 07777).to eq(0440)
end
describe "on Windows systems", :if => Puppet.features.microsoft_windows? do
def expects_sid_granted_full_access_explicitly(path, sid)
inherited_ace = Puppet::Util::Windows::AccessControlEntry::INHERITED_ACE
aces = get_aces_for_path_by_sid(path, sid)
- aces.should_not be_empty
+ expect(aces).not_to be_empty
aces.each do |ace|
- ace.mask.should == Puppet::Util::Windows::File::FILE_ALL_ACCESS
- (ace.flags & inherited_ace).should_not == inherited_ace
+ expect(ace.mask).to eq(Puppet::Util::Windows::File::FILE_ALL_ACCESS)
+ expect(ace.flags & inherited_ace).not_to eq(inherited_ace)
end
end
def expects_system_granted_full_access_explicitly(path)
expects_sid_granted_full_access_explicitly(path, @sids[:system])
end
def expects_at_least_one_inherited_ace_grants_full_access(path, sid)
inherited_ace = Puppet::Util::Windows::AccessControlEntry::INHERITED_ACE
aces = get_aces_for_path_by_sid(path, sid)
- aces.should_not be_empty
+ expect(aces).not_to be_empty
- aces.any? do |ace|
+ expect(aces.any? do |ace|
ace.mask == Puppet::Util::Windows::File::FILE_ALL_ACCESS &&
(ace.flags & inherited_ace) == inherited_ace
- end.should be_true
+ end).to be_truthy
end
def expects_at_least_one_inherited_system_ace_grants_full_access(path)
expects_at_least_one_inherited_ace_grants_full_access(path, @sids[:system])
end
describe "when processing SYSTEM ACEs" do
before do
@sids = {
:current_user => Puppet::Util::Windows::SID.name_to_sid(Puppet::Util::Windows::ADSI::User.current_user_name),
:system => Win32::Security::SID::LocalSystem,
:admin => Puppet::Util::Windows::SID.name_to_sid("Administrator"),
:guest => Puppet::Util::Windows::SID.name_to_sid("Guest"),
:users => Win32::Security::SID::BuiltinUsers,
:power_users => Win32::Security::SID::PowerUsers,
:none => Win32::Security::SID::Nobody
}
end
describe "on files" do
before :each do
@file = described_class.new(
:path => path,
:ensure => :file,
:source => source,
:backup => false
)
catalog.add_resource @file
end
describe "when permissions are not insync?" do
before :each do
@file[:owner] = 'None'
@file[:group] = 'None'
end
it "preserves the inherited SYSTEM ACE for an existing file" do
FileUtils.touch(path)
expects_at_least_one_inherited_system_ace_grants_full_access(path)
catalog.apply
expects_at_least_one_inherited_system_ace_grants_full_access(path)
end
it "applies the inherited SYSTEM ACEs for a new file" do
catalog.apply
expects_at_least_one_inherited_system_ace_grants_full_access(path)
end
end
describe "created with SYSTEM as the group" do
before :each do
@file[:owner] = @sids[:users]
@file[:group] = @sids[:system]
@file[:mode] = '0644'
catalog.apply
end
it "should allow the user to explicitly set the mode to 4" do
system_aces = get_aces_for_path_by_sid(path, @sids[:system])
- system_aces.should_not be_empty
+ expect(system_aces).not_to be_empty
system_aces.each do |ace|
- ace.mask.should == Puppet::Util::Windows::File::FILE_GENERIC_READ
+ expect(ace.mask).to eq(Puppet::Util::Windows::File::FILE_GENERIC_READ)
end
end
it "prepends SYSTEM ace when changing group from system to power users" do
@file[:group] = @sids[:power_users]
catalog.apply
system_aces = get_aces_for_path_by_sid(path, @sids[:system])
- system_aces.size.should == 1
+ expect(system_aces.size).to eq(1)
end
end
describe "with :links set to :follow" do
it "should not fail to apply" do
# at minimal, we need an owner and/or group
@file[:owner] = @sids[:users]
@file[:links] = :follow
catalog.apply do |transaction|
if transaction.any_failed?
pretty_transaction_error(transaction)
end
end
end
end
end
describe "on directories" do
before :each do
@directory = described_class.new(
:path => dir,
:ensure => :directory
)
catalog.add_resource @directory
end
def grant_everyone_full_access(path)
sd = Puppet::Util::Windows::Security.get_security_descriptor(path)
sd.dacl.allow(
'S-1-1-0', #everyone
Puppet::Util::Windows::File::FILE_ALL_ACCESS,
Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE |
Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE)
Puppet::Util::Windows::Security.set_security_descriptor(path, sd)
end
after :each do
grant_everyone_full_access(dir)
end
describe "when permissions are not insync?" do
before :each do
@directory[:owner] = 'None'
@directory[:group] = 'None'
end
it "preserves the inherited SYSTEM ACEs for an existing directory" do
FileUtils.mkdir(dir)
expects_at_least_one_inherited_system_ace_grants_full_access(dir)
catalog.apply
expects_at_least_one_inherited_system_ace_grants_full_access(dir)
end
it "applies the inherited SYSTEM ACEs for a new directory" do
catalog.apply
expects_at_least_one_inherited_system_ace_grants_full_access(dir)
end
describe "created with SYSTEM as the group" do
before :each do
@directory[:owner] = @sids[:users]
@directory[:group] = @sids[:system]
@directory[:mode] = '0644'
catalog.apply
end
it "should allow the user to explicitly set the mode to 4" do
system_aces = get_aces_for_path_by_sid(dir, @sids[:system])
- system_aces.should_not be_empty
+ expect(system_aces).not_to be_empty
system_aces.each do |ace|
# unlike files, Puppet sets execute bit on directories that are readable
- ace.mask.should == Puppet::Util::Windows::File::FILE_GENERIC_READ | Puppet::Util::Windows::File::FILE_GENERIC_EXECUTE
+ expect(ace.mask).to eq(Puppet::Util::Windows::File::FILE_GENERIC_READ | Puppet::Util::Windows::File::FILE_GENERIC_EXECUTE)
end
end
it "prepends SYSTEM ace when changing group from system to power users" do
@directory[:group] = @sids[:power_users]
catalog.apply
system_aces = get_aces_for_path_by_sid(dir, @sids[:system])
- system_aces.size.should == 1
+ expect(system_aces.size).to eq(1)
end
end
describe "with :links set to :follow" do
it "should not fail to apply" do
# at minimal, we need an owner and/or group
@directory[:owner] = @sids[:users]
@directory[:links] = :follow
catalog.apply do |transaction|
if transaction.any_failed?
pretty_transaction_error(transaction)
end
end
end
end
end
end
end
end
end
describe "when purging files" do
before do
sourcedir = tmpdir("purge_source")
destdir = tmpdir("purge_dest")
sourcefile = File.join(sourcedir, "sourcefile")
@copiedfile = File.join(destdir, "sourcefile")
@localfile = File.join(destdir, "localfile")
@purgee = File.join(destdir, "to_be_purged")
File.open(@localfile, "w") { |f| f.print "oldtest" }
File.open(sourcefile, "w") { |f| f.print "funtest" }
# this file should get removed
File.open(@purgee, "w") { |f| f.print "footest" }
lfobj = Puppet::Type.newfile(
:title => "localfile",
:path => @localfile,
:content => "rahtest",
:ensure => :file,
:backup => false
)
destobj = Puppet::Type.newfile(
:title => "destdir",
:path => destdir,
:source => sourcedir,
:backup => false,
:purge => true,
:recurse => true
)
catalog.add_resource lfobj, destobj
catalog.apply
end
it "should still copy remote files" do
- File.read(@copiedfile).should == 'funtest'
+ expect(File.read(@copiedfile)).to eq('funtest')
end
it "should not purge managed, local files" do
- File.read(@localfile).should == 'rahtest'
+ expect(File.read(@localfile)).to eq('rahtest')
end
it "should purge files that are neither remote nor otherwise managed" do
- Puppet::FileSystem.exist?(@purgee).should be_false
+ expect(Puppet::FileSystem.exist?(@purgee)).to be_falsey
end
end
describe "when using validate_cmd" do
it "should fail the file resource if command fails" do
catalog.add_resource(described_class.new(:path => path, :content => "foo", :validate_cmd => "/usr/bin/env false"))
Puppet::Util::Execution.expects(:execute).with("/usr/bin/env false", {:combine => true, :failonfail => true}).raises(Puppet::ExecutionFailure, "Failed")
report = catalog.apply.report
- report.resource_statuses["File[#{path}]"].should be_failed
- Puppet::FileSystem.exist?(path).should be_false
+ expect(report.resource_statuses["File[#{path}]"]).to be_failed
+ expect(Puppet::FileSystem.exist?(path)).to be_falsey
end
it "should succeed the file resource if command succeeds" do
catalog.add_resource(described_class.new(:path => path, :content => "foo", :validate_cmd => "/usr/bin/env true"))
Puppet::Util::Execution.expects(:execute).with("/usr/bin/env true", {:combine => true, :failonfail => true}).returns ''
report = catalog.apply.report
- report.resource_statuses["File[#{path}]"].should_not be_failed
- Puppet::FileSystem.exist?(path).should be_true
+ expect(report.resource_statuses["File[#{path}]"]).not_to be_failed
+ expect(Puppet::FileSystem.exist?(path)).to be_truthy
end
end
def tmpfile_with_contents(name, contents)
file = tmpfile(name)
File.open(file, "w") { |f| f.write contents }
file
end
def file_in_dir_with_contents(dir, name, contents)
full_name = File.join(dir, name)
File.open(full_name, "w") { |f| f.write contents }
full_name
end
def pretty_transaction_error(transaction)
report = transaction.report
status_failures = report.resource_statuses.values.select { |r| r.failed? }
status_fail_msg = status_failures.
collect(&:events).
flatten.
select { |event| event.status == 'failure' }.
collect { |event| "#{event.resource}: #{event.message}" }.join("; ")
raise "Got #{status_failures.length} failure(s) while applying: #{status_fail_msg}"
end
end
diff --git a/spec/integration/type/package_spec.rb b/spec/integration/type/package_spec.rb
index 0a3dfc2a7..a4dfad931 100755
--- a/spec/integration/type/package_spec.rb
+++ b/spec/integration/type/package_spec.rb
@@ -1,127 +1,127 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:package), "when choosing a default package provider" do
before do
# the default provider is cached.
Puppet::Type.type(:package).defaultprovider = nil
end
def provider_name(os)
case os
when 'Solaris'
if Puppet::Util::Package.versioncmp(Facter.value(:kernelrelease), '5.11') >= 0
:pkg
else
:sun
end
when 'Ubuntu'
:apt
when 'Debian'
:apt
when 'Darwin'
:pkgdmg
when 'RedHat'
if ['2.1', '3', '4'].include?(Facter.value(:lsbdistrelease))
:up2date
else
:yum
end
when 'Fedora'
:yum
when 'FreeBSD'
:ports
when 'OpenBSD'
:openbsd
when 'DragonFly'
:pkgin
when 'OpenWrt'
:opkg
end
end
it "should have a default provider" do
- Puppet::Type.type(:package).defaultprovider.should_not be_nil
+ expect(Puppet::Type.type(:package).defaultprovider).not_to be_nil
end
it "should choose the correct provider each platform" do
unless default_provider = provider_name(Facter.value(:operatingsystem))
pending("No default provider specified in this test for #{Facter.value(:operatingsystem)}")
end
- Puppet::Type.type(:package).defaultprovider.name.should == default_provider
+ expect(Puppet::Type.type(:package).defaultprovider.name).to eq(default_provider)
end
end
describe Puppet::Type.type(:package), "when packages with the same name are sourced" do
before :each do
@provider = stub(
'provider',
:class => Puppet::Type.type(:package).defaultprovider,
:clear => nil,
:satisfies? => true,
:name => :mock,
:validate_source => nil
)
Puppet::Type.type(:package).defaultprovider.stubs(:new).returns(@provider)
Puppet::Type.type(:package).defaultprovider.stubs(:instances).returns([])
@package = Puppet::Type.type(:package).new(:name => "yay", :ensure => :present)
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource(@package)
end
describe "with same title" do
before {
@alt_package = Puppet::Type.type(:package).new(:name => "yay", :ensure => :present)
}
it "should give an error" do
expect {
@catalog.add_resource(@alt_package)
}.to raise_error Puppet::Resource::Catalog::DuplicateResourceError, 'Duplicate declaration: Package[yay] is already declared; cannot redeclare'
end
end
describe "with different title" do
before :each do
@alt_package = Puppet::Type.type(:package).new(:name => "yay", :title => "gem-yay", :ensure => :present)
end
it "should give an error" do
provider_name = Puppet::Type.type(:package).defaultprovider.name
expect {
@catalog.add_resource(@alt_package)
}.to raise_error ArgumentError, "Cannot alias Package[gem-yay] to [\"yay\", :#{provider_name}]; resource [\"Package\", \"yay\", :#{provider_name}] already declared"
end
end
describe "from multiple providers" do
provider_class = Puppet::Type.type(:package).provider(:gem)
before :each do
@alt_provider = provider_class.new
@alt_package = Puppet::Type.type(:package).new(:name => "yay", :title => "gem-yay", :provider => @alt_provider, :ensure => :present)
@catalog.add_resource(@alt_package)
end
describe "when it should be present" do
[:present, :latest, "1.0"].each do |state|
it "should do nothing if it is #{state.to_s}" do
@provider.expects(:properties).returns(:ensure => state).at_least_once
@alt_provider.expects(:properties).returns(:ensure => state).at_least_once
@catalog.apply
end
end
[:purged, :absent].each do |state|
it "should install if it is #{state.to_s}" do
@provider.stubs(:properties).returns(:ensure => state)
@provider.expects(:install)
@alt_provider.stubs(:properties).returns(:ensure => state)
@alt_provider.expects(:install)
@catalog.apply
end
end
end
end
end
diff --git a/spec/integration/type/tidy_spec.rb b/spec/integration/type/tidy_spec.rb
index 7dbefb6ca..4beae8177 100755
--- a/spec/integration/type/tidy_spec.rb
+++ b/spec/integration/type/tidy_spec.rb
@@ -1,34 +1,34 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/file_bucket/dipper'
describe Puppet::Type.type(:tidy) do
include PuppetSpec::Files
before do
Puppet::Util::Storage.stubs(:store)
end
# Testing #355.
it "should be able to remove dead links", :if => Puppet.features.manages_symlinks? do
dir = tmpfile("tidy_link_testing")
link = File.join(dir, "link")
target = tmpfile("no_such_file_tidy_link_testing")
Dir.mkdir(dir)
Puppet::FileSystem.symlink(target, link)
tidy = Puppet::Type.type(:tidy).new :path => dir, :recurse => true
catalog = Puppet::Resource::Catalog.new
catalog.add_resource(tidy)
# avoid crude failures because of nil resources that result
# from implicit containment and lacking containers
catalog.stubs(:container_of).returns tidy
catalog.apply
- Puppet::FileSystem.symlink?(link).should be_false
+ expect(Puppet::FileSystem.symlink?(link)).to be_falsey
end
end
diff --git a/spec/integration/type/user_spec.rb b/spec/integration/type/user_spec.rb
index c542e51a9..f5993ef44 100644
--- a/spec/integration/type/user_spec.rb
+++ b/spec/integration/type/user_spec.rb
@@ -1,57 +1,57 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_spec/compiler'
describe Puppet::Type.type(:user), '(integration)', :unless => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
include PuppetSpec::Compiler
context "when set to purge ssh keys from a file" do
let(:tempfile) do
file_containing('user_spec', <<-EOF)
# comment
ssh-rsa KEY-DATA key-name
ssh-rsa KEY-DATA key name
EOF
end
# must use an existing user, or the generated key resource
# will fail on account of an invalid user for the key
# - root should be a safe default
let(:manifest) { "user { 'root': purge_ssh_keys => '#{tempfile}' }" }
it "should purge authorized ssh keys" do
apply_compiled_manifest(manifest)
- File.read(tempfile).should_not =~ /key-name/
+ expect(File.read(tempfile)).not_to match(/key-name/)
end
it "should purge keys with spaces in the comment string" do
apply_compiled_manifest(manifest)
- File.read(tempfile).should_not =~ /key name/
+ expect(File.read(tempfile)).not_to match(/key name/)
end
context "with other prefetching resources evaluated first" do
let(:manifest) { "host { 'test': before => User[root] } user { 'root': purge_ssh_keys => '#{tempfile}' }" }
it "should purge authorized ssh keys" do
apply_compiled_manifest(manifest)
- File.read(tempfile).should_not =~ /key-name/
+ expect(File.read(tempfile)).not_to match(/key-name/)
end
end
context "with multiple unnamed keys" do
let(:tempfile) do
file_containing('user_spec', <<-EOF)
# comment
ssh-rsa KEY-DATA1
ssh-rsa KEY-DATA2
EOF
end
it "should purge authorized ssh keys" do
apply_compiled_manifest(manifest)
- File.read(tempfile).should_not =~ /KEY-DATA/
+ expect(File.read(tempfile)).not_to match(/KEY-DATA/)
end
end
end
end
diff --git a/spec/integration/type_spec.rb b/spec/integration/type_spec.rb
index c684a193d..16e3f6ed5 100755
--- a/spec/integration/type_spec.rb
+++ b/spec/integration/type_spec.rb
@@ -1,32 +1,32 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/type'
describe Puppet::Type do
it "should not lose its provider list when it is reloaded" do
type = Puppet::Type.newtype(:integration_test) do
newparam(:name) {}
end
provider = type.provide(:myprovider) {}
# reload it
type = Puppet::Type.newtype(:integration_test) do
newparam(:name) {}
end
- type.provider(:myprovider).should equal(provider)
+ expect(type.provider(:myprovider)).to equal(provider)
end
it "should not lose its provider parameter when it is reloaded" do
type = Puppet::Type.newtype(:reload_test_type)
provider = type.provide(:test_provider)
# reload it
type = Puppet::Type.newtype(:reload_test_type)
- type.parameters.should include(:provider)
+ expect(type.parameters).to include(:provider)
end
end
diff --git a/spec/integration/util/autoload_spec.rb b/spec/integration/util/autoload_spec.rb
index 997e43074..b50036907 100755
--- a/spec/integration/util/autoload_spec.rb
+++ b/spec/integration/util/autoload_spec.rb
@@ -1,102 +1,102 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/autoload'
require 'fileutils'
class AutoloadIntegrator
@things = []
def self.newthing(name)
@things << name
end
def self.thing?(name)
@things.include? name
end
def self.clear
@things.clear
end
end
require 'puppet_spec/files'
describe Puppet::Util::Autoload do
include PuppetSpec::Files
def with_file(name, *path)
path = File.join(*path)
# Now create a file to load
File.open(path, "w") { |f|
f.puts "\nAutoloadIntegrator.newthing(:#{name.to_s})\n"
}
yield
File.delete(path)
end
def with_loader(name, path)
dir = tmpfile(name + path)
$LOAD_PATH << dir
Dir.mkdir(dir)
rbdir = File.join(dir, path.to_s)
Dir.mkdir(rbdir)
loader = Puppet::Util::Autoload.new(name, path)
yield rbdir, loader
Dir.rmdir(rbdir)
Dir.rmdir(dir)
$LOAD_PATH.pop
AutoloadIntegrator.clear
end
it "should not fail when asked to load a missing file" do
- Puppet::Util::Autoload.new("foo", "bar").load(:eh).should be_false
+ expect(Puppet::Util::Autoload.new("foo", "bar").load(:eh)).to be_falsey
end
it "should load and return true when it successfully loads a file" do
with_loader("foo", "bar") { |dir,loader|
with_file(:mything, dir, "mything.rb") {
- loader.load(:mything).should be_true
- loader.class.should be_loaded("bar/mything")
- AutoloadIntegrator.should be_thing(:mything)
+ expect(loader.load(:mything)).to be_truthy
+ expect(loader.class).to be_loaded("bar/mything")
+ expect(AutoloadIntegrator).to be_thing(:mything)
}
}
end
it "should consider a file loaded when asked for the name without an extension" do
with_loader("foo", "bar") { |dir,loader|
with_file(:noext, dir, "noext.rb") {
loader.load(:noext)
- loader.class.should be_loaded("bar/noext")
+ expect(loader.class).to be_loaded("bar/noext")
}
}
end
it "should consider a file loaded when asked for the name with an extension" do
with_loader("foo", "bar") { |dir,loader|
with_file(:noext, dir, "withext.rb") {
loader.load(:withext)
- loader.class.should be_loaded("bar/withext.rb")
+ expect(loader.class).to be_loaded("bar/withext.rb")
}
}
end
it "should be able to load files directly from modules" do
## modulepath can't be used until after app settings are initialized, so we need to simulate that:
Puppet.settings.expects(:app_defaults_initialized?).returns(true).at_least_once
modulepath = tmpfile("autoload_module_testing")
libdir = File.join(modulepath, "mymod", "lib", "foo")
FileUtils.mkdir_p(libdir)
file = File.join(libdir, "plugin.rb")
Puppet.override(:environments => Puppet::Environments::Static.new(Puppet::Node::Environment.create(:production, [modulepath]))) do
with_loader("foo", "foo") do |dir, loader|
with_file(:plugin, file.split("/")) do
loader.load(:plugin)
- loader.class.should be_loaded("foo/plugin.rb")
+ expect(loader.class).to be_loaded("foo/plugin.rb")
end
end
end
end
end
diff --git a/spec/integration/util/feature_spec.rb b/spec/integration/util/feature_spec.rb
deleted file mode 100755
index 1a3037b50..000000000
--- a/spec/integration/util/feature_spec.rb
+++ /dev/null
@@ -1,53 +0,0 @@
-#! /usr/bin/env ruby
-require 'spec_helper'
-
-require 'puppet/util/feature'
-require 'puppet_spec/files'
-
-describe Puppet::Util::Feature do
- include PuppetSpec::Files
-
- it "should be able to load features from disk" do
- libdir = tmpfile("feature_lib")
- Dir.mkdir(libdir)
-
- $LOAD_PATH << libdir
-
- $features = Puppet::Util::Feature.new("feature_lib")
-
- Dir.mkdir(File.join(libdir, "feature_lib"))
-
- File.open(File.join(libdir, "feature_lib", "able_to_load.rb"), "w") do |f|
- f.puts "$features.add(:able_to_load) { true }"
- end
-
- $features.should be_able_to_load
- end
-
- # TODO: Make this a spec test or remove it.
- def test_dynamic_loading
- $features = @features
- cleanup { $features = nil }
- # Now create a feature and make sure it loads.
- FileUtils.mkdir_p(@path)
- nope = File.join(@path, "nope.rb")
- File.open(nope, "w") { |f|
- f.puts "$features.add(:nope, :libs => %w{nosuchlib})"
- }
- assert_nothing_raised("Failed to autoload features") do
- assert(! @features.nope?, "'nope' returned true")
- end
-
- # First make sure "yep?" returns false
- assert_nothing_raised("Missing feature threw an exception") do
- assert(! @features.notyep?, "'notyep' returned true before definition")
- end
-
- yep = File.join(@path, "yep.rb")
- File.open(yep, "w") { |f|
- f.puts "$features.add(:yep, :libs => %w{puppet})"
- }
-
- assert(@features.yep?, "false 'yep' is apparently cached or feature could not be loaded")
- end
-end
diff --git a/spec/integration/util/rdoc/parser_spec.rb b/spec/integration/util/rdoc/parser_spec.rb
index d6a9094de..b594a9ba7 100755
--- a/spec/integration/util/rdoc/parser_spec.rb
+++ b/spec/integration/util/rdoc/parser_spec.rb
@@ -1,182 +1,182 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/rdoc'
describe "RDoc::Parser" do
require 'puppet_spec/files'
include PuppetSpec::Files
let(:document_all) { false }
let(:tmp_dir) { tmpdir('rdoc_parser_tmp') }
let(:doc_dir) { File.join(tmp_dir, 'doc') }
let(:manifests_dir) { File.join(tmp_dir, 'manifests') }
let(:modules_dir) { File.join(tmp_dir, 'modules') }
let(:modules_and_manifests) do
{
:site => [
File.join(manifests_dir, 'site.pp'),
<<-EOF
# The test class comment
class test {
# The virtual resource comment
@notify { virtual: }
# The a_notify_resource comment
notify { a_notify_resource:
message => "a_notify_resource message"
}
}
# The includes_another class comment
class includes_another {
include another
}
# The requires_another class comment
class requires_another {
require another
}
# node comment
node foo {
include test
$a_var = "var_value"
realize Notify[virtual]
notify { bar: }
}
EOF
],
:module_readme => [
File.join(modules_dir, 'a_module', 'README'),
<<-EOF
The a_module README docs.
EOF
],
:module_init => [
File.join(modules_dir, 'a_module', 'manifests', 'init.pp'),
<<-EOF
# The a_module class comment
class a_module {}
class another {}
EOF
],
:module_type => [
File.join(modules_dir, 'a_module', 'manifests', 'a_type.pp'),
<<-EOF
# The a_type type comment
define a_module::a_type() {}
EOF
],
:module_plugin => [
File.join(modules_dir, 'a_module', 'lib', 'puppet', 'type', 'a_plugin.rb'),
<<-EOF
# The a_plugin type comment
Puppet::Type.newtype(:a_plugin) do
@doc = "Not presented"
end
EOF
],
:module_function => [
File.join(modules_dir, 'a_module', 'lib', 'puppet', 'parser', 'a_function.rb'),
<<-EOF
# The a_function function comment
module Puppet::Parser::Functions
newfunction(:a_function, :type => :rvalue) do
return
end
end
EOF
],
:module_fact => [
File.join(modules_dir, 'a_module', 'lib', 'facter', 'a_fact.rb'),
<<-EOF
# The a_fact fact comment
Facter.add("a_fact") do
end
EOF
],
}
end
def write_file(file, content)
FileUtils.mkdir_p(File.dirname(file))
File.open(file, 'w') do |f|
f.puts(content)
end
end
def prepare_manifests_and_modules
modules_and_manifests.each do |key,array|
write_file(*array)
end
end
def file_exists_and_matches_content(file, *content_patterns)
- Puppet::FileSystem.exist?(file).should(be_true, "Cannot find #{file}")
+ expect(Puppet::FileSystem.exist?(file)).to(be_truthy, "Cannot find #{file}")
content_patterns.each do |pattern|
content = File.read(file)
- content.should match(pattern)
+ expect(content).to match(pattern)
end
end
def some_file_exists_with_matching_content(glob, *content_patterns)
- Dir.glob(glob).select do |f|
+ expect(Dir.glob(glob).select do |f|
contents = File.read(f)
content_patterns.all? { |p| p.match(contents) }
- end.should_not(be_empty, "Could not match #{content_patterns} in any of the files found in #{glob}")
+ end).not_to(be_empty, "Could not match #{content_patterns} in any of the files found in #{glob}")
end
around(:each) do |example|
env = Puppet::Node::Environment.create(:doc_test_env, [modules_dir], manifests_dir)
Puppet.override({:environments => Puppet::Environments::Static.new(env), :current_environment => env}) do
example.run
end
end
before :each do
prepare_manifests_and_modules
Puppet.settings[:document_all] = document_all
Puppet.settings[:modulepath] = modules_dir
Puppet::Util::RDoc.rdoc(doc_dir, [modules_dir, manifests_dir])
end
module RdocTesters
def has_plugin_rdoc(module_name, type, name)
file_exists_and_matches_content(plugin_path(module_name, type, name), /The .*?#{name}.*?\s*#{type} comment/m, /Type.*?#{type}/m)
end
end
shared_examples_for :an_rdoc_site do
# PUP-3274 / PUP-3638 not sure if this should be kept or not - it is now broken
# it "documents the __site__ module" do
# has_module_rdoc("__site__")
# end
# PUP-3274 / PUP-3638 not sure if this should be kept or not - it is now broken
# it "documents the a_module module" do
# has_module_rdoc("a_module", /The .*?a_module.*? .*?README.*?docs/m)
# end
it "documents the a_module::a_plugin type" do
has_plugin_rdoc("a_module", :type, 'a_plugin')
end
it "documents the a_module::a_function function" do
has_plugin_rdoc("a_module", :function, 'a_function')
end
it "documents the a_module::a_fact fact" do
has_plugin_rdoc("a_module", :fact, 'a_fact')
end
end
describe "rdoc2 support" do
def module_path(module_name); "#{doc_dir}/#{module_name}.html" end
def plugin_path(module_name, type, name); "#{doc_dir}/#{module_name}/__#{type}s__.html" end
include RdocTesters
it_behaves_like :an_rdoc_site
end
end
diff --git a/spec/integration/util/settings_spec.rb b/spec/integration/util/settings_spec.rb
index a76ade637..e97fd9745 100755
--- a/spec/integration/util/settings_spec.rb
+++ b/spec/integration/util/settings_spec.rb
@@ -1,89 +1,89 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
describe Puppet::Settings do
include PuppetSpec::Files
def minimal_default_settings
{ :noop => {:default => false, :desc => "noop"} }
end
def define_settings(section, settings_hash)
settings.define_settings(section, minimal_default_settings.update(settings_hash))
end
let(:settings) { Puppet::Settings.new }
it "should be able to make needed directories" do
define_settings(:main,
:maindir => {
:default => tmpfile("main"),
:type => :directory,
:desc => "a",
}
)
settings.use(:main)
- expect(File.directory?(settings[:maindir])).to be_true
+ expect(File.directory?(settings[:maindir])).to be_truthy
end
it "should make its directories with the correct modes" do
define_settings(:main,
:maindir => {
:default => tmpfile("main"),
:type => :directory,
:desc => "a",
:mode => 0750
}
)
settings.use(:main)
expect(Puppet::FileSystem.stat(settings[:maindir]).mode & 007777).to eq(0750)
end
it "reparses configuration if configuration file is touched", :if => !Puppet.features.microsoft_windows? do
config = tmpfile("config")
define_settings(:main,
:config => {
:type => :file,
:default => config,
:desc => "a"
},
:environment => {
:default => 'dingos',
:desc => 'test',
}
)
Puppet[:filetimeout] = '1s'
File.open(config, 'w') do |file|
file.puts <<-EOF
[main]
environment=toast
EOF
end
settings.initialize_global_settings
expect(settings[:environment]).to eq('toast')
# First reparse establishes WatchedFiles
settings.reparse_config_files
sleep 1
File.open(config, 'w') do |file|
file.puts <<-EOF
[main]
environment=bacon
EOF
end
# Second reparse if later than filetimeout, reparses if changed
settings.reparse_config_files
expect(settings[:environment]).to eq('bacon')
end
end
diff --git a/spec/integration/util/windows/process_spec.rb b/spec/integration/util/windows/process_spec.rb
index 60eae3443..31a329f24 100644
--- a/spec/integration/util/windows/process_spec.rb
+++ b/spec/integration/util/windows/process_spec.rb
@@ -1,34 +1,34 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'facter'
describe "Puppet::Util::Windows::Process", :if => Puppet.features.microsoft_windows? do
describe "as an admin" do
it "should have the SeCreateSymbolicLinkPrivilege necessary to create symlinks on Vista / 2008+",
:if => Facter.value(:kernelmajversion).to_f >= 6.0 && Puppet.features.microsoft_windows? do
# this is a bit of a lame duck test since it requires running user to be admin
# a better integration test would create a new user with the privilege and verify
- Puppet::Util::Windows::User.should be_admin
- Puppet::Util::Windows::Process.process_privilege_symlink?.should be_true
+ expect(Puppet::Util::Windows::User).to be_admin
+ expect(Puppet::Util::Windows::Process.process_privilege_symlink?).to be_truthy
end
it "should not have the SeCreateSymbolicLinkPrivilege necessary to create symlinks on 2003 and earlier",
:if => Facter.value(:kernelmajversion).to_f < 6.0 && Puppet.features.microsoft_windows? do
- Puppet::Util::Windows::User.should be_admin
- Puppet::Util::Windows::Process.process_privilege_symlink?.should be_false
+ expect(Puppet::Util::Windows::User).to be_admin
+ expect(Puppet::Util::Windows::Process.process_privilege_symlink?).to be_falsey
end
it "should be able to lookup a standard Windows process privilege" do
Puppet::Util::Windows::Process.lookup_privilege_value('SeShutdownPrivilege') do |luid|
- luid.should_not be_nil
- luid.should be_instance_of(Puppet::Util::Windows::Process::LUID)
+ expect(luid).not_to be_nil
+ expect(luid).to be_instance_of(Puppet::Util::Windows::Process::LUID)
end
end
it "should raise an error for an unknown privilege name" do
fail_msg = /LookupPrivilegeValue\(, foo, .*\): A specified privilege does not exist/
expect { Puppet::Util::Windows::Process.lookup_privilege_value('foo') }.to raise_error(Puppet::Util::Windows::Error, fail_msg)
end
end
end
diff --git a/spec/integration/util/windows/security_spec.rb b/spec/integration/util/windows/security_spec.rb
index fa3873aee..cb0d5bc59 100755
--- a/spec/integration/util/windows/security_spec.rb
+++ b/spec/integration/util/windows/security_spec.rb
@@ -1,864 +1,865 @@
#!/usr/bin/env ruby
require 'spec_helper'
if Puppet.features.microsoft_windows?
class WindowsSecurityTester
require 'puppet/util/windows/security'
include Puppet::Util::Windows::Security
end
end
describe "Puppet::Util::Windows::Security", :if => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
before :all do
@sids = {
:current_user => Puppet::Util::Windows::SID.name_to_sid(Puppet::Util::Windows::ADSI::User.current_user_name),
:system => Win32::Security::SID::LocalSystem,
:admin => Puppet::Util::Windows::SID.name_to_sid("Administrator"),
:administrators => Win32::Security::SID::BuiltinAdministrators,
:guest => Puppet::Util::Windows::SID.name_to_sid("Guest"),
:users => Win32::Security::SID::BuiltinUsers,
:power_users => Win32::Security::SID::PowerUsers,
:none => Win32::Security::SID::Nobody,
:everyone => Win32::Security::SID::Everyone
}
# The TCP/IP NetBIOS Helper service (aka 'lmhosts') has ended up
# disabled on some VMs for reasons we couldn't track down. This
# condition causes tests which rely on resolving UNC style paths
# (like \\localhost) to fail with unhelpful error messages.
# Put a check for this upfront to aid debug should this strike again.
service = Puppet::Type.type(:service).new(:name => 'lmhosts')
expect(service.provider.status).to eq(:running), 'lmhosts service is not running'
end
let (:sids) { @sids }
let (:winsec) { WindowsSecurityTester.new }
let (:klass) { Puppet::Util::Windows::File }
def set_group_depending_on_current_user(path)
if sids[:current_user] == sids[:system]
# if the current user is SYSTEM, by setting the group to
# guest, SYSTEM is automagically given full control, so instead
# override that behavior with SYSTEM as group and a specific mode
winsec.set_group(sids[:system], path)
mode = winsec.get_mode(path)
winsec.set_mode(mode & ~WindowsSecurityTester::S_IRWXG, path)
else
winsec.set_group(sids[:guest], path)
end
end
def grant_everyone_full_access(path)
sd = winsec.get_security_descriptor(path)
everyone = 'S-1-1-0'
inherit = Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE | Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE
sd.dacl.allow(everyone, klass::FILE_ALL_ACCESS, inherit)
winsec.set_security_descriptor(path, sd)
end
shared_examples_for "only child owner" do
it "should allow child owner" do
winsec.set_owner(sids[:guest], parent)
winsec.set_group(sids[:current_user], parent)
winsec.set_mode(0700, parent)
check_delete(path)
end
it "should deny parent owner" do
winsec.set_owner(sids[:guest], path)
winsec.set_group(sids[:current_user], path)
winsec.set_mode(0700, path)
- lambda { check_delete(path) }.should raise_error(Errno::EACCES)
+ expect { check_delete(path) }.to raise_error(Errno::EACCES)
end
it "should deny group" do
winsec.set_owner(sids[:guest], path)
winsec.set_group(sids[:current_user], path)
winsec.set_mode(0700, path)
- lambda { check_delete(path) }.should raise_error(Errno::EACCES)
+ expect { check_delete(path) }.to raise_error(Errno::EACCES)
end
it "should deny other" do
winsec.set_owner(sids[:guest], path)
winsec.set_group(sids[:current_user], path)
winsec.set_mode(0700, path)
- lambda { check_delete(path) }.should raise_error(Errno::EACCES)
+ expect { check_delete(path) }.to raise_error(Errno::EACCES)
end
end
shared_examples_for "a securable object" do
describe "on a volume that doesn't support ACLs" do
[:owner, :group, :mode].each do |p|
it "should return nil #{p}" do
winsec.stubs(:supports_acl?).returns false
- winsec.send("get_#{p}", path).should be_nil
+ expect(winsec.send("get_#{p}", path)).to be_nil
end
end
end
describe "on a volume that supports ACLs" do
describe "for a normal user" do
before :each do
Puppet.features.stubs(:root?).returns(false)
end
after :each do
winsec.set_mode(WindowsSecurityTester::S_IRWXU, parent)
winsec.set_mode(WindowsSecurityTester::S_IRWXU, path) if Puppet::FileSystem.exist?(path)
end
describe "#supports_acl?" do
%w[c:/ c:\\ c:/windows/system32 \\\\localhost\\C$ \\\\127.0.0.1\\C$\\foo].each do |path|
it "should accept #{path}" do
- winsec.should be_supports_acl(path)
+ expect(winsec).to be_supports_acl(path)
end
end
it "should raise an exception if it cannot get volume information" do
expect {
winsec.supports_acl?('foobar')
}.to raise_error(Puppet::Error, /Failed to get volume information/)
end
end
describe "#owner=" do
it "should allow setting to the current user" do
winsec.set_owner(sids[:current_user], path)
end
it "should raise an exception when setting to a different user" do
- lambda { winsec.set_owner(sids[:guest], path) }.should raise_error(Puppet::Error, /This security ID may not be assigned as the owner of this object./)
+ expect { winsec.set_owner(sids[:guest], path) }.to raise_error(Puppet::Error, /This security ID may not be assigned as the owner of this object./)
end
end
describe "#owner" do
it "it should not be empty" do
- winsec.get_owner(path).should_not be_empty
+ expect(winsec.get_owner(path)).not_to be_empty
end
it "should raise an exception if an invalid path is provided" do
- lambda { winsec.get_owner("c:\\doesnotexist.txt") }.should raise_error(Puppet::Error, /The system cannot find the file specified./)
+ expect { winsec.get_owner("c:\\doesnotexist.txt") }.to raise_error(Puppet::Error, /The system cannot find the file specified./)
end
end
describe "#group=" do
it "should allow setting to a group the current owner is a member of" do
winsec.set_group(sids[:users], path)
end
# Unlike unix, if the user has permission to WRITE_OWNER, which the file owner has by default,
# then they can set the primary group to a group that the user does not belong to.
it "should allow setting to a group the current owner is not a member of" do
winsec.set_group(sids[:power_users], path)
end
end
describe "#group" do
it "should not be empty" do
- winsec.get_group(path).should_not be_empty
+ expect(winsec.get_group(path)).not_to be_empty
end
it "should raise an exception if an invalid path is provided" do
- lambda { winsec.get_group("c:\\doesnotexist.txt") }.should raise_error(Puppet::Error, /The system cannot find the file specified./)
+ expect { winsec.get_group("c:\\doesnotexist.txt") }.to raise_error(Puppet::Error, /The system cannot find the file specified./)
end
end
it "should preserve inherited full control for SYSTEM when setting owner and group" do
# new file has SYSTEM
system_aces = winsec.get_aces_for_path_by_sid(path, sids[:system])
- system_aces.should_not be_empty
+ expect(system_aces).not_to be_empty
# when running under SYSTEM account, multiple ACEs come back
# so we only care that we have at least one of these
- system_aces.any? do |ace|
+ expect(system_aces.any? do |ace|
ace.mask == klass::FILE_ALL_ACCESS
- end.should be_true
+ end).to be_truthy
# changing the owner/group will no longer make the SD protected
winsec.set_group(sids[:power_users], path)
winsec.set_owner(sids[:administrators], path)
- system_aces.find do |ace|
+ expect(system_aces.find do |ace|
ace.mask == klass::FILE_ALL_ACCESS && ace.inherited?
- end.should_not be_nil
+ end).not_to be_nil
end
describe "#mode=" do
(0000..0700).step(0100) do |mode|
it "should enforce mode #{mode.to_s(8)}" do
winsec.set_mode(mode, path)
check_access(mode, path)
end
end
it "should round-trip all 128 modes that do not require deny ACEs" do
0.upto(1).each do |s|
0.upto(7).each do |u|
0.upto(u).each do |g|
0.upto(g).each do |o|
# if user is superset of group, and group superset of other, then
# no deny ace is required, and mode can be converted to win32
# access mask, and back to mode without loss of information
# (provided the owner and group are not the same)
next if ((u & g) != g) or ((g & o) != o)
mode = (s << 9 | u << 6 | g << 3 | o << 0)
winsec.set_mode(mode, path)
- winsec.get_mode(path).to_s(8).should == mode.to_s(8)
+ expect(winsec.get_mode(path).to_s(8)).to eq(mode.to_s(8))
end
end
end
end
end
it "should preserve full control for SYSTEM when setting mode" do
# new file has SYSTEM
system_aces = winsec.get_aces_for_path_by_sid(path, sids[:system])
- system_aces.should_not be_empty
+ expect(system_aces).not_to be_empty
# when running under SYSTEM account, multiple ACEs come back
# so we only care that we have at least one of these
- system_aces.any? do |ace|
+ expect(system_aces.any? do |ace|
ace.mask == klass::FILE_ALL_ACCESS
- end.should be_true
+ end).to be_truthy
# changing the mode will make the SD protected
winsec.set_group(sids[:none], path)
winsec.set_mode(0600, path)
# and should have a non-inherited SYSTEM ACE(s)
system_aces = winsec.get_aces_for_path_by_sid(path, sids[:system])
system_aces.each do |ace|
- ace.mask.should == klass::FILE_ALL_ACCESS && ! ace.inherited?
+ expect(ace.mask).to eq(klass::FILE_ALL_ACCESS)
+ expect(ace).not_to be_inherited
end
end
describe "for modes that require deny aces" do
it "should map everyone to group and owner" do
winsec.set_mode(0426, path)
- winsec.get_mode(path).to_s(8).should == "666"
+ expect(winsec.get_mode(path).to_s(8)).to eq("666")
end
it "should combine user and group modes when owner and group sids are equal" do
winsec.set_group(winsec.get_owner(path), path)
winsec.set_mode(0410, path)
- winsec.get_mode(path).to_s(8).should == "550"
+ expect(winsec.get_mode(path).to_s(8)).to eq("550")
end
end
describe "for read-only objects" do
before :each do
winsec.set_group(sids[:none], path)
winsec.set_mode(0600, path)
Puppet::Util::Windows::File.add_attributes(path, klass::FILE_ATTRIBUTE_READONLY)
- (Puppet::Util::Windows::File.get_attributes(path) & klass::FILE_ATTRIBUTE_READONLY).should be_nonzero
+ expect(Puppet::Util::Windows::File.get_attributes(path) & klass::FILE_ATTRIBUTE_READONLY).to be_nonzero
end
it "should make them writable if any sid has write permission" do
winsec.set_mode(WindowsSecurityTester::S_IWUSR, path)
- (Puppet::Util::Windows::File.get_attributes(path) & klass::FILE_ATTRIBUTE_READONLY).should == 0
+ expect(Puppet::Util::Windows::File.get_attributes(path) & klass::FILE_ATTRIBUTE_READONLY).to eq(0)
end
it "should leave them read-only if no sid has write permission and should allow full access for SYSTEM" do
winsec.set_mode(WindowsSecurityTester::S_IRUSR | WindowsSecurityTester::S_IXGRP, path)
- (Puppet::Util::Windows::File.get_attributes(path) & klass::FILE_ATTRIBUTE_READONLY).should be_nonzero
+ expect(Puppet::Util::Windows::File.get_attributes(path) & klass::FILE_ATTRIBUTE_READONLY).to be_nonzero
system_aces = winsec.get_aces_for_path_by_sid(path, sids[:system])
# when running under SYSTEM account, and set_group / set_owner hasn't been called
# SYSTEM full access will be restored
- system_aces.any? do |ace|
+ expect(system_aces.any? do |ace|
ace.mask == klass::FILE_ALL_ACCESS
- end.should be_true
+ end).to be_truthy
end
end
it "should raise an exception if an invalid path is provided" do
- lambda { winsec.set_mode(sids[:guest], "c:\\doesnotexist.txt") }.should raise_error(Puppet::Error, /The system cannot find the file specified./)
+ expect { winsec.set_mode(sids[:guest], "c:\\doesnotexist.txt") }.to raise_error(Puppet::Error, /The system cannot find the file specified./)
end
end
describe "#mode" do
it "should report when extra aces are encounted" do
sd = winsec.get_security_descriptor(path)
(544..547).each do |rid|
sd.dacl.allow("S-1-5-32-#{rid}", klass::STANDARD_RIGHTS_ALL)
end
winsec.set_security_descriptor(path, sd)
mode = winsec.get_mode(path)
- (mode & WindowsSecurityTester::S_IEXTRA).should == WindowsSecurityTester::S_IEXTRA
+ expect(mode & WindowsSecurityTester::S_IEXTRA).to eq(WindowsSecurityTester::S_IEXTRA)
end
it "should return deny aces" do
sd = winsec.get_security_descriptor(path)
sd.dacl.deny(sids[:guest], klass::FILE_GENERIC_WRITE)
winsec.set_security_descriptor(path, sd)
guest_aces = winsec.get_aces_for_path_by_sid(path, sids[:guest])
- guest_aces.find do |ace|
+ expect(guest_aces.find do |ace|
ace.type == Puppet::Util::Windows::AccessControlEntry::ACCESS_DENIED_ACE_TYPE
- end.should_not be_nil
+ end).not_to be_nil
end
it "should skip inherit-only ace" do
sd = winsec.get_security_descriptor(path)
dacl = Puppet::Util::Windows::AccessControlList.new
dacl.allow(
sids[:current_user], klass::STANDARD_RIGHTS_ALL | klass::SPECIFIC_RIGHTS_ALL
)
dacl.allow(
sids[:everyone],
klass::FILE_GENERIC_READ,
Puppet::Util::Windows::AccessControlEntry::INHERIT_ONLY_ACE | Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE
)
winsec.set_security_descriptor(path, sd)
- (winsec.get_mode(path) & WindowsSecurityTester::S_IRWXO).should == 0
+ expect(winsec.get_mode(path) & WindowsSecurityTester::S_IRWXO).to eq(0)
end
it "should raise an exception if an invalid path is provided" do
- lambda { winsec.get_mode("c:\\doesnotexist.txt") }.should raise_error(Puppet::Error, /The system cannot find the file specified./)
+ expect { winsec.get_mode("c:\\doesnotexist.txt") }.to raise_error(Puppet::Error, /The system cannot find the file specified./)
end
end
describe "inherited access control entries" do
it "should be absent when the access control list is protected, and should not remove SYSTEM" do
winsec.set_mode(WindowsSecurityTester::S_IRWXU, path)
mode = winsec.get_mode(path)
[ WindowsSecurityTester::S_IEXTRA,
WindowsSecurityTester::S_ISYSTEM_MISSING ].each do |flag|
- (mode & flag).should_not == flag
+ expect(mode & flag).not_to eq(flag)
end
end
it "should be present when the access control list is unprotected" do
# add a bunch of aces to the parent with permission to add children
allow = klass::STANDARD_RIGHTS_ALL | klass::SPECIFIC_RIGHTS_ALL
inherit = Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE | Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE
sd = winsec.get_security_descriptor(parent)
sd.dacl.allow(
"S-1-1-0", #everyone
allow,
inherit
)
(544..547).each do |rid|
sd.dacl.allow(
"S-1-5-32-#{rid}",
klass::STANDARD_RIGHTS_ALL,
inherit
)
end
winsec.set_security_descriptor(parent, sd)
# unprotect child, it should inherit from parent
winsec.set_mode(WindowsSecurityTester::S_IRWXU, path, false)
- (winsec.get_mode(path) & WindowsSecurityTester::S_IEXTRA).should == WindowsSecurityTester::S_IEXTRA
+ expect(winsec.get_mode(path) & WindowsSecurityTester::S_IEXTRA).to eq(WindowsSecurityTester::S_IEXTRA)
end
end
end
describe "for an administrator", :if => (Puppet.features.root? && Puppet.features.microsoft_windows?) do
before :each do
is_dir = Puppet::FileSystem.directory?(path)
winsec.set_mode(WindowsSecurityTester::S_IRWXU | WindowsSecurityTester::S_IRWXG, path)
set_group_depending_on_current_user(path)
winsec.set_owner(sids[:guest], path)
expected_error = RUBY_VERSION =~ /^2\./ && is_dir ? Errno::EISDIR : Errno::EACCES
- lambda { File.open(path, 'r') }.should raise_error(expected_error)
+ expect { File.open(path, 'r') }.to raise_error(expected_error)
end
after :each do
if Puppet::FileSystem.exist?(path)
winsec.set_owner(sids[:current_user], path)
winsec.set_mode(WindowsSecurityTester::S_IRWXU, path)
end
end
describe "#owner=" do
it "should accept a user sid" do
winsec.set_owner(sids[:admin], path)
- winsec.get_owner(path).should == sids[:admin]
+ expect(winsec.get_owner(path)).to eq(sids[:admin])
end
it "should accept a group sid" do
winsec.set_owner(sids[:power_users], path)
- winsec.get_owner(path).should == sids[:power_users]
+ expect(winsec.get_owner(path)).to eq(sids[:power_users])
end
it "should raise an exception if an invalid sid is provided" do
- lambda { winsec.set_owner("foobar", path) }.should raise_error(Puppet::Error, /Failed to convert string SID/)
+ expect { winsec.set_owner("foobar", path) }.to raise_error(Puppet::Error, /Failed to convert string SID/)
end
it "should raise an exception if an invalid path is provided" do
- lambda { winsec.set_owner(sids[:guest], "c:\\doesnotexist.txt") }.should raise_error(Puppet::Error, /The system cannot find the file specified./)
+ expect { winsec.set_owner(sids[:guest], "c:\\doesnotexist.txt") }.to raise_error(Puppet::Error, /The system cannot find the file specified./)
end
end
describe "#group=" do
it "should accept a group sid" do
winsec.set_group(sids[:power_users], path)
- winsec.get_group(path).should == sids[:power_users]
+ expect(winsec.get_group(path)).to eq(sids[:power_users])
end
it "should accept a user sid" do
winsec.set_group(sids[:admin], path)
- winsec.get_group(path).should == sids[:admin]
+ expect(winsec.get_group(path)).to eq(sids[:admin])
end
it "should combine owner and group rights when they are the same sid" do
winsec.set_owner(sids[:power_users], path)
winsec.set_group(sids[:power_users], path)
winsec.set_mode(0610, path)
- winsec.get_owner(path).should == sids[:power_users]
- winsec.get_group(path).should == sids[:power_users]
+ expect(winsec.get_owner(path)).to eq(sids[:power_users])
+ expect(winsec.get_group(path)).to eq(sids[:power_users])
# note group execute permission added to user ace, and then group rwx value
# reflected to match
# Exclude missing system ace, since that's not relevant
- (winsec.get_mode(path) & 0777).to_s(8).should == "770"
+ expect((winsec.get_mode(path) & 0777).to_s(8)).to eq("770")
end
it "should raise an exception if an invalid sid is provided" do
- lambda { winsec.set_group("foobar", path) }.should raise_error(Puppet::Error, /Failed to convert string SID/)
+ expect { winsec.set_group("foobar", path) }.to raise_error(Puppet::Error, /Failed to convert string SID/)
end
it "should raise an exception if an invalid path is provided" do
- lambda { winsec.set_group(sids[:guest], "c:\\doesnotexist.txt") }.should raise_error(Puppet::Error, /The system cannot find the file specified./)
+ expect { winsec.set_group(sids[:guest], "c:\\doesnotexist.txt") }.to raise_error(Puppet::Error, /The system cannot find the file specified./)
end
end
describe "when the sid is NULL" do
it "should retrieve an empty owner sid"
it "should retrieve an empty group sid"
end
describe "when the sid refers to a deleted trustee" do
it "should retrieve the user sid" do
sid = nil
user = Puppet::Util::Windows::ADSI::User.create("puppet#{rand(10000)}")
user.commit
begin
sid = Puppet::Util::Windows::ADSI::User.new(user.name).sid.to_s
winsec.set_owner(sid, path)
winsec.set_mode(WindowsSecurityTester::S_IRWXU, path)
ensure
Puppet::Util::Windows::ADSI::User.delete(user.name)
end
- winsec.get_owner(path).should == sid
- winsec.get_mode(path).should == WindowsSecurityTester::S_IRWXU
+ expect(winsec.get_owner(path)).to eq(sid)
+ expect(winsec.get_mode(path)).to eq(WindowsSecurityTester::S_IRWXU)
end
it "should retrieve the group sid" do
sid = nil
group = Puppet::Util::Windows::ADSI::Group.create("puppet#{rand(10000)}")
group.commit
begin
sid = Puppet::Util::Windows::ADSI::Group.new(group.name).sid.to_s
winsec.set_group(sid, path)
winsec.set_mode(WindowsSecurityTester::S_IRWXG, path)
ensure
Puppet::Util::Windows::ADSI::Group.delete(group.name)
end
- winsec.get_group(path).should == sid
- winsec.get_mode(path).should == WindowsSecurityTester::S_IRWXG
+ expect(winsec.get_group(path)).to eq(sid)
+ expect(winsec.get_mode(path)).to eq(WindowsSecurityTester::S_IRWXG)
end
end
describe "#mode" do
it "should deny all access when the DACL is empty, including SYSTEM" do
sd = winsec.get_security_descriptor(path)
# don't allow inherited aces to affect the test
protect = true
new_sd = Puppet::Util::Windows::SecurityDescriptor.new(sd.owner, sd.group, [], protect)
winsec.set_security_descriptor(path, new_sd)
- winsec.get_mode(path).should == WindowsSecurityTester::S_ISYSTEM_MISSING
+ expect(winsec.get_mode(path)).to eq(WindowsSecurityTester::S_ISYSTEM_MISSING)
end
# REMIND: ruby crashes when trying to set a NULL DACL
# it "should allow all when it is nil" do
# winsec.set_owner(sids[:current_user], path)
# winsec.open_file(path, WindowsSecurityTester::READ_CONTROL | WindowsSecurityTester::WRITE_DAC) do |handle|
# winsec.set_security_info(handle, WindowsSecurityTester::DACL_SECURITY_INFORMATION | WindowsSecurityTester::PROTECTED_DACL_SECURITY_INFORMATION, nil)
# end
# winsec.get_mode(path).to_s(8).should == "777"
# end
end
describe "when the parent directory" do
before :each do
winsec.set_owner(sids[:current_user], parent)
winsec.set_owner(sids[:current_user], path)
winsec.set_mode(0777, path, false)
end
describe "is writable and executable" do
describe "and sticky bit is set" do
it "should allow child owner" do
winsec.set_owner(sids[:guest], parent)
winsec.set_group(sids[:current_user], parent)
winsec.set_mode(01700, parent)
check_delete(path)
end
it "should allow parent owner" do
winsec.set_owner(sids[:current_user], parent)
winsec.set_group(sids[:guest], parent)
winsec.set_mode(01700, parent)
winsec.set_owner(sids[:current_user], path)
winsec.set_group(sids[:guest], path)
winsec.set_mode(0700, path)
check_delete(path)
end
it "should deny group" do
winsec.set_owner(sids[:guest], parent)
winsec.set_group(sids[:current_user], parent)
winsec.set_mode(01770, parent)
winsec.set_owner(sids[:guest], path)
winsec.set_group(sids[:current_user], path)
winsec.set_mode(0700, path)
- lambda { check_delete(path) }.should raise_error(Errno::EACCES)
+ expect { check_delete(path) }.to raise_error(Errno::EACCES)
end
it "should deny other" do
winsec.set_owner(sids[:guest], parent)
winsec.set_group(sids[:current_user], parent)
winsec.set_mode(01777, parent)
winsec.set_owner(sids[:guest], path)
winsec.set_group(sids[:current_user], path)
winsec.set_mode(0700, path)
- lambda { check_delete(path) }.should raise_error(Errno::EACCES)
+ expect { check_delete(path) }.to raise_error(Errno::EACCES)
end
end
describe "and sticky bit is not set" do
it "should allow child owner" do
winsec.set_owner(sids[:guest], parent)
winsec.set_group(sids[:current_user], parent)
winsec.set_mode(0700, parent)
check_delete(path)
end
it "should allow parent owner" do
winsec.set_owner(sids[:current_user], parent)
winsec.set_group(sids[:guest], parent)
winsec.set_mode(0700, parent)
winsec.set_owner(sids[:current_user], path)
winsec.set_group(sids[:guest], path)
winsec.set_mode(0700, path)
check_delete(path)
end
it "should allow group" do
winsec.set_owner(sids[:guest], parent)
winsec.set_group(sids[:current_user], parent)
winsec.set_mode(0770, parent)
winsec.set_owner(sids[:guest], path)
winsec.set_group(sids[:current_user], path)
winsec.set_mode(0700, path)
check_delete(path)
end
it "should allow other" do
winsec.set_owner(sids[:guest], parent)
winsec.set_group(sids[:current_user], parent)
winsec.set_mode(0777, parent)
winsec.set_owner(sids[:guest], path)
winsec.set_group(sids[:current_user], path)
winsec.set_mode(0700, path)
check_delete(path)
end
end
end
describe "is not writable" do
before :each do
winsec.set_group(sids[:current_user], parent)
winsec.set_mode(0555, parent)
end
it_behaves_like "only child owner"
end
describe "is not executable" do
before :each do
winsec.set_group(sids[:current_user], parent)
winsec.set_mode(0666, parent)
end
it_behaves_like "only child owner"
end
end
end
end
end
describe "file" do
let (:parent) do
tmpdir('win_sec_test_file')
end
let (:path) do
path = File.join(parent, 'childfile')
File.new(path, 'w').close
path
end
after :each do
# allow temp files to be cleaned up
grant_everyone_full_access(parent)
end
it_behaves_like "a securable object" do
def check_access(mode, path)
if (mode & WindowsSecurityTester::S_IRUSR).nonzero?
check_read(path)
else
- lambda { check_read(path) }.should raise_error(Errno::EACCES)
+ expect { check_read(path) }.to raise_error(Errno::EACCES)
end
if (mode & WindowsSecurityTester::S_IWUSR).nonzero?
check_write(path)
else
- lambda { check_write(path) }.should raise_error(Errno::EACCES)
+ expect { check_write(path) }.to raise_error(Errno::EACCES)
end
if (mode & WindowsSecurityTester::S_IXUSR).nonzero?
- lambda { check_execute(path) }.should raise_error(Errno::ENOEXEC)
+ expect { check_execute(path) }.to raise_error(Errno::ENOEXEC)
else
- lambda { check_execute(path) }.should raise_error(Errno::EACCES)
+ expect { check_execute(path) }.to raise_error(Errno::EACCES)
end
end
def check_read(path)
File.open(path, 'r').close
end
def check_write(path)
File.open(path, 'w').close
end
def check_execute(path)
Kernel.exec(path)
end
def check_delete(path)
File.delete(path)
end
end
describe "locked files" do
let (:explorer) { File.join(Dir::WINDOWS, "explorer.exe") }
it "should get the owner" do
- winsec.get_owner(explorer).should match /^S-1-5-/
+ expect(winsec.get_owner(explorer)).to match /^S-1-5-/
end
it "should get the group" do
- winsec.get_group(explorer).should match /^S-1-5-/
+ expect(winsec.get_group(explorer)).to match /^S-1-5-/
end
it "should get the mode" do
- winsec.get_mode(explorer).should == (WindowsSecurityTester::S_IRWXU | WindowsSecurityTester::S_IRWXG | WindowsSecurityTester::S_IEXTRA)
+ expect(winsec.get_mode(explorer)).to eq(WindowsSecurityTester::S_IRWXU | WindowsSecurityTester::S_IRWXG | WindowsSecurityTester::S_IEXTRA)
end
end
end
describe "directory" do
let (:parent) do
tmpdir('win_sec_test_dir')
end
let (:path) do
path = File.join(parent, 'childdir')
Dir.mkdir(path)
path
end
after :each do
# allow temp files to be cleaned up
grant_everyone_full_access(parent)
end
it_behaves_like "a securable object" do
def check_access(mode, path)
if (mode & WindowsSecurityTester::S_IRUSR).nonzero?
check_read(path)
else
- lambda { check_read(path) }.should raise_error(Errno::EACCES)
+ expect { check_read(path) }.to raise_error(Errno::EACCES)
end
if (mode & WindowsSecurityTester::S_IWUSR).nonzero?
check_write(path)
else
- lambda { check_write(path) }.should raise_error(Errno::EACCES)
+ expect { check_write(path) }.to raise_error(Errno::EACCES)
end
if (mode & WindowsSecurityTester::S_IXUSR).nonzero?
check_execute(path)
else
- lambda { check_execute(path) }.should raise_error(Errno::EACCES)
+ expect { check_execute(path) }.to raise_error(Errno::EACCES)
end
end
def check_read(path)
Dir.entries(path)
end
def check_write(path)
Dir.mkdir(File.join(path, "subdir"))
end
def check_execute(path)
Dir.chdir(path) {}
end
def check_delete(path)
Dir.rmdir(path)
end
end
describe "inheritable aces" do
it "should be applied to child objects" do
mode640 = WindowsSecurityTester::S_IRUSR | WindowsSecurityTester::S_IWUSR | WindowsSecurityTester::S_IRGRP
winsec.set_mode(mode640, path)
newfile = File.join(path, "newfile.txt")
File.new(newfile, "w").close
newdir = File.join(path, "newdir")
Dir.mkdir(newdir)
[newfile, newdir].each do |p|
mode = winsec.get_mode(p)
- (mode & 07777).to_s(8).should == mode640.to_s(8)
+ expect((mode & 07777).to_s(8)).to eq(mode640.to_s(8))
end
end
end
end
context "security descriptor" do
let(:path) { tmpfile('sec_descriptor') }
let(:read_execute) { 0x201FF }
let(:synchronize) { 0x100000 }
before :each do
FileUtils.touch(path)
end
it "preserves aces for other users" do
dacl = Puppet::Util::Windows::AccessControlList.new
sids_in_dacl = [sids[:current_user], sids[:users]]
sids_in_dacl.each do |sid|
dacl.allow(sid, read_execute)
end
sd = Puppet::Util::Windows::SecurityDescriptor.new(sids[:guest], sids[:guest], dacl, true)
winsec.set_security_descriptor(path, sd)
aces = winsec.get_security_descriptor(path).dacl.to_a
- aces.map(&:sid).should == sids_in_dacl
- aces.map(&:mask).all? { |mask| mask == read_execute }.should be_true
+ expect(aces.map(&:sid)).to eq(sids_in_dacl)
+ expect(aces.map(&:mask).all? { |mask| mask == read_execute }).to be_truthy
end
it "changes the sid for all aces that were assigned to the old owner" do
sd = winsec.get_security_descriptor(path)
- sd.owner.should_not == sids[:guest]
+ expect(sd.owner).not_to eq(sids[:guest])
sd.dacl.allow(sd.owner, read_execute)
sd.dacl.allow(sd.owner, synchronize)
sd.owner = sids[:guest]
winsec.set_security_descriptor(path, sd)
dacl = winsec.get_security_descriptor(path).dacl
aces = dacl.find_all { |ace| ace.sid == sids[:guest] }
# only non-inherited aces will be reassigned to guest, so
# make sure we find at least the two we added
- aces.size.should >= 2
+ expect(aces.size).to be >= 2
end
it "preserves INHERIT_ONLY_ACEs" do
# inherit only aces can only be set on directories
dir = tmpdir('inheritonlyace')
inherit_flags = Puppet::Util::Windows::AccessControlEntry::INHERIT_ONLY_ACE |
Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE |
Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE
sd = winsec.get_security_descriptor(dir)
sd.dacl.allow(sd.owner, klass::FILE_ALL_ACCESS, inherit_flags)
winsec.set_security_descriptor(dir, sd)
sd = winsec.get_security_descriptor(dir)
winsec.set_owner(sids[:guest], dir)
sd = winsec.get_security_descriptor(dir)
- sd.dacl.find do |ace|
+ expect(sd.dacl.find do |ace|
ace.sid == sids[:guest] && ace.inherit_only?
- end.should_not be_nil
+ end).not_to be_nil
end
it "allows deny ACEs with inheritance" do
# inheritance can only be set on directories
dir = tmpdir('denyaces')
inherit_flags = Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE |
Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE
sd = winsec.get_security_descriptor(dir)
sd.dacl.deny(sids[:guest], klass::FILE_ALL_ACCESS, inherit_flags)
winsec.set_security_descriptor(dir, sd)
sd = winsec.get_security_descriptor(dir)
- sd.dacl.find do |ace|
+ expect(sd.dacl.find do |ace|
ace.sid == sids[:guest] && ace.flags != 0
- end.should_not be_nil
+ end).not_to be_nil
end
context "when managing mode" do
it "removes aces for sids that are neither the owner nor group" do
# add a guest ace, it's never owner or group
sd = winsec.get_security_descriptor(path)
sd.dacl.allow(sids[:guest], read_execute)
winsec.set_security_descriptor(path, sd)
# setting the mode, it should remove extra aces
winsec.set_mode(0770, path)
# make sure it's gone
dacl = winsec.get_security_descriptor(path).dacl
aces = dacl.find_all { |ace| ace.sid == sids[:guest] }
- aces.should be_empty
+ expect(aces).to be_empty
end
end
end
end
diff --git a/spec/integration/util/windows/user_spec.rb b/spec/integration/util/windows/user_spec.rb
index 4e873b34c..cf18ebb4f 100755
--- a/spec/integration/util/windows/user_spec.rb
+++ b/spec/integration/util/windows/user_spec.rb
@@ -1,125 +1,125 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "Puppet::Util::Windows::User", :if => Puppet.features.microsoft_windows? do
describe "2003 without UAC" do
before :each do
Facter.stubs(:value).with(:kernelmajversion).returns("5.2")
end
it "should be an admin if user's token contains the Administrators SID" do
Puppet::Util::Windows::User.expects(:check_token_membership).returns(true)
Puppet::Util::Windows::Process.expects(:elevated_security?).never
- Puppet::Util::Windows::User.should be_admin
+ expect(Puppet::Util::Windows::User).to be_admin
end
it "should not be an admin if user's token doesn't contain the Administrators SID" do
Puppet::Util::Windows::User.expects(:check_token_membership).returns(false)
Puppet::Util::Windows::Process.expects(:elevated_security?).never
- Puppet::Util::Windows::User.should_not be_admin
+ expect(Puppet::Util::Windows::User).not_to be_admin
end
it "should raise an exception if we can't check token membership" do
Puppet::Util::Windows::User.expects(:check_token_membership).raises(Puppet::Util::Windows::Error, "Access denied.")
Puppet::Util::Windows::Process.expects(:elevated_security?).never
- lambda { Puppet::Util::Windows::User.admin? }.should raise_error(Puppet::Util::Windows::Error, /Access denied./)
+ expect { Puppet::Util::Windows::User.admin? }.to raise_error(Puppet::Util::Windows::Error, /Access denied./)
end
end
describe "2008 with UAC" do
before :each do
Facter.stubs(:value).with(:kernelmajversion).returns("6.0")
end
it "should be an admin if user is running with elevated privileges" do
Puppet::Util::Windows::Process.stubs(:elevated_security?).returns(true)
Puppet::Util::Windows::User.expects(:check_token_membership).never
- Puppet::Util::Windows::User.should be_admin
+ expect(Puppet::Util::Windows::User).to be_admin
end
it "should not be an admin if user is not running with elevated privileges" do
Puppet::Util::Windows::Process.stubs(:elevated_security?).returns(false)
Puppet::Util::Windows::User.expects(:check_token_membership).never
- Puppet::Util::Windows::User.should_not be_admin
+ expect(Puppet::Util::Windows::User).not_to be_admin
end
it "should raise an exception if the process fails to open the process token" do
Puppet::Util::Windows::Process.stubs(:elevated_security?).raises(Puppet::Util::Windows::Error, "Access denied.")
Puppet::Util::Windows::User.expects(:check_token_membership).never
- lambda { Puppet::Util::Windows::User.admin? }.should raise_error(Puppet::Util::Windows::Error, /Access denied./)
+ expect { Puppet::Util::Windows::User.admin? }.to raise_error(Puppet::Util::Windows::Error, /Access denied./)
end
end
describe "module function" do
let(:username) { 'fabio' }
let(:bad_password) { 'goldilocks' }
let(:logon_fail_msg) { /Failed to logon user "fabio": Logon failure: unknown user name or bad password./ }
def expect_logon_failure_error(&block)
expect {
yield
}.to raise_error { |error|
expect(error).to be_a(Puppet::Util::Windows::Error)
# http://msdn.microsoft.com/en-us/library/windows/desktop/ms681385(v=vs.85).aspx
# ERROR_LOGON_FAILURE 1326
expect(error.code).to eq(1326)
}
end
describe "load_profile" do
it "should raise an error when provided with an incorrect username and password" do
expect_logon_failure_error {
Puppet::Util::Windows::User.load_profile(username, bad_password)
}
end
it "should raise an error when provided with an incorrect username and nil password" do
expect_logon_failure_error {
Puppet::Util::Windows::User.load_profile(username, nil)
}
end
end
describe "logon_user" do
it "should raise an error when provided with an incorrect username and password" do
expect_logon_failure_error {
Puppet::Util::Windows::User.logon_user(username, bad_password)
}
end
it "should raise an error when provided with an incorrect username and nil password" do
expect_logon_failure_error {
Puppet::Util::Windows::User.logon_user(username, nil)
}
end
end
describe "password_is?" do
it "should return false given an incorrect username and password" do
- Puppet::Util::Windows::User.password_is?(username, bad_password).should be_false
+ expect(Puppet::Util::Windows::User.password_is?(username, bad_password)).to be_falsey
end
it "should return false given an incorrect username and nil password" do
- Puppet::Util::Windows::User.password_is?(username, nil).should be_false
+ expect(Puppet::Util::Windows::User.password_is?(username, nil)).to be_falsey
end
it "should return false given a nil username and an incorrect password" do
- Puppet::Util::Windows::User.password_is?(nil, bad_password).should be_false
+ expect(Puppet::Util::Windows::User.password_is?(nil, bad_password)).to be_falsey
end
end
describe "check_token_membership" do
it "should not raise an error" do
# added just to call an FFI code path on all platforms
- lambda { Puppet::Util::Windows::User.check_token_membership }.should_not raise_error
+ expect { Puppet::Util::Windows::User.check_token_membership }.not_to raise_error
end
end
end
end
diff --git a/spec/integration/util_spec.rb b/spec/integration/util_spec.rb
index 84f155123..2ffcad9b3 100755
--- a/spec/integration/util_spec.rb
+++ b/spec/integration/util_spec.rb
@@ -1,111 +1,111 @@
#!/usr/bin/env ruby
require 'spec_helper'
describe Puppet::Util do
include PuppetSpec::Files
describe "#execute" do
it "should properly allow stdout and stderr to share a file" do
command = "ruby -e '(1..10).each {|i| (i%2==0) ? $stdout.puts(i) : $stderr.puts(i)}'"
- Puppet::Util::Execution.execute(command, :combine => true).split.should =~ [*'1'..'10']
+ expect(Puppet::Util::Execution.execute(command, :combine => true).split).to match_array([*'1'..'10'])
end
it "should return output and set $CHILD_STATUS" do
command = "ruby -e 'puts \"foo\"; exit 42'"
output = Puppet::Util::Execution.execute(command, {:failonfail => false})
- output.should == "foo\n"
- $CHILD_STATUS.exitstatus.should == 42
+ expect(output).to eq("foo\n")
+ expect($CHILD_STATUS.exitstatus).to eq(42)
end
it "should raise an error if non-zero exit status is returned" do
command = "ruby -e 'exit 43'"
expect { Puppet::Util::Execution.execute(command) }.to raise_error(Puppet::ExecutionFailure, /Execution of '#{command}' returned 43: /)
- $CHILD_STATUS.exitstatus.should == 43
+ expect($CHILD_STATUS.exitstatus).to eq(43)
end
it "replace_file should preserve original ACEs from existing replaced file on Windows",
:if => Puppet.features.microsoft_windows? do
file = tmpfile("somefile")
FileUtils.touch(file)
admins = 'S-1-5-32-544'
dacl = Puppet::Util::Windows::AccessControlList.new
dacl.allow(admins, Puppet::Util::Windows::File::FILE_ALL_ACCESS)
protect = true
expected_sd = Puppet::Util::Windows::SecurityDescriptor.new(admins, admins, dacl, protect)
Puppet::Util::Windows::Security.set_security_descriptor(file, expected_sd)
ignored_mode = 0644
Puppet::Util.replace_file(file, ignored_mode) do |temp_file|
ignored_sd = Puppet::Util::Windows::Security.get_security_descriptor(temp_file.path)
users = 'S-1-5-11'
ignored_sd.dacl.allow(users, Puppet::Util::Windows::File::FILE_GENERIC_READ)
Puppet::Util::Windows::Security.set_security_descriptor(temp_file.path, ignored_sd)
end
replaced_sd = Puppet::Util::Windows::Security.get_security_descriptor(file)
- replaced_sd.dacl.should == expected_sd.dacl
+ expect(replaced_sd.dacl).to eq(expected_sd.dacl)
end
it "replace_file should use reasonable default ACEs on a new file on Windows",
:if => Puppet.features.microsoft_windows? do
dir = tmpdir('DACL_playground')
protected_sd = Puppet::Util::Windows::Security.get_security_descriptor(dir)
protected_sd.protect = true
Puppet::Util::Windows::Security.set_security_descriptor(dir, protected_sd)
sibling_path = File.join(dir, 'sibling_file')
FileUtils.touch(sibling_path)
expected_sd = Puppet::Util::Windows::Security.get_security_descriptor(sibling_path)
new_file_path = File.join(dir, 'new_file')
ignored_mode = nil
Puppet::Util.replace_file(new_file_path, ignored_mode) { |tmp_file| }
new_sd = Puppet::Util::Windows::Security.get_security_descriptor(new_file_path)
- new_sd.dacl.should == expected_sd.dacl
+ expect(new_sd.dacl).to eq(expected_sd.dacl)
end
end
it "replace_file should work with filenames that include - and . (PUP-1389)", :if => Puppet.features.microsoft_windows? do
expected_content = 'some content'
dir = tmpdir('ReplaceFile_playground')
destination_file = File.join(dir, 'some-file.xml')
Puppet::Util.replace_file(destination_file, nil) do |temp_file|
temp_file.open
temp_file.write(expected_content)
end
actual_content = File.read(destination_file)
- actual_content.should == expected_content
+ expect(actual_content).to eq(expected_content)
end
it "replace_file should work with filenames that include special characters (PUP-1389)", :if => Puppet.features.microsoft_windows? do
expected_content = 'some content'
dir = tmpdir('ReplaceFile_playground')
# http://www.fileformat.info/info/unicode/char/00e8/index.htm
# dest_name = "somèfile.xml"
dest_name = "som\u00E8file.xml"
destination_file = File.join(dir, dest_name)
Puppet::Util.replace_file(destination_file, nil) do |temp_file|
temp_file.open
temp_file.write(expected_content)
end
actual_content = File.read(destination_file)
- actual_content.should == expected_content
+ expect(actual_content).to eq(expected_content)
end
end
diff --git a/spec/lib/matchers/containment_matchers.rb b/spec/lib/matchers/containment_matchers.rb
index bc412fc5e..06c48b6a4 100644
--- a/spec/lib/matchers/containment_matchers.rb
+++ b/spec/lib/matchers/containment_matchers.rb
@@ -1,52 +1,52 @@
module ContainmentMatchers
class ContainClass
def initialize(containee)
@containee = containee
end
def in(container)
@container = container
self
end
def matches?(catalog)
@catalog = catalog
raise ArgumentError, "You must set the container using #in" unless @container
@container_resource = catalog.resource("Class", @container)
@containee_resource = catalog.resource("Class", @containee)
if @containee_resource && @container_resource
catalog.edge?(@container_resource, @containee_resource)
else
false
end
end
- def failure_message_for_should
+ def failure_message
message = "Expected #{@catalog.to_dot} to contain Class #{@containee.inspect} inside of Class #{@container.inspect} but "
missing = []
if @container_resource.nil?
missing << @container
end
if @containee_resource.nil?
missing << @containee
end
if ! missing.empty?
message << "the catalog does not contain #{missing.map(&:inspect).join(' or ')}"
else
message << "no containment relationship exists"
end
message
end
end
# expect(catalog).to contain_class(containee).in(container)
def contain_class(containee)
ContainClass.new(containee)
end
end
diff --git a/spec/lib/matchers/include.rb b/spec/lib/matchers/include.rb
index c34725856..35606a615 100644
--- a/spec/lib/matchers/include.rb
+++ b/spec/lib/matchers/include.rb
@@ -1,27 +1,27 @@
module Matchers; module Include
extend RSpec::Matchers::DSL
matcher :include_in_any_order do |*matchers|
match do |enumerable|
@not_matched = []
- expected.each do |matcher|
+ expected_as_array.each do |matcher|
if enumerable.empty?
break
end
if found = enumerable.find { |elem| matcher.matches?(elem) }
enumerable = enumerable.reject { |elem| elem == found }
else
@not_matched << matcher
end
end
@not_matched.empty? && enumerable.empty?
end
- failure_message_for_should do |enumerable|
- "did not match #{@not_matched.collect(&:description).join(', ')} in #{enumerable.inspect}: <#{@not_matched.collect(&:failure_message_for_should).join('>, <')}>"
+ failure_message do |enumerable|
+ "did not match #{@not_matched.collect(&:description).join(', ')} in #{enumerable.inspect}: <#{@not_matched.collect(&:failure_message).join('>, <')}>"
end
end
end; end
diff --git a/spec/lib/matchers/include_in_order.rb b/spec/lib/matchers/include_in_order.rb
index 56e4e41c7..3b70d5de7 100644
--- a/spec/lib/matchers/include_in_order.rb
+++ b/spec/lib/matchers/include_in_order.rb
@@ -1,21 +1,21 @@
RSpec::Matchers.define :include_in_order do |*expected|
include RSpec::Matchers::Pretty
match do |actual|
elements = expected.dup
actual.each do |elt|
if elt == elements.first
elements.shift
end
end
elements.empty?
end
- def failure_message_for_should
+ def failure_message
"expected #{@actual.inspect} to include#{expected_to_sentence} in order"
end
- def failure_message_for_should_not
+ def failure_message_when_negated
"expected #{@actual.inspect} not to include#{expected_to_sentence} in order"
end
end
diff --git a/spec/lib/matchers/json.rb b/spec/lib/matchers/json.rb
index e49a31705..089d08412 100644
--- a/spec/lib/matchers/json.rb
+++ b/spec/lib/matchers/json.rb
@@ -1,137 +1,137 @@
module JSONMatchers
class SetJsonAttribute
def initialize(attributes)
@attributes = attributes
end
def format
@format ||= Puppet::Network::FormatHandler.format('pson')
end
def json(instance)
PSON.parse(instance.to_pson)
end
def attr_value(attrs, instance)
attrs = attrs.dup
hash = json(instance)
while attrs.length > 0
name = attrs.shift
hash = hash[name]
end
hash
end
def to(value)
@value = value
self
end
def matches?(instance)
result = attr_value(@attributes, instance)
if @value
result == @value
else
! result.nil?
end
end
- def failure_message_for_should(instance)
+ def failure_message(instance)
if @value
"expected #{instance.inspect} to set #{@attributes.inspect} to #{@value.inspect}; got #{attr_value(@attributes, instance).inspect}"
else
"expected #{instance.inspect} to set #{@attributes.inspect} but was nil"
end
end
- def failure_message_for_should_not(instance)
+ def failure_message_when_negated(instance)
if @value
"expected #{instance.inspect} not to set #{@attributes.inspect} to #{@value.inspect}"
else
"expected #{instance.inspect} not to set #{@attributes.inspect} to nil"
end
end
end
class ReadJsonAttribute
def initialize(attribute)
@attribute = attribute
end
def format
@format ||= Puppet::Network::FormatHandler.format('pson')
end
def from(value)
@json = value
self
end
def as(as)
@value = as
self
end
def matches?(klass)
raise "Must specify json with 'from'" unless @json
@instance = format.intern(klass, @json)
if @value
@instance.send(@attribute) == @value
else
! @instance.send(@attribute).nil?
end
end
- def failure_message_for_should(klass)
+ def failure_message(klass)
if @value
"expected #{klass} to read #{@attribute} from #{@json} as #{@value.inspect}; got #{@instance.send(@attribute).inspect}"
else
"expected #{klass} to read #{@attribute} from #{@json} but was nil"
end
end
- def failure_message_for_should_not(klass)
+ def failure_message_when_negated(klass)
if @value
"expected #{klass} not to set #{@attribute} to #{@value}"
else
"expected #{klass} not to set #{@attribute} to nil"
end
end
end
if !Puppet.features.microsoft_windows?
require 'json'
require 'json-schema'
class SchemaMatcher
JSON_META_SCHEMA = JSON.parse(File.read('api/schemas/json-meta-schema.json'))
def initialize(schema)
@schema = schema
end
def matches?(json)
JSON::Validator.validate!(JSON_META_SCHEMA, @schema)
JSON::Validator.validate!(@schema, json)
end
end
end
def validate_against(schema_file)
if Puppet.features.microsoft_windows?
pending("Schema checks cannot be done on windows because of json-schema problems")
else
schema = JSON.parse(File.read(schema_file))
SchemaMatcher.new(schema)
end
end
def set_json_attribute(*attributes)
SetJsonAttribute.new(attributes)
end
def read_json_attribute(attribute)
ReadJsonAttribute.new(attribute)
end
end
diff --git a/spec/lib/matchers/match_tokens2.rb b/spec/lib/matchers/match_tokens2.rb
index c1872e68f..95d0662e9 100644
--- a/spec/lib/matchers/match_tokens2.rb
+++ b/spec/lib/matchers/match_tokens2.rb
@@ -1,74 +1,74 @@
# Matches tokens produced by lexer
# The given exepected is one or more entries where an entry is one of
# - a token symbol
# - an Array with a token symbol and the text value
# - an Array with a token symbol and a Hash specifying all attributes of the token
# - nil (ignore)
#
RSpec::Matchers.define :match_tokens2 do | *expected |
match do | actual |
expected.zip(actual).all? do |e, a|
compare(e, a)
end
end
- def failure_message_for_should
+ def failure_message
msg = ["Expected (#{expected.size}):"]
expected.each {|e| msg << e.to_s }
zipped = expected.zip(actual)
msg << "\nGot (#{actual.size}):"
actual.each_with_index do |e, idx|
if zipped[idx]
zipped_expected = zipped[idx][0]
zipped_actual = zipped[idx][1]
prefix = compare(zipped_expected, zipped_actual) ? ' ' : '*'
msg2 = ["#{prefix}[:"]
msg2 << e[0].to_s
msg2 << ', '
if e[1] == false
msg2 << 'false'
else
msg2 << e[1][:value].to_s.dump
end
# If expectation has options, output them
if zipped_expected.is_a?(Array) && zipped_expected[2] && zipped_expected[2].is_a?(Hash)
msg2 << ", {"
msg3 = []
zipped_expected[2].each do |k,v|
prefix = e[1][k] != v ? "*" : ''
msg3 << "#{prefix}:#{k}=>#{e[1][k]}"
end
msg2 << msg3.join(", ")
msg2 << "}"
end
msg2 << ']'
msg << msg2.join('')
end
end
msg.join("\n")
end
def compare(e, a)
# if expected ends before actual
return true if !e
# If actual ends before expected
return false if !a
# Simple - only expect token to match
return true if a[0] == e
# Expect value and optional attributes to match
if e.is_a? Array
# tokens must match
return false unless a[0] == e[0]
if e[2].is_a?(Hash)
e[2].each {|k,v| return false unless a[1][k] == v }
end
return (a[1] == e[1] || (a[1][:value] == e[1]))
end
false
end
end
diff --git a/spec/lib/matchers/relationship_graph_matchers.rb b/spec/lib/matchers/relationship_graph_matchers.rb
index 3d08cdd87..9912a8828 100644
--- a/spec/lib/matchers/relationship_graph_matchers.rb
+++ b/spec/lib/matchers/relationship_graph_matchers.rb
@@ -1,48 +1,48 @@
module RelationshipGraphMatchers
class EnforceOrderWithEdge
def initialize(before, after)
@before = before
@after = after
end
def matches?(actual_graph)
@actual_graph = actual_graph
@reverse_edge = actual_graph.edge?(
vertex_called(actual_graph, @after),
vertex_called(actual_graph, @before))
@forward_edge = actual_graph.edge?(
vertex_called(actual_graph, @before),
vertex_called(actual_graph, @after))
@forward_edge && !@reverse_edge
end
- def failure_message_for_should
+ def failure_message
"expect #{@actual_graph.to_dot_graph} to only contain an edge from #{@before} to #{@after} but #{[forward_failure_message, reverse_failure_message].compact.join(' and ')}"
end
def forward_failure_message
if !@forward_edge
"did not contain an edge from #{@before} to #{@after}"
end
end
def reverse_failure_message
if @reverse_edge
"contained an edge from #{@after} to #{@before}"
end
end
private
def vertex_called(graph, name)
graph.vertices.find { |v| v.ref =~ /#{Regexp.escape(name)}/ }
end
end
def enforce_order_with_edge(before, after)
EnforceOrderWithEdge.new(before, after)
end
end
diff --git a/spec/lib/matchers/resource.rb b/spec/lib/matchers/resource.rb
index fc305d0d2..cd4394ffe 100644
--- a/spec/lib/matchers/resource.rb
+++ b/spec/lib/matchers/resource.rb
@@ -1,68 +1,53 @@
module Matchers; module Resource
extend RSpec::Matchers::DSL
- matcher :be_resource do |expected_resource|
- @params = {}
-
- match do |actual_resource|
+ matcher :have_resource do |expected_resource|
+ def resource_match(expected_resource, actual_resource)
matched = true
failures = []
if actual_resource.ref != expected_resource
matched = false
failures << "expected #{expected_resource} but was #{actual_resource.ref}"
end
+ @params ||= {}
@params.each do |name, value|
case value
when RSpec::Matchers::DSL::Matcher
if !value.matches?(actual_resource[name])
matched = false
failures << "expected #{name} to match '#{value.description}' but was '#{actual_resource[name]}'"
end
else
if actual_resource[name] != value
matched = false
failures << "expected #{name} to be '#{value}' but was '#{actual_resource[name]}'"
end
end
end
@mismatch = failures.join("\n")
matched
end
- chain :with_parameter do |name, value|
- @params[name] = value
- end
-
- def failure_message_for_should
- @mismatch
- end
- end
- module_function :be_resource
-
- matcher :have_resource do |expected_resource|
- @params = {}
- @matcher = Matchers::Resource.be_resource(expected_resource)
-
match do |actual_catalog|
@mismatch = ""
if resource = actual_catalog.resource(expected_resource)
- @matcher.matches?(resource)
+ resource_match(expected_resource, resource)
else
@mismatch = "expected #{@actual.to_dot} to include #{@expected[0]}"
false
end
end
chain :with_parameter do |name, value|
- @matcher.with_parameter(name, value)
+ @params ||= {}
+ @params[name] = value
end
- def failure_message_for_should
- @mismatch.empty? ? @matcher.failure_message_for_should : @mismatch
+ def failure_message
+ @mismatch
end
end
- module_function :have_resource
end; end
diff --git a/spec/lib/puppet_spec/matchers.rb b/spec/lib/puppet_spec/matchers.rb
index 033397cb8..11e2e9c4d 100644
--- a/spec/lib/puppet_spec/matchers.rb
+++ b/spec/lib/puppet_spec/matchers.rb
@@ -1,152 +1,159 @@
require 'stringio'
########################################################################
# Backward compatibility for Jenkins outdated environment.
module RSpec
module Matchers
module BlockAliases
alias_method :to, :should unless method_defined? :to
alias_method :to_not, :should_not unless method_defined? :to_not
alias_method :not_to, :should_not unless method_defined? :not_to
end
end
end
########################################################################
# Custom matchers...
RSpec::Matchers.define :have_matching_element do |expected|
match do |actual|
actual.any? { |item| item =~ expected }
end
end
RSpec::Matchers.define :have_matching_log do |expected|
match do |actual|
actual.map(&:to_s).any? { |item| item =~ expected }
end
end
RSpec::Matchers.define :exit_with do |expected|
actual = nil
match do |block|
begin
block.call
rescue SystemExit => e
actual = e.status
end
actual and actual == expected
end
- failure_message_for_should do |block|
+
+ supports_block_expectations
+
+ failure_message do |block|
"expected exit with code #{expected} but " +
(actual.nil? ? " exit was not called" : "we exited with #{actual} instead")
end
- failure_message_for_should_not do |block|
+
+ failure_message_when_negated do |block|
"expected that exit would not be called with #{expected}"
end
+
description do
"expect exit with #{expected}"
end
end
RSpec::Matchers.define :have_printed do |expected|
case expected
when String, Regexp
expected = expected
else
expected = expected.to_s
end
chain :and_exit_with do |code|
@expected_exit_code = code
end
define_method :matches_exit_code? do |actual|
@expected_exit_code.nil? || @expected_exit_code == actual
end
define_method :matches_output? do |actual|
return false unless actual
case expected
when String
actual.include?(expected)
when Regexp
expected.match(actual)
else
raise ArgumentError, "No idea how to match a #{actual.class.name}"
end
end
match do |block|
$stderr = $stdout = StringIO.new
$stdout.set_encoding('UTF-8') if $stdout.respond_to?(:set_encoding)
begin
block.call
rescue SystemExit => e
raise unless @expected_exit_code
@actual_exit_code = e.status
ensure
$stdout.rewind
@actual = $stdout.read
$stdout = STDOUT
$stderr = STDERR
end
matches_output?(@actual) && matches_exit_code?(@actual_exit_code)
end
- failure_message_for_should do |actual|
+ supports_block_expectations
+
+ failure_message do |actual|
if actual.nil? then
"expected #{expected.inspect}, but nothing was printed"
else
if !@expected_exit_code.nil? && matches_output?(actual)
"expected exit with code #{@expected_exit_code} but " +
(@actual_exit_code.nil? ? " exit was not called" : "exited with #{@actual_exit_code} instead")
else
"expected #{expected.inspect} to be printed; got:\n#{actual}"
end
end
end
- failure_message_for_should_not do |actual|
+ failure_message_when_negated do |actual|
if @expected_exit_code && matches_exit_code?(@actual_exit_code)
"expected exit code to not be #{@actual_exit_code}"
else
"expected #{expected.inspect} to not be printed; got:\n#{actual}"
end
end
description do
"expect #{expected.inspect} to be printed" + (@expected_exit_code.nil ? '' : " with exit code #{@expected_exit_code}")
end
end
RSpec::Matchers.define :equal_attributes_of do |expected|
match do |actual|
actual.instance_variables.all? do |attr|
actual.instance_variable_get(attr) == expected.instance_variable_get(attr)
end
end
end
RSpec::Matchers.define :equal_resource_attributes_of do |expected|
match do |actual|
actual.keys do |attr|
actual[attr] == expected[attr]
end
end
end
RSpec::Matchers.define :be_one_of do |*expected|
match do |actual|
expected.include? actual
end
- failure_message_for_should do |actual|
+ failure_message do |actual|
"expected #{actual.inspect} to be one of #{expected.map(&:inspect).join(' or ')}"
end
end
diff --git a/spec/lib/puppet_spec/module_tool/shared_functions.rb b/spec/lib/puppet_spec/module_tool/shared_functions.rb
index 27da4f8c7..634028f4f 100644
--- a/spec/lib/puppet_spec/module_tool/shared_functions.rb
+++ b/spec/lib/puppet_spec/module_tool/shared_functions.rb
@@ -1,56 +1,56 @@
require 'json'
module PuppetSpec
module ModuleTool
module SharedFunctions
def remote_release(name, version)
remote_source.available_releases[name][version]
end
def preinstall(name, version, options = { :into => primary_dir })
release = remote_release(name, version)
raise "Could not preinstall #{name} v#{version}" if release.nil?
name = release.name[/-(.*)/, 1]
moddir = File.join(options[:into], name)
FileUtils.mkdir_p(moddir)
File.open(File.join(moddir, 'metadata.json'), 'w') do |file|
file.puts(JSON.generate(release.metadata))
end
end
def mark_changed(path)
app = Puppet::ModuleTool::Applications::Checksummer
app.stubs(:run).with(path).returns(['README'])
end
def graph_should_include(name, options)
releases = flatten_graph(subject[:graph] || [])
release = releases.find { |x| x[:name] == name }
if options.nil?
- release.should be_nil
+ expect(release).to be_nil
else
from = options.keys.find { |k| k.nil? || k.is_a?(Semantic::Version) }
to = options.delete(from)
if to or from
options[:previous_version] ||= from
options[:version] ||= to
end
- release.should_not be_nil
- release.should include options
+ expect(release).not_to be_nil
+ expect(release).to include options
end
end
def flatten_graph(graph)
graph + graph.map { |sub| flatten_graph(sub[:dependencies]) }.flatten
end
def v(str)
Semantic::Version.parse(str)
end
end
end
end
diff --git a/spec/lib/puppet_spec/pops.rb b/spec/lib/puppet_spec/pops.rb
index 442c85ba6..2cf133d87 100644
--- a/spec/lib/puppet_spec/pops.rb
+++ b/spec/lib/puppet_spec/pops.rb
@@ -1,16 +1,16 @@
module PuppetSpec::Pops
extend RSpec::Matchers::DSL
# Checks if an Acceptor has a specific issue in its list of diagnostics
matcher :have_issue do |expected|
match do |actual|
actual.diagnostics.index { |i| i.issue == expected } != nil
end
- failure_message_for_should do |actual|
+ failure_message do |actual|
"expected Acceptor[#{actual.diagnostics.collect { |i| i.issue.issue_code }.join(',')}] to contain issue #{expected.issue_code}"
end
- failure_message_for_should_not do |actual|
+ failure_message_when_negated do |actual|
"expected Acceptor[#{actual.diagnostics.collect { |i| i.issue.issue_code }.join(',')}] to not contain issue #{expected.issue_code}"
end
end
end
diff --git a/spec/monkey_patches/alias_should_to_must.rb b/spec/monkey_patches/alias_should_to_must.rb
deleted file mode 100755
index 389ff8247..000000000
--- a/spec/monkey_patches/alias_should_to_must.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-require 'rspec'
-
-# This is necessary because the RAL has a 'should' method.
-class Object
- alias :must :should
- alias :must_not :should_not
-end
-
-# ...and this is because we want to make sure we don't ignore that change
-# above. Gotta love overwriting functions, but the performance cost at
-# runtime is pretty terrible if we don't.
-require 'puppet/type'
-class Puppet::Type
- alias :should_native :should
- def should(value)
- unless value.is_a? String or value.is_a? Symbol
- raise "you need to call .must rather than .should on Puppet::Type instances"
- end
- should_native(value)
- end
-end
diff --git a/spec/shared_behaviours/all_parsedfile_providers.rb b/spec/shared_behaviours/all_parsedfile_providers.rb
index 9cb199b5f..9fdf54b60 100755
--- a/spec/shared_behaviours/all_parsedfile_providers.rb
+++ b/spec/shared_behaviours/all_parsedfile_providers.rb
@@ -1,21 +1,21 @@
shared_examples_for "all parsedfile providers" do |provider, *files|
if files.empty? then
files = my_fixtures
end
files.flatten.each do |file|
it "should rewrite #{file} reasonably unchanged" do
provider.stubs(:default_target).returns(file)
provider.prefetch
text = provider.to_file(provider.target_records(file))
text.gsub!(/^# HEADER.+\n/, '')
oldlines = File.readlines(file)
newlines = text.chomp.split "\n"
oldlines.zip(newlines).each do |old, new|
- new.gsub(/\s+/, '').should == old.chomp.gsub(/\s+/, '')
+ expect(new.gsub(/\s+/, '')).to eq(old.chomp.gsub(/\s+/, ''))
end
end
end
end
diff --git a/spec/shared_behaviours/an_indirector_face.rb b/spec/shared_behaviours/an_indirector_face.rb
index cba74b696..1eb5ab8fe 100644
--- a/spec/shared_behaviours/an_indirector_face.rb
+++ b/spec/shared_behaviours/an_indirector_face.rb
@@ -1,6 +1,6 @@
shared_examples_for "an indirector face" do
[:find, :search, :save, :destroy, :info].each do |action|
- it { should be_action action }
- it { should respond_to action }
+ it { is_expected.to be_action action }
+ it { is_expected.to respond_to action }
end
end
diff --git a/spec/shared_behaviours/documentation_on_faces.rb b/spec/shared_behaviours/documentation_on_faces.rb
index 7c4d9e04b..7f54bcc20 100644
--- a/spec/shared_behaviours/documentation_on_faces.rb
+++ b/spec/shared_behaviours/documentation_on_faces.rb
@@ -1,263 +1,263 @@
# encoding: UTF-8
shared_examples_for "documentation on faces" do
defined?(Attrs) or
Attrs = [:summary, :description, :examples, :short_description, :notes, :author]
defined?(SingleLineAttrs) or
SingleLineAttrs = [:summary, :author]
# Simple, procedural tests that apply to a bunch of methods.
Attrs.each do |attr|
it "should accept a #{attr}" do
expect { subject.send("#{attr}=", "hello") }.not_to raise_error
- subject.send(attr).should == "hello"
+ expect(subject.send(attr)).to eq("hello")
end
it "should accept a long (single line) value for #{attr}" do
text = "I never know when to stop with the word banana" + ("na" * 1000)
expect { subject.send("#{attr}=", text) }.to_not raise_error
- subject.send(attr).should == text
+ expect(subject.send(attr)).to eq(text)
end
end
Attrs.each do |getter|
setter = "#{getter}=".to_sym
context "#{getter}" do
it "should strip leading whitespace on a single line" do
subject.send(setter, " death to whitespace")
- subject.send(getter).should == "death to whitespace"
+ expect(subject.send(getter)).to eq("death to whitespace")
end
it "should strip trailing whitespace on a single line" do
subject.send(setter, "death to whitespace ")
- subject.send(getter).should == "death to whitespace"
+ expect(subject.send(getter)).to eq("death to whitespace")
end
it "should strip whitespace at both ends at once" do
subject.send(setter, " death to whitespace ")
- subject.send(getter).should == "death to whitespace"
+ expect(subject.send(getter)).to eq("death to whitespace")
end
multiline_text = "with\nnewlines"
if SingleLineAttrs.include? getter then
it "should not accept multiline values" do
expect { subject.send(setter, multiline_text) }.
to raise_error ArgumentError, /#{getter} should be a single line/
- subject.send(getter).should be_nil
+ expect(subject.send(getter)).to be_nil
end
else
it "should accept multiline values" do
expect { subject.send(setter, multiline_text) }.not_to raise_error
- subject.send(getter).should == multiline_text
+ expect(subject.send(getter)).to eq(multiline_text)
end
[1, 2, 4, 7, 25].each do |length|
context "#{length} chars indent" do
indent = ' ' * length
it "should strip leading whitespace on multiple lines" do
text = "this\nis\the\final\outcome"
subject.send(setter, text.gsub(/^/, indent))
- subject.send(getter).should == text
+ expect(subject.send(getter)).to eq(text)
end
it "should not remove formatting whitespace, only global indent" do
text = "this\n is\n the\n ultimate\ntest"
subject.send(setter, text.gsub(/^/, indent))
- subject.send(getter).should == text
+ expect(subject.send(getter)).to eq(text)
end
end
end
it "should strip whitespace with a blank line" do
subject.send(setter, " this\n\n should outdent")
- subject.send(getter).should == "this\n\nshould outdent"
+ expect(subject.send(getter)).to eq("this\n\nshould outdent")
end
end
end
end
describe "#short_description" do
it "should return the set value if set after description" do
subject.description = "hello\ngoodbye"
subject.short_description = "whatever"
- subject.short_description.should == "whatever"
+ expect(subject.short_description).to eq("whatever")
end
it "should return the set value if set before description" do
subject.short_description = "whatever"
subject.description = "hello\ngoodbye"
- subject.short_description.should == "whatever"
+ expect(subject.short_description).to eq("whatever")
end
it "should return nothing if not set and no description" do
- subject.short_description.should be_nil
+ expect(subject.short_description).to be_nil
end
it "should return the first paragraph of description if not set (where it is one line long)" do
subject.description = "hello"
- subject.short_description.should == subject.description
+ expect(subject.short_description).to eq(subject.description)
end
it "should return the first paragraph of description if not set (where there is no paragraph break)" do
subject.description = "hello\ngoodbye"
- subject.short_description.should == subject.description
+ expect(subject.short_description).to eq(subject.description)
end
it "should return the first paragraph of description if not set (where there is a paragraph break)" do
subject.description = "hello\ngoodbye\n\nmore\ntext\nhere\n\nfinal\nparagraph"
- subject.short_description.should == "hello\ngoodbye"
+ expect(subject.short_description).to eq("hello\ngoodbye")
end
it "should trim a very, very long first paragraph and add ellipsis" do
line = "this is a very, very, very long long line full of text\n"
subject.description = line * 20 + "\n\nwhatever, dude."
- subject.short_description.should == (line * 5).chomp + ' [...]'
+ expect(subject.short_description).to eq((line * 5).chomp + ' [...]')
end
it "should trim a very very long only paragraph even if it is followed by a new paragraph" do
line = "this is a very, very, very long long line full of text\n"
subject.description = line * 20
- subject.short_description.should == (line * 5).chomp + ' [...]'
+ expect(subject.short_description).to eq((line * 5).chomp + ' [...]')
end
end
describe "multiple authors" do
authors = %w{John Paul George Ringo}
context "in the DSL" do
it "should support multiple authors" do
authors.each {|name| subject.author name }
- subject.authors.should =~ authors
+ expect(subject.authors).to match_array(authors)
- subject.author.should == authors.join("\n")
+ expect(subject.author).to eq(authors.join("\n"))
end
it "should reject author as an array" do
expect { subject.author ["Foo", "Bar"] }.
to raise_error ArgumentError, /author must be a string/
end
end
context "#author=" do
it "should accept a single name" do
subject.author = "Fred"
- subject.author.should == "Fred"
+ expect(subject.author).to eq("Fred")
end
it "should accept an array of names" do
subject.author = authors
- subject.authors.should =~ authors
- subject.author.should == authors.join("\n")
+ expect(subject.authors).to match_array(authors)
+ expect(subject.author).to eq(authors.join("\n"))
end
it "should not append when set multiple times" do
subject.author = "Fred"
subject.author = "John"
- subject.author.should == "John"
+ expect(subject.author).to eq("John")
end
it "should reject arrays with embedded newlines" do
expect { subject.author = ["Fred\nJohn"] }.
to raise_error ArgumentError, /author should be a single line/
end
end
end
describe "#license" do
it "should default to reserving rights" do
- subject.license.should =~ /All Rights Reserved/
+ expect(subject.license).to match(/All Rights Reserved/)
end
it "should accept an arbitrary license string on the object" do
subject.license = "foo"
- subject.license.should == "foo"
+ expect(subject.license).to eq("foo")
end
it "should accept symbols to specify existing licenses..."
end
describe "#copyright" do
it "should fail with just a name" do
expect { subject.copyright("invalid") }.
to raise_error ArgumentError, /copyright takes the owners names, then the years covered/
end
[1997, "1997"].each do |year|
it "should accept an entity name and a #{year.class.name} year" do
subject.copyright("me", year)
- subject.copyright.should =~ /\bme\b/
- subject.copyright.should =~ /#{year}/
+ expect(subject.copyright).to match(/\bme\b/)
+ expect(subject.copyright).to match(/#{year}/)
end
it "should accept multiple entity names and a #{year.class.name} year" do
subject.copyright ["me", "you"], year
- subject.copyright.should =~ /\bme\b/
- subject.copyright.should =~ /\byou\b/
- subject.copyright.should =~ /#{year}/
+ expect(subject.copyright).to match(/\bme\b/)
+ expect(subject.copyright).to match(/\byou\b/)
+ expect(subject.copyright).to match(/#{year}/)
end
end
["1997-2003", "1997 - 2003", 1997..2003].each do |range|
it "should accept a #{range.class.name} range of years" do
subject.copyright("me", range)
- subject.copyright.should =~ /\bme\b/
- subject.copyright.should =~ /1997-2003/
+ expect(subject.copyright).to match(/\bme\b/)
+ expect(subject.copyright).to match(/1997-2003/)
end
it "should accept a #{range.class.name} range of years" do
subject.copyright ["me", "you"], range
- subject.copyright.should =~ /\bme\b/
- subject.copyright.should =~ /\byou\b/
- subject.copyright.should =~ /1997-2003/
+ expect(subject.copyright).to match(/\bme\b/)
+ expect(subject.copyright).to match(/\byou\b/)
+ expect(subject.copyright).to match(/1997-2003/)
end
end
[[1997, 2003], ["1997", 2003], ["1997", "2003"]].each do |input|
it "should accept the set of years #{input.inspect} in an array" do
subject.copyright "me", input
- subject.copyright.should =~ /\bme\b/
- subject.copyright.should =~ /1997, 2003/
+ expect(subject.copyright).to match(/\bme\b/)
+ expect(subject.copyright).to match(/1997, 2003/)
end
it "should accept the set of years #{input.inspect} in an array" do
subject.copyright ["me", "you"], input
- subject.copyright.should =~ /\bme\b/
- subject.copyright.should =~ /\byou\b/
- subject.copyright.should =~ /1997, 2003/
+ expect(subject.copyright).to match(/\bme\b/)
+ expect(subject.copyright).to match(/\byou\b/)
+ expect(subject.copyright).to match(/1997, 2003/)
end
end
it "should warn if someone does math accidentally on the range of years" do
expect { subject.copyright "me", 1997-2003 }.
to raise_error ArgumentError, /copyright with a year before 1970 is very strange; did you accidentally add or subtract two years\?/
end
it "should accept complex copyright years" do
years = [1997, 1999, 2000..2002, 2005].reverse
subject.copyright "me", years
- subject.copyright.should =~ /\bme\b/
- subject.copyright.should =~ /1997, 1999, 2000-2002, 2005/
+ expect(subject.copyright).to match(/\bme\b/)
+ expect(subject.copyright).to match(/1997, 1999, 2000-2002, 2005/)
end
end
# Things that are automatically generated.
[:name, :options, :synopsis].each do |attr|
describe "##{attr}" do
it "should not allow you to set #{attr}" do
- subject.should_not respond_to :"#{attr}="
+ expect(subject).not_to respond_to :"#{attr}="
end
it "should have a #{attr}" do
- subject.send(attr).should_not be_nil
+ expect(subject.send(attr)).not_to be_nil
end
it "'s #{attr} should not be empty..." do
- subject.send(attr).should_not == ''
+ expect(subject.send(attr)).not_to eq('')
end
end
end
end
diff --git a/spec/shared_behaviours/file_server_terminus.rb b/spec/shared_behaviours/file_server_terminus.rb
index 25d24682a..ce3b150fb 100755
--- a/spec/shared_behaviours/file_server_terminus.rb
+++ b/spec/shared_behaviours/file_server_terminus.rb
@@ -1,41 +1,41 @@
#! /usr/bin/env ruby
shared_examples_for "Puppet::Indirector::FileServerTerminus" do
# This only works if the shared behaviour is included before
# the 'before' block in the including context.
before do
Puppet::FileServing::Configuration.instance_variable_set(:@configuration, nil)
Puppet::FileSystem.stubs(:exist?).returns true
Puppet::FileSystem.stubs(:exist?).with(Puppet[:fileserverconfig]).returns(true)
@path = Tempfile.new("file_server_testing")
path = @path.path
@path.close!
@path = path
Dir.mkdir(@path)
File.open(File.join(@path, "myfile"), "w") { |f| f.print "my content" }
# Use a real mount, so the integration is a bit deeper.
@mount1 = Puppet::FileServing::Configuration::Mount::File.new("one")
@mount1.path = @path
@parser = stub 'parser', :changed? => false
@parser.stubs(:parse).returns("one" => @mount1)
Puppet::FileServing::Configuration::Parser.stubs(:new).returns(@parser)
# Stub out the modules terminus
@modules = mock 'modules terminus'
@request = Puppet::Indirector::Request.new(:indirection, :method, "puppet://myhost/one/myfile", nil)
end
it "should use the file server configuration to find files" do
@modules.stubs(:find).returns(nil)
@terminus.indirection.stubs(:terminus).with(:modules).returns(@modules)
path = File.join(@path, "myfile")
- @terminus.find(@request).should be_instance_of(@test_class)
+ expect(@terminus.find(@request)).to be_instance_of(@test_class)
end
end
diff --git a/spec/shared_behaviours/hiera_indirections.rb b/spec/shared_behaviours/hiera_indirections.rb
index fe6dc35ad..d135a0f61 100644
--- a/spec/shared_behaviours/hiera_indirections.rb
+++ b/spec/shared_behaviours/hiera_indirections.rb
@@ -1,99 +1,99 @@
shared_examples_for "Hiera indirection" do |test_klass, fixture_dir|
include PuppetSpec::Files
def write_hiera_config(config_file, datadir)
File.open(config_file, 'w') do |f|
f.write("---
:yaml:
:datadir: #{datadir}
:hierarchy: ['global', 'invalid']
:logger: 'noop'
:backends: ['yaml']
")
end
end
def request(key)
Puppet::Indirector::Request.new(:hiera, :find, key, nil)
end
before do
hiera_config_file = tmpfile("hiera.yaml")
Puppet.settings[:hiera_config] = hiera_config_file
write_hiera_config(hiera_config_file, fixture_dir)
end
after do
test_klass.instance_variable_set(:@hiera, nil)
end
it "should be the default data_binding terminus" do
- Puppet.settings[:data_binding_terminus].should == :hiera
+ expect(Puppet.settings[:data_binding_terminus]).to eq(:hiera)
end
it "should raise an error if we don't have the hiera feature" do
Puppet.features.expects(:hiera?).returns(false)
- lambda { test_klass.new }.should raise_error RuntimeError,
+ expect { test_klass.new }.to raise_error RuntimeError,
"Hiera terminus not supported without hiera library"
end
describe "the behavior of the hiera_config method", :if => Puppet.features.hiera? do
it "should override the logger and set it to puppet" do
- test_klass.hiera_config[:logger].should == "puppet"
+ expect(test_klass.hiera_config[:logger]).to eq("puppet")
end
context "when the Hiera configuration file does not exist" do
let(:path) { File.expand_path('/doesnotexist') }
before do
Puppet.settings[:hiera_config] = path
end
it "should log a warning" do
Puppet.expects(:warning).with(
"Config file #{path} not found, using Hiera defaults")
test_klass.hiera_config
end
it "should only configure the logger and set it to puppet" do
Puppet.expects(:warning).with(
"Config file #{path} not found, using Hiera defaults")
- test_klass.hiera_config.should == { :logger => 'puppet' }
+ expect(test_klass.hiera_config).to eq({ :logger => 'puppet' })
end
end
end
describe "the behavior of the find method", :if => Puppet.features.hiera? do
let(:data_binder) { test_klass.new }
it "should support looking up an integer" do
- data_binder.find(request("integer")).should == 3000
+ expect(data_binder.find(request("integer"))).to eq(3000)
end
it "should support looking up a string" do
- data_binder.find(request("string")).should == 'apache'
+ expect(data_binder.find(request("string"))).to eq('apache')
end
it "should support looking up an array" do
- data_binder.find(request("array")).should == [
+ expect(data_binder.find(request("array"))).to eq([
'0.ntp.puppetlabs.com',
'1.ntp.puppetlabs.com',
- ]
+ ])
end
it "should support looking up a hash" do
- data_binder.find(request("hash")).should == {
+ expect(data_binder.find(request("hash"))).to eq({
'user' => 'Hightower',
'group' => 'admin',
'mode' => '0644'
- }
+ })
end
it "raises a data binding error if hiera cannot parse the yaml data" do
expect do
data_binder.find(request('invalid'))
end.to raise_error(Puppet::DataBinding::LookupError)
end
end
end
diff --git a/spec/shared_behaviours/iterative_functions.rb b/spec/shared_behaviours/iterative_functions.rb
index 1910a3c80..f7c73aa32 100644
--- a/spec/shared_behaviours/iterative_functions.rb
+++ b/spec/shared_behaviours/iterative_functions.rb
@@ -1,69 +1,69 @@
shared_examples_for 'all iterative functions hash handling' do |func|
it 'passes a hash entry as an array of the key and value' do
catalog = compile_to_catalog(<<-MANIFEST)
{a=>1}.#{func} |$v| { notify { "${v[0]} ${v[1]}": } }
MANIFEST
- catalog.resource(:notify, "a 1").should_not be_nil
+ expect(catalog.resource(:notify, "a 1")).not_to be_nil
end
end
shared_examples_for 'all iterative functions argument checks' do |func|
it 'raises an error when used against an unsupported type' do
expect do
compile_to_catalog(<<-MANIFEST)
3.14.#{func} |$k, $v| { }
MANIFEST
end.to raise_error(Puppet::Error, /must be something enumerable/)
end
it 'raises an error when called with any parameters besides a block' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].#{func}(1) |$v| { }
MANIFEST
end.to raise_error(Puppet::Error, /mis-matched arguments.*expected.*arg count \{2\}.*actual.*arg count \{3\}/m)
end
it 'raises an error when called without a block' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].#{func}()
MANIFEST
end.to raise_error(Puppet::Error, /mis-matched arguments.*expected.*arg count \{2\}.*actual.*arg count \{1\}/m)
end
it 'raises an error when called with something that is not a block' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].#{func}(1)
MANIFEST
end.to raise_error(Puppet::Error, /mis-matched arguments.*expected.*Callable.*actual(?!Callable\)).*/m)
end
it 'raises an error when called with a block with too many required parameters' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].#{func}() |$v1, $v2, $v3| { }
MANIFEST
end.to raise_error(Puppet::Error, /mis-matched arguments.*expected.*arg count \{2\}.*actual.*Callable\[Any, Any, Any\]/m)
end
it 'raises an error when called with a block with too few parameters' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].#{func}() | | { }
MANIFEST
end.to raise_error(Puppet::Error, /mis-matched arguments.*expected.*arg count \{2\}.*actual.*Callable\[0, 0\]/m)
end
it 'does not raise an error when called with a block with too many but optional arguments' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].#{func}() |$v1, $v2, $v3=extra| { }
MANIFEST
end.to_not raise_error
end
end
diff --git a/spec/shared_behaviours/memory_terminus.rb b/spec/shared_behaviours/memory_terminus.rb
index 0d9017100..9893e0fc1 100755
--- a/spec/shared_behaviours/memory_terminus.rb
+++ b/spec/shared_behaviours/memory_terminus.rb
@@ -1,28 +1,28 @@
shared_examples_for "A Memory Terminus" do
it "should find no instances by default" do
- @searcher.find(@request).should be_nil
+ expect(@searcher.find(@request)).to be_nil
end
it "should be able to find instances that were previously saved" do
@searcher.save(@request)
- @searcher.find(@request).should equal(@instance)
+ expect(@searcher.find(@request)).to equal(@instance)
end
it "should replace existing saved instances when a new instance with the same name is saved" do
@searcher.save(@request)
two = stub 'second', :name => @name
trequest = stub 'request', :key => @name, :instance => two
@searcher.save(trequest)
- @searcher.find(@request).should equal(two)
+ expect(@searcher.find(@request)).to equal(two)
end
it "should be able to remove previously saved instances" do
@searcher.save(@request)
@searcher.destroy(@request)
- @searcher.find(@request).should be_nil
+ expect(@searcher.find(@request)).to be_nil
end
it "should fail when asked to destroy an instance that does not exist" do
- proc { @searcher.destroy(@request) }.should raise_error(ArgumentError)
+ expect { @searcher.destroy(@request) }.to raise_error(ArgumentError)
end
end
diff --git a/spec/shared_behaviours/path_parameters.rb b/spec/shared_behaviours/path_parameters.rb
index a33a24365..7a266087c 100755
--- a/spec/shared_behaviours/path_parameters.rb
+++ b/spec/shared_behaviours/path_parameters.rb
@@ -1,160 +1,160 @@
# In order to use this correctly you must define a method to get an instance
# of the type being tested, so that this code can remain generic:
#
# it_should_behave_like "all path parameters", :path do
# def instance(path)
# Puppet::Type.type(:example).new(
# :name => 'foo', :require => 'bar', :path_param => path
# )
# end
#
# That method will be invoked for each test to create the instance that we
# subsequently test through the system; you should ensure that the minimum of
# possible attributes are set to keep the tests clean.
#
# You must also pass the symbolic name of the parameter being tested to the
# block, and optionally can pass a hash of additional options to the block.
#
# The known options are:
# :array :: boolean, does this support arrays of paths, default true.
shared_examples_for "all pathname parameters with arrays" do |win32|
path_types = {
"unix absolute" => %q{/foo/bar},
"unix relative" => %q{foo/bar},
"win32 non-drive absolute" => %q{\foo\bar},
"win32 non-drive relative" => %q{foo\bar},
"win32 drive absolute" => %q{c:\foo\bar},
"win32 drive relative" => %q{c:foo\bar}
}
describe "when given an array of paths" do
(1..path_types.length).each do |n|
path_types.keys.combination(n) do |set|
data = path_types.collect { |k, v| set.member?(k) ? v : nil } .compact
has_relative = set.find { |k| k =~ /relative/ or k =~ /non-drive/ }
has_windows = set.find { |k| k =~ /win32/ }
has_unix = set.find { |k| k =~ /unix/ }
if has_relative or (has_windows and !win32) or (has_unix and win32)
reject = true
else
reject = false
end
it "should #{reject ? 'reject' : 'accept'} #{set.join(", ")}" do
if reject then
expect { instance(data) }.
to raise_error Puppet::Error, /fully qualified/
else
instance = instance(data)
- instance[@param].should == data
+ expect(instance[@param]).to eq(data)
end
end
it "should #{reject ? 'reject' : 'accept'} #{set.join(", ")} doubled" do
if reject then
expect { instance(data + data) }.
to raise_error Puppet::Error, /fully qualified/
else
instance = instance(data + data)
- instance[@param].should == (data + data)
+ expect(instance[@param]).to eq(data + data)
end
end
end
end
end
end
shared_examples_for "all path parameters" do |param, options|
# Extract and process options to the block.
options ||= {}
array = options[:array].nil? ? true : options.delete(:array)
if options.keys.length > 0 then
fail "unknown options for 'all path parameters': " +
options.keys.sort.join(', ')
end
def instance(path)
fail "we didn't implement the 'instance(path)' method in the it_should_behave_like block"
end
########################################################################
# The actual testing code...
before :all do
@param = param
end
describe "on a Unix-like platform it", :if => Puppet.features.posix? do
if array then
it_should_behave_like "all pathname parameters with arrays", false
end
it "should accept a fully qualified path" do
path = File.join('', 'foo')
instance = instance(path)
- instance[@param].should == path
+ expect(instance[@param]).to eq(path)
end
it "should give a useful error when the path is not absolute" do
path = 'foo'
expect { instance(path) }.
to raise_error Puppet::Error, /fully qualified/
end
{ "Unix" => '/', "Win32" => '\\' }.each do |style, slash|
%w{q Q a A z Z c C}.sort.each do |drive|
it "should reject drive letter '#{drive}' with #{style} path separators" do
path = "#{drive}:#{slash}Program Files"
expect { instance(path) }.
to raise_error Puppet::Error, /fully qualified/
end
end
end
end
describe "on a Windows-like platform it", :if => Puppet.features.microsoft_windows? do
if array then
it_should_behave_like "all pathname parameters with arrays", true
end
it "should reject a fully qualified unix path" do
path = '/foo'
expect { instance(path) }.to raise_error(Puppet::Error, /fully qualified/)
end
it "should give a useful error when the path is not absolute" do
path = 'foo'
expect { instance(path) }.
to raise_error Puppet::Error, /fully qualified/
end
it "also accepts Unix style path separators" do
path = 'C:/Program Files'
instance = instance(path)
- instance[@param].should == path
+ expect(instance[@param]).to eq(path)
end
{ "Unix" => '/', "Win32" => '\\' }.each do |style, slash|
%w{q Q a A z Z c C}.sort.each do |drive|
it "should accept drive letter '#{drive}' with #{style} path separators " do
path = "#{drive}:#{slash}Program Files"
instance = instance(path)
- instance[@param].should == path
+ expect(instance[@param]).to eq(path)
end
end
end
{ "UNC paths" => %q{\\\\foo\bar},
"unparsed local paths" => %q{\\\\?\c:\foo},
"unparsed UNC paths" => %q{\\\\?\foo\bar}
}.each do |name, path|
it "should accept #{name} as absolute" do
instance = instance(path)
- instance[@param].should == path
+ expect(instance[@param]).to eq(path)
end
end
end
end
diff --git a/spec/shared_behaviours/store_configs_terminus.rb b/spec/shared_behaviours/store_configs_terminus.rb
index c1f02a562..b6ff67ed8 100644
--- a/spec/shared_behaviours/store_configs_terminus.rb
+++ b/spec/shared_behaviours/store_configs_terminus.rb
@@ -1,21 +1,21 @@
shared_examples_for "a StoreConfigs terminus" do
before :each do
Puppet[:storeconfigs] = true
Puppet[:storeconfigs_backend] = "store_configs_testing"
end
api = [:find, :search, :save, :destroy, :head]
api.each do |name|
- it { should respond_to(name) }
+ it { is_expected.to respond_to(name) }
end
it "should fail if an invalid backend is configured" do
Puppet[:storeconfigs_backend] = "synergy"
expect { subject }.to raise_error(ArgumentError, /could not find terminus synergy/i)
end
it "should wrap the declared backend" do
- subject.target.class.name.should == :store_configs_testing
+ expect(subject.target.class.name).to eq(:store_configs_testing)
end
end
diff --git a/spec/shared_behaviours/things_that_declare_options.rb b/spec/shared_behaviours/things_that_declare_options.rb
index 017a5ed78..0e151db54 100755
--- a/spec/shared_behaviours/things_that_declare_options.rb
+++ b/spec/shared_behaviours/things_that_declare_options.rb
@@ -1,262 +1,262 @@
# encoding: UTF-8
shared_examples_for "things that declare options" do
it "should support options without arguments" do
thing = add_options_to { option "--bar" }
- thing.should be_option :bar
+ expect(thing).to be_option :bar
end
it "should support options with an empty block" do
thing = add_options_to do
option "--foo" do
# this section deliberately left blank
end
end
- thing.should be
- thing.should be_option :foo
+ expect(thing).to be
+ expect(thing).to be_option :foo
end
{ "--foo=" => :foo }.each do |input, option|
it "should accept #{name.inspect}" do
thing = add_options_to { option input }
- thing.should be_option option
+ expect(thing).to be_option option
end
end
it "should support option documentation" do
text = "Sturm und Drang (German pronunciation: [ˈʃtʊʁm ʊnt ˈdʁaŋ]) …"
thing = add_options_to do
option "--foo" do
description text
summary text
end
end
- thing.get_option(:foo).description.should == text
+ expect(thing.get_option(:foo).description).to eq(text)
end
it "should list all the options" do
thing = add_options_to do
option "--foo"
option "--bar", '-b'
option "-q", "--quux"
option "-f"
option "--baz"
end
- thing.options.should == [:foo, :bar, :quux, :f, :baz]
+ expect(thing.options).to eq([:foo, :bar, :quux, :f, :baz])
end
it "should detect conflicts in long options" do
expect {
add_options_to do
option "--foo"
option "--foo"
end
}.to raise_error ArgumentError, /Option foo conflicts with existing option foo/i
end
it "should detect conflicts in short options" do
expect {
add_options_to do
option "-f"
option "-f"
end
}.to raise_error ArgumentError, /Option f conflicts with existing option f/
end
["-f", "--foo"].each do |option|
["", " FOO", "=FOO", " [FOO]", "=[FOO]"].each do |argument|
input = option + argument
it "should detect conflicts within a single option like #{input.inspect}" do
expect {
add_options_to do
option input, input
end
}.to raise_error ArgumentError, /duplicates existing alias/
end
end
end
# Verify the range of interesting conflicts to check for ordering causing
# the behaviour to change, or anything exciting like that.
[ %w{--foo}, %w{-f}, %w{-f --foo}, %w{--baz -f},
%w{-f --baz}, %w{-b --foo}, %w{--foo -b}
].each do |conflict|
base = %w{--foo -f}
it "should detect conflicts between #{base.inspect} and #{conflict.inspect}" do
expect {
add_options_to do
option *base
option *conflict
end
}.to raise_error ArgumentError, /conflicts with existing option/
end
end
it "should fail if we are not consistent about taking an argument" do
expect { add_options_to do option "--foo=bar", "--bar" end }.
to raise_error ArgumentError, /inconsistent about taking an argument/
end
it "should not accept optional arguments" do
expect do
thing = add_options_to do option "--foo=[baz]", "--bar=[baz]" end
[:foo, :bar].each do |name|
- thing.should be_option name
+ expect(thing).to be_option name
end
end.to raise_error(ArgumentError, /optional arguments are not supported/)
end
describe "#takes_argument?" do
it "should detect an argument being absent" do
thing = add_options_to do option "--foo" end
- thing.get_option(:foo).should_not be_takes_argument
+ expect(thing.get_option(:foo)).not_to be_takes_argument
end
["=FOO", " FOO"].each do |input|
it "should detect an argument given #{input.inspect}" do
thing = add_options_to do option "--foo#{input}" end
- thing.get_option(:foo).should be_takes_argument
+ expect(thing.get_option(:foo)).to be_takes_argument
end
end
end
describe "#optional_argument?" do
it "should be false if no argument is present" do
option = add_options_to do option "--foo" end.get_option(:foo)
- option.should_not be_takes_argument
- option.should_not be_optional_argument
+ expect(option).not_to be_takes_argument
+ expect(option).not_to be_optional_argument
end
["=FOO", " FOO"].each do |input|
it "should be false if the argument is mandatory (like #{input.inspect})" do
option = add_options_to do option "--foo#{input}" end.get_option(:foo)
- option.should be_takes_argument
- option.should_not be_optional_argument
+ expect(option).to be_takes_argument
+ expect(option).not_to be_optional_argument
end
end
["=[FOO]", " [FOO]"].each do |input|
it "should fail if the argument is optional (like #{input.inspect})" do
expect do
option = add_options_to do option "--foo#{input}" end.get_option(:foo)
- option.should be_takes_argument
- option.should be_optional_argument
+ expect(option).to be_takes_argument
+ expect(option).to be_optional_argument
end.to raise_error(ArgumentError, /optional arguments are not supported/)
end
end
end
describe "#default_to" do
it "should not have a default value by default" do
option = add_options_to do option "--foo" end.get_option(:foo)
- option.should_not be_has_default
+ expect(option).not_to be_has_default
end
it "should accept a block for the default value" do
option = add_options_to do
option "--foo" do
default_to do
12
end
end
end.get_option(:foo)
- option.should be_has_default
+ expect(option).to be_has_default
end
it "should invoke the block when asked for the default value" do
invoked = false
option = add_options_to do
option "--foo" do
default_to do
invoked = true
end
end
end.get_option(:foo)
- option.should be_has_default
- option.default.should be_true
- invoked.should be_true
+ expect(option).to be_has_default
+ expect(option.default).to be_truthy
+ expect(invoked).to be_truthy
end
it "should return the value of the block when asked for the default" do
option = add_options_to do
option "--foo" do
default_to do
12
end
end
end.get_option(:foo)
- option.should be_has_default
- option.default.should == 12
+ expect(option).to be_has_default
+ expect(option.default).to eq(12)
end
it "should invoke the block every time the default is requested" do
option = add_options_to do
option "--foo" do
default_to do
{}
end
end
end.get_option(:foo)
first = option.default.object_id
second = option.default.object_id
third = option.default.object_id
- first.should_not == second
- first.should_not == third
- second.should_not == third
+ expect(first).not_to eq(second)
+ expect(first).not_to eq(third)
+ expect(second).not_to eq(third)
end
it "should fail if the option has a default and is required" do
expect {
add_options_to do
option "--foo" do
required
default_to do 12 end
end
end
}.to raise_error ArgumentError, /can't be optional and have a default value/
expect {
add_options_to do
option "--foo" do
default_to do 12 end
required
end
end
}.to raise_error ArgumentError, /can't be optional and have a default value/
end
it "should fail if default_to has no block" do
expect { add_options_to do option "--foo" do default_to end end }.
to raise_error ArgumentError, /default_to requires a block/
end
it "should fail if default_to is invoked twice" do
expect {
add_options_to do
option "--foo" do
default_to do 12 end
default_to do "fun" end
end
end
}.to raise_error ArgumentError, /already has a default value/
end
[ "one", "one, two", "one, *two" ].each do |input|
it "should fail if the block has the wrong arity (#{input})" do
expect {
add_options_to do
option "--foo" do
eval "default_to do |#{input}| 12 end"
end
end
}.to raise_error ArgumentError, /should not take any arguments/
end
end
end
end
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 3cc496424..816d4972f 100755
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,192 +1,193 @@
# NOTE: a lot of the stuff in this file is duplicated in the "puppet_spec_helper" in the project
# puppetlabs_spec_helper. We should probably eat our own dog food and get rid of most of this from here,
# and have the puppet core itself use puppetlabs_spec_helper
dir = File.expand_path(File.dirname(__FILE__))
$LOAD_PATH.unshift File.join(dir, 'lib')
# Don't want puppet getting the command line arguments for rake or autotest
ARGV.clear
begin
require 'rubygems'
rescue LoadError
end
require 'puppet'
-gem 'rspec', '>=2.0.0'
+gem 'rspec', '>=3.1.0'
require 'rspec/expectations'
+require 'rspec/its'
+require 'rspec/collection_matchers'
# So everyone else doesn't have to include this base constant.
module PuppetSpec
FIXTURE_DIR = File.join(dir = File.expand_path(File.dirname(__FILE__)), "fixtures") unless defined?(FIXTURE_DIR)
end
require 'pathname'
require 'tmpdir'
require 'fileutils'
require 'puppet_spec/verbose'
require 'puppet_spec/files'
require 'puppet_spec/settings'
require 'puppet_spec/fixtures'
require 'puppet_spec/matchers'
-require 'monkey_patches/alias_should_to_must'
require 'puppet/test/test_helper'
Pathname.glob("#{dir}/shared_contexts/*.rb") do |file|
require file.relative_path_from(Pathname.new(dir))
end
Pathname.glob("#{dir}/shared_behaviours/**/*.rb") do |behaviour|
require behaviour.relative_path_from(Pathname.new(dir))
end
RSpec.configure do |config|
include PuppetSpec::Fixtures
# Examples or groups can selectively tag themselves as broken.
# For example;
#
# rbv = "#{RUBY_VERSION}-p#{RbConfig::CONFIG['PATCHLEVEL']}"
# describe "mostly working", :broken => false unless rbv == "1.9.3-p327" do
# it "parses a valid IP" do
# IPAddr.new("::2:3:4:5:6:7:8")
# end
# end
exclude_filters = {:broken => true}
exclude_filters[:benchmark] = true unless ENV['BENCHMARK']
config.filter_run_excluding exclude_filters
config.mock_with :mocha
tmpdir = Dir.mktmpdir("rspecrun")
oldtmpdir = Dir.tmpdir()
ENV['TMPDIR'] = tmpdir
if Puppet::Util::Platform.windows?
config.output_stream = $stdout
config.error_stream = $stderr
config.formatters.each do |f|
if not f.instance_variable_get(:@output).kind_of?(::File)
f.instance_variable_set(:@output, $stdout)
end
end
end
Puppet::Test::TestHelper.initialize
config.before :all do
Puppet::Test::TestHelper.before_all_tests()
if ENV['PROFILE'] == 'all'
require 'ruby-prof'
RubyProf.start
end
end
config.after :all do
if ENV['PROFILE'] == 'all'
require 'ruby-prof'
result = RubyProf.stop
printer = RubyProf::CallTreePrinter.new(result)
open(File.join(ENV['PROFILEOUT'],"callgrind.all.#{Time.now.to_i}.trace"), "w") do |f|
printer.print(f)
end
end
Puppet::Test::TestHelper.after_all_tests()
end
config.before :each do
# Disabling garbage collection inside each test, and only running it at
# the end of each block, gives us an ~ 15 percent speedup, and more on
# some platforms *cough* windows *cough* that are a little slower.
GC.disable
# REVISIT: I think this conceals other bad tests, but I don't have time to
# fully diagnose those right now. When you read this, please come tell me
# I suck for letting this float. --daniel 2011-04-21
Signal.stubs(:trap)
# TODO: in a more sane world, we'd move this logging redirection into our TestHelper class.
# Without doing so, external projects will all have to roll their own solution for
# redirecting logging, and for validating expected log messages. However, because the
# current implementation of this involves creating an instance variable "@logs" on
# EVERY SINGLE TEST CLASS, and because there are over 1300 tests that are written to expect
# this instance variable to be available--we can't easily solve this problem right now.
#
# redirecting logging away from console, because otherwise the test output will be
# obscured by all of the log output
@logs = []
Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(@logs))
@log_level = Puppet::Util::Log.level
base = PuppetSpec::Files.tmpdir('tmp_settings')
Puppet[:vardir] = File.join(base, 'var')
Puppet[:confdir] = File.join(base, 'etc')
Puppet[:logdir] = "$vardir/log"
Puppet[:rundir] = "$vardir/run"
Puppet[:hiera_config] = File.join(base, 'hiera')
Puppet::Test::TestHelper.before_each_test()
end
config.after :each do
Puppet::Test::TestHelper.after_each_test()
# TODO: would like to move this into puppetlabs_spec_helper, but there are namespace issues at the moment.
PuppetSpec::Files.cleanup
# TODO: this should be abstracted in the future--see comments above the '@logs' block in the
# "before" code above.
#
# clean up after the logging changes that we made before each test.
@logs.clear
Puppet::Util::Log.close_all
Puppet::Util::Log.level = @log_level
# This will perform a GC between tests, but only if actually required. We
# experimented with forcing a GC run, and that was less efficient than
# just letting it run all the time.
GC.enable
end
config.after :suite do
# Log the spec order to a file, but only if the LOG_SPEC_ORDER environment variable is
# set. This should be enabled on Jenkins runs, as it can be used with Nick L.'s bisect
# script to help identify and debug order-dependent spec failures.
if ENV['LOG_SPEC_ORDER']
File.open("./spec_order.txt", "w") do |logfile|
config.instance_variable_get(:@files_to_run).each { |f| logfile.puts f }
end
end
# return to original tmpdir
ENV['TMPDIR'] = oldtmpdir
FileUtils.rm_rf(tmpdir)
end
if ENV['PROFILE']
require 'ruby-prof'
def profile
result = RubyProf.profile { yield }
- name = example.metadata[:full_description].downcase.gsub(/[^a-z0-9_-]/, "-").gsub(/-+/, "-")
+ name = RSpec.current_example.metadata[:full_description].downcase.gsub(/[^a-z0-9_-]/, "-").gsub(/-+/, "-")
printer = RubyProf::CallTreePrinter.new(result)
open(File.join(ENV['PROFILEOUT'],"callgrind.#{name}.#{Time.now.to_i}.trace"), "w") do |f|
printer.print(f)
end
end
config.around(:each) do |example|
if ENV['PROFILE'] == 'each' or (example.metadata[:profile] and ENV['PROFILE'])
profile { example.run }
else
example.run
end
end
end
end
diff --git a/spec/unit/agent/disabler_spec.rb b/spec/unit/agent/disabler_spec.rb
index 3c99f3db5..2fee269fa 100644
--- a/spec/unit/agent/disabler_spec.rb
+++ b/spec/unit/agent/disabler_spec.rb
@@ -1,64 +1,64 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/agent'
require 'puppet/agent/locker'
class DisablerTester
include Puppet::Agent::Disabler
end
describe Puppet::Agent::Disabler do
before do
@disabler = DisablerTester.new
end
## These tests are currently very implementation-specific, and they rely heavily on
## having access to the "disable_lockfile" method. However, I've made this method private
## because it really shouldn't be exposed outside of our implementation... therefore
## these tests have to use a lot of ".send" calls. They should probably be cleaned up
## but for the moment I wanted to make sure not to lose any of the functionality of
## the tests. --cprice 2012-04-16
it "should use an JsonLockfile instance as its disable_lockfile" do
- @disabler.send(:disable_lockfile).should be_instance_of(Puppet::Util::JsonLockfile)
+ expect(@disabler.send(:disable_lockfile)).to be_instance_of(Puppet::Util::JsonLockfile)
end
it "should use puppet's :agent_disabled_lockfile' setting to determine its lockfile path" do
lockfile = File.expand_path("/my/lock.disabled")
Puppet[:agent_disabled_lockfile] = lockfile
lock = Puppet::Util::JsonLockfile.new(lockfile)
Puppet::Util::JsonLockfile.expects(:new).with(lockfile).returns lock
@disabler.send(:disable_lockfile)
end
it "should reuse the same lock file each time" do
- @disabler.send(:disable_lockfile).should equal(@disabler.send(:disable_lockfile))
+ expect(@disabler.send(:disable_lockfile)).to equal(@disabler.send(:disable_lockfile))
end
it "should lock the file when disabled" do
@disabler.send(:disable_lockfile).expects(:lock)
@disabler.disable
end
it "should unlock the file when enabled" do
@disabler.send(:disable_lockfile).expects(:unlock)
@disabler.enable
end
it "should check the lock if it is disabled" do
@disabler.send(:disable_lockfile).expects(:locked?)
@disabler.disabled?
end
it "should report the disable message when disabled" do
Puppet[:agent_disabled_lockfile] = PuppetSpec::Files.tmpfile("lock")
msg = "I'm busy, go away"
@disabler.disable(msg)
- @disabler.disable_message.should == msg
+ expect(@disabler.disable_message).to eq(msg)
end
end
diff --git a/spec/unit/agent/locker_spec.rb b/spec/unit/agent/locker_spec.rb
index 5a4df3de2..8d43208cc 100755
--- a/spec/unit/agent/locker_spec.rb
+++ b/spec/unit/agent/locker_spec.rb
@@ -1,100 +1,100 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/agent'
require 'puppet/agent/locker'
class LockerTester
include Puppet::Agent::Locker
end
describe Puppet::Agent::Locker do
before do
@locker = LockerTester.new
end
## These tests are currently very implementation-specific, and they rely heavily on
## having access to the lockfile object. However, I've made this method private
## because it really shouldn't be exposed outside of our implementation... therefore
## these tests have to use a lot of ".send" calls. They should probably be cleaned up
## but for the moment I wanted to make sure not to lose any of the functionality of
## the tests. --cprice 2012-04-16
it "should use a Pidlock instance as its lockfile" do
- @locker.send(:lockfile).should be_instance_of(Puppet::Util::Pidlock)
+ expect(@locker.send(:lockfile)).to be_instance_of(Puppet::Util::Pidlock)
end
it "should use puppet's agent_catalog_run_lockfile' setting to determine its lockfile path" do
lockfile = File.expand_path("/my/lock")
Puppet[:agent_catalog_run_lockfile] = lockfile
lock = Puppet::Util::Pidlock.new(lockfile)
Puppet::Util::Pidlock.expects(:new).with(lockfile).returns lock
@locker.send(:lockfile)
end
it "#lockfile_path provides the path to the lockfile" do
lockfile = File.expand_path("/my/lock")
Puppet[:agent_catalog_run_lockfile] = lockfile
- @locker.lockfile_path.should == File.expand_path("/my/lock")
+ expect(@locker.lockfile_path).to eq(File.expand_path("/my/lock"))
end
it "should reuse the same lock file each time" do
- @locker.send(:lockfile).should equal(@locker.send(:lockfile))
+ expect(@locker.send(:lockfile)).to equal(@locker.send(:lockfile))
end
it "should have a method that yields when a lock is attained" do
@locker.send(:lockfile).expects(:lock).returns true
yielded = false
@locker.lock do
yielded = true
end
- yielded.should be_true
+ expect(yielded).to be_truthy
end
it "should return the block result when the lock method successfully locked" do
@locker.send(:lockfile).expects(:lock).returns true
- @locker.lock { :result }.should == :result
+ expect(@locker.lock { :result }).to eq(:result)
end
it "should return nil when the lock method does not receive the lock" do
@locker.send(:lockfile).expects(:lock).returns false
- @locker.lock {}.should be_nil
+ expect(@locker.lock {}).to be_nil
end
it "should not yield when the lock method does not receive the lock" do
@locker.send(:lockfile).expects(:lock).returns false
yielded = false
@locker.lock { yielded = true }
- yielded.should be_false
+ expect(yielded).to be_falsey
end
it "should not unlock when a lock was not received" do
@locker.send(:lockfile).expects(:lock).returns false
@locker.send(:lockfile).expects(:unlock).never
@locker.lock {}
end
it "should unlock after yielding upon obtaining a lock" do
@locker.send(:lockfile).stubs(:lock).returns true
@locker.send(:lockfile).expects(:unlock)
@locker.lock {}
end
it "should unlock after yielding upon obtaining a lock, even if the block throws an exception" do
@locker.send(:lockfile).stubs(:lock).returns true
@locker.send(:lockfile).expects(:unlock)
- lambda { @locker.lock { raise "foo" } }.should raise_error(RuntimeError)
+ expect { @locker.lock { raise "foo" } }.to raise_error(RuntimeError)
end
it "should be considered running if the lockfile is locked" do
@locker.send(:lockfile).expects(:locked?).returns true
- @locker.should be_running
+ expect(@locker).to be_running
end
end
diff --git a/spec/unit/agent_spec.rb b/spec/unit/agent_spec.rb
index 95319a624..2958c651e 100755
--- a/spec/unit/agent_spec.rb
+++ b/spec/unit/agent_spec.rb
@@ -1,327 +1,327 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/agent'
class AgentTestClient
def run
# no-op
end
def stop
# no-op
end
end
def without_warnings
flag = $VERBOSE
$VERBOSE = nil
yield
$VERBOSE = flag
end
describe Puppet::Agent do
before do
Puppet::Status.indirection.stubs(:find).returns Puppet::Status.new("version" => Puppet.version)
@agent = Puppet::Agent.new(AgentTestClient, false)
# So we don't actually try to hit the filesystem.
@agent.stubs(:lock).yields
# make Puppet::Application safe for stubbing; restore in an :after block; silence warnings for this.
without_warnings { Puppet::Application = Class.new(Puppet::Application) }
Puppet::Application.stubs(:clear?).returns(true)
Puppet::Application.class_eval do
class << self
def controlled_run(&block)
block.call
end
end
end
end
after do
# restore Puppet::Application from stub-safe subclass, and silence warnings
without_warnings { Puppet::Application = Puppet::Application.superclass }
end
it "should set its client class at initialization" do
- Puppet::Agent.new("foo", false).client_class.should == "foo"
+ expect(Puppet::Agent.new("foo", false).client_class).to eq("foo")
end
it "should include the Locker module" do
- Puppet::Agent.ancestors.should be_include(Puppet::Agent::Locker)
+ expect(Puppet::Agent.ancestors).to be_include(Puppet::Agent::Locker)
end
it "should create an instance of its client class and run it when asked to run" do
client = mock 'client'
AgentTestClient.expects(:new).returns client
client.expects(:run)
@agent.stubs(:running?).returns false
@agent.stubs(:disabled?).returns false
@agent.run
end
it "should be considered running if the lock file is locked" do
lockfile = mock 'lockfile'
@agent.expects(:lockfile).returns(lockfile)
lockfile.expects(:locked?).returns true
- @agent.should be_running
+ expect(@agent).to be_running
end
describe "when being run" do
before do
AgentTestClient.stubs(:lockfile_path).returns "/my/lock"
@agent.stubs(:running?).returns false
@agent.stubs(:disabled?).returns false
end
it "should splay" do
@agent.expects(:splay)
@agent.run
end
it "should do nothing if already running" do
@agent.expects(:running?).returns true
AgentTestClient.expects(:new).never
@agent.run
end
it "should do nothing if disabled" do
@agent.expects(:disabled?).returns(true)
AgentTestClient.expects(:new).never
@agent.run
end
it "(#11057) should notify the user about why a run is skipped" do
Puppet::Application.stubs(:controlled_run).returns(false)
Puppet::Application.stubs(:run_status).returns('MOCK_RUN_STATUS')
# This is the actual test that we inform the user why the run is skipped.
# We assume this information is contained in
# Puppet::Application.run_status
Puppet.expects(:notice).with(regexp_matches(/MOCK_RUN_STATUS/))
@agent.run
end
it "should display an informative message if the agent is administratively disabled" do
@agent.expects(:disabled?).returns true
@agent.expects(:disable_message).returns "foo"
Puppet.expects(:notice).with(regexp_matches(/Skipping run of .*; administratively disabled.*\(Reason: 'foo'\)/))
@agent.run
end
it "should use Puppet::Application.controlled_run to manage process state behavior" do
calls = sequence('calls')
Puppet::Application.expects(:controlled_run).yields.in_sequence(calls)
AgentTestClient.expects(:new).once.in_sequence(calls)
@agent.run
end
it "should not fail if a client class instance cannot be created" do
AgentTestClient.expects(:new).raises "eh"
Puppet.expects(:err)
@agent.run
end
it "should not fail if there is an exception while running its client" do
client = AgentTestClient.new
AgentTestClient.expects(:new).returns client
client.expects(:run).raises "eh"
Puppet.expects(:err)
@agent.run
end
it "should use a filesystem lock to restrict multiple processes running the agent" do
client = AgentTestClient.new
AgentTestClient.expects(:new).returns client
@agent.expects(:lock)
client.expects(:run).never # if it doesn't run, then we know our yield is what triggers it
@agent.run
end
it "should make its client instance available while running" do
client = AgentTestClient.new
AgentTestClient.expects(:new).returns client
- client.expects(:run).with { @agent.client.should equal(client); true }
+ client.expects(:run).with { expect(@agent.client).to equal(client); true }
@agent.run
end
it "should run the client instance with any arguments passed to it" do
client = AgentTestClient.new
AgentTestClient.expects(:new).returns client
client.expects(:run).with(:pluginsync => true, :other => :options)
@agent.run(:other => :options)
end
it "should return the agent result" do
client = AgentTestClient.new
AgentTestClient.expects(:new).returns client
@agent.expects(:lock).returns(:result)
- @agent.run.should == :result
+ expect(@agent.run).to eq(:result)
end
describe "when should_fork is true", :if => Puppet.features.posix? do
before do
@agent = Puppet::Agent.new(AgentTestClient, true)
# So we don't actually try to hit the filesystem.
@agent.stubs(:lock).yields
Kernel.stubs(:fork)
Process.stubs(:waitpid2).returns [123, (stub 'process::status', :exitstatus => 0)]
@agent.stubs(:exit)
end
it "should run the agent in a forked process" do
client = AgentTestClient.new
AgentTestClient.expects(:new).returns client
client.expects(:run)
Kernel.expects(:fork).yields
@agent.run
end
it "should exit child process if child exit" do
client = AgentTestClient.new
AgentTestClient.expects(:new).returns client
client.expects(:run).raises(SystemExit)
Kernel.expects(:fork).yields
@agent.expects(:exit).with(-1)
@agent.run
end
it "should re-raise exit happening in the child" do
Process.stubs(:waitpid2).returns [123, (stub 'process::status', :exitstatus => -1)]
- lambda { @agent.run }.should raise_error(SystemExit)
+ expect { @agent.run }.to raise_error(SystemExit)
end
it "should re-raise NoMoreMemory happening in the child" do
Process.stubs(:waitpid2).returns [123, (stub 'process::status', :exitstatus => -2)]
- lambda { @agent.run }.should raise_error(NoMemoryError)
+ expect { @agent.run }.to raise_error(NoMemoryError)
end
it "should return the child exit code" do
Process.stubs(:waitpid2).returns [123, (stub 'process::status', :exitstatus => 777)]
- @agent.run.should == 777
+ expect(@agent.run).to eq(777)
end
it "should return the block exit code as the child exit code" do
Kernel.expects(:fork).yields
@agent.expects(:exit).with(777)
@agent.run_in_fork {
777
}
end
end
describe "on Windows", :if => Puppet.features.microsoft_windows? do
it "should never fork" do
agent = Puppet::Agent.new(AgentTestClient, true)
- expect(agent.should_fork).to be_false
+ expect(agent.should_fork).to be_falsey
end
end
end
describe "when splaying" do
before do
Puppet[:splay] = true
Puppet[:splaylimit] = "10"
end
it "should do nothing if splay is disabled" do
Puppet[:splay] = false
@agent.expects(:sleep).never
@agent.splay
end
it "should do nothing if it has already splayed" do
@agent.expects(:splayed?).returns true
@agent.expects(:sleep).never
@agent.splay
end
it "should log that it is splaying" do
@agent.stubs :sleep
Puppet.expects :info
@agent.splay
end
it "should sleep for a random portion of the splaylimit plus 1" do
Puppet[:splaylimit] = "50"
@agent.expects(:rand).with(51).returns 10
@agent.expects(:sleep).with(10)
@agent.splay
end
it "should mark that it has splayed" do
@agent.stubs(:sleep)
@agent.splay
- @agent.should be_splayed
+ expect(@agent).to be_splayed
end
end
describe "when checking execution state" do
describe 'with regular run status' do
before :each do
Puppet::Application.stubs(:restart_requested?).returns(false)
Puppet::Application.stubs(:stop_requested?).returns(false)
Puppet::Application.stubs(:interrupted?).returns(false)
Puppet::Application.stubs(:clear?).returns(true)
end
it 'should be false for :stopping?' do
- @agent.stopping?.should be_false
+ expect(@agent.stopping?).to be_falsey
end
it 'should be false for :needing_restart?' do
- @agent.needing_restart?.should be_false
+ expect(@agent.needing_restart?).to be_falsey
end
end
describe 'with a stop requested' do
before :each do
Puppet::Application.stubs(:clear?).returns(false)
Puppet::Application.stubs(:restart_requested?).returns(false)
Puppet::Application.stubs(:stop_requested?).returns(true)
Puppet::Application.stubs(:interrupted?).returns(true)
end
it 'should be true for :stopping?' do
- @agent.stopping?.should be_true
+ expect(@agent.stopping?).to be_truthy
end
it 'should be false for :needing_restart?' do
- @agent.needing_restart?.should be_false
+ expect(@agent.needing_restart?).to be_falsey
end
end
describe 'with a restart requested' do
before :each do
Puppet::Application.stubs(:clear?).returns(false)
Puppet::Application.stubs(:restart_requested?).returns(true)
Puppet::Application.stubs(:stop_requested?).returns(false)
Puppet::Application.stubs(:interrupted?).returns(true)
end
it 'should be false for :stopping?' do
- @agent.stopping?.should be_false
+ expect(@agent.stopping?).to be_falsey
end
it 'should be true for :needing_restart?' do
- @agent.needing_restart?.should be_true
+ expect(@agent.needing_restart?).to be_truthy
end
end
end
end
diff --git a/spec/unit/application/agent_spec.rb b/spec/unit/application/agent_spec.rb
index a82b54546..6ac4405d9 100755
--- a/spec/unit/application/agent_spec.rb
+++ b/spec/unit/application/agent_spec.rb
@@ -1,589 +1,589 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/agent'
require 'puppet/application/agent'
require 'puppet/network/server'
require 'puppet/daemon'
describe Puppet::Application::Agent do
include PuppetSpec::Files
before :each do
@puppetd = Puppet::Application[:agent]
@daemon = Puppet::Daemon.new(nil)
@daemon.stubs(:daemonize)
@daemon.stubs(:start)
@daemon.stubs(:stop)
Puppet::Daemon.stubs(:new).returns(@daemon)
Puppet[:daemonize] = false
@agent = stub_everything 'agent'
Puppet::Agent.stubs(:new).returns(@agent)
@puppetd.preinit
Puppet::Util::Log.stubs(:newdestination)
@ssl_host = stub_everything 'ssl host'
Puppet::SSL::Host.stubs(:new).returns(@ssl_host)
Puppet::Node.indirection.stubs(:terminus_class=)
Puppet::Node.indirection.stubs(:cache_class=)
Puppet::Node::Facts.indirection.stubs(:terminus_class=)
$stderr.expects(:puts).never
Puppet.settings.stubs(:use)
end
it "should operate in agent run_mode" do
- @puppetd.class.run_mode.name.should == :agent
+ expect(@puppetd.class.run_mode.name).to eq(:agent)
end
it "should declare a main command" do
- @puppetd.should respond_to(:main)
+ expect(@puppetd).to respond_to(:main)
end
it "should declare a onetime command" do
- @puppetd.should respond_to(:onetime)
+ expect(@puppetd).to respond_to(:onetime)
end
it "should declare a fingerprint command" do
- @puppetd.should respond_to(:fingerprint)
+ expect(@puppetd).to respond_to(:fingerprint)
end
it "should declare a preinit block" do
- @puppetd.should respond_to(:preinit)
+ expect(@puppetd).to respond_to(:preinit)
end
describe "in preinit" do
it "should catch INT" do
Signal.expects(:trap).with { |arg,block| arg == :INT }
@puppetd.preinit
end
it "should init fqdn to nil" do
@puppetd.preinit
- @puppetd.options[:fqdn].should be_nil
+ expect(@puppetd.options[:fqdn]).to be_nil
end
it "should init serve to []" do
@puppetd.preinit
- @puppetd.options[:serve].should == []
+ expect(@puppetd.options[:serve]).to eq([])
end
it "should use SHA256 as default digest algorithm" do
@puppetd.preinit
- @puppetd.options[:digest].should == 'SHA256'
+ expect(@puppetd.options[:digest]).to eq('SHA256')
end
it "should not fingerprint by default" do
@puppetd.preinit
- @puppetd.options[:fingerprint].should be_false
+ expect(@puppetd.options[:fingerprint]).to be_falsey
end
it "should init waitforcert to nil" do
@puppetd.preinit
- @puppetd.options[:waitforcert].should be_nil
+ expect(@puppetd.options[:waitforcert]).to be_nil
end
end
describe "when handling options" do
before do
@puppetd.command_line.stubs(:args).returns([])
end
[:enable, :debug, :fqdn, :test, :verbose, :digest].each do |option|
it "should declare handle_#{option} method" do
- @puppetd.should respond_to("handle_#{option}".to_sym)
+ expect(@puppetd).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
@puppetd.send("handle_#{option}".to_sym, 'arg')
- @puppetd.options[option].should == 'arg'
+ expect(@puppetd.options[option]).to eq('arg')
end
end
describe "when handling --disable" do
it "should set disable to true" do
@puppetd.handle_disable('')
- @puppetd.options[:disable].should == true
+ expect(@puppetd.options[:disable]).to eq(true)
end
it "should store disable message" do
@puppetd.handle_disable('message')
- @puppetd.options[:disable_message].should == 'message'
+ expect(@puppetd.options[:disable_message]).to eq('message')
end
end
it "should set waitforcert to 0 with --onetime and if --waitforcert wasn't given" do
@agent.stubs(:run).returns(2)
Puppet[:onetime] = true
@ssl_host.expects(:wait_for_cert).with(0)
expect { execute_agent }.to exit_with 0
end
it "should use supplied waitforcert when --onetime is specified" do
@agent.stubs(:run).returns(2)
Puppet[:onetime] = true
@puppetd.handle_waitforcert(60)
@ssl_host.expects(:wait_for_cert).with(60)
expect { execute_agent }.to exit_with 0
end
it "should use a default value for waitforcert when --onetime and --waitforcert are not specified" do
@ssl_host.expects(:wait_for_cert).with(120)
execute_agent
end
it "should use the waitforcert setting when checking for a signed certificate" do
Puppet[:waitforcert] = 10
@ssl_host.expects(:wait_for_cert).with(10)
execute_agent
end
it "should set the log destination with --logdest" do
Puppet::Log.expects(:newdestination).with("console")
@puppetd.handle_logdest("console")
end
it "should put the setdest options to true" do
@puppetd.handle_logdest("console")
- @puppetd.options[:setdest].should == true
+ expect(@puppetd.options[:setdest]).to eq(true)
end
it "should parse the log destination from the command line" do
@puppetd.command_line.stubs(:args).returns(%w{--logdest /my/file})
Puppet::Util::Log.expects(:newdestination).with("/my/file")
@puppetd.parse_options
end
it "should store the waitforcert options with --waitforcert" do
@puppetd.handle_waitforcert("42")
- @puppetd.options[:waitforcert].should == 42
+ expect(@puppetd.options[:waitforcert]).to eq(42)
end
end
describe "during setup" do
before :each do
Puppet.stubs(:info)
Puppet[:libdir] = "/dev/null/lib"
Puppet::Transaction::Report.indirection.stubs(:terminus_class=)
Puppet::Transaction::Report.indirection.stubs(:cache_class=)
Puppet::Resource::Catalog.indirection.stubs(:terminus_class=)
Puppet::Resource::Catalog.indirection.stubs(:cache_class=)
Puppet::Node::Facts.indirection.stubs(:terminus_class=)
Puppet.stubs(:settraps)
end
describe "with --test" do
it "should call setup_test" do
@puppetd.options[:test] = true
@puppetd.expects(:setup_test)
@puppetd.setup
end
it "should set options[:verbose] to true" do
@puppetd.setup_test
- @puppetd.options[:verbose].should == true
+ expect(@puppetd.options[:verbose]).to eq(true)
end
it "should set options[:onetime] to true" do
Puppet[:onetime] = false
@puppetd.setup_test
- Puppet[:onetime].should == true
+ expect(Puppet[:onetime]).to eq(true)
end
it "should set options[:detailed_exitcodes] to true" do
@puppetd.setup_test
- @puppetd.options[:detailed_exitcodes].should == true
+ expect(@puppetd.options[:detailed_exitcodes]).to eq(true)
end
end
it "should call setup_logs" do
@puppetd.expects(:setup_logs)
@puppetd.setup
end
describe "when setting up logs" do
before :each do
Puppet::Util::Log.stubs(:newdestination)
end
it "should set log level to debug if --debug was passed" do
@puppetd.options[:debug] = true
@puppetd.setup_logs
- Puppet::Util::Log.level.should == :debug
+ expect(Puppet::Util::Log.level).to eq(:debug)
end
it "should set log level to info if --verbose was passed" do
@puppetd.options[:verbose] = true
@puppetd.setup_logs
- Puppet::Util::Log.level.should == :info
+ expect(Puppet::Util::Log.level).to eq(:info)
end
[:verbose, :debug].each do |level|
it "should set console as the log destination with level #{level}" do
@puppetd.options[level] = true
Puppet::Util::Log.expects(:newdestination).at_least_once
Puppet::Util::Log.expects(:newdestination).with(:console).once
@puppetd.setup_logs
end
end
it "should set a default log destination if no --logdest" do
@puppetd.options[:setdest] = false
Puppet::Util::Log.expects(:setup_default)
@puppetd.setup_logs
end
end
it "should print puppet config if asked to in Puppet config" do
Puppet[:configprint] = "pluginsync"
Puppet.settings.expects(:print_configs).returns true
expect { execute_agent }.to exit_with 0
end
it "should exit after printing puppet config if asked to in Puppet config" do
path = make_absolute('/my/path')
Puppet[:modulepath] = path
Puppet[:configprint] = "modulepath"
Puppet::Settings.any_instance.expects(:puts).with(path)
expect { execute_agent }.to exit_with 0
end
it "should use :main, :puppetd, and :ssl" do
Puppet.settings.unstub(:use)
Puppet.settings.expects(:use).with(:main, :agent, :ssl)
@puppetd.setup
end
it "should install a remote ca location" do
Puppet::SSL::Host.expects(:ca_location=).with(:remote)
@puppetd.setup
end
it "should install a none ca location in fingerprint mode" do
@puppetd.options[:fingerprint] = true
Puppet::SSL::Host.expects(:ca_location=).with(:none)
@puppetd.setup
end
it "should tell the report handler to use REST" do
Puppet::Transaction::Report.indirection.expects(:terminus_class=).with(:rest)
@puppetd.setup
end
it "should tell the report handler to cache locally as yaml" do
Puppet::Transaction::Report.indirection.expects(:cache_class=).with(:yaml)
@puppetd.setup
end
it "should default catalog_terminus setting to 'rest'" do
@puppetd.initialize_app_defaults
- Puppet[:catalog_terminus].should == :rest
+ expect(Puppet[:catalog_terminus]).to eq(:rest)
end
it "should default node_terminus setting to 'rest'" do
@puppetd.initialize_app_defaults
- Puppet[:node_terminus].should == :rest
+ expect(Puppet[:node_terminus]).to eq(:rest)
end
it "has an application default :catalog_cache_terminus setting of 'json'" do
Puppet::Resource::Catalog.indirection.expects(:cache_class=).with(:json)
@puppetd.initialize_app_defaults
@puppetd.setup
end
it "should tell the catalog cache class based on the :catalog_cache_terminus setting" do
Puppet[:catalog_cache_terminus] = "yaml"
Puppet::Resource::Catalog.indirection.expects(:cache_class=).with(:yaml)
@puppetd.initialize_app_defaults
@puppetd.setup
end
it "should not set catalog cache class if :catalog_cache_terminus is explicitly nil" do
Puppet[:catalog_cache_terminus] = nil
Puppet::Resource::Catalog.indirection.expects(:cache_class=).never
@puppetd.initialize_app_defaults
@puppetd.setup
end
it "should default facts_terminus setting to 'facter'" do
@puppetd.initialize_app_defaults
- Puppet[:facts_terminus].should == :facter
+ expect(Puppet[:facts_terminus]).to eq(:facter)
end
it "should create an agent" do
Puppet::Agent.stubs(:new).with(Puppet::Configurer)
@puppetd.setup
end
[:enable, :disable].each do |action|
it "should delegate to enable_disable_client if we #{action} the agent" do
@puppetd.options[action] = true
@puppetd.expects(:enable_disable_client).with(@agent)
@puppetd.setup
end
end
describe "when enabling or disabling agent" do
[:enable, :disable].each do |action|
it "should call client.#{action}" do
@puppetd.options[action] = true
@agent.expects(action)
expect { execute_agent }.to exit_with 0
end
end
it "should pass the disable message when disabling" do
@puppetd.options[:disable] = true
@puppetd.options[:disable_message] = "message"
@agent.expects(:disable).with("message")
expect { execute_agent }.to exit_with 0
end
it "should pass the default disable message when disabling without a message" do
@puppetd.options[:disable] = true
@puppetd.options[:disable_message] = nil
@agent.expects(:disable).with("reason not specified")
expect { execute_agent }.to exit_with 0
end
end
it "should inform the daemon about our agent if :client is set to 'true'" do
@puppetd.options[:client] = true
execute_agent
- @daemon.agent.should == @agent
+ expect(@daemon.agent).to eq(@agent)
end
it "should daemonize if needed" do
Puppet.features.stubs(:microsoft_windows?).returns false
Puppet[:daemonize] = true
@daemon.expects(:daemonize)
execute_agent
end
it "should wait for a certificate" do
@puppetd.options[:waitforcert] = 123
@ssl_host.expects(:wait_for_cert).with(123)
execute_agent
end
it "should not wait for a certificate in fingerprint mode" do
@puppetd.options[:fingerprint] = true
@puppetd.options[:waitforcert] = 123
@puppetd.options[:digest] = 'MD5'
certificate = mock 'certificate'
certificate.stubs(:digest).with('MD5').returns('ABCDE')
@ssl_host.stubs(:certificate).returns(certificate)
@ssl_host.expects(:wait_for_cert).never
@puppetd.expects(:puts).with('ABCDE')
execute_agent
end
describe "when setting up for fingerprint" do
before(:each) do
@puppetd.options[:fingerprint] = true
end
it "should not setup as an agent" do
@puppetd.expects(:setup_agent).never
@puppetd.setup
end
it "should not create an agent" do
Puppet::Agent.stubs(:new).with(Puppet::Configurer).never
@puppetd.setup
end
it "should not daemonize" do
@daemon.expects(:daemonize).never
@puppetd.setup
end
end
describe "when configuring agent for catalog run" do
it "should set should_fork as true when running normally" do
Puppet::Agent.expects(:new).with(anything, true)
@puppetd.setup
end
it "should not set should_fork as false for --onetime" do
Puppet[:onetime] = true
Puppet::Agent.expects(:new).with(anything, false)
@puppetd.setup
end
end
end
describe "when running" do
before :each do
@puppetd.options[:fingerprint] = false
end
it "should dispatch to fingerprint if --fingerprint is used" do
@puppetd.options[:fingerprint] = true
@puppetd.stubs(:fingerprint)
execute_agent
end
it "should dispatch to onetime if --onetime is used" do
@puppetd.options[:onetime] = true
@puppetd.stubs(:onetime)
execute_agent
end
it "should dispatch to main if --onetime and --fingerprint are not used" do
@puppetd.options[:onetime] = false
@puppetd.stubs(:main)
execute_agent
end
describe "with --onetime" do
before :each do
@agent.stubs(:run).returns(:report)
Puppet[:onetime] = true
@puppetd.options[:client] = :client
@puppetd.options[:detailed_exitcodes] = false
end
it "should setup traps" do
@daemon.expects(:set_signal_traps)
expect { execute_agent }.to exit_with 0
end
it "should let the agent run" do
@agent.expects(:run).returns(:report)
expect { execute_agent }.to exit_with 0
end
it "should stop the daemon" do
@daemon.expects(:stop).with(:exit => false)
expect { execute_agent }.to exit_with 0
end
describe "and --detailed-exitcodes" do
before :each do
@puppetd.options[:detailed_exitcodes] = true
end
it "should exit with agent computed exit status" do
Puppet[:noop] = false
@agent.stubs(:run).returns(666)
expect { execute_agent }.to exit_with 666
end
it "should exit with the agent's exit status, even if --noop is set." do
Puppet[:noop] = true
@agent.stubs(:run).returns(666)
expect { execute_agent }.to exit_with 666
end
end
end
describe "with --fingerprint" do
before :each do
@cert = mock 'cert'
@puppetd.options[:fingerprint] = true
@puppetd.options[:digest] = :MD5
end
it "should fingerprint the certificate if it exists" do
@ssl_host.stubs(:certificate).returns(@cert)
@cert.stubs(:digest).with('MD5').returns "fingerprint"
@puppetd.expects(:puts).with "fingerprint"
@puppetd.fingerprint
end
it "should fingerprint the certificate request if no certificate have been signed" do
@ssl_host.stubs(:certificate).returns(nil)
@ssl_host.stubs(:certificate_request).returns(@cert)
@cert.stubs(:digest).with('MD5').returns "fingerprint"
@puppetd.expects(:puts).with "fingerprint"
@puppetd.fingerprint
end
end
describe "without --onetime and --fingerprint" do
before :each do
Puppet.stubs(:notice)
end
it "should start our daemon" do
@daemon.expects(:start)
execute_agent
end
end
end
def execute_agent
@puppetd.setup
@puppetd.run_command
end
end
diff --git a/spec/unit/application/apply_spec.rb b/spec/unit/application/apply_spec.rb
index ec6afee66..5bc9282af 100755
--- a/spec/unit/application/apply_spec.rb
+++ b/spec/unit/application/apply_spec.rb
@@ -1,460 +1,460 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/application/apply'
require 'puppet/file_bucket/dipper'
require 'puppet/configurer'
require 'fileutils'
describe Puppet::Application::Apply do
before :each do
@apply = Puppet::Application[:apply]
Puppet::Util::Log.stubs(:newdestination)
Puppet[:reports] = "none"
end
after :each do
Puppet::Node::Facts.indirection.reset_terminus_class
Puppet::Node::Facts.indirection.cache_class = nil
Puppet::Node.indirection.reset_terminus_class
Puppet::Node.indirection.cache_class = nil
end
[:debug,:loadclasses,:test,:verbose,:use_nodes,:detailed_exitcodes,:catalog, :write_catalog_summary].each do |option|
it "should declare handle_#{option} method" do
- @apply.should respond_to("handle_#{option}".to_sym)
+ expect(@apply).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
@apply.options.expects(:[]=).with(option, 'arg')
@apply.send("handle_#{option}".to_sym, 'arg')
end
end
it "should set the code to the provided code when :execute is used" do
@apply.options.expects(:[]=).with(:code, 'arg')
@apply.send("handle_execute".to_sym, 'arg')
end
describe "when applying options" do
it "should set the log destination with --logdest" do
Puppet::Log.expects(:newdestination).with("console")
@apply.handle_logdest("console")
end
it "should set the setdest options to true" do
@apply.options.expects(:[]=).with(:setdest,true)
@apply.handle_logdest("console")
end
end
describe "during setup" do
before :each do
Puppet::Log.stubs(:newdestination)
Puppet::FileBucket::Dipper.stubs(:new)
STDIN.stubs(:read)
Puppet::Transaction::Report.indirection.stubs(:cache_class=)
end
describe "with --test" do
it "should call setup_test" do
@apply.options[:test] = true
@apply.expects(:setup_test)
@apply.setup
end
it "should set options[:verbose] to true" do
@apply.setup_test
- @apply.options[:verbose].should == true
+ expect(@apply.options[:verbose]).to eq(true)
end
it "should set options[:show_diff] to true" do
Puppet.settings.override_default(:show_diff, false)
@apply.setup_test
- Puppet[:show_diff].should == true
+ expect(Puppet[:show_diff]).to eq(true)
end
it "should set options[:detailed_exitcodes] to true" do
@apply.setup_test
- @apply.options[:detailed_exitcodes].should == true
+ expect(@apply.options[:detailed_exitcodes]).to eq(true)
end
end
it "should set console as the log destination if logdest option wasn't provided" do
Puppet::Log.expects(:newdestination).with(:console)
@apply.setup
end
it "should set INT trap" do
Signal.expects(:trap).with(:INT)
@apply.setup
end
it "should set log level to debug if --debug was passed" do
@apply.options[:debug] = true
@apply.setup
- Puppet::Log.level.should == :debug
+ expect(Puppet::Log.level).to eq(:debug)
end
it "should set log level to info if --verbose was passed" do
@apply.options[:verbose] = true
@apply.setup
- Puppet::Log.level.should == :info
+ expect(Puppet::Log.level).to eq(:info)
end
it "should print puppet config if asked to in Puppet config" do
Puppet.settings.stubs(:print_configs?).returns true
Puppet.settings.expects(:print_configs).returns true
expect { @apply.setup }.to exit_with 0
end
it "should exit after printing puppet config if asked to in Puppet config" do
Puppet.settings.stubs(:print_configs?).returns(true)
expect { @apply.setup }.to exit_with 1
end
it "should tell the report handler to cache locally as yaml" do
Puppet::Transaction::Report.indirection.expects(:cache_class=).with(:yaml)
@apply.setup
end
it "configures a profiler when profiling is enabled" do
Puppet[:profile] = true
@apply.setup
expect(Puppet::Util::Profiler.current).to satisfy do |ps|
ps.any? {|p| p.is_a? Puppet::Util::Profiler::WallClock }
end
end
it "does not have a profiler if profiling is disabled" do
Puppet[:profile] = false
@apply.setup
expect(Puppet::Util::Profiler.current.length).to be 0
end
it "should set default_file_terminus to `file_server` to be local" do
- @apply.app_defaults[:default_file_terminus].should == :file_server
+ expect(@apply.app_defaults[:default_file_terminus]).to eq(:file_server)
end
end
describe "when executing" do
it "should dispatch to 'apply' if it was called with 'apply'" do
@apply.options[:catalog] = "foo"
@apply.expects(:apply)
@apply.run_command
end
it "should dispatch to main otherwise" do
@apply.stubs(:options).returns({})
@apply.expects(:main)
@apply.run_command
end
describe "the main command" do
include PuppetSpec::Files
before :each do
Puppet[:prerun_command] = ''
Puppet[:postrun_command] = ''
Puppet::Node::Facts.indirection.terminus_class = :memory
Puppet::Node::Facts.indirection.cache_class = :memory
Puppet::Node.indirection.terminus_class = :memory
Puppet::Node.indirection.cache_class = :memory
@facts = Puppet::Node::Facts.new(Puppet[:node_name_value])
Puppet::Node::Facts.indirection.save(@facts)
@node = Puppet::Node.new(Puppet[:node_name_value])
Puppet::Node.indirection.save(@node)
@catalog = Puppet::Resource::Catalog.new("testing", Puppet.lookup(:environments).get(Puppet[:environment]))
@catalog.stubs(:to_ral).returns(@catalog)
Puppet::Resource::Catalog.indirection.stubs(:find).returns(@catalog)
STDIN.stubs(:read)
@transaction = stub('transaction')
@catalog.stubs(:apply).returns(@transaction)
Puppet::Util::Storage.stubs(:load)
Puppet::Configurer.any_instance.stubs(:save_last_run_summary) # to prevent it from trying to write files
end
after :each do
Puppet::Node::Facts.indirection.reset_terminus_class
Puppet::Node::Facts.indirection.cache_class = nil
end
around :each do |example|
Puppet.override(:current_environment =>
Puppet::Node::Environment.create(:production, [])) do
example.run
end
end
it "should set the code to run from --code" do
@apply.options[:code] = "code to run"
Puppet.expects(:[]=).with(:code,"code to run")
expect { @apply.main }.to exit_with 0
end
it "should set the code to run from STDIN if no arguments" do
@apply.command_line.stubs(:args).returns([])
STDIN.stubs(:read).returns("code to run")
Puppet.expects(:[]=).with(:code,"code to run")
expect { @apply.main }.to exit_with 0
end
it "should raise an error if a file is passed on command line and the file does not exist" do
noexist = tmpfile('noexist.pp')
@apply.command_line.stubs(:args).returns([noexist])
- lambda { @apply.main }.should raise_error(RuntimeError, "Could not find file #{noexist}")
+ expect { @apply.main }.to raise_error(RuntimeError, "Could not find file #{noexist}")
end
it "should set the manifest to the first file and warn other files will be skipped" do
manifest = tmpfile('starwarsIV')
FileUtils.touch(manifest)
@apply.command_line.stubs(:args).returns([manifest, 'starwarsI', 'starwarsII'])
expect { @apply.main }.to exit_with 0
msg = @logs.find {|m| m.message =~ /Only one file can be applied per run/ }
- msg.message.should == 'Only one file can be applied per run. Skipping starwarsI, starwarsII'
- msg.level.should == :warning
+ expect(msg.message).to eq('Only one file can be applied per run. Skipping starwarsI, starwarsII')
+ expect(msg.level).to eq(:warning)
end
it "should raise an error if we can't find the node" do
Puppet::Node.indirection.expects(:find).returns(nil)
- lambda { @apply.main }.should raise_error(RuntimeError, /Could not find node/)
+ expect { @apply.main }.to raise_error(RuntimeError, /Could not find node/)
end
it "should load custom classes if loadclasses" do
@apply.options[:loadclasses] = true
classfile = tmpfile('classfile')
File.open(classfile, 'w') { |c| c.puts 'class' }
Puppet[:classfile] = classfile
@node.expects(:classes=).with(['class'])
expect { @apply.main }.to exit_with 0
end
it "should compile the catalog" do
Puppet::Resource::Catalog.indirection.expects(:find).returns(@catalog)
expect { @apply.main }.to exit_with 0
end
it "should transform the catalog to ral" do
@catalog.expects(:to_ral).returns(@catalog)
expect { @apply.main }.to exit_with 0
end
it "should finalize the catalog" do
@catalog.expects(:finalize)
expect { @apply.main }.to exit_with 0
end
it "should not save the classes or resource file by default" do
@catalog.expects(:write_class_file).never
@catalog.expects(:write_resource_file).never
expect { @apply.main }.to exit_with 0
end
it "should save the classes and resources files when requested" do
@apply.options[:write_catalog_summary] = true
@catalog.expects(:write_class_file).once
@catalog.expects(:write_resource_file).once
expect { @apply.main }.to exit_with 0
end
it "should call the prerun and postrun commands on a Configurer instance" do
Puppet::Configurer.any_instance.expects(:execute_prerun_command).returns(true)
Puppet::Configurer.any_instance.expects(:execute_postrun_command).returns(true)
expect { @apply.main }.to exit_with 0
end
it "should apply the catalog" do
@catalog.expects(:apply).returns(stub_everything('transaction'))
expect { @apply.main }.to exit_with 0
end
it "should save the last run summary" do
Puppet[:noop] = false
report = Puppet::Transaction::Report.new("apply")
Puppet::Transaction::Report.stubs(:new).returns(report)
Puppet::Configurer.any_instance.expects(:save_last_run_summary).with(report)
expect { @apply.main }.to exit_with 0
end
describe "when using node_name_fact" do
before :each do
@facts = Puppet::Node::Facts.new(Puppet[:node_name_value], 'my_name_fact' => 'other_node_name')
Puppet::Node::Facts.indirection.save(@facts)
@node = Puppet::Node.new('other_node_name')
Puppet::Node.indirection.save(@node)
Puppet[:node_name_fact] = 'my_name_fact'
end
it "should set the facts name based on the node_name_fact" do
expect { @apply.main }.to exit_with 0
- @facts.name.should == 'other_node_name'
+ expect(@facts.name).to eq('other_node_name')
end
it "should set the node_name_value based on the node_name_fact" do
expect { @apply.main }.to exit_with 0
- Puppet[:node_name_value].should == 'other_node_name'
+ expect(Puppet[:node_name_value]).to eq('other_node_name')
end
it "should merge in our node the loaded facts" do
@facts.values.merge!('key' => 'value')
expect { @apply.main }.to exit_with 0
- @node.parameters['key'].should == 'value'
+ expect(@node.parameters['key']).to eq('value')
end
it "should raise an error if we can't find the facts" do
Puppet::Node::Facts.indirection.expects(:find).returns(nil)
- lambda { @apply.main }.should raise_error
+ expect { @apply.main }.to raise_error
end
end
describe "with detailed_exitcodes" do
before :each do
@apply.options[:detailed_exitcodes] = true
end
it "should exit with report's computed exit status" do
Puppet[:noop] = false
Puppet::Transaction::Report.any_instance.stubs(:exit_status).returns(666)
expect { @apply.main }.to exit_with 666
end
it "should exit with report's computed exit status, even if --noop is set" do
Puppet[:noop] = true
Puppet::Transaction::Report.any_instance.stubs(:exit_status).returns(666)
expect { @apply.main }.to exit_with 666
end
it "should always exit with 0 if option is disabled" do
Puppet[:noop] = false
report = stub 'report', :exit_status => 666
@transaction.stubs(:report).returns(report)
expect { @apply.main }.to exit_with 0
end
it "should always exit with 0 if --noop" do
Puppet[:noop] = true
report = stub 'report', :exit_status => 666
@transaction.stubs(:report).returns(report)
expect { @apply.main }.to exit_with 0
end
end
end
describe "the 'apply' command" do
# We want this memoized, and to be able to adjust the content, so we
# have to do it ourselves.
def temporary_catalog(content = '"something"')
@tempfile = Tempfile.new('catalog.pson')
@tempfile.write(content)
@tempfile.close
@tempfile.path
end
it "should read the catalog in from disk if a file name is provided" do
@apply.options[:catalog] = temporary_catalog
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
Puppet::Resource::Catalog.stubs(:convert_from).with(:pson,'"something"').returns(catalog)
@apply.apply
end
it "should read the catalog in from stdin if '-' is provided" do
@apply.options[:catalog] = "-"
$stdin.expects(:read).returns '"something"'
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
Puppet::Resource::Catalog.stubs(:convert_from).with(:pson,'"something"').returns(catalog)
@apply.apply
end
it "should deserialize the catalog from the default format" do
@apply.options[:catalog] = temporary_catalog
Puppet::Resource::Catalog.stubs(:default_format).returns :rot13_piglatin
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
Puppet::Resource::Catalog.stubs(:convert_from).with(:rot13_piglatin,'"something"').returns(catalog)
@apply.apply
end
it "should fail helpfully if deserializing fails" do
@apply.options[:catalog] = temporary_catalog('something syntactically invalid')
- lambda { @apply.apply }.should raise_error(Puppet::Error)
+ expect { @apply.apply }.to raise_error(Puppet::Error)
end
it "should convert plain data structures into a catalog if deserialization does not do so" do
@apply.options[:catalog] = temporary_catalog
Puppet::Resource::Catalog.stubs(:convert_from).with(:pson,'"something"').returns({:foo => "bar"})
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
Puppet::Resource::Catalog.expects(:pson_create).with({:foo => "bar"}).returns(catalog)
@apply.apply
end
it "should convert the catalog to a RAL catalog and use a Configurer instance to apply it" do
@apply.options[:catalog] = temporary_catalog
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
Puppet::Resource::Catalog.stubs(:convert_from).with(:pson,'"something"').returns catalog
catalog.expects(:to_ral).returns "mycatalog"
configurer = stub 'configurer'
Puppet::Configurer.expects(:new).returns configurer
configurer.expects(:run).
with(:catalog => "mycatalog", :pluginsync => false)
@apply.apply
end
end
end
describe "apply_catalog" do
it "should call the configurer with the catalog" do
catalog = "I am a catalog"
Puppet::Configurer.any_instance.expects(:run).
with(:catalog => catalog, :pluginsync => false)
@apply.send(:apply_catalog, catalog)
end
end
end
diff --git a/spec/unit/application/cert_spec.rb b/spec/unit/application/cert_spec.rb
index f24ef8677..fda0c9e05 100755
--- a/spec/unit/application/cert_spec.rb
+++ b/spec/unit/application/cert_spec.rb
@@ -1,220 +1,220 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/application/cert'
describe Puppet::Application::Cert => true do
before :each do
@cert_app = Puppet::Application[:cert]
Puppet::Util::Log.stubs(:newdestination)
end
it "should operate in master run_mode" do
- @cert_app.class.run_mode.name.should equal(:master)
+ expect(@cert_app.class.run_mode.name).to equal(:master)
end
it "should declare a main command" do
- @cert_app.should respond_to(:main)
+ expect(@cert_app).to respond_to(:main)
end
Puppet::SSL::CertificateAuthority::Interface::INTERFACE_METHODS.reject{ |m| m == :destroy }.each do |method|
it "should declare option --#{method}" do
- @cert_app.should respond_to("handle_#{method}".to_sym)
+ expect(@cert_app).to respond_to("handle_#{method}".to_sym)
end
end
it "should set log level to info with the --verbose option" do
@cert_app.handle_verbose(0)
- Puppet::Log.level.should == :info
+ expect(Puppet::Log.level).to eq(:info)
end
it "should set log level to debug with the --debug option" do
@cert_app.handle_debug(0)
- Puppet::Log.level.should == :debug
+ expect(Puppet::Log.level).to eq(:debug)
end
it "should set the fingerprint digest with the --digest option" do
@cert_app.handle_digest(:digest)
- @cert_app.digest.should == :digest
+ expect(@cert_app.digest).to eq(:digest)
end
it "should set cert_mode to :destroy for --clean" do
@cert_app.handle_clean(0)
- @cert_app.subcommand.should == :destroy
+ expect(@cert_app.subcommand).to eq(:destroy)
end
it "should set all to true for --all" do
@cert_app.handle_all(0)
- @cert_app.all.should be_true
+ expect(@cert_app.all).to be_truthy
end
it "should set signed to true for --signed" do
@cert_app.handle_signed(0)
- @cert_app.signed.should be_true
+ expect(@cert_app.signed).to be_truthy
end
Puppet::SSL::CertificateAuthority::Interface::INTERFACE_METHODS.reject { |m| m == :destroy }.each do |method|
it "should set cert_mode to #{method} with option --#{method}" do
@cert_app.send("handle_#{method}".to_sym, nil)
- @cert_app.subcommand.should == method
+ expect(@cert_app.subcommand).to eq(method)
end
end
describe "during setup" do
before :each do
Puppet::Log.stubs(:newdestination)
Puppet::SSL::Host.stubs(:ca_location=)
Puppet::SSL::CertificateAuthority.stubs(:new)
end
it "should set console as the log destination" do
Puppet::Log.expects(:newdestination).with(:console)
@cert_app.setup
end
it "should print puppet config if asked to in Puppet config" do
Puppet.settings.stubs(:print_configs?).returns(true)
Puppet.settings.expects(:print_configs).returns true
expect { @cert_app.setup }.to exit_with 0
end
it "should exit after printing puppet config if asked to in Puppet config" do
Puppet.settings.stubs(:print_configs?).returns(true)
expect { @cert_app.setup }.to exit_with 1
end
it "should set the CA location to 'only'" do
Puppet::SSL::Host.expects(:ca_location=).with(:only)
@cert_app.setup
end
it "should create a new certificate authority" do
Puppet::SSL::CertificateAuthority.expects(:new)
@cert_app.setup
end
it "should set the ca_location to :local if the cert_mode is generate" do
@cert_app.subcommand = 'generate'
Puppet::SSL::Host.expects(:ca_location=).with(:local)
@cert_app.setup
end
it "should set the ca_location to :local if the cert_mode is destroy" do
@cert_app.subcommand = 'destroy'
Puppet::SSL::Host.expects(:ca_location=).with(:local)
@cert_app.setup
end
it "should set the ca_location to :only if the cert_mode is print" do
@cert_app.subcommand = 'print'
Puppet::SSL::Host.expects(:ca_location=).with(:only)
@cert_app.setup
end
end
describe "when running" do
before :each do
@cert_app.all = false
@ca = stub_everything 'ca'
@cert_app.ca = @ca
@cert_app.command_line.stubs(:args).returns([])
@iface = stub_everything 'iface'
Puppet::SSL::CertificateAuthority::Interface.stubs(:new).returns(@iface)
end
it "should delegate to the CertificateAuthority" do
@iface.expects(:apply)
@cert_app.main
end
it "should delegate with :all if option --all was given" do
@cert_app.handle_all(0)
Puppet::SSL::CertificateAuthority::Interface.expects(:new).returns(@iface).with { |cert_mode,to| to[:to] == :all }
@cert_app.main
end
it "should delegate to ca.apply with the hosts given on command line" do
@cert_app.command_line.stubs(:args).returns(["host"])
Puppet::SSL::CertificateAuthority::Interface.expects(:new).returns(@iface).with { |cert_mode,to| to[:to] == ["host"]}
@cert_app.main
end
it "should send the currently set digest" do
@cert_app.command_line.stubs(:args).returns(["host"])
@cert_app.handle_digest(:digest)
Puppet::SSL::CertificateAuthority::Interface.expects(:new).returns(@iface).with { |cert_mode,to| to[:digest] == :digest}
@cert_app.main
end
it "should revoke cert if cert_mode is clean" do
@cert_app.subcommand = :destroy
@cert_app.command_line.stubs(:args).returns(["host"])
Puppet::SSL::CertificateAuthority::Interface.expects(:new).returns(@iface).with { |cert_mode,to| cert_mode == :revoke }
Puppet::SSL::CertificateAuthority::Interface.expects(:new).returns(@iface).with { |cert_mode,to| cert_mode == :destroy }
@cert_app.main
end
end
describe "when identifying subcommands" do
before :each do
@cert_app.all = false
@ca = stub_everything 'ca'
@cert_app.ca = @ca
end
%w{list revoke generate sign print verify fingerprint}.each do |cmd|
short = cmd[0,1]
[cmd, "--#{cmd}", "-#{short}"].each do |option|
# In our command line '-v' was eaten by 'verbose', so we can't consume
# it here; this is a special case from our otherwise standard
# processing. --daniel 2011-02-22
next if option == "-v"
it "should recognise '#{option}'" do
args = [option, "fun.example.com"]
@cert_app.command_line.stubs(:args).returns(args)
@cert_app.parse_options
- @cert_app.subcommand.should == cmd.to_sym
+ expect(@cert_app.subcommand).to eq(cmd.to_sym)
- args.should == ["fun.example.com"]
+ expect(args).to eq(["fun.example.com"])
end
end
end
%w{clean --clean -c}.each do |ugly|
it "should recognise the '#{ugly}' option as destroy" do
args = [ugly, "fun.example.com"]
@cert_app.command_line.stubs(:args).returns(args)
@cert_app.parse_options
- @cert_app.subcommand.should == :destroy
+ expect(@cert_app.subcommand).to eq(:destroy)
- args.should == ["fun.example.com"]
+ expect(args).to eq(["fun.example.com"])
end
end
it "should print help and exit if there is no subcommand" do
args = []
@cert_app.command_line.stubs(:args).returns(args)
@cert_app.stubs(:help).returns("I called for help!")
@cert_app.expects(:puts).with("I called for help!")
expect { @cert_app.parse_options }.to exit_with 0
- @cert_app.subcommand.should be_nil
+ expect(@cert_app.subcommand).to be_nil
end
end
end
diff --git a/spec/unit/application/certificate_spec.rb b/spec/unit/application/certificate_spec.rb
index cd8f34302..2d089d77a 100755
--- a/spec/unit/application/certificate_spec.rb
+++ b/spec/unit/application/certificate_spec.rb
@@ -1,22 +1,22 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/application/certificate'
describe Puppet::Application::Certificate do
it "should have a 'ca-location' option" do
# REVISIT: This is delegated from the face, and we will have a test there,
# so is this actually a valuable test? --daniel 2011-04-07
subject.command_line.stubs(:args).returns %w{list}
subject.preinit
subject.parse_options
- subject.should respond_to(:handle_ca_location)
+ expect(subject).to respond_to(:handle_ca_location)
end
it "should accept the ca-location option" do
subject.command_line.stubs(:args).returns %w{--ca-location local list}
subject.preinit
subject.parse_options
subject.setup
- subject.arguments.should == [{ :ca_location => "local" }]
+ expect(subject.arguments).to eq([{ :ca_location => "local" }])
end
end
diff --git a/spec/unit/application/config_spec.rb b/spec/unit/application/config_spec.rb
index 14352fb98..fa83a33da 100755
--- a/spec/unit/application/config_spec.rb
+++ b/spec/unit/application/config_spec.rb
@@ -1,9 +1,9 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/application/config'
describe Puppet::Application::Config do
it "should be a subclass of Puppet::Application::FaceBase" do
- Puppet::Application::Config.superclass.should equal(Puppet::Application::FaceBase)
+ expect(Puppet::Application::Config.superclass).to equal(Puppet::Application::FaceBase)
end
end
diff --git a/spec/unit/application/describe_spec.rb b/spec/unit/application/describe_spec.rb
index 2d5f13c89..0f1dfac11 100755
--- a/spec/unit/application/describe_spec.rb
+++ b/spec/unit/application/describe_spec.rb
@@ -1,79 +1,79 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/application/describe'
describe Puppet::Application::Describe do
before :each do
@describe = Puppet::Application[:describe]
end
it "should declare a main command" do
- @describe.should respond_to(:main)
+ expect(@describe).to respond_to(:main)
end
it "should declare a preinit block" do
- @describe.should respond_to(:preinit)
+ expect(@describe).to respond_to(:preinit)
end
[:providers,:list,:meta].each do |option|
it "should declare handle_#{option} method" do
- @describe.should respond_to("handle_#{option}".to_sym)
+ expect(@describe).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
@describe.options.expects(:[]=).with("#{option}".to_sym, 'arg')
@describe.send("handle_#{option}".to_sym, 'arg')
end
end
describe "in preinit" do
it "should set options[:parameters] to true" do
@describe.preinit
- @describe.options[:parameters].should be_true
+ expect(@describe.options[:parameters]).to be_truthy
end
end
describe "when handling parameters" do
it "should set options[:parameters] to false" do
@describe.handle_short(nil)
- @describe.options[:parameters].should be_false
+ expect(@describe.options[:parameters]).to be_falsey
end
end
describe "during setup" do
it "should collect arguments in options[:types]" do
@describe.command_line.stubs(:args).returns(['1','2'])
@describe.setup
- @describe.options[:types].should == ['1','2']
+ expect(@describe.options[:types]).to eq(['1','2'])
end
end
describe "when running" do
before :each do
@typedoc = stub 'type_doc'
TypeDoc.stubs(:new).returns(@typedoc)
end
it "should call list_types if options list is set" do
@describe.options[:list] = true
@typedoc.expects(:list_types)
@describe.run_command
end
it "should call format_type for each given types" do
@describe.options[:list] = false
@describe.options[:types] = ['type']
@typedoc.expects(:format_type).with('type', @describe.options)
@describe.run_command
end
end
end
diff --git a/spec/unit/application/device_spec.rb b/spec/unit/application/device_spec.rb
index 25a4f83de..4a992ba3e 100755
--- a/spec/unit/application/device_spec.rb
+++ b/spec/unit/application/device_spec.rb
@@ -1,415 +1,415 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/application/device'
require 'puppet/util/network_device/config'
require 'ostruct'
require 'puppet/configurer'
describe Puppet::Application::Device do
include PuppetSpec::Files
before :each do
@device = Puppet::Application[:device]
@device.preinit
Puppet::Util::Log.stubs(:newdestination)
Puppet::Node.indirection.stubs(:terminus_class=)
Puppet::Node.indirection.stubs(:cache_class=)
Puppet::Node::Facts.indirection.stubs(:terminus_class=)
end
it "should operate in agent run_mode" do
- @device.class.run_mode.name.should == :agent
+ expect(@device.class.run_mode.name).to eq(:agent)
end
it "should declare a main command" do
- @device.should respond_to(:main)
+ expect(@device).to respond_to(:main)
end
it "should declare a preinit block" do
- @device.should respond_to(:preinit)
+ expect(@device).to respond_to(:preinit)
end
describe "in preinit" do
before :each do
@device.stubs(:trap)
end
it "should catch INT" do
Signal.expects(:trap).with { |arg,block| arg == :INT }
@device.preinit
end
it "should init waitforcert to nil" do
@device.preinit
- @device.options[:waitforcert].should be_nil
+ expect(@device.options[:waitforcert]).to be_nil
end
end
describe "when handling options" do
before do
@device.command_line.stubs(:args).returns([])
end
[:centrallogging, :debug, :verbose,].each do |option|
it "should declare handle_#{option} method" do
- @device.should respond_to("handle_#{option}".to_sym)
+ expect(@device).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
@device.options.expects(:[]=).with(option, 'arg')
@device.send("handle_#{option}".to_sym, 'arg')
end
end
it "should set waitforcert to 0 with --onetime and if --waitforcert wasn't given" do
Puppet[:onetime] = true
Puppet::SSL::Host.any_instance.expects(:wait_for_cert).with(0)
@device.setup_host
end
it "should use supplied waitforcert when --onetime is specified" do
Puppet[:onetime] = true
@device.handle_waitforcert(60)
Puppet::SSL::Host.any_instance.expects(:wait_for_cert).with(60)
@device.setup_host
end
it "should use a default value for waitforcert when --onetime and --waitforcert are not specified" do
Puppet::SSL::Host.any_instance.expects(:wait_for_cert).with(120)
@device.setup_host
end
it "should use the waitforcert setting when checking for a signed certificate" do
Puppet[:waitforcert] = 10
Puppet::SSL::Host.any_instance.expects(:wait_for_cert).with(10)
@device.setup_host
end
it "should set the log destination with --logdest" do
@device.options.stubs(:[]=).with { |opt,val| opt == :setdest }
Puppet::Log.expects(:newdestination).with("console")
@device.handle_logdest("console")
end
it "should put the setdest options to true" do
@device.options.expects(:[]=).with(:setdest,true)
@device.handle_logdest("console")
end
it "should parse the log destination from the command line" do
@device.command_line.stubs(:args).returns(%w{--logdest /my/file})
Puppet::Util::Log.expects(:newdestination).with("/my/file")
@device.parse_options
end
it "should store the waitforcert options with --waitforcert" do
@device.options.expects(:[]=).with(:waitforcert,42)
@device.handle_waitforcert("42")
end
it "should set args[:Port] with --port" do
@device.handle_port("42")
- @device.args[:Port].should == "42"
+ expect(@device.args[:Port]).to eq("42")
end
end
describe "during setup" do
before :each do
@device.options.stubs(:[])
Puppet.stubs(:info)
Puppet[:libdir] = "/dev/null/lib"
Puppet::SSL::Host.stubs(:ca_location=)
Puppet::Transaction::Report.indirection.stubs(:terminus_class=)
Puppet::Resource::Catalog.indirection.stubs(:terminus_class=)
Puppet::Resource::Catalog.indirection.stubs(:cache_class=)
Puppet::Node::Facts.indirection.stubs(:terminus_class=)
@host = stub_everything 'host'
Puppet::SSL::Host.stubs(:new).returns(@host)
Puppet.stubs(:settraps)
end
it "should call setup_logs" do
@device.expects(:setup_logs)
@device.setup
end
describe "when setting up logs" do
before :each do
Puppet::Util::Log.stubs(:newdestination)
end
it "should set log level to debug if --debug was passed" do
@device.options.stubs(:[]).with(:debug).returns(true)
@device.setup_logs
- Puppet::Util::Log.level.should == :debug
+ expect(Puppet::Util::Log.level).to eq(:debug)
end
it "should set log level to info if --verbose was passed" do
@device.options.stubs(:[]).with(:verbose).returns(true)
@device.setup_logs
- Puppet::Util::Log.level.should == :info
+ expect(Puppet::Util::Log.level).to eq(:info)
end
[:verbose, :debug].each do |level|
it "should set console as the log destination with level #{level}" do
@device.options.stubs(:[]).with(level).returns(true)
Puppet::Util::Log.expects(:newdestination).with(:console)
@device.setup_logs
end
end
it "should set a default log destination if no --logdest" do
@device.options.stubs(:[]).with(:setdest).returns(false)
Puppet::Util::Log.expects(:setup_default)
@device.setup_logs
end
end
it "should set a central log destination with --centrallogs" do
@device.options.stubs(:[]).with(:centrallogs).returns(true)
Puppet[:server] = "puppet.reductivelabs.com"
Puppet::Util::Log.stubs(:newdestination).with(:syslog)
Puppet::Util::Log.expects(:newdestination).with("puppet.reductivelabs.com")
@device.setup
end
it "should use :main, :agent, :device and :ssl config" do
Puppet.settings.expects(:use).with(:main, :agent, :device, :ssl)
@device.setup
end
it "should install a remote ca location" do
Puppet::SSL::Host.expects(:ca_location=).with(:remote)
@device.setup
end
it "should tell the report handler to use REST" do
Puppet::Transaction::Report.indirection.expects(:terminus_class=).with(:rest)
@device.setup
end
it "should default the catalog_terminus setting to 'rest'" do
@device.initialize_app_defaults
- Puppet[:catalog_terminus].should == :rest
+ expect(Puppet[:catalog_terminus]).to eq(:rest)
end
it "should default the node_terminus setting to 'rest'" do
@device.initialize_app_defaults
- Puppet[:node_terminus].should == :rest
+ expect(Puppet[:node_terminus]).to eq(:rest)
end
it "has an application default :catalog_cache_terminus setting of 'json'" do
Puppet::Resource::Catalog.indirection.expects(:cache_class=).with(:json)
@device.initialize_app_defaults
@device.setup
end
it "should tell the catalog cache class based on the :catalog_cache_terminus setting" do
Puppet[:catalog_cache_terminus] = "yaml"
Puppet::Resource::Catalog.indirection.expects(:cache_class=).with(:yaml)
@device.initialize_app_defaults
@device.setup
end
it "should not set catalog cache class if :catalog_cache_terminus is explicitly nil" do
Puppet[:catalog_cache_terminus] = nil
Puppet::Resource::Catalog.indirection.expects(:cache_class=).never
@device.initialize_app_defaults
@device.setup
end
it "should default the facts_terminus setting to 'network_device'" do
@device.initialize_app_defaults
- Puppet[:facts_terminus].should == :network_device
+ expect(Puppet[:facts_terminus]).to eq(:network_device)
end
end
describe "when initializing each devices SSL" do
before(:each) do
@host = stub_everything 'host'
Puppet::SSL::Host.stubs(:new).returns(@host)
end
it "should create a new ssl host" do
Puppet::SSL::Host.expects(:new).returns(@host)
@device.setup_host
end
it "should wait for a certificate" do
@device.options.stubs(:[]).with(:waitforcert).returns(123)
@host.expects(:wait_for_cert).with(123)
@device.setup_host
end
end
describe "when running" do
before :each do
@device.options.stubs(:[]).with(:fingerprint).returns(false)
Puppet.stubs(:notice)
@device.options.stubs(:[]).with(:client)
Puppet::Util::NetworkDevice::Config.stubs(:devices).returns({})
end
it "should dispatch to main" do
@device.stubs(:main)
@device.run_command
end
it "should get the device list" do
device_hash = stub_everything 'device hash'
Puppet::Util::NetworkDevice::Config.expects(:devices).returns(device_hash)
@device.main
end
it "should exit if the device list is empty" do
expect { @device.main }.to exit_with 1
end
describe "for each device" do
before(:each) do
Puppet[:vardir] = make_absolute("/dummy")
Puppet[:confdir] = make_absolute("/dummy")
Puppet[:certname] = "certname"
@device_hash = {
"device1" => OpenStruct.new(:name => "device1", :url => "url", :provider => "cisco"),
"device2" => OpenStruct.new(:name => "device2", :url => "url", :provider => "cisco"),
}
Puppet::Util::NetworkDevice::Config.stubs(:devices).returns(@device_hash)
Puppet.stubs(:[]=)
Puppet.settings.stubs(:use)
@device.stubs(:setup_host)
Puppet::Util::NetworkDevice.stubs(:init)
@configurer = stub_everything 'configurer'
Puppet::Configurer.stubs(:new).returns(@configurer)
end
it "should set vardir to the device vardir" do
Puppet.expects(:[]=).with(:vardir, make_absolute("/dummy/devices/device1"))
@device.main
end
it "should set confdir to the device confdir" do
Puppet.expects(:[]=).with(:confdir, make_absolute("/dummy/devices/device1"))
@device.main
end
it "should set certname to the device certname" do
Puppet.expects(:[]=).with(:certname, "device1")
Puppet.expects(:[]=).with(:certname, "device2")
@device.main
end
it "should make sure all the required folders and files are created" do
Puppet.settings.expects(:use).with(:main, :agent, :ssl).twice
@device.main
end
it "should initialize the device singleton" do
Puppet::Util::NetworkDevice.expects(:init).with(@device_hash["device1"]).then.with(@device_hash["device2"])
@device.main
end
it "should setup the SSL context" do
@device.expects(:setup_host).twice
@device.main
end
it "should launch a configurer for this device" do
@configurer.expects(:run).twice
@device.main
end
[:vardir, :confdir].each do |setting|
it "should cleanup the #{setting} setting after the run" do
all_devices = Set.new(@device_hash.keys.map do |device_name| make_absolute("/dummy/devices/#{device_name}") end)
found_devices = Set.new()
# a block to use in a few places later to validate the updated settings
p = Proc.new do |my_setting, my_value|
if my_setting == setting && all_devices.include?(my_value)
found_devices.add(my_value)
true
else
false
end
end
seq = sequence("clean up dirs")
all_devices.size.times do
## one occurrence of set / run / set("/dummy") for each device
Puppet.expects(:[]=).with(&p).in_sequence(seq)
@configurer.expects(:run).in_sequence(seq)
Puppet.expects(:[]=).with(setting, make_absolute("/dummy")).in_sequence(seq)
end
@device.main
expect(found_devices).to eq(all_devices)
end
end
it "should cleanup the certname setting after the run" do
all_devices = Set.new(@device_hash.keys)
found_devices = Set.new()
# a block to use in a few places later to validate the updated settings
p = Proc.new do |my_setting, my_value|
if my_setting == :certname && all_devices.include?(my_value)
found_devices.add(my_value)
true
else
false
end
end
seq = sequence("clean up certname")
all_devices.size.times do
## one occurrence of set / run / set("certname") for each device
Puppet.expects(:[]=).with(&p).in_sequence(seq)
@configurer.expects(:run).in_sequence(seq)
Puppet.expects(:[]=).with(:certname, "certname").in_sequence(seq)
end
@device.main
# make sure that we were called with each of the defined devices
expect(found_devices).to eq(all_devices)
end
it "should expire all cached attributes" do
Puppet::SSL::Host.expects(:reset).twice
@device.main
end
end
end
end
diff --git a/spec/unit/application/doc_spec.rb b/spec/unit/application/doc_spec.rb
index 80dfd6e7f..0a90680b3 100755
--- a/spec/unit/application/doc_spec.rb
+++ b/spec/unit/application/doc_spec.rb
@@ -1,335 +1,335 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/application/doc'
require 'puppet/util/reference'
require 'puppet/util/rdoc'
describe Puppet::Application::Doc do
before :each do
@doc = Puppet::Application[:doc]
@doc.stubs(:puts)
@doc.preinit
Puppet::Util::Log.stubs(:newdestination)
end
it "should declare an other command" do
- @doc.should respond_to(:other)
+ expect(@doc).to respond_to(:other)
end
it "should declare a rdoc command" do
- @doc.should respond_to(:rdoc)
+ expect(@doc).to respond_to(:rdoc)
end
it "should declare a fallback for unknown options" do
- @doc.should respond_to(:handle_unknown)
+ expect(@doc).to respond_to(:handle_unknown)
end
it "should declare a preinit block" do
- @doc.should respond_to(:preinit)
+ expect(@doc).to respond_to(:preinit)
end
describe "in preinit" do
it "should set references to []" do
@doc.preinit
- @doc.options[:references].should == []
+ expect(@doc.options[:references]).to eq([])
end
it "should init mode to text" do
@doc.preinit
- @doc.options[:mode].should == :text
+ expect(@doc.options[:mode]).to eq(:text)
end
it "should init format to to_markdown" do
@doc.preinit
- @doc.options[:format].should == :to_markdown
+ expect(@doc.options[:format]).to eq(:to_markdown)
end
end
describe "when handling options" do
[:all, :outputdir, :verbose, :debug, :charset].each do |option|
it "should declare handle_#{option} method" do
- @doc.should respond_to("handle_#{option}".to_sym)
+ expect(@doc).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
@doc.options.expects(:[]=).with(option, 'arg')
@doc.send("handle_#{option}".to_sym, 'arg')
end
end
it "should store the format if valid" do
Puppet::Util::Reference.stubs(:method_defined?).with('to_format').returns(true)
@doc.handle_format('format')
- @doc.options[:format].should == 'to_format'
+ expect(@doc.options[:format]).to eq('to_format')
end
it "should raise an error if the format is not valid" do
Puppet::Util::Reference.stubs(:method_defined?).with('to_format').returns(false)
expect { @doc.handle_format('format') }.to raise_error(RuntimeError, /Invalid output format/)
end
it "should store the mode if valid" do
Puppet::Util::Reference.stubs(:modes).returns(stub('mode', :include? => true))
@doc.handle_mode('mode')
- @doc.options[:mode].should == :mode
+ expect(@doc.options[:mode]).to eq(:mode)
end
it "should store the mode if :rdoc" do
Puppet::Util::Reference.modes.stubs(:include?).with('rdoc').returns(false)
@doc.handle_mode('rdoc')
- @doc.options[:mode].should == :rdoc
+ expect(@doc.options[:mode]).to eq(:rdoc)
end
it "should raise an error if the mode is not valid" do
Puppet::Util::Reference.modes.stubs(:include?).with('unknown').returns(false)
expect { @doc.handle_mode('unknown') }.to raise_error(RuntimeError, /Invalid output mode/)
end
it "should list all references on list and exit" do
reference = stubs 'reference'
ref = stubs 'ref'
Puppet::Util::Reference.stubs(:references).returns([reference])
Puppet::Util::Reference.expects(:reference).with(reference).returns(ref)
ref.expects(:doc)
expect { @doc.handle_list(nil) }.to exit_with 0
end
it "should add reference to references list with --reference" do
@doc.options[:references] = [:ref1]
@doc.handle_reference('ref2')
- @doc.options[:references].should == [:ref1,:ref2]
+ expect(@doc.options[:references]).to eq([:ref1,:ref2])
end
end
describe "during setup" do
before :each do
Puppet::Log.stubs(:newdestination)
@doc.command_line.stubs(:args).returns([])
end
it "should default to rdoc mode if there are command line arguments" do
@doc.command_line.stubs(:args).returns(["1"])
@doc.stubs(:setup_rdoc)
@doc.setup
- @doc.options[:mode].should == :rdoc
+ expect(@doc.options[:mode]).to eq(:rdoc)
end
it "should call setup_rdoc in rdoc mode" do
@doc.options[:mode] = :rdoc
@doc.expects(:setup_rdoc)
@doc.setup
end
it "should call setup_reference if not rdoc" do
@doc.options[:mode] = :test
@doc.expects(:setup_reference)
@doc.setup
end
describe "configuring logging" do
before :each do
Puppet::Util::Log.stubs(:newdestination)
end
describe "with --debug" do
before do
@doc.options[:debug] = true
end
it "should set log level to debug" do
@doc.setup
- Puppet::Util::Log.level.should == :debug
+ expect(Puppet::Util::Log.level).to eq(:debug)
end
it "should set log destination to console" do
Puppet::Util::Log.expects(:newdestination).with(:console)
@doc.setup
end
end
describe "with --verbose" do
before do
@doc.options[:verbose] = true
end
it "should set log level to info" do
@doc.setup
- Puppet::Util::Log.level.should == :info
+ expect(Puppet::Util::Log.level).to eq(:info)
end
it "should set log destination to console" do
Puppet::Util::Log.expects(:newdestination).with(:console)
@doc.setup
end
end
describe "without --debug or --verbose" do
before do
@doc.options[:debug] = false
@doc.options[:verbose] = false
end
it "should set log level to warning" do
@doc.setup
- Puppet::Util::Log.level.should == :warning
+ expect(Puppet::Util::Log.level).to eq(:warning)
end
it "should set log destination to console" do
Puppet::Util::Log.expects(:newdestination).with(:console)
@doc.setup
end
end
end
describe "in non-rdoc mode" do
it "should get all non-dynamic reference if --all" do
@doc.options[:all] = true
static = stub 'static', :dynamic? => false
dynamic = stub 'dynamic', :dynamic? => true
Puppet::Util::Reference.stubs(:reference).with(:static).returns(static)
Puppet::Util::Reference.stubs(:reference).with(:dynamic).returns(dynamic)
Puppet::Util::Reference.stubs(:references).returns([:static,:dynamic])
@doc.setup_reference
- @doc.options[:references].should == [:static]
+ expect(@doc.options[:references]).to eq([:static])
end
it "should default to :type if no references" do
@doc.setup_reference
- @doc.options[:references].should == [:type]
+ expect(@doc.options[:references]).to eq([:type])
end
end
describe "in rdoc mode" do
describe "when there are unknown args" do
it "should expand --modulepath if any" do
@doc.unknown_args = [ { :opt => "--modulepath", :arg => "path" } ]
Puppet.settings.stubs(:handlearg)
@doc.setup_rdoc
- @doc.unknown_args[0][:arg].should == File.expand_path('path')
+ expect(@doc.unknown_args[0][:arg]).to eq(File.expand_path('path'))
end
it "should give them to Puppet.settings" do
@doc.unknown_args = [ { :opt => :option, :arg => :argument } ]
Puppet.settings.expects(:handlearg).with(:option,:argument)
@doc.setup_rdoc
end
end
it "should operate in master run_mode" do
- @doc.class.run_mode.name.should == :master
+ expect(@doc.class.run_mode.name).to eq(:master)
@doc.setup_rdoc
end
end
end
describe "when running" do
describe "in rdoc mode" do
include PuppetSpec::Files
let(:envdir) { tmpdir('env') }
let(:modules) { File.join(envdir, "modules") }
let(:modules2) { File.join(envdir, "modules2") }
let(:manifests) { File.join(envdir, "manifests") }
before :each do
@doc.manifest = false
Puppet.stubs(:info)
Puppet[:trace] = false
Puppet[:modulepath] = modules
Puppet[:manifest] = manifests
@doc.options[:all] = false
@doc.options[:outputdir] = 'doc'
@doc.options[:charset] = nil
Puppet.settings.stubs(:define_settings)
Puppet::Util::RDoc.stubs(:rdoc)
@doc.command_line.stubs(:args).returns([])
end
around(:each) do |example|
FileUtils.mkdir_p(modules)
env = Puppet::Node::Environment.create(Puppet[:environment].to_sym, [modules], "#{manifests}/site.pp")
Puppet.override({:environments => Puppet::Environments::Static.new(env), :current_environment => env}) do
example.run
end
end
it "should set document_all on --all" do
@doc.options[:all] = true
Puppet.settings.expects(:[]=).with(:document_all, true)
expect { @doc.rdoc }.to exit_with(0)
end
it "should call Puppet::Util::RDoc.rdoc in full mode" do
Puppet::Util::RDoc.expects(:rdoc).with('doc', [modules, manifests], nil)
expect { @doc.rdoc }.to exit_with(0)
end
it "should call Puppet::Util::RDoc.rdoc with a charset if --charset has been provided" do
@doc.options[:charset] = 'utf-8'
Puppet::Util::RDoc.expects(:rdoc).with('doc', [modules, manifests], "utf-8")
expect { @doc.rdoc }.to exit_with(0)
end
it "should call Puppet::Util::RDoc.rdoc in full mode with outputdir set to doc if no --outputdir" do
@doc.options[:outputdir] = false
Puppet::Util::RDoc.expects(:rdoc).with('doc', [modules, manifests], nil)
expect { @doc.rdoc }.to exit_with(0)
end
it "should call Puppet::Util::RDoc.manifestdoc in manifest mode" do
@doc.manifest = true
Puppet::Util::RDoc.expects(:manifestdoc)
expect { @doc.rdoc }.to exit_with(0)
end
it "should get modulepath and manifest values from the environment" do
FileUtils.mkdir_p(modules)
FileUtils.mkdir_p(modules2)
env = Puppet::Node::Environment.create(Puppet[:environment].to_sym,
[modules, modules2],
"envmanifests/site.pp")
Puppet.override({:environments => Puppet::Environments::Static.new(env), :current_environment => env}) do
Puppet::Util::RDoc.stubs(:rdoc).with('doc', [modules.to_s, modules2.to_s, env.manifest.to_s], nil)
expect { @doc.rdoc }.to exit_with(0)
end
end
end
describe "in the other modes" do
it "should get reference in given format" do
reference = stub 'reference'
@doc.options[:mode] = :none
@doc.options[:references] = [:ref]
Puppet::Util::Reference.expects(:reference).with(:ref).returns(reference)
@doc.options[:format] = :format
@doc.stubs(:exit)
reference.expects(:send).with { |format,contents| format == :format }.returns('doc')
@doc.other
end
end
end
end
diff --git a/spec/unit/application/face_base_spec.rb b/spec/unit/application/face_base_spec.rb
index ffb213804..c36eb3e72 100755
--- a/spec/unit/application/face_base_spec.rb
+++ b/spec/unit/application/face_base_spec.rb
@@ -1,423 +1,423 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/application/face_base'
require 'tmpdir'
class Puppet::Application::FaceBase::Basetest < Puppet::Application::FaceBase
end
describe Puppet::Application::FaceBase do
let :app do
app = Puppet::Application::FaceBase::Basetest.new
app.command_line.stubs(:subcommand_name).returns('subcommand')
Puppet::Util::Log.stubs(:newdestination)
app
end
after :each do
app.class.clear_everything_for_tests
end
describe "#find_global_settings_argument" do
it "should not match --ca to --ca-location" do
option = mock('ca option', :optparse_args => ["--ca"])
Puppet.settings.expects(:each).yields(:ca, option)
- app.find_global_settings_argument("--ca-location").should be_nil
+ expect(app.find_global_settings_argument("--ca-location")).to be_nil
end
end
describe "#parse_options" do
before :each do
app.command_line.stubs(:args).returns %w{}
end
describe "with just an action" do
before(:each) do
# We have to stub Signal.trap to avoid a crazy mess where we take
# over signal handling and make it impossible to cancel the test
# suite run.
#
# It would be nice to fix this elsewhere, but it is actually hard to
# capture this in rspec 2.5 and all. :( --daniel 2011-04-08
Signal.stubs(:trap)
app.command_line.stubs(:args).returns %w{foo}
app.preinit
app.parse_options
end
it "should set the face based on the type" do
- app.face.name.should == :basetest
+ expect(app.face.name).to eq(:basetest)
end
it "should find the action" do
- app.action.should be
- app.action.name.should == :foo
+ expect(app.action).to be
+ expect(app.action.name).to eq(:foo)
end
end
it "should stop if the first thing found is not an action" do
app.command_line.stubs(:args).returns %w{banana count_args}
expect { app.run }.to exit_with(1)
- @logs.map(&:message).should == ["'basetest' has no 'banana' action. See `puppet help basetest`."]
+ expect(@logs.map(&:message)).to eq(["'basetest' has no 'banana' action. See `puppet help basetest`."])
end
it "should use the default action if not given any arguments" do
app.command_line.stubs(:args).returns []
action = stub(:options => [], :render_as => nil)
Puppet::Face[:basetest, '0.0.1'].expects(:get_default_action).returns(action)
app.stubs(:main)
app.run
- app.action.should == action
- app.arguments.should == [ { } ]
+ expect(app.action).to eq(action)
+ expect(app.arguments).to eq([ { } ])
end
it "should use the default action if not given a valid one" do
app.command_line.stubs(:args).returns %w{bar}
action = stub(:options => [], :render_as => nil)
Puppet::Face[:basetest, '0.0.1'].expects(:get_default_action).returns(action)
app.stubs(:main)
app.run
- app.action.should == action
- app.arguments.should == [ 'bar', { } ]
+ expect(app.action).to eq(action)
+ expect(app.arguments).to eq([ 'bar', { } ])
end
it "should have no action if not given a valid one and there is no default action" do
app.command_line.stubs(:args).returns %w{bar}
Puppet::Face[:basetest, '0.0.1'].expects(:get_default_action).returns(nil)
app.stubs(:main)
expect { app.run }.to exit_with(1)
- @logs.first.message.should =~ /has no 'bar' action./
+ expect(@logs.first.message).to match(/has no 'bar' action./)
end
[%w{something_I_cannot_do},
%w{something_I_cannot_do argument}].each do |input|
it "should report unknown actions nicely" do
app.command_line.stubs(:args).returns input
Puppet::Face[:basetest, '0.0.1'].expects(:get_default_action).returns(nil)
app.stubs(:main)
expect { app.run }.to exit_with(1)
- @logs.first.message.should =~ /has no 'something_I_cannot_do' action/
+ expect(@logs.first.message).to match(/has no 'something_I_cannot_do' action/)
end
end
[%w{something_I_cannot_do --unknown-option},
%w{something_I_cannot_do argument --unknown-option}].each do |input|
it "should report unknown actions even if there are unknown options" do
app.command_line.stubs(:args).returns input
Puppet::Face[:basetest, '0.0.1'].expects(:get_default_action).returns(nil)
app.stubs(:main)
expect { app.run }.to exit_with(1)
- @logs.first.message.should =~ /has no 'something_I_cannot_do' action/
+ expect(@logs.first.message).to match(/has no 'something_I_cannot_do' action/)
end
end
it "should report a sensible error when options with = fail" do
app.command_line.stubs(:args).returns %w{--action=bar foo}
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --action/)
end
it "should fail if an action option is before the action" do
app.command_line.stubs(:args).returns %w{--action foo}
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --action/)
end
it "should fail if an unknown option is before the action" do
app.command_line.stubs(:args).returns %w{--bar foo}
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --bar/)
end
it "should fail if an unknown option is after the action" do
app.command_line.stubs(:args).returns %w{foo --bar}
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --bar/)
end
it "should accept --bar as an argument to a mandatory option after action" do
app.command_line.stubs(:args).returns %w{foo --mandatory --bar}
app.preinit
app.parse_options
- app.action.name.should == :foo
- app.options.should == { :mandatory => "--bar" }
+ expect(app.action.name).to eq(:foo)
+ expect(app.options).to eq({ :mandatory => "--bar" })
end
it "should accept --bar as an argument to a mandatory option before action" do
app.command_line.stubs(:args).returns %w{--mandatory --bar foo}
app.preinit
app.parse_options
- app.action.name.should == :foo
- app.options.should == { :mandatory => "--bar" }
+ expect(app.action.name).to eq(:foo)
+ expect(app.options).to eq({ :mandatory => "--bar" })
end
it "should not skip when --foo=bar is given" do
app.command_line.stubs(:args).returns %w{--mandatory=bar --bar foo}
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --bar/)
end
it "does not skip when a puppet global setting is given as one item" do
app.command_line.stubs(:args).returns %w{--confdir=/tmp/puppet foo}
app.preinit
app.parse_options
- app.action.name.should == :foo
- app.options.should == {}
+ expect(app.action.name).to eq(:foo)
+ expect(app.options).to eq({})
end
it "does not skip when a puppet global setting is given as two items" do
app.command_line.stubs(:args).returns %w{--confdir /tmp/puppet foo}
app.preinit
app.parse_options
- app.action.name.should == :foo
- app.options.should == {}
+ expect(app.action.name).to eq(:foo)
+ expect(app.options).to eq({})
end
it "should not add :debug to the application-level options" do
app.command_line.stubs(:args).returns %w{--confdir /tmp/puppet foo --debug}
app.preinit
app.parse_options
- app.action.name.should == :foo
- app.options.should == {}
+ expect(app.action.name).to eq(:foo)
+ expect(app.options).to eq({})
end
it "should not add :verbose to the application-level options" do
app.command_line.stubs(:args).returns %w{--confdir /tmp/puppet foo --verbose}
app.preinit
app.parse_options
- app.action.name.should == :foo
- app.options.should == {}
+ expect(app.action.name).to eq(:foo)
+ expect(app.options).to eq({})
end
{ "boolean options before" => %w{--trace foo},
"boolean options after" => %w{foo --trace}
}.each do |name, args|
it "should accept global boolean settings #{name} the action" do
app.command_line.stubs(:args).returns args
Puppet.settings.initialize_global_settings(args)
app.preinit
app.parse_options
- Puppet[:trace].should be_true
+ expect(Puppet[:trace]).to be_truthy
end
end
{ "before" => %w{--syslogfacility user1 foo},
" after" => %w{foo --syslogfacility user1}
}.each do |name, args|
it "should accept global settings with arguments #{name} the action" do
app.command_line.stubs(:args).returns args
Puppet.settings.initialize_global_settings(args)
app.preinit
app.parse_options
- Puppet[:syslogfacility].should == "user1"
+ expect(Puppet[:syslogfacility]).to eq("user1")
end
end
it "should handle application-level options" do
app.command_line.stubs(:args).returns %w{--verbose return_true}
app.preinit
app.parse_options
- app.face.name.should == :basetest
+ expect(app.face.name).to eq(:basetest)
end
end
describe "#setup" do
it "should remove the action name from the arguments" do
app.command_line.stubs(:args).returns %w{--mandatory --bar foo}
app.preinit
app.parse_options
app.setup
- app.arguments.should == [{ :mandatory => "--bar" }]
+ expect(app.arguments).to eq([{ :mandatory => "--bar" }])
end
it "should pass positional arguments" do
myargs = %w{--mandatory --bar foo bar baz quux}
app.command_line.stubs(:args).returns(myargs)
app.preinit
app.parse_options
app.setup
- app.arguments.should == ['bar', 'baz', 'quux', { :mandatory => "--bar" }]
+ expect(app.arguments).to eq(['bar', 'baz', 'quux', { :mandatory => "--bar" }])
end
end
describe "#main" do
before :each do
app.stubs(:puts) # don't dump text to screen.
app.face = Puppet::Face[:basetest, '0.0.1']
app.action = app.face.get_action(:foo)
app.arguments = ["myname", "myarg"]
end
it "should send the specified verb and name to the face" do
app.face.expects(:foo).with(*app.arguments)
expect { app.main }.to exit_with(0)
end
it "should lookup help when it cannot do anything else" do
app.action = nil
Puppet::Face[:help, :current].expects(:help).with(:basetest)
expect { app.main }.to exit_with(1)
end
it "should use its render method to render any result" do
app.expects(:render).with(app.arguments.length + 1, ["myname", "myarg"])
expect { app.main }.to exit_with(0)
end
end
describe "error reporting" do
before :each do
app.stubs(:puts) # don't dump text to screen.
app.render_as = :json
app.face = Puppet::Face[:basetest, '0.0.1']
app.arguments = [{}] # we always have options in there...
end
it "should exit 0 when the action returns true" do
app.action = app.face.get_action :return_true
expect { app.main }.to exit_with(0)
end
it "should exit 0 when the action returns false" do
app.action = app.face.get_action :return_false
expect { app.main }.to exit_with(0)
end
it "should exit 0 when the action returns nil" do
app.action = app.face.get_action :return_nil
expect { app.main }.to exit_with(0)
end
it "should exit non-0 when the action raises" do
app.action = app.face.get_action :return_raise
expect { app.main }.not_to exit_with(0)
end
it "should use the exit code set by the action" do
app.action = app.face.get_action :with_specific_exit_code
expect { app.main }.to exit_with(5)
end
end
describe "#render" do
before :each do
app.face = Puppet::Interface.new('basetest', '0.0.1')
app.action = Puppet::Interface::Action.new(app.face, :foo)
end
context "default rendering" do
before :each do app.setup end
["hello", 1, 1.0].each do |input|
it "should just return a #{input.class.name}" do
- app.render(input, {}).should == input
+ expect(app.render(input, {})).to eq(input)
end
end
[[1, 2], ["one"], [{ 1 => 1 }]].each do |input|
it "should render Array as one item per line" do
- app.render(input, {}).should == input.collect { |item| item.to_s + "\n" }.join('')
+ expect(app.render(input, {})).to eq(input.collect { |item| item.to_s + "\n" }.join(''))
end
end
it "should render a non-trivially-keyed Hash with using JSON" do
hash = { [1,2] => 3, [2,3] => 5, [3,4] => 7 }
- app.render(hash, {}).should == hash.to_pson.chomp
+ expect(app.render(hash, {})).to eq(hash.to_pson.chomp)
end
it "should render a {String,Numeric}-keyed Hash into a table" do
object = Object.new
hash = { "one" => 1, "two" => [], "three" => {}, "four" => object,
5 => 5, 6.0 => 6 }
# Gotta love ASCII-betical sort order. Hope your objects are better
# structured for display than my test one is. --daniel 2011-04-18
- app.render(hash, {}).should == <<EOT
+ expect(app.render(hash, {})).to eq <<EOT
5 5
6.0 6
four #{object.to_pson.chomp}
one 1
three {}
two []
EOT
end
it "should render a hash nicely with a multi-line value" do
pending "Moving to PSON rather than PP makes this unsupportable."
hash = {
"number" => { "1" => '1' * 40, "2" => '2' * 40, '3' => '3' * 40 },
"text" => { "a" => 'a' * 40, 'b' => 'b' * 40, 'c' => 'c' * 40 }
}
- app.render(hash, {}).should == <<EOT
+ expect(app.render(hash, {})).to eq <<EOT
number {"1"=>"1111111111111111111111111111111111111111",
"2"=>"2222222222222222222222222222222222222222",
"3"=>"3333333333333333333333333333333333333333"}
text {"a"=>"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"b"=>"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"c"=>"cccccccccccccccccccccccccccccccccccccccc"}
EOT
end
describe "when setting the rendering method" do
after do
# need to reset the when_rendering block so that other tests can set it later
app.action.instance_variable_set("@when_rendering", {})
end
it "should invoke the action rendering hook while rendering" do
app.action.set_rendering_method_for(:console, proc { |value| "bi-winning!" })
- app.render("bi-polar?", {}).should == "bi-winning!"
+ expect(app.render("bi-polar?", {})).to eq("bi-winning!")
end
it "should invoke the action rendering hook with args and options while rendering" do
app.action.instance_variable_set("@when_rendering", {})
app.action.when_invoked = proc { |name, options| 'just need to match arity for rendering' }
app.action.set_rendering_method_for(
:console,
proc { |value, name, options| "I'm #{name}, no wait, I'm #{options[:altername]}" }
)
- app.render("bi-polar?", ['bob', {:altername => 'sue'}]).should == "I'm bob, no wait, I'm sue"
+ expect(app.render("bi-polar?", ['bob', {:altername => 'sue'}])).to eq("I'm bob, no wait, I'm sue")
end
end
it "should render JSON when asked for json" do
app.render_as = :json
json = app.render({ :one => 1, :two => 2 }, {})
- json.should =~ /"one":\s*1\b/
- json.should =~ /"two":\s*2\b/
- PSON.parse(json).should == { "one" => 1, "two" => 2 }
+ expect(json).to match(/"one":\s*1\b/)
+ expect(json).to match(/"two":\s*2\b/)
+ expect(PSON.parse(json)).to eq({ "one" => 1, "two" => 2 })
end
end
it "should fail early if asked to render an invalid format" do
app.command_line.stubs(:args).returns %w{--render-as interpretive-dance return_true}
# We shouldn't get here, thanks to the exception, and our expectation on
# it, but this helps us fail if that slips up and all. --daniel 2011-04-27
Puppet::Face[:help, :current].expects(:help).never
Puppet.expects(:err).with("Could not parse application options: I don't know how to render 'interpretive-dance'")
expect { app.run }.to exit_with(1)
end
it "should work if asked to render a NetworkHandler format" do
app.command_line.stubs(:args).returns %w{count_args a b c --render-as pson}
expect {
expect { app.run }.to exit_with(0)
}.to have_printed(/3/)
end
it "should invoke when_rendering hook 's' when asked to render-as 's'" do
app.command_line.stubs(:args).returns %w{with_s_rendering_hook --render-as s}
app.action = app.face.get_action(:with_s_rendering_hook)
expect {
expect { app.run }.to exit_with(0)
}.to have_printed(/you invoked the 's' rendering hook/)
end
end
end
diff --git a/spec/unit/application/facts_spec.rb b/spec/unit/application/facts_spec.rb
index 4739389b0..ebe041f19 100755
--- a/spec/unit/application/facts_spec.rb
+++ b/spec/unit/application/facts_spec.rb
@@ -1,23 +1,23 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/application/facts'
describe Puppet::Application::Facts do
before :each do
subject.command_line.stubs(:subcommand_name).returns 'facts'
end
it "should return facts if a key is given to find" do
Puppet::Node::Facts.indirection.reset_terminus_class
Puppet::Node::Facts.indirection.expects(:find).returns(Puppet::Node::Facts.new('whatever', {}))
subject.command_line.stubs(:args).returns %w{find whatever --render-as yaml}
expect {
expect {
subject.run
}.to exit_with(0)
}.to have_printed(/object:Puppet::Node::Facts/)
- @logs.should be_empty
+ expect(@logs).to be_empty
end
end
diff --git a/spec/unit/application/filebucket_spec.rb b/spec/unit/application/filebucket_spec.rb
index 926ea9c1d..fb79f1dbe 100755
--- a/spec/unit/application/filebucket_spec.rb
+++ b/spec/unit/application/filebucket_spec.rb
@@ -1,207 +1,207 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/application/filebucket'
require 'puppet/file_bucket/dipper'
describe Puppet::Application::Filebucket do
before :each do
@filebucket = Puppet::Application[:filebucket]
end
it "should declare a get command" do
- @filebucket.should respond_to(:get)
+ expect(@filebucket).to respond_to(:get)
end
it "should declare a backup command" do
- @filebucket.should respond_to(:backup)
+ expect(@filebucket).to respond_to(:backup)
end
it "should declare a restore command" do
- @filebucket.should respond_to(:restore)
+ expect(@filebucket).to respond_to(:restore)
end
[:bucket, :debug, :local, :remote, :verbose].each do |option|
it "should declare handle_#{option} method" do
- @filebucket.should respond_to("handle_#{option}".to_sym)
+ expect(@filebucket).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
@filebucket.options.expects(:[]=).with("#{option}".to_sym, 'arg')
@filebucket.send("handle_#{option}".to_sym, 'arg')
end
end
describe "during setup" do
before :each do
Puppet::Log.stubs(:newdestination)
Puppet.stubs(:settraps)
Puppet::FileBucket::Dipper.stubs(:new)
@filebucket.options.stubs(:[]).with(any_parameters)
end
it "should set console as the log destination" do
Puppet::Log.expects(:newdestination).with(:console)
@filebucket.setup
end
it "should trap INT" do
Signal.expects(:trap).with(:INT)
@filebucket.setup
end
it "should set log level to debug if --debug was passed" do
@filebucket.options.stubs(:[]).with(:debug).returns(true)
@filebucket.setup
- Puppet::Log.level.should == :debug
+ expect(Puppet::Log.level).to eq(:debug)
end
it "should set log level to info if --verbose was passed" do
@filebucket.options.stubs(:[]).with(:verbose).returns(true)
@filebucket.setup
- Puppet::Log.level.should == :info
+ expect(Puppet::Log.level).to eq(:info)
end
it "should print puppet config if asked to in Puppet config" do
Puppet.settings.stubs(:print_configs?).returns(true)
Puppet.settings.expects(:print_configs).returns(true)
expect { @filebucket.setup }.to exit_with 0
end
it "should exit after printing puppet config if asked to in Puppet config" do
Puppet.settings.stubs(:print_configs?).returns(true)
expect { @filebucket.setup }.to exit_with 1
end
describe "with local bucket" do
let(:path) { File.expand_path("path") }
before :each do
@filebucket.options.stubs(:[]).with(:local).returns(true)
end
it "should create a client with the default bucket if none passed" do
Puppet[:bucketdir] = path
Puppet::FileBucket::Dipper.expects(:new).with { |h| h[:Path] == path }
@filebucket.setup
end
it "should create a local Dipper with the given bucket" do
@filebucket.options.stubs(:[]).with(:bucket).returns(path)
Puppet::FileBucket::Dipper.expects(:new).with { |h| h[:Path] == path }
@filebucket.setup
end
end
describe "with remote bucket" do
it "should create a remote Client to the configured server" do
Puppet[:server] = "puppet.reductivelabs.com"
Puppet::FileBucket::Dipper.expects(:new).with { |h| h[:Server] == "puppet.reductivelabs.com" }
@filebucket.setup
end
end
end
describe "when running" do
before :each do
Puppet::Log.stubs(:newdestination)
Puppet.stubs(:settraps)
Puppet::FileBucket::Dipper.stubs(:new)
@filebucket.options.stubs(:[]).with(any_parameters)
@client = stub 'client'
Puppet::FileBucket::Dipper.stubs(:new).returns(@client)
@filebucket.setup
end
it "should use the first non-option parameter as the dispatch" do
@filebucket.command_line.stubs(:args).returns(['get'])
@filebucket.expects(:get)
@filebucket.run_command
end
describe "the command get" do
before :each do
@filebucket.stubs(:print)
@filebucket.stubs(:args).returns([])
end
it "should call the client getfile method" do
@client.expects(:getfile)
@filebucket.get
end
it "should call the client getfile method with the given md5" do
md5="DEADBEEF"
@filebucket.stubs(:args).returns([md5])
@client.expects(:getfile).with(md5)
@filebucket.get
end
it "should print the file content" do
@client.stubs(:getfile).returns("content")
@filebucket.expects(:print).returns("content")
@filebucket.get
end
end
describe "the command backup" do
it "should fail if no arguments are specified" do
@filebucket.stubs(:args).returns([])
- lambda { @filebucket.backup }.should raise_error
+ expect { @filebucket.backup }.to raise_error
end
it "should call the client backup method for each given parameter" do
@filebucket.stubs(:puts)
Puppet::FileSystem.stubs(:exist?).returns(true)
FileTest.stubs(:readable?).returns(true)
@filebucket.stubs(:args).returns(["file1", "file2"])
@client.expects(:backup).with("file1")
@client.expects(:backup).with("file2")
@filebucket.backup
end
end
describe "the command restore" do
it "should call the client getfile method with the given md5" do
md5="DEADBEEF"
file="testfile"
@filebucket.stubs(:args).returns([file, md5])
@client.expects(:restore).with(file,md5)
@filebucket.restore
end
end
end
end
diff --git a/spec/unit/application/inspect_spec.rb b/spec/unit/application/inspect_spec.rb
index fa1f5dc58..dc8688423 100755
--- a/spec/unit/application/inspect_spec.rb
+++ b/spec/unit/application/inspect_spec.rb
@@ -1,287 +1,287 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/application/inspect'
require 'puppet/resource/catalog'
require 'puppet/indirector/catalog/yaml'
require 'puppet/indirector/report/rest'
require 'puppet/indirector/file_bucket_file/rest'
describe Puppet::Application::Inspect do
include PuppetSpec::Files
before :each do
@inspect = Puppet::Application[:inspect]
@inspect.preinit
end
it "should operate in agent run_mode" do
- @inspect.class.run_mode.name.should == :agent
+ expect(@inspect.class.run_mode.name).to eq(:agent)
end
describe "during setup" do
it "should print its configuration if asked" do
Puppet[:configprint] = "all"
Puppet.settings.expects(:print_configs).returns(true)
expect { @inspect.setup }.to exit_with 0
end
it "should fail if reporting is turned off" do
Puppet[:report] = false
- lambda { @inspect.setup }.should raise_error(/report=true/)
+ expect { @inspect.setup }.to raise_error(/report=true/)
end
end
describe "when executing", :uses_checksums => true do
before :each do
Puppet[:report] = true
@inspect.options[:setdest] = true
Puppet::Transaction::Report::Rest.any_instance.stubs(:save)
@inspect.setup
end
it "should retrieve the local catalog" do
Puppet::Resource::Catalog::Yaml.any_instance.expects(:find).with {|request| request.key == Puppet[:certname] }.returns(Puppet::Resource::Catalog.new)
@inspect.run_command
end
it "should save the report to REST" do
Puppet::Resource::Catalog::Yaml.any_instance.stubs(:find).returns(Puppet::Resource::Catalog.new)
Puppet::Transaction::Report::Rest.any_instance.expects(:save).with {|request| request.instance.host == Puppet[:certname] }
@inspect.run_command
end
with_digest_algorithms do
it "should audit the specified properties" do
catalog = Puppet::Resource::Catalog.new
file = Tempfile.new("foo")
file.binmode
file.print plaintext
file.close
resource = Puppet::Resource.new(:file, file.path, :parameters => {:audit => "all"})
catalog.add_resource(resource)
Puppet::Resource::Catalog::Yaml.any_instance.stubs(:find).returns(catalog)
events = nil
Puppet::Transaction::Report::Rest.any_instance.expects(:save).with do |request|
events = request.instance.resource_statuses.values.first.events
end
@inspect.run_command
properties = events.inject({}) do |property_values, event|
property_values.merge(event.property => event.previous_value)
end
- properties["ensure"].should == :file
- properties["content"].should == "{#{digest_algorithm}}#{checksum}"
- properties.has_key?("target").should == false
+ expect(properties["ensure"]).to eq(:file)
+ expect(properties["content"]).to eq("{#{digest_algorithm}}#{checksum}")
+ expect(properties.has_key?("target")).to eq(false)
end
end
it "should set audited to true for all events" do
catalog = Puppet::Resource::Catalog.new
file = Tempfile.new("foo")
resource = Puppet::Resource.new(:file, file.path, :parameters => {:audit => "all"})
catalog.add_resource(resource)
Puppet::Resource::Catalog::Yaml.any_instance.stubs(:find).returns(catalog)
events = nil
Puppet::Transaction::Report::Rest.any_instance.expects(:save).with do |request|
events = request.instance.resource_statuses.values.first.events
end
@inspect.run_command
events.each do |event|
- event.audited.should == true
+ expect(event.audited).to eq(true)
end
end
it "should not report irrelevent attributes if the resource is absent" do
catalog = Puppet::Resource::Catalog.new
file = Tempfile.new("foo")
resource = Puppet::Resource.new(:file, file.path, :parameters => {:audit => "all"})
file.close
file.delete
catalog.add_resource(resource)
Puppet::Resource::Catalog::Yaml.any_instance.stubs(:find).returns(catalog)
events = nil
Puppet::Transaction::Report::Rest.any_instance.expects(:save).with do |request|
events = request.instance.resource_statuses.values.first.events
end
@inspect.run_command
properties = events.inject({}) do |property_values, event|
property_values.merge(event.property => event.previous_value)
end
- properties.should == {"ensure" => :absent}
+ expect(properties).to eq({"ensure" => :absent})
end
describe "when archiving to a bucket" do
before :each do
Puppet[:archive_files] = true
Puppet[:archive_file_server] = "filebucketserver"
@catalog = Puppet::Resource::Catalog.new
Puppet::Resource::Catalog::Yaml.any_instance.stubs(:find).returns(@catalog)
end
describe "when auditing files" do
before :each do
@file = tmpfile("foo")
@resource = Puppet::Resource.new(:file, @file, :parameters => {:audit => "content"})
@catalog.add_resource(@resource)
end
it "should send an existing file to the file bucket" do
File.open(@file, 'w') { |f| f.write('stuff') }
Puppet::FileBucketFile::Rest.any_instance.expects(:head).with do |request|
request.server == Puppet[:archive_file_server]
end.returns(false)
Puppet::FileBucketFile::Rest.any_instance.expects(:save).with do |request|
request.server == Puppet[:archive_file_server] and request.instance.contents == 'stuff'
end
@inspect.run_command
end
it "should not send unreadable files", :unless => (Puppet.features.microsoft_windows? || Puppet.features.root?) do
File.open(@file, 'w') { |f| f.write('stuff') }
File.chmod(0, @file)
Puppet::FileBucketFile::Rest.any_instance.expects(:head).never
Puppet::FileBucketFile::Rest.any_instance.expects(:save).never
@inspect.run_command
end
it "should not try to send non-existent files" do
Puppet::FileBucketFile::Rest.any_instance.expects(:head).never
Puppet::FileBucketFile::Rest.any_instance.expects(:save).never
@inspect.run_command
end
it "should not try to send files whose content we are not auditing" do
@resource[:audit] = "group"
Puppet::FileBucketFile::Rest.any_instance.expects(:head).never
Puppet::FileBucketFile::Rest.any_instance.expects(:save).never
@inspect.run_command
end
it "should continue if bucketing a file fails" do
File.open(@file, 'w') { |f| f.write('stuff') }
Puppet::FileBucketFile::Rest.any_instance.stubs(:head).returns false
Puppet::FileBucketFile::Rest.any_instance.stubs(:save).raises "failure"
Puppet::Transaction::Report::Rest.any_instance.expects(:save).with do |request|
@report = request.instance
end
@inspect.run_command
- @report.logs.first.should_not == nil
- @report.logs.first.message.should =~ /Could not back up/
+ expect(@report.logs.first).not_to eq(nil)
+ expect(@report.logs.first.message).to match(/Could not back up/)
end
end
describe "when auditing non-files" do
before :each do
Puppet::Type.newtype(:stub_type) do
newparam(:name) do
desc "The name var"
isnamevar
end
newproperty(:content) do
desc "content"
def retrieve
:whatever
end
end
end
@resource = Puppet::Resource.new(:stub_type, 'foo', :parameters => {:audit => "all"})
@catalog.add_resource(@resource)
end
after :each do
Puppet::Type.rmtype(:stub_type)
end
it "should not try to send non-files" do
Puppet::FileBucketFile::Rest.any_instance.expects(:head).never
Puppet::FileBucketFile::Rest.any_instance.expects(:save).never
@inspect.run_command
end
end
end
describe "when there are failures" do
before :each do
Puppet::Type.newtype(:stub_type) do
newparam(:name) do
desc "The name var"
isnamevar
end
newproperty(:content) do
desc "content"
def retrieve
raise "failed"
end
end
end
@catalog = Puppet::Resource::Catalog.new
Puppet::Resource::Catalog::Yaml.any_instance.stubs(:find).returns(@catalog)
Puppet::Transaction::Report::Rest.any_instance.expects(:save).with do |request|
@report = request.instance
end
end
after :each do
Puppet::Type.rmtype(:stub_type)
end
it "should mark the report failed and create failed events for each property" do
@resource = Puppet::Resource.new(:stub_type, 'foo', :parameters => {:audit => "all"})
@catalog.add_resource(@resource)
@inspect.run_command
- @report.status.should == "failed"
- @report.logs.select{|log| log.message =~ /Could not inspect/}.size.should == 1
- @report.resource_statuses.size.should == 1
- @report.resource_statuses['Stub_type[foo]'].events.size.should == 1
+ expect(@report.status).to eq("failed")
+ expect(@report.logs.select{|log| log.message =~ /Could not inspect/}.size).to eq(1)
+ expect(@report.resource_statuses.size).to eq(1)
+ expect(@report.resource_statuses['Stub_type[foo]'].events.size).to eq(1)
event = @report.resource_statuses['Stub_type[foo]'].events.first
- event.property.should == "content"
- event.status.should == "failure"
- event.audited.should == true
- event.instance_variables.should_not include "@previous_value"
- event.instance_variables.should_not include :@previous_value
+ expect(event.property).to eq("content")
+ expect(event.status).to eq("failure")
+ expect(event.audited).to eq(true)
+ expect(event.instance_variables).not_to include "@previous_value"
+ expect(event.instance_variables).not_to include :@previous_value
end
it "should continue to the next resource" do
@resource = Puppet::Resource.new(:stub_type, 'foo', :parameters => {:audit => "all"})
@other_resource = Puppet::Resource.new(:stub_type, 'bar', :parameters => {:audit => "all"})
@catalog.add_resource(@resource)
@catalog.add_resource(@other_resource)
@inspect.run_command
- @report.resource_statuses.size.should == 2
- @report.resource_statuses.keys.should =~ ['Stub_type[foo]', 'Stub_type[bar]']
+ expect(@report.resource_statuses.size).to eq(2)
+ expect(@report.resource_statuses.keys).to match_array(['Stub_type[foo]', 'Stub_type[bar]'])
end
end
end
after :all do
Puppet::Resource::Catalog.indirection.reset_terminus_class
Puppet::Transaction::Report.indirection.terminus_class = :processor
end
end
diff --git a/spec/unit/application/master_spec.rb b/spec/unit/application/master_spec.rb
index 06ced966b..81973db82 100755
--- a/spec/unit/application/master_spec.rb
+++ b/spec/unit/application/master_spec.rb
@@ -1,362 +1,362 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/application/master'
require 'puppet/daemon'
require 'puppet/network/server'
describe Puppet::Application::Master, :unless => Puppet.features.microsoft_windows? do
before :each do
@master = Puppet::Application[:master]
@daemon = stub_everything 'daemon'
Puppet::Daemon.stubs(:new).returns(@daemon)
Puppet::Util::Log.stubs(:newdestination)
Puppet::Node.indirection.stubs(:terminus_class=)
Puppet::Node.indirection.stubs(:cache_class=)
Puppet::Node::Facts.indirection.stubs(:terminus_class=)
Puppet::Node::Facts.indirection.stubs(:cache_class=)
Puppet::Transaction::Report.indirection.stubs(:terminus_class=)
Puppet::Resource::Catalog.indirection.stubs(:terminus_class=)
Puppet::SSL::Host.stubs(:ca_location=)
end
it "should operate in master run_mode" do
- @master.class.run_mode.name.should equal(:master)
+ expect(@master.class.run_mode.name).to equal(:master)
end
it "should declare a main command" do
- @master.should respond_to(:main)
+ expect(@master).to respond_to(:main)
end
it "should declare a compile command" do
- @master.should respond_to(:compile)
+ expect(@master).to respond_to(:compile)
end
it "should declare a preinit block" do
- @master.should respond_to(:preinit)
+ expect(@master).to respond_to(:preinit)
end
describe "during preinit" do
before :each do
@master.stubs(:trap)
end
it "should catch INT" do
@master.stubs(:trap).with { |arg,block| arg == :INT }
@master.preinit
end
end
[:debug,:verbose].each do |option|
it "should declare handle_#{option} method" do
- @master.should respond_to("handle_#{option}".to_sym)
+ expect(@master).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
@master.options.expects(:[]=).with(option, 'arg')
@master.send("handle_#{option}".to_sym, 'arg')
end
end
describe "when applying options" do
before do
@master.command_line.stubs(:args).returns([])
end
it "should set the log destination with --logdest" do
Puppet::Log.expects(:newdestination).with("console")
@master.handle_logdest("console")
end
it "should put the setdest options to true" do
@master.options.expects(:[]=).with(:setdest,true)
@master.handle_logdest("console")
end
it "should parse the log destination from ARGV" do
@master.command_line.stubs(:args).returns(%w{--logdest /my/file})
Puppet::Util::Log.expects(:newdestination).with("/my/file")
@master.parse_options
end
it "should support dns alt names from ARGV" do
Puppet.settings.initialize_global_settings(["--dns_alt_names", "foo,bar,baz"])
@master.preinit
@master.parse_options
- Puppet[:dns_alt_names].should == "foo,bar,baz"
+ expect(Puppet[:dns_alt_names]).to eq("foo,bar,baz")
end
end
describe "during setup" do
before :each do
Puppet::Log.stubs(:newdestination)
Puppet.stubs(:settraps)
Puppet::SSL::CertificateAuthority.stubs(:instance)
Puppet::SSL::CertificateAuthority.stubs(:ca?)
Puppet.settings.stubs(:use)
@master.options.stubs(:[]).with(any_parameters)
end
it "should abort stating that the master is not supported on Windows" do
Puppet.features.stubs(:microsoft_windows?).returns(true)
expect { @master.setup }.to raise_error(Puppet::Error, /Puppet master is not supported on Microsoft Windows/)
end
describe "setting up logging" do
it "sets the log level" do
@master.expects(:set_log_level)
@master.setup
end
describe "when the log destination is not explicitly configured" do
before do
@master.options.stubs(:[]).with(:setdest).returns false
end
it "logs to the console when --compile is given" do
@master.options.stubs(:[]).with(:node).returns "default"
Puppet::Util::Log.expects(:newdestination).with(:console)
@master.setup
end
it "logs to the console when the master is not daemonized or run with rack" do
Puppet::Util::Log.expects(:newdestination).with(:console)
Puppet[:daemonize] = false
@master.options.stubs(:[]).with(:rack).returns(false)
@master.setup
end
it "logs to syslog when the master is daemonized" do
Puppet::Util::Log.expects(:newdestination).with(:console).never
Puppet::Util::Log.expects(:newdestination).with(:syslog)
Puppet[:daemonize] = true
@master.options.stubs(:[]).with(:rack).returns(false)
@master.setup
end
it "logs to syslog when the master is run with rack" do
Puppet::Util::Log.expects(:newdestination).with(:console).never
Puppet::Util::Log.expects(:newdestination).with(:syslog)
Puppet[:daemonize] = false
@master.options.stubs(:[]).with(:rack).returns(true)
@master.setup
end
end
end
it "should print puppet config if asked to in Puppet config" do
Puppet.settings.stubs(:print_configs?).returns(true)
Puppet.settings.expects(:print_configs).returns(true)
expect { @master.setup }.to exit_with 0
end
it "should exit after printing puppet config if asked to in Puppet config" do
Puppet.settings.stubs(:print_configs?).returns(true)
expect { @master.setup }.to exit_with 1
end
it "should tell Puppet.settings to use :main,:ssl,:master and :metrics category" do
Puppet.settings.expects(:use).with(:main,:master,:ssl,:metrics)
@master.setup
end
describe "with no ca" do
it "should set the ca_location to none" do
Puppet::SSL::Host.expects(:ca_location=).with(:none)
@master.setup
end
end
describe "with a ca configured" do
before :each do
Puppet::SSL::CertificateAuthority.stubs(:ca?).returns(true)
end
it "should set the ca_location to local" do
Puppet::SSL::Host.expects(:ca_location=).with(:local)
@master.setup
end
it "should tell Puppet.settings to use :ca category" do
Puppet.settings.expects(:use).with(:ca)
@master.setup
end
it "should instantiate the CertificateAuthority singleton" do
Puppet::SSL::CertificateAuthority.expects(:instance)
@master.setup
end
end
end
describe "when running" do
before do
@master.preinit
end
it "should dispatch to compile if called with --compile" do
@master.options[:node] = "foo"
@master.expects(:compile)
@master.run_command
end
it "should dispatch to main otherwise" do
@master.options[:node] = nil
@master.expects(:main)
@master.run_command
end
describe "the compile command" do
before do
Puppet[:manifest] = "site.pp"
Puppet.stubs(:err)
@master.stubs(:puts)
end
it "should compile a catalog for the specified node" do
@master.options[:node] = "foo"
Puppet::Resource::Catalog.indirection.expects(:find).with("foo").returns Puppet::Resource::Catalog.new
expect { @master.compile }.to exit_with 0
end
it "should convert the catalog to a pure-resource catalog and use 'PSON::pretty_generate' to pretty-print the catalog" do
catalog = Puppet::Resource::Catalog.new
PSON.stubs(:pretty_generate)
Puppet::Resource::Catalog.indirection.expects(:find).returns catalog
catalog.expects(:to_resource).returns("rescat")
@master.options[:node] = "foo"
PSON.expects(:pretty_generate).with('rescat', :allow_nan => true, :max_nesting => false)
expect { @master.compile }.to exit_with 0
end
it "should exit with error code 30 if no catalog can be found" do
@master.options[:node] = "foo"
Puppet::Resource::Catalog.indirection.expects(:find).returns nil
Puppet.expects(:log_exception)
expect { @master.compile }.to exit_with 30
end
it "should exit with error code 30 if there's a failure" do
@master.options[:node] = "foo"
Puppet::Resource::Catalog.indirection.expects(:find).raises ArgumentError
Puppet.expects(:log_exception)
expect { @master.compile }.to exit_with 30
end
end
describe "the main command" do
before :each do
@master.preinit
@server = stub_everything 'server'
Puppet::Network::Server.stubs(:new).returns(@server)
@app = stub_everything 'app'
Puppet::SSL::Host.stubs(:localhost)
Puppet::SSL::CertificateAuthority.stubs(:ca?)
Process.stubs(:uid).returns(1000)
Puppet.stubs(:service)
Puppet[:daemonize] = false
Puppet.stubs(:notice)
Puppet.stubs(:start)
Puppet::Util.stubs(:chuser)
end
it "should create a Server" do
Puppet::Network::Server.expects(:new)
@master.main
end
it "should give the server to the daemon" do
@daemon.expects(:server=).with(@server)
@master.main
end
it "should generate a SSL cert for localhost" do
Puppet::SSL::Host.expects(:localhost)
@master.main
end
it "should make sure to *only* hit the CA for data" do
Puppet::SSL::CertificateAuthority.stubs(:ca?).returns(true)
Puppet::SSL::Host.expects(:ca_location=).with(:only)
@master.main
end
it "should drop privileges if running as root" do
Puppet.features.stubs(:root?).returns true
Puppet::Util.expects(:chuser)
@master.main
end
it "should daemonize if needed" do
Puppet[:daemonize] = true
@daemon.expects(:daemonize)
@master.main
end
it "should start the service" do
@daemon.expects(:start)
@master.main
end
describe "with --rack", :if => Puppet.features.rack? do
before do
require 'puppet/network/http/rack'
Puppet::Network::HTTP::Rack.stubs(:new).returns(@app)
end
it "it should not start a daemon" do
@master.options.stubs(:[]).with(:rack).returns(:true)
@daemon.expects(:start).never
@master.main
end
it "it should return the app" do
@master.options.stubs(:[]).with(:rack).returns(:true)
app = @master.main
- app.should equal(@app)
+ expect(app).to equal(@app)
end
end
end
end
end
diff --git a/spec/unit/application/resource_spec.rb b/spec/unit/application/resource_spec.rb
index 7435b8bee..9ac053ca2 100755
--- a/spec/unit/application/resource_spec.rb
+++ b/spec/unit/application/resource_spec.rb
@@ -1,157 +1,157 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/application/resource'
describe Puppet::Application::Resource do
include PuppetSpec::Files
before :each do
@resource_app = Puppet::Application[:resource]
Puppet::Util::Log.stubs(:newdestination)
end
describe "in preinit" do
it "should init extra_params to empty array" do
@resource_app.preinit
- @resource_app.extra_params.should == []
+ expect(@resource_app.extra_params).to eq([])
end
end
describe "when handling options" do
[:debug, :verbose, :edit].each do |option|
it "should store argument value when calling handle_#{option}" do
@resource_app.options.expects(:[]=).with(option, 'arg')
@resource_app.send("handle_#{option}".to_sym, 'arg')
end
end
it "should load a display all types with types option" do
type1 = stub_everything 'type1', :name => :type1
type2 = stub_everything 'type2', :name => :type2
Puppet::Type.stubs(:loadall)
Puppet::Type.stubs(:eachtype).multiple_yields(type1,type2)
@resource_app.expects(:puts).with(['type1','type2'])
expect { @resource_app.handle_types(nil) }.to exit_with 0
end
it "should add param to extra_params list" do
@resource_app.extra_params = [ :param1 ]
@resource_app.handle_param("whatever")
- @resource_app.extra_params.should == [ :param1, :whatever ]
+ expect(@resource_app.extra_params).to eq([ :param1, :whatever ])
end
it "should get a parameter in the printed data if extra_params are passed" do
tty = stub("tty", :tty? => true )
path = tmpfile('testfile')
command_line = Puppet::Util::CommandLine.new("puppet", [ 'resource', 'file', path ], tty )
@resource_app.stubs(:command_line).returns command_line
# provider is a parameter that should always be available
@resource_app.extra_params = [ :provider ]
expect { @resource_app.main }.to have_printed /provider\s+=>/
end
end
describe "during setup" do
before :each do
Puppet::Log.stubs(:newdestination)
end
it "should set console as the log destination" do
Puppet::Log.expects(:newdestination).with(:console)
@resource_app.setup
end
it "should set log level to debug if --debug was passed" do
@resource_app.options.stubs(:[]).with(:debug).returns(true)
@resource_app.setup
- Puppet::Log.level.should == :debug
+ expect(Puppet::Log.level).to eq(:debug)
end
it "should set log level to info if --verbose was passed" do
@resource_app.options.stubs(:[]).with(:debug).returns(false)
@resource_app.options.stubs(:[]).with(:verbose).returns(true)
@resource_app.setup
- Puppet::Log.level.should == :info
+ expect(Puppet::Log.level).to eq(:info)
end
end
describe "when running" do
before :each do
@type = stub_everything 'type', :properties => []
@resource_app.command_line.stubs(:args).returns(['mytype'])
Puppet::Type.stubs(:type).returns(@type)
@res = stub_everything "resource"
@res.stubs(:prune_parameters).returns(@res)
@report = stub_everything "report"
@resource_app.stubs(:puts)
Puppet::Resource.indirection.stubs(:find ).never
Puppet::Resource.indirection.stubs(:search).never
Puppet::Resource.indirection.stubs(:save ).never
end
it "should raise an error if no type is given" do
@resource_app.command_line.stubs(:args).returns([])
- lambda { @resource_app.main }.should raise_error(RuntimeError, "You must specify the type to display")
+ expect { @resource_app.main }.to raise_error(RuntimeError, "You must specify the type to display")
end
it "should raise an error if the type is not found" do
Puppet::Type.stubs(:type).returns(nil)
- lambda { @resource_app.main }.should raise_error(RuntimeError, 'Could not find type mytype')
+ expect { @resource_app.main }.to raise_error(RuntimeError, 'Could not find type mytype')
end
it "should search for resources" do
Puppet::Resource.indirection.expects(:search).with('mytype/', {}).returns([])
@resource_app.main
end
it "should describe the given resource" do
@resource_app.command_line.stubs(:args).returns(['type','name'])
Puppet::Resource.indirection.expects(:find).with('type/name').returns(@res)
@resource_app.main
end
it "should add given parameters to the object" do
@resource_app.command_line.stubs(:args).returns(['type','name','param=temp'])
Puppet::Resource.indirection.expects(:save).with(@res, 'type/name').returns([@res, @report])
Puppet::Resource.expects(:new).with('type', 'name', :parameters => {'param' => 'temp'}).returns(@res)
@resource_app.main
end
end
describe "when handling file type" do
before :each do
Facter.stubs(:loadfacts)
@resource_app.preinit
end
it "should raise an exception if no file specified" do
@resource_app.command_line.stubs(:args).returns(['file'])
- lambda { @resource_app.main }.should raise_error(RuntimeError, /Listing all file instances is not supported/)
+ expect { @resource_app.main }.to raise_error(RuntimeError, /Listing all file instances is not supported/)
end
it "should output a file resource when given a file path" do
path = File.expand_path('/etc')
res = Puppet::Type.type(:file).new(:path => path).to_resource
Puppet::Resource.indirection.expects(:find).returns(res)
@resource_app.command_line.stubs(:args).returns(['file', path])
@resource_app.expects(:puts).with do |args|
- args.should =~ /file \{ '#{Regexp.escape(path)}'/m
+ expect(args).to match(/file \{ '#{Regexp.escape(path)}'/m)
end
@resource_app.main
end
end
end
diff --git a/spec/unit/application_spec.rb b/spec/unit/application_spec.rb
index 11f7440a6..01618547d 100755
--- a/spec/unit/application_spec.rb
+++ b/spec/unit/application_spec.rb
@@ -1,641 +1,641 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/application'
require 'puppet'
require 'getoptlong'
require 'timeout'
describe Puppet::Application do
before(:each) do
@app = Class.new(Puppet::Application).new
@appclass = @app.class
@app.stubs(:name).returns("test_app")
end
describe "application commandline" do
it "should not pick up changes to the array of arguments" do
args = %w{subcommand --arg}
command_line = Puppet::Util::CommandLine.new('puppet', args)
app = Puppet::Application.new(command_line)
args[0] = 'different_subcommand'
args[1] = '--other-arg'
- app.command_line.subcommand_name.should == 'subcommand'
- app.command_line.args.should == ['--arg']
+ expect(app.command_line.subcommand_name).to eq('subcommand')
+ expect(app.command_line.args).to eq(['--arg'])
end
end
describe "application defaults" do
it "should fail if required app default values are missing" do
@app.stubs(:app_defaults).returns({ :foo => 'bar' })
Puppet.expects(:err).with(regexp_matches(/missing required app default setting/))
expect {
@app.run
}.to exit_with(1)
end
end
describe "finding" do
before do
@klass = Puppet::Application
@klass.stubs(:puts)
end
it "should find classes in the namespace" do
- @klass.find("Agent").should == @klass::Agent
+ expect(@klass.find("Agent")).to eq(@klass::Agent)
end
it "should not find classes outside the namespace" do
expect { @klass.find("String") }.to raise_error(LoadError)
end
it "should error if it can't find a class" do
Puppet.expects(:err).with do |value|
value =~ /Unable to find application 'ThisShallNeverEverEverExist'/ and
value =~ /puppet\/application\/thisshallneverevereverexist/ and
value =~ /no such file to load|cannot load such file/
end
expect {
@klass.find("ThisShallNeverEverEverExist")
}.to raise_error(LoadError)
end
it "#12114: should prevent File namespace collisions" do
# have to require the file face once, then the second time around it would fail
- @klass.find("File").should == Puppet::Application::File
- @klass.find("File").should == Puppet::Application::File
+ expect(@klass.find("File")).to eq(Puppet::Application::File)
+ expect(@klass.find("File")).to eq(Puppet::Application::File)
end
end
describe "#available_application_names" do
it 'should be able to find available application names' do
apps = %w{describe filebucket kick queue resource agent cert apply doc master}
Puppet::Util::Autoload.expects(:files_to_load).returns(apps)
- Puppet::Application.available_application_names.should =~ apps
+ expect(Puppet::Application.available_application_names).to match_array(apps)
end
it 'should find applications from multiple paths' do
Puppet::Util::Autoload.expects(:files_to_load).with('puppet/application').returns(%w{ /a/foo.rb /b/bar.rb })
- Puppet::Application.available_application_names.should =~ %w{ foo bar }
+ expect(Puppet::Application.available_application_names).to match_array(%w{ foo bar })
end
it 'should return unique application names' do
Puppet::Util::Autoload.expects(:files_to_load).with('puppet/application').returns(%w{ /a/foo.rb /b/foo.rb })
- Puppet::Application.available_application_names.should == %w{ foo }
+ expect(Puppet::Application.available_application_names).to eq(%w{ foo })
end
end
describe ".run_mode" do
it "should default to user" do
- @appclass.run_mode.name.should == :user
+ expect(@appclass.run_mode.name).to eq(:user)
end
it "should set and get a value" do
@appclass.run_mode :agent
- @appclass.run_mode.name.should == :agent
+ expect(@appclass.run_mode.name).to eq(:agent)
end
end
# These tests may look a little weird and repetative in its current state;
# it used to illustrate several ways that the run_mode could be changed
# at run time; there are fewer ways now, but it would still be nice to
# get to a point where it was entirely impossible.
describe "when dealing with run_mode" do
class TestApp < Puppet::Application
run_mode :master
def run_command
# no-op
end
end
it "should sadly and frighteningly allow run_mode to change at runtime via #initialize_app_defaults" do
Puppet.features.stubs(:syslog?).returns(true)
app = TestApp.new
app.initialize_app_defaults
- Puppet.run_mode.should be_master
+ expect(Puppet.run_mode).to be_master
end
it "should sadly and frighteningly allow run_mode to change at runtime via #run" do
app = TestApp.new
app.run
- app.class.run_mode.name.should == :master
+ expect(app.class.run_mode.name).to eq(:master)
- Puppet.run_mode.should be_master
+ expect(Puppet.run_mode).to be_master
end
end
it "should explode when an invalid run mode is set at runtime, for great victory" do
expect {
class InvalidRunModeTestApp < Puppet::Application
run_mode :abracadabra
def run_command
# no-op
end
end
}.to raise_error
end
it "should have a run entry-point" do
- @app.should respond_to(:run)
+ expect(@app).to respond_to(:run)
end
it "should have a read accessor to options" do
- @app.should respond_to(:options)
+ expect(@app).to respond_to(:options)
end
it "should include a default setup method" do
- @app.should respond_to(:setup)
+ expect(@app).to respond_to(:setup)
end
it "should include a default preinit method" do
- @app.should respond_to(:preinit)
+ expect(@app).to respond_to(:preinit)
end
it "should include a default run_command method" do
- @app.should respond_to(:run_command)
+ expect(@app).to respond_to(:run_command)
end
it "should invoke main as the default" do
@app.expects( :main )
@app.run_command
end
describe 'when invoking clear!' do
before :each do
Puppet::Application.run_status = :stop_requested
Puppet::Application.clear!
end
it 'should have nil run_status' do
- Puppet::Application.run_status.should be_nil
+ expect(Puppet::Application.run_status).to be_nil
end
it 'should return false for restart_requested?' do
- Puppet::Application.restart_requested?.should be_false
+ expect(Puppet::Application.restart_requested?).to be_falsey
end
it 'should return false for stop_requested?' do
- Puppet::Application.stop_requested?.should be_false
+ expect(Puppet::Application.stop_requested?).to be_falsey
end
it 'should return false for interrupted?' do
- Puppet::Application.interrupted?.should be_false
+ expect(Puppet::Application.interrupted?).to be_falsey
end
it 'should return true for clear?' do
- Puppet::Application.clear?.should be_true
+ expect(Puppet::Application.clear?).to be_truthy
end
end
describe 'after invoking stop!' do
before :each do
Puppet::Application.run_status = nil
Puppet::Application.stop!
end
after :each do
Puppet::Application.run_status = nil
end
it 'should have run_status of :stop_requested' do
- Puppet::Application.run_status.should == :stop_requested
+ expect(Puppet::Application.run_status).to eq(:stop_requested)
end
it 'should return true for stop_requested?' do
- Puppet::Application.stop_requested?.should be_true
+ expect(Puppet::Application.stop_requested?).to be_truthy
end
it 'should return false for restart_requested?' do
- Puppet::Application.restart_requested?.should be_false
+ expect(Puppet::Application.restart_requested?).to be_falsey
end
it 'should return true for interrupted?' do
- Puppet::Application.interrupted?.should be_true
+ expect(Puppet::Application.interrupted?).to be_truthy
end
it 'should return false for clear?' do
- Puppet::Application.clear?.should be_false
+ expect(Puppet::Application.clear?).to be_falsey
end
end
describe 'when invoking restart!' do
before :each do
Puppet::Application.run_status = nil
Puppet::Application.restart!
end
after :each do
Puppet::Application.run_status = nil
end
it 'should have run_status of :restart_requested' do
- Puppet::Application.run_status.should == :restart_requested
+ expect(Puppet::Application.run_status).to eq(:restart_requested)
end
it 'should return true for restart_requested?' do
- Puppet::Application.restart_requested?.should be_true
+ expect(Puppet::Application.restart_requested?).to be_truthy
end
it 'should return false for stop_requested?' do
- Puppet::Application.stop_requested?.should be_false
+ expect(Puppet::Application.stop_requested?).to be_falsey
end
it 'should return true for interrupted?' do
- Puppet::Application.interrupted?.should be_true
+ expect(Puppet::Application.interrupted?).to be_truthy
end
it 'should return false for clear?' do
- Puppet::Application.clear?.should be_false
+ expect(Puppet::Application.clear?).to be_falsey
end
end
describe 'when performing a controlled_run' do
it 'should not execute block if not :clear?' do
Puppet::Application.run_status = :stop_requested
target = mock 'target'
target.expects(:some_method).never
Puppet::Application.controlled_run do
target.some_method
end
end
it 'should execute block if :clear?' do
Puppet::Application.run_status = nil
target = mock 'target'
target.expects(:some_method).once
Puppet::Application.controlled_run do
target.some_method
end
end
describe 'on POSIX systems', :if => Puppet.features.posix? do
it 'should signal process with HUP after block if restart requested during block execution' do
Timeout::timeout(3) do # if the signal doesn't fire, this causes failure.
has_run = false
old_handler = trap('HUP') { has_run = true }
begin
Puppet::Application.controlled_run do
Puppet::Application.run_status = :restart_requested
end
# Ruby 1.9 uses a separate OS level thread to run the signal
# handler, so we have to poll - ideally, in a way that will kick
# the OS into running other threads - for a while.
#
# You can't just use the Ruby Thread yield thing either, because
# that is just an OS hint, and Linux ... doesn't take that
# seriously. --daniel 2012-03-22
sleep 0.001 while not has_run
ensure
trap('HUP', old_handler)
end
end
end
end
after :each do
Puppet::Application.run_status = nil
end
end
describe "when parsing command-line options" do
before :each do
@app.command_line.stubs(:args).returns([])
Puppet.settings.stubs(:optparse_addargs).returns([])
end
it "should pass the banner to the option parser" do
option_parser = stub "option parser"
option_parser.stubs(:on)
option_parser.stubs(:parse!)
@app.class.instance_eval do
banner "banner"
end
OptionParser.expects(:new).with("banner").returns(option_parser)
@app.parse_options
end
it "should ask OptionParser to parse the command-line argument" do
@app.command_line.stubs(:args).returns(%w{ fake args })
OptionParser.any_instance.expects(:parse!).with(%w{ fake args })
@app.parse_options
end
describe "when using --help" do
it "should call exit" do
@app.stubs(:puts)
expect { @app.handle_help(nil) }.to exit_with 0
end
end
describe "when using --version" do
it "should declare a version option" do
- @app.should respond_to(:handle_version)
+ expect(@app).to respond_to(:handle_version)
end
it "should exit after printing the version" do
@app.stubs(:puts)
expect { @app.handle_version(nil) }.to exit_with 0
end
end
describe "when dealing with an argument not declared directly by the application" do
it "should pass it to handle_unknown if this method exists" do
Puppet.settings.stubs(:optparse_addargs).returns([["--not-handled", :REQUIRED]])
@app.expects(:handle_unknown).with("--not-handled", "value").returns(true)
@app.command_line.stubs(:args).returns(["--not-handled", "value"])
@app.parse_options
end
it "should transform boolean option to normal form for Puppet.settings" do
@app.expects(:handle_unknown).with("--option", true)
@app.send(:handlearg, "--[no-]option", true)
end
it "should transform boolean option to no- form for Puppet.settings" do
@app.expects(:handle_unknown).with("--no-option", false)
@app.send(:handlearg, "--[no-]option", false)
end
end
end
describe "when calling default setup" do
before :each do
@app.options.stubs(:[])
end
[ :debug, :verbose ].each do |level|
it "should honor option #{level}" do
@app.options.stubs(:[]).with(level).returns(true)
Puppet::Util::Log.stubs(:newdestination)
@app.setup
- Puppet::Util::Log.level.should == (level == :verbose ? :info : :debug)
+ expect(Puppet::Util::Log.level).to eq(level == :verbose ? :info : :debug)
end
end
it "should honor setdest option" do
@app.options.stubs(:[]).with(:setdest).returns(false)
Puppet::Util::Log.expects(:setup_default)
@app.setup
end
it "does not downgrade the loglevel when --verbose is specified" do
Puppet[:log_level] = :debug
@app.options.stubs(:[]).with(:verbose).returns(true)
@app.setup_logs
- Puppet::Util::Log.level.should == :debug
+ expect(Puppet::Util::Log.level).to eq(:debug)
end
it "allows the loglevel to be specified as an argument" do
@app.set_log_level(:debug => true)
- Puppet::Util::Log.level.should == :debug
+ expect(Puppet::Util::Log.level).to eq(:debug)
end
end
describe "when configuring routes" do
include PuppetSpec::Files
before :each do
Puppet::Node.indirection.reset_terminus_class
end
after :each do
Puppet::Node.indirection.reset_terminus_class
end
it "should use the routes specified for only the active application" do
Puppet[:route_file] = tmpfile('routes')
File.open(Puppet[:route_file], 'w') do |f|
f.print <<-ROUTES
test_app:
node:
terminus: exec
other_app:
node:
terminus: plain
catalog:
terminus: invalid
ROUTES
end
@app.configure_indirector_routes
- Puppet::Node.indirection.terminus_class.should == 'exec'
+ expect(Puppet::Node.indirection.terminus_class).to eq('exec')
end
it "should not fail if the route file doesn't exist" do
Puppet[:route_file] = "/dev/null/non-existent"
expect { @app.configure_indirector_routes }.to_not raise_error
end
it "should raise an error if the routes file is invalid" do
Puppet[:route_file] = tmpfile('routes')
File.open(Puppet[:route_file], 'w') do |f|
f.print <<-ROUTES
invalid : : yaml
ROUTES
end
expect { @app.configure_indirector_routes }.to raise_error
end
end
describe "when running" do
before :each do
@app.stubs(:preinit)
@app.stubs(:setup)
@app.stubs(:parse_options)
end
it "should call preinit" do
@app.stubs(:run_command)
@app.expects(:preinit)
@app.run
end
it "should call parse_options" do
@app.stubs(:run_command)
@app.expects(:parse_options)
@app.run
end
it "should call run_command" do
@app.expects(:run_command)
@app.run
end
it "should call run_command" do
@app.expects(:run_command)
@app.run
end
it "should call main as the default command" do
@app.expects(:main)
@app.run
end
it "should warn and exit if no command can be called" do
Puppet.expects(:err)
expect { @app.run }.to exit_with 1
end
it "should raise an error if dispatch returns no command" do
@app.stubs(:get_command).returns(nil)
Puppet.expects(:err)
expect { @app.run }.to exit_with 1
end
it "should raise an error if dispatch returns an invalid command" do
@app.stubs(:get_command).returns(:this_function_doesnt_exist)
Puppet.expects(:err)
expect { @app.run }.to exit_with 1
end
end
describe "when metaprogramming" do
describe "when calling option" do
it "should create a new method named after the option" do
@app.class.option("--test1","-t") do
end
- @app.should respond_to(:handle_test1)
+ expect(@app).to respond_to(:handle_test1)
end
it "should transpose in option name any '-' into '_'" do
@app.class.option("--test-dashes-again","-t") do
end
- @app.should respond_to(:handle_test_dashes_again)
+ expect(@app).to respond_to(:handle_test_dashes_again)
end
it "should create a new method called handle_test2 with option(\"--[no-]test2\")" do
@app.class.option("--[no-]test2","-t") do
end
- @app.should respond_to(:handle_test2)
+ expect(@app).to respond_to(:handle_test2)
end
describe "when a block is passed" do
it "should create a new method with it" do
@app.class.option("--[no-]test2","-t") do
raise "I can't believe it, it works!"
end
expect { @app.handle_test2 }.to raise_error
end
it "should declare the option to OptionParser" do
OptionParser.any_instance.stubs(:on)
OptionParser.any_instance.expects(:on).with { |*arg| arg[0] == "--[no-]test3" }
@app.class.option("--[no-]test3","-t") do
end
@app.parse_options
end
it "should pass a block that calls our defined method" do
OptionParser.any_instance.stubs(:on)
OptionParser.any_instance.stubs(:on).with('--test4','-t').yields(nil)
@app.expects(:send).with(:handle_test4, nil)
@app.class.option("--test4","-t") do
end
@app.parse_options
end
end
describe "when no block is given" do
it "should declare the option to OptionParser" do
OptionParser.any_instance.stubs(:on)
OptionParser.any_instance.expects(:on).with("--test4","-t")
@app.class.option("--test4","-t")
@app.parse_options
end
it "should give to OptionParser a block that adds the value to the options array" do
OptionParser.any_instance.stubs(:on)
OptionParser.any_instance.stubs(:on).with("--test4","-t").yields(nil)
@app.options.expects(:[]=).with(:test4,nil)
@app.class.option("--test4","-t")
@app.parse_options
end
end
end
end
describe "#handle_logdest_arg" do
let(:test_arg) { "arg_test_logdest" }
it "should log an exception that is raised" do
our_exception = Puppet::DevError.new("test exception")
Puppet::Util::Log.expects(:newdestination).with(test_arg).raises(our_exception)
Puppet.expects(:log_exception).with(our_exception)
@app.handle_logdest_arg(test_arg)
end
it "should set the new log destination" do
Puppet::Util::Log.expects(:newdestination).with(test_arg)
@app.handle_logdest_arg(test_arg)
end
it "should set the flag that a destination is set in the options hash" do
Puppet::Util::Log.stubs(:newdestination).with(test_arg)
@app.handle_logdest_arg(test_arg)
- @app.options[:setdest].should be_true
+ expect(@app.options[:setdest]).to be_truthy
end
end
end
diff --git a/spec/unit/configurer/downloader_spec.rb b/spec/unit/configurer/downloader_spec.rb
index 4aa74afaf..1f79ae74d 100755
--- a/spec/unit/configurer/downloader_spec.rb
+++ b/spec/unit/configurer/downloader_spec.rb
@@ -1,222 +1,222 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/configurer/downloader'
describe Puppet::Configurer::Downloader do
require 'puppet_spec/files'
include PuppetSpec::Files
let(:path) { Puppet[:plugindest] }
let(:source) { 'puppet://puppet/plugins' }
it "should require a name" do
- lambda { Puppet::Configurer::Downloader.new }.should raise_error(ArgumentError)
+ expect { Puppet::Configurer::Downloader.new }.to raise_error(ArgumentError)
end
it "should require a path and a source at initialization" do
- lambda { Puppet::Configurer::Downloader.new("name") }.should raise_error(ArgumentError)
+ expect { Puppet::Configurer::Downloader.new("name") }.to raise_error(ArgumentError)
end
it "should set the name, path and source appropriately" do
dler = Puppet::Configurer::Downloader.new("facts", "path", "source")
- dler.name.should == "facts"
- dler.path.should == "path"
- dler.source.should == "source"
+ expect(dler.name).to eq("facts")
+ expect(dler.path).to eq("path")
+ expect(dler.source).to eq("source")
end
def downloader(options = {})
options[:name] ||= "facts"
options[:path] ||= path
options[:source_permissions] ||= :ignore
Puppet::Configurer::Downloader.new(options[:name], options[:path], source, options[:ignore], options[:environment], options[:source_permissions])
end
def generate_file_resource(options = {})
dler = downloader(options)
dler.file
end
describe "when creating the file that does the downloading" do
it "should create a file instance with the right path and source" do
file = generate_file_resource(:path => path, :source => source)
expect(file[:path]).to eq(path)
expect(file[:source]).to eq([source])
end
it "should tag the file with the downloader name" do
name = "mydownloader"
file = generate_file_resource(:name => name)
expect(file[:tag]).to eq([name])
end
it "should always recurse" do
file = generate_file_resource
- expect(file[:recurse]).to be_true
+ expect(file[:recurse]).to be_truthy
end
it "should always purge" do
file = generate_file_resource
- expect(file[:purge]).to be_true
+ expect(file[:purge]).to be_truthy
end
it "should never be in noop" do
file = generate_file_resource
- expect(file[:noop]).to be_false
+ expect(file[:noop]).to be_falsey
end
it "should set source_permissions to ignore by default" do
file = generate_file_resource
expect(file[:source_permissions]).to eq(:ignore)
end
it "should allow source_permissions to be overridden" do
file = generate_file_resource(:source_permissions => :use)
expect(file[:source_permissions]).to eq(:use)
end
describe "on POSIX", :if => Puppet.features.posix? do
it "should always set the owner to the current UID" do
Process.expects(:uid).returns 51
file = generate_file_resource(:path => '/path')
expect(file[:owner]).to eq(51)
end
it "should always set the group to the current GID" do
Process.expects(:gid).returns 61
file = generate_file_resource(:path => '/path')
expect(file[:group]).to eq(61)
end
end
describe "on Windows", :if => Puppet.features.microsoft_windows? do
it "should omit the owner" do
file = generate_file_resource(:path => 'C:/path')
expect(file[:owner]).to be_nil
end
it "should omit the group" do
file = generate_file_resource(:path => 'C:/path')
expect(file[:group]).to be_nil
end
end
it "should always force the download" do
file = generate_file_resource
- expect(file[:force]).to be_true
+ expect(file[:force]).to be_truthy
end
it "should never back up when downloading" do
file = generate_file_resource
- expect(file[:backup]).to be_false
+ expect(file[:backup]).to be_falsey
end
it "should support providing an 'ignore' parameter" do
file = generate_file_resource(:ignore => '.svn')
expect(file[:ignore]).to eq(['.svn'])
end
it "should split the 'ignore' parameter on whitespace" do
file = generate_file_resource(:ignore => '.svn CVS')
expect(file[:ignore]).to eq(['.svn', 'CVS'])
end
end
describe "when creating the catalog to do the downloading" do
before do
@path = make_absolute("/download/path")
@dler = Puppet::Configurer::Downloader.new("foo", @path, make_absolute("source"))
end
it "should create a catalog and add the file to it" do
catalog = @dler.catalog
- catalog.resources.size.should == 1
- catalog.resources.first.class.should == Puppet::Type::File
- catalog.resources.first.name.should == @path
+ expect(catalog.resources.size).to eq(1)
+ expect(catalog.resources.first.class).to eq(Puppet::Type::File)
+ expect(catalog.resources.first.name).to eq(@path)
end
it "should specify that it is not managing a host catalog" do
- @dler.catalog.host_config.should == false
+ expect(@dler.catalog.host_config).to eq(false)
end
end
describe "when downloading" do
before do
@dl_name = tmpfile("downloadpath")
source_name = tmpfile("source")
File.open(source_name, 'w') {|f| f.write('hola mundo') }
env = Puppet::Node::Environment.remote('foo')
@dler = Puppet::Configurer::Downloader.new("foo", @dl_name, source_name, Puppet[:pluginsignore], env)
end
it "should not skip downloaded resources when filtering on tags" do
Puppet[:tags] = 'maytag'
@dler.evaluate
- Puppet::FileSystem.exist?(@dl_name).should be_true
+ expect(Puppet::FileSystem.exist?(@dl_name)).to be_truthy
end
it "should log that it is downloading" do
Puppet.expects(:info)
@dler.evaluate
end
it "should return all changed file paths" do
trans = mock 'transaction'
catalog = mock 'catalog'
@dler.expects(:catalog).returns(catalog)
catalog.expects(:apply).yields(trans)
resource = mock 'resource'
resource.expects(:[]).with(:path).returns "/changed/file"
trans.expects(:changed?).returns([resource])
- @dler.evaluate.should == %w{/changed/file}
+ expect(@dler.evaluate).to eq(%w{/changed/file})
end
it "should yield the resources if a block is given" do
trans = mock 'transaction'
catalog = mock 'catalog'
@dler.expects(:catalog).returns(catalog)
catalog.expects(:apply).yields(trans)
resource = mock 'resource'
resource.expects(:[]).with(:path).returns "/changed/file"
trans.expects(:changed?).returns([resource])
yielded = nil
@dler.evaluate { |r| yielded = r }
- yielded.should == resource
+ expect(yielded).to eq(resource)
end
it "should catch and log exceptions" do
Puppet.expects(:err)
# The downloader creates a new catalog for each apply, and really the only object
# that it is possible to stub for the purpose of generating a puppet error
Puppet::Resource::Catalog.any_instance.stubs(:apply).raises(Puppet::Error, "testing")
- lambda { @dler.evaluate }.should_not raise_error
+ expect { @dler.evaluate }.not_to raise_error
end
end
end
diff --git a/spec/unit/configurer/fact_handler_spec.rb b/spec/unit/configurer/fact_handler_spec.rb
index 8d933655a..a354aebf5 100755
--- a/spec/unit/configurer/fact_handler_spec.rb
+++ b/spec/unit/configurer/fact_handler_spec.rb
@@ -1,96 +1,96 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/configurer'
require 'puppet/configurer/fact_handler'
require 'matchers/json'
class FactHandlerTester
include Puppet::Configurer::FactHandler
attr_accessor :environment
def initialize(environment)
self.environment = environment
end
def reload_facter
# don't want to do this in tests
end
end
describe Puppet::Configurer::FactHandler do
include JSONMatchers
let(:facthandler) { FactHandlerTester.new('production') }
before :each do
Puppet::Node::Facts.indirection.terminus_class = :memory
end
describe "when finding facts" do
it "should use the node name value to retrieve the facts" do
foo_facts = Puppet::Node::Facts.new('foo')
bar_facts = Puppet::Node::Facts.new('bar')
Puppet::Node::Facts.indirection.save(foo_facts)
Puppet::Node::Facts.indirection.save(bar_facts)
Puppet[:certname] = 'foo'
Puppet[:node_name_value] = 'bar'
- facthandler.find_facts.should == bar_facts
+ expect(facthandler.find_facts).to eq(bar_facts)
end
it "should set the facts name based on the node_name_fact" do
facts = Puppet::Node::Facts.new(Puppet[:node_name_value], 'my_name_fact' => 'other_node_name')
Puppet::Node::Facts.indirection.save(facts)
Puppet[:node_name_fact] = 'my_name_fact'
- facthandler.find_facts.name.should == 'other_node_name'
+ expect(facthandler.find_facts.name).to eq('other_node_name')
end
it "should set the node_name_value based on the node_name_fact" do
facts = Puppet::Node::Facts.new(Puppet[:node_name_value], 'my_name_fact' => 'other_node_name')
Puppet::Node::Facts.indirection.save(facts)
Puppet[:node_name_fact] = 'my_name_fact'
facthandler.find_facts
- Puppet[:node_name_value].should == 'other_node_name'
+ expect(Puppet[:node_name_value]).to eq('other_node_name')
end
it "should fail if finding facts fails" do
Puppet::Node::Facts.indirection.expects(:find).raises RuntimeError
expect { facthandler.find_facts }.to raise_error(Puppet::Error, /Could not retrieve local facts/)
end
it "should only load fact plugins once" do
Puppet::Node::Facts.indirection.expects(:find).once
facthandler.find_facts
end
end
it "should serialize and CGI escape the fact values for uploading" do
facts = Puppet::Node::Facts.new(Puppet[:node_name_value], 'my_name_fact' => 'other_node_name')
Puppet::Node::Facts.indirection.save(facts)
text = CGI.escape(facthandler.find_facts.render(:pson))
- facthandler.facts_for_uploading.should == {:facts_format => :pson, :facts => text}
+ expect(facthandler.facts_for_uploading).to eq({:facts_format => :pson, :facts => text})
end
it "should properly accept facts containing a '+'" do
facts = Puppet::Node::Facts.new('foo', 'afact' => 'a+b')
Puppet::Node::Facts.indirection.save(facts)
text = CGI.escape(facthandler.find_facts.render(:pson))
- facthandler.facts_for_uploading.should == {:facts_format => :pson, :facts => text}
+ expect(facthandler.facts_for_uploading).to eq({:facts_format => :pson, :facts => text})
end
it "should generate valid facts data against the facts schema" do
facts = Puppet::Node::Facts.new(Puppet[:node_name_value], 'my_name_fact' => 'other_node_name')
Puppet::Node::Facts.indirection.save(facts)
expect(CGI.unescape(facthandler.facts_for_uploading[:facts])).to validate_against('api/schemas/facts.json')
end
end
diff --git a/spec/unit/configurer_spec.rb b/spec/unit/configurer_spec.rb
index fdcb6acb6..3adcdf23c 100755
--- a/spec/unit/configurer_spec.rb
+++ b/spec/unit/configurer_spec.rb
@@ -1,680 +1,680 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/configurer'
describe Puppet::Configurer do
before do
Puppet.settings.stubs(:use).returns(true)
@agent = Puppet::Configurer.new
@agent.stubs(:init_storage)
Puppet::Util::Storage.stubs(:store)
Puppet[:server] = "puppetmaster"
Puppet[:report] = true
end
it "should include the Fact Handler module" do
- Puppet::Configurer.ancestors.should be_include(Puppet::Configurer::FactHandler)
+ expect(Puppet::Configurer.ancestors).to be_include(Puppet::Configurer::FactHandler)
end
describe "when executing a pre-run hook" do
it "should do nothing if the hook is set to an empty string" do
Puppet.settings[:prerun_command] = ""
Puppet::Util.expects(:exec).never
@agent.execute_prerun_command
end
it "should execute any pre-run command provided via the 'prerun_command' setting" do
Puppet.settings[:prerun_command] = "/my/command"
Puppet::Util::Execution.expects(:execute).with(["/my/command"]).raises(Puppet::ExecutionFailure, "Failed")
@agent.execute_prerun_command
end
it "should fail if the command fails" do
Puppet.settings[:prerun_command] = "/my/command"
Puppet::Util::Execution.expects(:execute).with(["/my/command"]).raises(Puppet::ExecutionFailure, "Failed")
- @agent.execute_prerun_command.should be_false
+ expect(@agent.execute_prerun_command).to be_falsey
end
end
describe "when executing a post-run hook" do
it "should do nothing if the hook is set to an empty string" do
Puppet.settings[:postrun_command] = ""
Puppet::Util.expects(:exec).never
@agent.execute_postrun_command
end
it "should execute any post-run command provided via the 'postrun_command' setting" do
Puppet.settings[:postrun_command] = "/my/command"
Puppet::Util::Execution.expects(:execute).with(["/my/command"]).raises(Puppet::ExecutionFailure, "Failed")
@agent.execute_postrun_command
end
it "should fail if the command fails" do
Puppet.settings[:postrun_command] = "/my/command"
Puppet::Util::Execution.expects(:execute).with(["/my/command"]).raises(Puppet::ExecutionFailure, "Failed")
- @agent.execute_postrun_command.should be_false
+ expect(@agent.execute_postrun_command).to be_falsey
end
end
describe "when executing a catalog run" do
before do
Puppet.settings.stubs(:use).returns(true)
@agent.stubs(:download_plugins)
Puppet::Node::Facts.indirection.terminus_class = :memory
@facts = Puppet::Node::Facts.new(Puppet[:node_name_value])
Puppet::Node::Facts.indirection.save(@facts)
@catalog = Puppet::Resource::Catalog.new("tester", Puppet::Node::Environment.remote(Puppet[:environment].to_sym))
@catalog.stubs(:to_ral).returns(@catalog)
Puppet::Resource::Catalog.indirection.terminus_class = :rest
Puppet::Resource::Catalog.indirection.stubs(:find).returns(@catalog)
@agent.stubs(:send_report)
@agent.stubs(:save_last_run_summary)
Puppet::Util::Log.stubs(:close_all)
end
after :all do
Puppet::Node::Facts.indirection.reset_terminus_class
Puppet::Resource::Catalog.indirection.reset_terminus_class
end
it "should initialize storage" do
Puppet::Util::Storage.expects(:load)
@agent.run
end
it "downloads plugins when told" do
@agent.expects(:download_plugins)
@agent.run(:pluginsync => true)
end
it "does not download plugins when told" do
@agent.expects(:download_plugins).never
@agent.run(:pluginsync => false)
end
it "should carry on when it can't fetch its node definition" do
error = Net::HTTPError.new(400, 'dummy server communication error')
Puppet::Node.indirection.expects(:find).raises(error)
- @agent.run.should == 0
+ expect(@agent.run).to eq(0)
end
it "applies a cached catalog when it can't connect to the master" do
error = Errno::ECONNREFUSED.new('Connection refused - connect(2)')
Puppet::Node.indirection.expects(:find).raises(error)
Puppet::Resource::Catalog.indirection.expects(:find).with(anything, has_entry(:ignore_cache => true)).raises(error)
Puppet::Resource::Catalog.indirection.expects(:find).with(anything, has_entry(:ignore_terminus => true)).returns(@catalog)
- @agent.run.should == 0
+ expect(@agent.run).to eq(0)
end
it "should initialize a transaction report if one is not provided" do
report = Puppet::Transaction::Report.new("apply")
Puppet::Transaction::Report.expects(:new).returns report
@agent.run
end
it "should respect node_name_fact when setting the host on a report" do
Puppet[:node_name_fact] = 'my_name_fact'
@facts.values = {'my_name_fact' => 'node_name_from_fact'}
report = Puppet::Transaction::Report.new("apply")
@agent.run(:report => report)
- report.host.should == 'node_name_from_fact'
+ expect(report.host).to eq('node_name_from_fact')
end
it "should pass the new report to the catalog" do
report = Puppet::Transaction::Report.new("apply")
Puppet::Transaction::Report.stubs(:new).returns report
@catalog.expects(:apply).with{|options| options[:report] == report}
@agent.run
end
it "should use the provided report if it was passed one" do
report = Puppet::Transaction::Report.new("apply")
@catalog.expects(:apply).with {|options| options[:report] == report}
@agent.run(:report => report)
end
it "should set the report as a log destination" do
report = Puppet::Transaction::Report.new("apply")
report.expects(:<<).with(instance_of(Puppet::Util::Log)).at_least_once
@agent.run(:report => report)
end
it "should retrieve the catalog" do
@agent.expects(:retrieve_catalog)
@agent.run
end
it "should log a failure and do nothing if no catalog can be retrieved" do
@agent.expects(:retrieve_catalog).returns nil
Puppet.expects(:err).with "Could not retrieve catalog; skipping run"
@agent.run
end
it "should apply the catalog with all options to :run" do
@agent.expects(:retrieve_catalog).returns @catalog
@catalog.expects(:apply).with { |args| args[:one] == true }
@agent.run :one => true
end
it "should accept a catalog and use it instead of retrieving a different one" do
@agent.expects(:retrieve_catalog).never
@catalog.expects(:apply)
@agent.run :one => true, :catalog => @catalog
end
it "should benchmark how long it takes to apply the catalog" do
@agent.expects(:benchmark).with(:notice, instance_of(String))
@agent.expects(:retrieve_catalog).returns @catalog
@catalog.expects(:apply).never # because we're not yielding
@agent.run
end
it "should execute post-run hooks after the run" do
@agent.expects(:execute_postrun_command)
@agent.run
end
it "should send the report" do
report = Puppet::Transaction::Report.new("apply", nil, "test", "aaaa")
Puppet::Transaction::Report.expects(:new).returns(report)
@agent.expects(:send_report).with(report)
- report.environment.should == "test"
- report.transaction_uuid.should == "aaaa"
+ expect(report.environment).to eq("test")
+ expect(report.transaction_uuid).to eq("aaaa")
@agent.run
end
it "should send the transaction report even if the catalog could not be retrieved" do
@agent.expects(:retrieve_catalog).returns nil
report = Puppet::Transaction::Report.new("apply", nil, "test", "aaaa")
Puppet::Transaction::Report.expects(:new).returns(report)
@agent.expects(:send_report).with(report)
- report.environment.should == "test"
- report.transaction_uuid.should == "aaaa"
+ expect(report.environment).to eq("test")
+ expect(report.transaction_uuid).to eq("aaaa")
@agent.run
end
it "should send the transaction report even if there is a failure" do
@agent.expects(:retrieve_catalog).raises "whatever"
report = Puppet::Transaction::Report.new("apply", nil, "test", "aaaa")
Puppet::Transaction::Report.expects(:new).returns(report)
@agent.expects(:send_report).with(report)
- report.environment.should == "test"
- report.transaction_uuid.should == "aaaa"
+ expect(report.environment).to eq("test")
+ expect(report.transaction_uuid).to eq("aaaa")
- @agent.run.should be_nil
+ expect(@agent.run).to be_nil
end
it "should remove the report as a log destination when the run is finished" do
report = Puppet::Transaction::Report.new("apply")
Puppet::Transaction::Report.expects(:new).returns(report)
@agent.run
- Puppet::Util::Log.destinations.should_not include(report)
+ expect(Puppet::Util::Log.destinations).not_to include(report)
end
it "should return the report exit_status as the result of the run" do
report = Puppet::Transaction::Report.new("apply")
Puppet::Transaction::Report.expects(:new).returns(report)
report.expects(:exit_status).returns(1234)
- @agent.run.should == 1234
+ expect(@agent.run).to eq(1234)
end
it "should send the transaction report even if the pre-run command fails" do
report = Puppet::Transaction::Report.new("apply")
Puppet::Transaction::Report.expects(:new).returns(report)
Puppet.settings[:prerun_command] = "/my/command"
Puppet::Util::Execution.expects(:execute).with(["/my/command"]).raises(Puppet::ExecutionFailure, "Failed")
@agent.expects(:send_report).with(report)
- @agent.run.should be_nil
+ expect(@agent.run).to be_nil
end
it "should include the pre-run command failure in the report" do
report = Puppet::Transaction::Report.new("apply")
Puppet::Transaction::Report.expects(:new).returns(report)
Puppet.settings[:prerun_command] = "/my/command"
Puppet::Util::Execution.expects(:execute).with(["/my/command"]).raises(Puppet::ExecutionFailure, "Failed")
- @agent.run.should be_nil
- report.logs.find { |x| x.message =~ /Could not run command from prerun_command/ }.should be
+ expect(@agent.run).to be_nil
+ expect(report.logs.find { |x| x.message =~ /Could not run command from prerun_command/ }).to be
end
it "should send the transaction report even if the post-run command fails" do
report = Puppet::Transaction::Report.new("apply")
Puppet::Transaction::Report.expects(:new).returns(report)
Puppet.settings[:postrun_command] = "/my/command"
Puppet::Util::Execution.expects(:execute).with(["/my/command"]).raises(Puppet::ExecutionFailure, "Failed")
@agent.expects(:send_report).with(report)
- @agent.run.should be_nil
+ expect(@agent.run).to be_nil
end
it "should include the post-run command failure in the report" do
report = Puppet::Transaction::Report.new("apply")
Puppet::Transaction::Report.expects(:new).returns(report)
Puppet.settings[:postrun_command] = "/my/command"
Puppet::Util::Execution.expects(:execute).with(["/my/command"]).raises(Puppet::ExecutionFailure, "Failed")
report.expects(:<<).with { |log| log.message.include?("Could not run command from postrun_command") }
- @agent.run.should be_nil
+ expect(@agent.run).to be_nil
end
it "should execute post-run command even if the pre-run command fails" do
Puppet.settings[:prerun_command] = "/my/precommand"
Puppet.settings[:postrun_command] = "/my/postcommand"
Puppet::Util::Execution.expects(:execute).with(["/my/precommand"]).raises(Puppet::ExecutionFailure, "Failed")
Puppet::Util::Execution.expects(:execute).with(["/my/postcommand"])
- @agent.run.should be_nil
+ expect(@agent.run).to be_nil
end
it "should finalize the report" do
report = Puppet::Transaction::Report.new("apply")
Puppet::Transaction::Report.expects(:new).returns(report)
report.expects(:finalize_report)
@agent.run
end
it "should not apply the catalog if the pre-run command fails" do
report = Puppet::Transaction::Report.new("apply")
Puppet::Transaction::Report.expects(:new).returns(report)
Puppet.settings[:prerun_command] = "/my/command"
Puppet::Util::Execution.expects(:execute).with(["/my/command"]).raises(Puppet::ExecutionFailure, "Failed")
@catalog.expects(:apply).never()
@agent.expects(:send_report)
- @agent.run.should be_nil
+ expect(@agent.run).to be_nil
end
it "should apply the catalog, send the report, and return nil if the post-run command fails" do
report = Puppet::Transaction::Report.new("apply")
Puppet::Transaction::Report.expects(:new).returns(report)
Puppet.settings[:postrun_command] = "/my/command"
Puppet::Util::Execution.expects(:execute).with(["/my/command"]).raises(Puppet::ExecutionFailure, "Failed")
@catalog.expects(:apply)
@agent.expects(:send_report)
- @agent.run.should be_nil
+ expect(@agent.run).to be_nil
end
it "should refetch the catalog if the server specifies a new environment in the catalog" do
catalog = Puppet::Resource::Catalog.new("tester", Puppet::Node::Environment.remote('second_env'))
@agent.expects(:retrieve_catalog).returns(catalog).twice
@agent.run
end
it "should change the environment setting if the server specifies a new environment in the catalog" do
@catalog.stubs(:environment).returns("second_env")
@agent.run
- @agent.environment.should == "second_env"
+ expect(@agent.environment).to eq("second_env")
end
it "should fix the report if the server specifies a new environment in the catalog" do
report = Puppet::Transaction::Report.new("apply", nil, "test", "aaaa")
Puppet::Transaction::Report.expects(:new).returns(report)
@agent.expects(:send_report).with(report)
@catalog.stubs(:environment).returns("second_env")
@agent.stubs(:retrieve_catalog).returns(@catalog)
@agent.run
- report.environment.should == "second_env"
+ expect(report.environment).to eq("second_env")
end
it "should clear the global caches" do
$env_module_directories = false
@agent.run
- $env_module_directories.should == nil
+ expect($env_module_directories).to eq(nil)
end
describe "when not using a REST terminus for catalogs" do
it "should not pass any facts when retrieving the catalog" do
Puppet::Resource::Catalog.indirection.terminus_class = :compiler
@agent.expects(:facts_for_uploading).never
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options|
options[:facts].nil?
}.returns @catalog
@agent.run
end
end
describe "when using a REST terminus for catalogs" do
it "should pass the prepared facts and the facts format as arguments when retrieving the catalog" do
Puppet::Resource::Catalog.indirection.terminus_class = :rest
@agent.expects(:facts_for_uploading).returns(:facts => "myfacts", :facts_format => :foo)
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options|
options[:facts] == "myfacts" and options[:facts_format] == :foo
}.returns @catalog
@agent.run
end
end
end
describe "when sending a report" do
include PuppetSpec::Files
before do
Puppet.settings.stubs(:use).returns(true)
@configurer = Puppet::Configurer.new
Puppet[:lastrunfile] = tmpfile('last_run_file')
@report = Puppet::Transaction::Report.new("apply")
Puppet[:reports] = "none"
end
it "should print a report summary if configured to do so" do
Puppet.settings[:summarize] = true
@report.expects(:summary).returns "stuff"
@configurer.expects(:puts).with("stuff")
@configurer.send_report(@report)
end
it "should not print a report summary if not configured to do so" do
Puppet.settings[:summarize] = false
@configurer.expects(:puts).never
@configurer.send_report(@report)
end
it "should save the report if reporting is enabled" do
Puppet.settings[:report] = true
Puppet::Transaction::Report.indirection.expects(:save).with(@report, nil, instance_of(Hash))
@configurer.send_report(@report)
end
it "should not save the report if reporting is disabled" do
Puppet.settings[:report] = false
Puppet::Transaction::Report.indirection.expects(:save).with(@report, nil, instance_of(Hash)).never
@configurer.send_report(@report)
end
it "should save the last run summary if reporting is enabled" do
Puppet.settings[:report] = true
@configurer.expects(:save_last_run_summary).with(@report)
@configurer.send_report(@report)
end
it "should save the last run summary if reporting is disabled" do
Puppet.settings[:report] = false
@configurer.expects(:save_last_run_summary).with(@report)
@configurer.send_report(@report)
end
it "should log but not fail if saving the report fails" do
Puppet.settings[:report] = true
Puppet::Transaction::Report.indirection.expects(:save).raises("whatever")
Puppet.expects(:err)
- lambda { @configurer.send_report(@report) }.should_not raise_error
+ expect { @configurer.send_report(@report) }.not_to raise_error
end
end
describe "when saving the summary report file" do
include PuppetSpec::Files
before do
Puppet.settings.stubs(:use).returns(true)
@configurer = Puppet::Configurer.new
@report = stub 'report', :raw_summary => {}
Puppet[:lastrunfile] = tmpfile('last_run_file')
end
it "should write the last run file" do
@configurer.save_last_run_summary(@report)
- Puppet::FileSystem.exist?(Puppet[:lastrunfile]).should be_true
+ expect(Puppet::FileSystem.exist?(Puppet[:lastrunfile])).to be_truthy
end
it "should write the raw summary as yaml" do
@report.expects(:raw_summary).returns("summary")
@configurer.save_last_run_summary(@report)
- File.read(Puppet[:lastrunfile]).should == YAML.dump("summary")
+ expect(File.read(Puppet[:lastrunfile])).to eq(YAML.dump("summary"))
end
it "should log but not fail if saving the last run summary fails" do
# The mock will raise an exception on any method used. This should
# simulate a nice hard failure from the underlying OS for us.
fh = Class.new(Object) do
def method_missing(*args)
raise "failed to do #{args[0]}"
end
end.new
Puppet::Util.expects(:replace_file).yields(fh)
Puppet.expects(:err)
expect { @configurer.save_last_run_summary(@report) }.to_not raise_error
end
it "should create the last run file with the correct mode" do
Puppet.settings.setting(:lastrunfile).expects(:mode).returns('664')
@configurer.save_last_run_summary(@report)
if Puppet::Util::Platform.windows?
require 'puppet/util/windows/security'
mode = Puppet::Util::Windows::Security.get_mode(Puppet[:lastrunfile])
else
mode = Puppet::FileSystem.stat(Puppet[:lastrunfile]).mode
end
- (mode & 0777).should == 0664
+ expect(mode & 0777).to eq(0664)
end
it "should report invalid last run file permissions" do
Puppet.settings.setting(:lastrunfile).expects(:mode).returns('892')
Puppet.expects(:err).with(regexp_matches(/Could not save last run local report.*892 is invalid/))
@configurer.save_last_run_summary(@report)
end
end
describe "when requesting a node" do
it "uses the transaction uuid in the request" do
Puppet::Node.indirection.expects(:find).with(anything, has_entries(:transaction_uuid => anything)).twice
@agent.run
end
end
describe "when retrieving a catalog" do
before do
Puppet.settings.stubs(:use).returns(true)
@agent.stubs(:facts_for_uploading).returns({})
@catalog = Puppet::Resource::Catalog.new
# this is the default when using a Configurer instance
Puppet::Resource::Catalog.indirection.stubs(:terminus_class).returns :rest
@agent.stubs(:convert_catalog).returns @catalog
end
describe "and configured to only retrieve a catalog from the cache" do
before do
Puppet.settings[:use_cached_catalog] = true
end
it "should first look in the cache for a catalog" do
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| options[:ignore_terminus] == true }.returns @catalog
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| options[:ignore_cache] == true }.never
- @agent.retrieve_catalog({}).should == @catalog
+ expect(@agent.retrieve_catalog({})).to eq(@catalog)
end
it "should compile a new catalog if none is found in the cache" do
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| options[:ignore_terminus] == true }.returns nil
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| options[:ignore_cache] == true }.returns @catalog
- @agent.retrieve_catalog({}).should == @catalog
+ expect(@agent.retrieve_catalog({})).to eq(@catalog)
end
end
it "should use the Catalog class to get its catalog" do
Puppet::Resource::Catalog.indirection.expects(:find).returns @catalog
@agent.retrieve_catalog({})
end
it "should use its node_name_value to retrieve the catalog" do
Facter.stubs(:value).returns "eh"
Puppet.settings[:node_name_value] = "myhost.domain.com"
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| name == "myhost.domain.com" }.returns @catalog
@agent.retrieve_catalog({})
end
it "should default to returning a catalog retrieved directly from the server, skipping the cache" do
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| options[:ignore_cache] == true }.returns @catalog
- @agent.retrieve_catalog({}).should == @catalog
+ expect(@agent.retrieve_catalog({})).to eq(@catalog)
end
it "should log and return the cached catalog when no catalog can be retrieved from the server" do
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| options[:ignore_cache] == true }.returns nil
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| options[:ignore_terminus] == true }.returns @catalog
Puppet.expects(:notice)
- @agent.retrieve_catalog({}).should == @catalog
+ expect(@agent.retrieve_catalog({})).to eq(@catalog)
end
it "should not look in the cache for a catalog if one is returned from the server" do
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| options[:ignore_cache] == true }.returns @catalog
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| options[:ignore_terminus] == true }.never
- @agent.retrieve_catalog({}).should == @catalog
+ expect(@agent.retrieve_catalog({})).to eq(@catalog)
end
it "should return the cached catalog when retrieving the remote catalog throws an exception" do
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| options[:ignore_cache] == true }.raises "eh"
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| options[:ignore_terminus] == true }.returns @catalog
- @agent.retrieve_catalog({}).should == @catalog
+ expect(@agent.retrieve_catalog({})).to eq(@catalog)
end
it "should log and return nil if no catalog can be retrieved from the server and :usecacheonfailure is disabled" do
Puppet[:usecacheonfailure] = false
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| options[:ignore_cache] == true }.returns nil
Puppet.expects(:warning)
- @agent.retrieve_catalog({}).should be_nil
+ expect(@agent.retrieve_catalog({})).to be_nil
end
it "should return nil if no cached catalog is available and no catalog can be retrieved from the server" do
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| options[:ignore_cache] == true }.returns nil
Puppet::Resource::Catalog.indirection.expects(:find).with { |name, options| options[:ignore_terminus] == true }.returns nil
- @agent.retrieve_catalog({}).should be_nil
+ expect(@agent.retrieve_catalog({})).to be_nil
end
it "should convert the catalog before returning" do
Puppet::Resource::Catalog.indirection.stubs(:find).returns @catalog
@agent.expects(:convert_catalog).with { |cat, dur| cat == @catalog }.returns "converted catalog"
- @agent.retrieve_catalog({}).should == "converted catalog"
+ expect(@agent.retrieve_catalog({})).to eq("converted catalog")
end
it "should return nil if there is an error while retrieving the catalog" do
Puppet::Resource::Catalog.indirection.expects(:find).at_least_once.raises "eh"
- @agent.retrieve_catalog({}).should be_nil
+ expect(@agent.retrieve_catalog({})).to be_nil
end
end
describe "when converting the catalog" do
before do
Puppet.settings.stubs(:use).returns(true)
@catalog = Puppet::Resource::Catalog.new
@oldcatalog = stub 'old_catalog', :to_ral => @catalog
end
it "should convert the catalog to a RAL-formed catalog" do
@oldcatalog.expects(:to_ral).returns @catalog
- @agent.convert_catalog(@oldcatalog, 10).should equal(@catalog)
+ expect(@agent.convert_catalog(@oldcatalog, 10)).to equal(@catalog)
end
it "should finalize the catalog" do
@catalog.expects(:finalize)
@agent.convert_catalog(@oldcatalog, 10)
end
it "should record the passed retrieval time with the RAL catalog" do
@catalog.expects(:retrieval_duration=).with 10
@agent.convert_catalog(@oldcatalog, 10)
end
it "should write the RAL catalog's class file" do
@catalog.expects(:write_class_file)
@agent.convert_catalog(@oldcatalog, 10)
end
it "should write the RAL catalog's resource file" do
@catalog.expects(:write_resource_file)
@agent.convert_catalog(@oldcatalog, 10)
end
end
end
diff --git a/spec/unit/confine/exists_spec.rb b/spec/unit/confine/exists_spec.rb
index a2a575bd2..a4f24e024 100755
--- a/spec/unit/confine/exists_spec.rb
+++ b/spec/unit/confine/exists_spec.rb
@@ -1,80 +1,80 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/confine/exists'
describe Puppet::Confine::Exists do
before do
@confine = Puppet::Confine::Exists.new("/my/file")
@confine.label = "eh"
end
it "should be named :exists" do
- Puppet::Confine::Exists.name.should == :exists
+ expect(Puppet::Confine::Exists.name).to eq(:exists)
end
it "should not pass if exists is nil" do
confine = Puppet::Confine::Exists.new(nil)
confine.label = ":exists => nil"
confine.expects(:pass?).with(nil)
- confine.should_not be_valid
+ expect(confine).not_to be_valid
end
it "should use the 'pass?' method to test validity" do
@confine.expects(:pass?).with("/my/file")
@confine.valid?
end
it "should return false if the value is false" do
- @confine.pass?(false).should be_false
+ expect(@confine.pass?(false)).to be_falsey
end
it "should return false if the value does not point to a file" do
Puppet::FileSystem.expects(:exist?).with("/my/file").returns false
- @confine.pass?("/my/file").should be_false
+ expect(@confine.pass?("/my/file")).to be_falsey
end
it "should return true if the value points to a file" do
Puppet::FileSystem.expects(:exist?).with("/my/file").returns true
- @confine.pass?("/my/file").should be_true
+ expect(@confine.pass?("/my/file")).to be_truthy
end
it "should produce a message saying that a file is missing" do
- @confine.message("/my/file").should be_include("does not exist")
+ expect(@confine.message("/my/file")).to be_include("does not exist")
end
describe "and the confine is for binaries" do
before { @confine.stubs(:for_binary).returns true }
it "should use its 'which' method to look up the full path of the file" do
@confine.expects(:which).returns nil
@confine.pass?("/my/file")
end
it "should return false if no executable can be found" do
@confine.expects(:which).with("/my/file").returns nil
- @confine.pass?("/my/file").should be_false
+ expect(@confine.pass?("/my/file")).to be_falsey
end
it "should return true if the executable can be found" do
@confine.expects(:which).with("/my/file").returns "/my/file"
- @confine.pass?("/my/file").should be_true
+ expect(@confine.pass?("/my/file")).to be_truthy
end
end
it "should produce a summary containing all missing files" do
Puppet::FileSystem.stubs(:exist?).returns true
Puppet::FileSystem.expects(:exist?).with("/two").returns false
Puppet::FileSystem.expects(:exist?).with("/four").returns false
confine = Puppet::Confine::Exists.new %w{/one /two /three /four}
- confine.summary.should == %w{/two /four}
+ expect(confine.summary).to eq(%w{/two /four})
end
it "should summarize multiple instances by returning a flattened array of their summaries" do
c1 = mock '1', :summary => %w{one}
c2 = mock '2', :summary => %w{two}
c3 = mock '3', :summary => %w{three}
- Puppet::Confine::Exists.summarize([c1, c2, c3]).should == %w{one two three}
+ expect(Puppet::Confine::Exists.summarize([c1, c2, c3])).to eq(%w{one two three})
end
end
diff --git a/spec/unit/confine/false_spec.rb b/spec/unit/confine/false_spec.rb
index 44ecd40ed..dd55fa2ef 100755
--- a/spec/unit/confine/false_spec.rb
+++ b/spec/unit/confine/false_spec.rb
@@ -1,52 +1,52 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/confine/false'
describe Puppet::Confine::False do
it "should be named :false" do
- Puppet::Confine::False.name.should == :false
+ expect(Puppet::Confine::False.name).to eq(:false)
end
it "should require a value" do
- lambda { Puppet::Confine.new }.should raise_error(ArgumentError)
+ expect { Puppet::Confine.new }.to raise_error(ArgumentError)
end
describe "when testing values" do
before { @confine = Puppet::Confine::False.new("foo") }
it "should use the 'pass?' method to test validity" do
@confine = Puppet::Confine::False.new("foo")
@confine.label = "eh"
@confine.expects(:pass?).with("foo")
@confine.valid?
end
it "should return true if the value is false" do
- @confine.pass?(false).should be_true
+ expect(@confine.pass?(false)).to be_truthy
end
it "should return false if the value is not false" do
- @confine.pass?("else").should be_false
+ expect(@confine.pass?("else")).to be_falsey
end
it "should produce a message that a value is true" do
@confine = Puppet::Confine::False.new("foo")
- @confine.message("eh").should be_include("true")
+ expect(@confine.message("eh")).to be_include("true")
end
end
it "should be able to produce a summary with the number of incorrectly true values" do
confine = Puppet::Confine::False.new %w{one two three four}
confine.expects(:pass?).times(4).returns(true).returns(false).returns(true).returns(false)
- confine.summary.should == 2
+ expect(confine.summary).to eq(2)
end
it "should summarize multiple instances by summing their summaries" do
c1 = mock '1', :summary => 1
c2 = mock '2', :summary => 2
c3 = mock '3', :summary => 3
- Puppet::Confine::False.summarize([c1, c2, c3]).should == 6
+ expect(Puppet::Confine::False.summarize([c1, c2, c3])).to eq(6)
end
end
diff --git a/spec/unit/confine/feature_spec.rb b/spec/unit/confine/feature_spec.rb
index dad9d9b8b..640c810f5 100755
--- a/spec/unit/confine/feature_spec.rb
+++ b/spec/unit/confine/feature_spec.rb
@@ -1,57 +1,57 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/confine/feature'
describe Puppet::Confine::Feature do
it "should be named :feature" do
- Puppet::Confine::Feature.name.should == :feature
+ expect(Puppet::Confine::Feature.name).to eq(:feature)
end
it "should require a value" do
- lambda { Puppet::Confine::Feature.new }.should raise_error(ArgumentError)
+ expect { Puppet::Confine::Feature.new }.to raise_error(ArgumentError)
end
it "should always convert values to an array" do
- Puppet::Confine::Feature.new("/some/file").values.should be_instance_of(Array)
+ expect(Puppet::Confine::Feature.new("/some/file").values).to be_instance_of(Array)
end
describe "when testing values" do
before do
@confine = Puppet::Confine::Feature.new("myfeature")
@confine.label = "eh"
end
it "should use the Puppet features instance to test validity" do
Puppet.features.expects(:myfeature?)
@confine.valid?
end
it "should return true if the feature is present" do
Puppet.features.add(:myfeature) do true end
- @confine.pass?("myfeature").should be_true
+ expect(@confine.pass?("myfeature")).to be_truthy
end
it "should return false if the value is false" do
Puppet.features.add(:myfeature) do false end
- @confine.pass?("myfeature").should be_false
+ expect(@confine.pass?("myfeature")).to be_falsey
end
it "should log that a feature is missing" do
- @confine.message("myfeat").should be_include("missing")
+ expect(@confine.message("myfeat")).to be_include("missing")
end
end
it "should summarize multiple instances by returning a flattened array of all missing features" do
confines = []
confines << Puppet::Confine::Feature.new(%w{one two})
confines << Puppet::Confine::Feature.new(%w{two})
confines << Puppet::Confine::Feature.new(%w{three four})
features = mock 'feature'
features.stub_everything
Puppet.stubs(:features).returns features
- Puppet::Confine::Feature.summarize(confines).sort.should == %w{one two three four}.sort
+ expect(Puppet::Confine::Feature.summarize(confines).sort).to eq(%w{one two three four}.sort)
end
end
diff --git a/spec/unit/confine/true_spec.rb b/spec/unit/confine/true_spec.rb
index d7484d59c..233465afb 100755
--- a/spec/unit/confine/true_spec.rb
+++ b/spec/unit/confine/true_spec.rb
@@ -1,52 +1,52 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/confine/true'
describe Puppet::Confine::True do
it "should be named :true" do
- Puppet::Confine::True.name.should == :true
+ expect(Puppet::Confine::True.name).to eq(:true)
end
it "should require a value" do
- lambda { Puppet::Confine::True.new }.should raise_error(ArgumentError)
+ expect { Puppet::Confine::True.new }.to raise_error(ArgumentError)
end
describe "when testing values" do
before do
@confine = Puppet::Confine::True.new("foo")
@confine.label = "eh"
end
it "should use the 'pass?' method to test validity" do
@confine.expects(:pass?).with("foo")
@confine.valid?
end
it "should return true if the value is not false" do
- @confine.pass?("else").should be_true
+ expect(@confine.pass?("else")).to be_truthy
end
it "should return false if the value is false" do
- @confine.pass?(nil).should be_false
+ expect(@confine.pass?(nil)).to be_falsey
end
it "should produce the message that a value is false" do
- @confine.message("eh").should be_include("false")
+ expect(@confine.message("eh")).to be_include("false")
end
end
it "should produce the number of false values when asked for a summary" do
@confine = Puppet::Confine::True.new %w{one two three four}
@confine.expects(:pass?).times(4).returns(true).returns(false).returns(true).returns(false)
- @confine.summary.should == 2
+ expect(@confine.summary).to eq(2)
end
it "should summarize multiple instances by summing their summaries" do
c1 = mock '1', :summary => 1
c2 = mock '2', :summary => 2
c3 = mock '3', :summary => 3
- Puppet::Confine::True.summarize([c1, c2, c3]).should == 6
+ expect(Puppet::Confine::True.summarize([c1, c2, c3])).to eq(6)
end
end
diff --git a/spec/unit/confine/variable_spec.rb b/spec/unit/confine/variable_spec.rb
index be45e3bb1..db01f1d12 100755
--- a/spec/unit/confine/variable_spec.rb
+++ b/spec/unit/confine/variable_spec.rb
@@ -1,106 +1,106 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/confine/variable'
describe Puppet::Confine::Variable do
it "should be named :variable" do
- Puppet::Confine::Variable.name.should == :variable
+ expect(Puppet::Confine::Variable.name).to eq(:variable)
end
it "should require a value" do
- lambda { Puppet::Confine::Variable.new }.should raise_error(ArgumentError)
+ expect { Puppet::Confine::Variable.new }.to raise_error(ArgumentError)
end
it "should always convert values to an array" do
- Puppet::Confine::Variable.new("/some/file").values.should be_instance_of(Array)
+ expect(Puppet::Confine::Variable.new("/some/file").values).to be_instance_of(Array)
end
it "should have an accessor for its name" do
- Puppet::Confine::Variable.new(:bar).should respond_to(:name)
+ expect(Puppet::Confine::Variable.new(:bar)).to respond_to(:name)
end
describe "when testing values" do
before do
@confine = Puppet::Confine::Variable.new("foo")
@confine.name = :myvar
end
it "should use settings if the variable name is a valid setting" do
Puppet.settings.expects(:valid?).with(:myvar).returns true
Puppet.settings.expects(:value).with(:myvar).returns "foo"
@confine.valid?
end
it "should use Facter if the variable name is not a valid setting" do
Puppet.settings.expects(:valid?).with(:myvar).returns false
Facter.expects(:value).with(:myvar).returns "foo"
@confine.valid?
end
it "should be valid if the value matches the facter value" do
@confine.expects(:test_value).returns "foo"
- @confine.should be_valid
+ expect(@confine).to be_valid
end
it "should return false if the value does not match the facter value" do
@confine.expects(:test_value).returns "fee"
- @confine.should_not be_valid
+ expect(@confine).not_to be_valid
end
it "should be case insensitive" do
@confine.expects(:test_value).returns "FOO"
- @confine.should be_valid
+ expect(@confine).to be_valid
end
it "should not care whether the value is a string or symbol" do
@confine.expects(:test_value).returns "FOO"
- @confine.should be_valid
+ expect(@confine).to be_valid
end
it "should produce a message that the fact value is not correct" do
@confine = Puppet::Confine::Variable.new(%w{bar bee})
@confine.name = "eh"
message = @confine.message("value")
- message.should be_include("facter")
- message.should be_include("bar,bee")
+ expect(message).to be_include("facter")
+ expect(message).to be_include("bar,bee")
end
it "should be valid if the test value matches any of the provided values" do
@confine = Puppet::Confine::Variable.new(%w{bar bee})
@confine.expects(:test_value).returns "bee"
- @confine.should be_valid
+ expect(@confine).to be_valid
end
end
describe "when summarizing multiple instances" do
it "should return a hash of failing variables and their values" do
c1 = Puppet::Confine::Variable.new("one")
c1.name = "uno"
c1.expects(:valid?).returns false
c2 = Puppet::Confine::Variable.new("two")
c2.name = "dos"
c2.expects(:valid?).returns true
c3 = Puppet::Confine::Variable.new("three")
c3.name = "tres"
c3.expects(:valid?).returns false
- Puppet::Confine::Variable.summarize([c1, c2, c3]).should == {"uno" => %w{one}, "tres" => %w{three}}
+ expect(Puppet::Confine::Variable.summarize([c1, c2, c3])).to eq({"uno" => %w{one}, "tres" => %w{three}})
end
it "should combine the values of multiple confines with the same fact" do
c1 = Puppet::Confine::Variable.new("one")
c1.name = "uno"
c1.expects(:valid?).returns false
c2 = Puppet::Confine::Variable.new("two")
c2.name = "uno"
c2.expects(:valid?).returns false
- Puppet::Confine::Variable.summarize([c1, c2]).should == {"uno" => %w{one two}}
+ expect(Puppet::Confine::Variable.summarize([c1, c2])).to eq({"uno" => %w{one two}})
end
end
end
diff --git a/spec/unit/confine_collection_spec.rb b/spec/unit/confine_collection_spec.rb
index 958f69197..0988da22f 100755
--- a/spec/unit/confine_collection_spec.rb
+++ b/spec/unit/confine_collection_spec.rb
@@ -1,133 +1,133 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/confine_collection'
describe Puppet::ConfineCollection do
it "should be able to add confines" do
- Puppet::ConfineCollection.new("label").should respond_to(:confine)
+ expect(Puppet::ConfineCollection.new("label")).to respond_to(:confine)
end
it "should require a label at initialization" do
- lambda { Puppet::ConfineCollection.new }.should raise_error(ArgumentError)
+ expect { Puppet::ConfineCollection.new }.to raise_error(ArgumentError)
end
it "should make its label available" do
- Puppet::ConfineCollection.new("mylabel").label.should == "mylabel"
+ expect(Puppet::ConfineCollection.new("mylabel").label).to eq("mylabel")
end
describe "when creating confine instances" do
it "should create an instance of the named test with the provided values" do
test_class = mock 'test_class'
test_class.expects(:new).with(%w{my values}).returns(stub('confine', :label= => nil))
Puppet::Confine.expects(:test).with(:foo).returns test_class
Puppet::ConfineCollection.new("label").confine :foo => %w{my values}
end
it "should copy its label to the confine instance" do
confine = mock 'confine'
test_class = mock 'test_class'
test_class.expects(:new).returns confine
Puppet::Confine.expects(:test).returns test_class
confine.expects(:label=).with("label")
Puppet::ConfineCollection.new("label").confine :foo => %w{my values}
end
describe "and the test cannot be found" do
it "should create a Facter test with the provided values and set the name to the test name" do
confine = Puppet::Confine.test(:variable).new(%w{my values})
confine.expects(:name=).with(:foo)
confine.class.expects(:new).with(%w{my values}).returns confine
Puppet::ConfineCollection.new("label").confine(:foo => %w{my values})
end
end
describe "and the 'for_binary' option was provided" do
it "should mark the test as a binary confine" do
confine = Puppet::Confine.test(:exists).new(:bar)
confine.expects(:for_binary=).with true
Puppet::Confine.test(:exists).expects(:new).with(:bar).returns confine
Puppet::ConfineCollection.new("label").confine :exists => :bar, :for_binary => true
end
end
end
it "should be valid if no confines are present" do
- Puppet::ConfineCollection.new("label").should be_valid
+ expect(Puppet::ConfineCollection.new("label")).to be_valid
end
it "should be valid if all confines pass" do
c1 = stub 'c1', :valid? => true, :label= => nil
c2 = stub 'c2', :valid? => true, :label= => nil
Puppet::Confine.test(:true).expects(:new).returns(c1)
Puppet::Confine.test(:false).expects(:new).returns(c2)
confiner = Puppet::ConfineCollection.new("label")
confiner.confine :true => :bar, :false => :bee
- confiner.should be_valid
+ expect(confiner).to be_valid
end
it "should not be valid if any confines fail" do
c1 = stub 'c1', :valid? => true, :label= => nil
c2 = stub 'c2', :valid? => false, :label= => nil
Puppet::Confine.test(:true).expects(:new).returns(c1)
Puppet::Confine.test(:false).expects(:new).returns(c2)
confiner = Puppet::ConfineCollection.new("label")
confiner.confine :true => :bar, :false => :bee
- confiner.should_not be_valid
+ expect(confiner).not_to be_valid
end
describe "when providing a summary" do
before do
@confiner = Puppet::ConfineCollection.new("label")
end
it "should return a hash" do
- @confiner.summary.should be_instance_of(Hash)
+ expect(@confiner.summary).to be_instance_of(Hash)
end
it "should return an empty hash if the confiner is valid" do
- @confiner.summary.should == {}
+ expect(@confiner.summary).to eq({})
end
it "should add each test type's summary to the hash" do
@confiner.confine :true => :bar, :false => :bee
Puppet::Confine.test(:true).expects(:summarize).returns :tsumm
Puppet::Confine.test(:false).expects(:summarize).returns :fsumm
- @confiner.summary.should == {:true => :tsumm, :false => :fsumm}
+ expect(@confiner.summary).to eq({:true => :tsumm, :false => :fsumm})
end
it "should not include tests that return 0" do
@confiner.confine :true => :bar, :false => :bee
Puppet::Confine.test(:true).expects(:summarize).returns 0
Puppet::Confine.test(:false).expects(:summarize).returns :fsumm
- @confiner.summary.should == {:false => :fsumm}
+ expect(@confiner.summary).to eq({:false => :fsumm})
end
it "should not include tests that return empty arrays" do
@confiner.confine :true => :bar, :false => :bee
Puppet::Confine.test(:true).expects(:summarize).returns []
Puppet::Confine.test(:false).expects(:summarize).returns :fsumm
- @confiner.summary.should == {:false => :fsumm}
+ expect(@confiner.summary).to eq({:false => :fsumm})
end
it "should not include tests that return empty hashes" do
@confiner.confine :true => :bar, :false => :bee
Puppet::Confine.test(:true).expects(:summarize).returns({})
Puppet::Confine.test(:false).expects(:summarize).returns :fsumm
- @confiner.summary.should == {:false => :fsumm}
+ expect(@confiner.summary).to eq({:false => :fsumm})
end
end
end
diff --git a/spec/unit/confine_spec.rb b/spec/unit/confine_spec.rb
index 06c10abd7..3bb7e0457 100755
--- a/spec/unit/confine_spec.rb
+++ b/spec/unit/confine_spec.rb
@@ -1,77 +1,77 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/confine'
describe Puppet::Confine do
it "should require a value" do
- lambda { Puppet::Confine.new }.should raise_error(ArgumentError)
+ expect { Puppet::Confine.new }.to raise_error(ArgumentError)
end
it "should always convert values to an array" do
- Puppet::Confine.new("/some/file").values.should be_instance_of(Array)
+ expect(Puppet::Confine.new("/some/file").values).to be_instance_of(Array)
end
it "should have a 'true' test" do
- Puppet::Confine.test(:true).should be_instance_of(Class)
+ expect(Puppet::Confine.test(:true)).to be_instance_of(Class)
end
it "should have a 'false' test" do
- Puppet::Confine.test(:false).should be_instance_of(Class)
+ expect(Puppet::Confine.test(:false)).to be_instance_of(Class)
end
it "should have a 'feature' test" do
- Puppet::Confine.test(:feature).should be_instance_of(Class)
+ expect(Puppet::Confine.test(:feature)).to be_instance_of(Class)
end
it "should have an 'exists' test" do
- Puppet::Confine.test(:exists).should be_instance_of(Class)
+ expect(Puppet::Confine.test(:exists)).to be_instance_of(Class)
end
it "should have a 'variable' test" do
- Puppet::Confine.test(:variable).should be_instance_of(Class)
+ expect(Puppet::Confine.test(:variable)).to be_instance_of(Class)
end
describe "when testing all values" do
before do
@confine = Puppet::Confine.new(%w{a b c})
@confine.label = "foo"
end
it "should be invalid if any values fail" do
@confine.stubs(:pass?).returns true
@confine.expects(:pass?).with("b").returns false
- @confine.should_not be_valid
+ expect(@confine).not_to be_valid
end
it "should be valid if all values pass" do
@confine.stubs(:pass?).returns true
- @confine.should be_valid
+ expect(@confine).to be_valid
end
it "should short-cut at the first failing value" do
@confine.expects(:pass?).once.returns false
@confine.valid?
end
it "should log failing confines with the label and message" do
@confine.stubs(:pass?).returns false
@confine.expects(:message).returns "My message"
@confine.expects(:label).returns "Mylabel"
Puppet.expects(:debug).with("Mylabel: My message")
@confine.valid?
end
end
describe "when testing the result of the values" do
before { @confine = Puppet::Confine.new(%w{a b c d}) }
it "should return an array with the result of the test for each value" do
@confine.stubs(:pass?).returns true
@confine.expects(:pass?).with("b").returns false
@confine.expects(:pass?).with("d").returns false
- @confine.result.should == [true, false, true, false]
+ expect(@confine.result).to eq([true, false, true, false])
end
end
end
diff --git a/spec/unit/confiner_spec.rb b/spec/unit/confiner_spec.rb
index 2d71054fe..3ba7df75b 100755
--- a/spec/unit/confiner_spec.rb
+++ b/spec/unit/confiner_spec.rb
@@ -1,62 +1,62 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/confiner'
describe Puppet::Confiner do
before do
@object = Object.new
@object.extend(Puppet::Confiner)
end
it "should have a method for defining confines" do
- @object.should respond_to(:confine)
+ expect(@object).to respond_to(:confine)
end
it "should have a method for returning its confine collection" do
- @object.should respond_to(:confine_collection)
+ expect(@object).to respond_to(:confine_collection)
end
it "should have a method for testing suitability" do
- @object.should respond_to(:suitable?)
+ expect(@object).to respond_to(:suitable?)
end
it "should delegate its confine method to its confine collection" do
coll = mock 'collection'
@object.stubs(:confine_collection).returns coll
coll.expects(:confine).with(:foo => :bar, :bee => :baz)
@object.confine(:foo => :bar, :bee => :baz)
end
it "should create a new confine collection if one does not exist" do
Puppet::ConfineCollection.expects(:new).with("mylabel").returns "mycoll"
@object.expects(:to_s).returns "mylabel"
- @object.confine_collection.should == "mycoll"
+ expect(@object.confine_collection).to eq("mycoll")
end
it "should reuse the confine collection" do
- @object.confine_collection.should equal(@object.confine_collection)
+ expect(@object.confine_collection).to equal(@object.confine_collection)
end
describe "when testing suitability" do
before do
@coll = mock 'collection'
@object.stubs(:confine_collection).returns @coll
end
it "should return true if the confine collection is valid" do
@coll.expects(:valid?).returns true
- @object.should be_suitable
+ expect(@object).to be_suitable
end
it "should return false if the confine collection is invalid" do
@coll.expects(:valid?).returns false
- @object.should_not be_suitable
+ expect(@object).not_to be_suitable
end
it "should return the summary of the confine collection if a long result is asked for" do
@coll.expects(:summary).returns "myresult"
- @object.suitable?(false).should == "myresult"
+ expect(@object.suitable?(false)).to eq("myresult")
end
end
end
diff --git a/spec/unit/context/trusted_information_spec.rb b/spec/unit/context/trusted_information_spec.rb
index a22b0113c..d6bb0a7c3 100644
--- a/spec/unit/context/trusted_information_spec.rb
+++ b/spec/unit/context/trusted_information_spec.rb
@@ -1,131 +1,131 @@
require 'spec_helper'
require 'puppet/context/trusted_information'
describe Puppet::Context::TrustedInformation do
let(:key) do
key = Puppet::SSL::Key.new("myname")
key.generate
key
end
let(:csr) do
csr = Puppet::SSL::CertificateRequest.new("csr")
csr.generate(key, :extension_requests => {
'1.3.6.1.4.1.15.1.2.1' => 'Ignored CSR extension',
'1.3.6.1.4.1.34380.1.2.1' => 'CSR specific info',
'1.3.6.1.4.1.34380.1.2.2' => 'more CSR specific info',
})
csr
end
let(:cert) do
cert = Puppet::SSL::Certificate.from_instance(Puppet::SSL::CertificateFactory.build('ca', csr, csr.content, 1))
# The cert must be signed so that it can be successfully be DER-decoded later
signer = Puppet::SSL::CertificateSigner.new
signer.sign(cert.content, key.content)
cert
end
context "when remote" do
it "has no cert information when it isn't authenticated" do
trusted = Puppet::Context::TrustedInformation.remote(false, 'ignored', nil)
expect(trusted.authenticated).to eq(false)
expect(trusted.certname).to be_nil
expect(trusted.extensions).to eq({})
end
it "is remote and has certificate information when it is authenticated" do
trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', cert)
expect(trusted.authenticated).to eq('remote')
expect(trusted.certname).to eq('cert name')
expect(trusted.extensions).to eq({
'1.3.6.1.4.1.34380.1.2.1' => 'CSR specific info',
'1.3.6.1.4.1.34380.1.2.2' => 'more CSR specific info',
})
end
it "is remote but lacks certificate information when it is authenticated" do
Puppet.expects(:info).once.with("TrustedInformation expected a certificate, but none was given.")
trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', nil)
expect(trusted.authenticated).to eq('remote')
expect(trusted.certname).to eq('cert name')
expect(trusted.extensions).to eq({})
end
end
context "when local" do
it "is authenticated local with the nodes clientcert" do
node = Puppet::Node.new('testing', :parameters => { 'clientcert' => 'cert name' })
trusted = Puppet::Context::TrustedInformation.local(node)
expect(trusted.authenticated).to eq('local')
expect(trusted.certname).to eq('cert name')
expect(trusted.extensions).to eq({})
end
it "is authenticated local with no clientcert when there is no node" do
trusted = Puppet::Context::TrustedInformation.local(nil)
expect(trusted.authenticated).to eq('local')
expect(trusted.certname).to be_nil
expect(trusted.extensions).to eq({})
end
end
it "converts itself to a hash" do
trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', cert)
expect(trusted.to_h).to eq({
'authenticated' => 'remote',
'certname' => 'cert name',
'extensions' => {
'1.3.6.1.4.1.34380.1.2.1' => 'CSR specific info',
'1.3.6.1.4.1.34380.1.2.2' => 'more CSR specific info',
}
})
end
it "freezes the hash" do
trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', cert)
expect(trusted.to_h).to be_deeply_frozen
end
matcher :be_deeply_frozen do
match do |actual|
unfrozen_items(actual).empty?
end
- failure_message_for_should do |actual|
+ failure_message do |actual|
"expected all items to be frozen but <#{unfrozen_items(actual).join(', ')}> was not"
end
define_method :unfrozen_items do |actual|
unfrozen = []
stack = [actual]
while item = stack.pop
if !item.frozen?
unfrozen.push(item)
end
case item
when Hash
stack.concat(item.keys)
stack.concat(item.values)
when Array
stack.concat(item)
end
end
unfrozen
end
end
end
diff --git a/spec/unit/daemon_spec.rb b/spec/unit/daemon_spec.rb
index b727d669c..36ec0adc7 100755
--- a/spec/unit/daemon_spec.rb
+++ b/spec/unit/daemon_spec.rb
@@ -1,255 +1,253 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/daemon'
require 'puppet/agent'
def without_warnings
flag = $VERBOSE
$VERBOSE = nil
yield
$VERBOSE = flag
end
class TestClient
def lockfile_path
"/dev/null"
end
end
describe Puppet::Daemon, :unless => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
class RecordingScheduler
attr_reader :jobs
def run_loop(jobs)
@jobs = jobs
end
end
- let(:server) { stub("Server", :start => nil, :wait_for_shutdown => nil) }
let(:agent) { Puppet::Agent.new(TestClient.new, false) }
+ let(:server) { stub("Server", :start => nil, :wait_for_shutdown => nil) }
let(:pidfile) { stub("PidFile", :lock => true, :unlock => true, :file_path => 'fake.pid') }
let(:scheduler) { RecordingScheduler.new }
let(:daemon) { Puppet::Daemon.new(pidfile, scheduler) }
before do
daemon.stubs(:close_streams).returns nil
end
it "should reopen the Log logs when told to reopen logs" do
Puppet::Util::Log.expects(:reopen)
daemon.reopen_logs
end
- let(:server) { stub("Server", :start => nil, :wait_for_shutdown => nil) }
-
describe "when setting signal traps" do
signals = {:INT => :stop, :TERM => :stop }
signals.update({:HUP => :restart, :USR1 => :reload, :USR2 => :reopen_logs}) unless Puppet.features.microsoft_windows?
signals.each do |signal, method|
it "should log and call #{method} when it receives #{signal}" do
Signal.expects(:trap).with(signal).yields
Puppet.expects(:notice)
daemon.expects(method)
daemon.set_signal_traps
end
end
end
describe "when starting" do
before do
daemon.stubs(:set_signal_traps)
end
it "should fail if it has neither agent nor server" do
expect { daemon.start }.to raise_error(Puppet::DevError)
end
it "should create its pidfile" do
pidfile.expects(:lock).returns(true)
daemon.agent = agent
daemon.start
end
it "should fail if it cannot lock" do
pidfile.expects(:lock).returns(false)
daemon.agent = agent
expect { daemon.start }.to raise_error(RuntimeError, "Could not create PID file: #{pidfile.file_path}")
end
it "should start its server if one is configured" do
daemon.server = server
server.expects(:start)
daemon.start
end
it "disables the reparse of configs if the filetimeout is 0" do
Puppet[:filetimeout] = 0
daemon.agent = agent
daemon.start
- scheduler.jobs[0].should_not be_enabled
+ expect(scheduler.jobs[0]).not_to be_enabled
end
it "disables the agent run when there is no agent" do
Puppet[:filetimeout] = 0
daemon.server = server
daemon.start
- scheduler.jobs[1].should_not be_enabled
+ expect(scheduler.jobs[1]).not_to be_enabled
end
it "waits for the server to shutdown when there is one" do
daemon.server = server
server.expects(:wait_for_shutdown)
daemon.start
end
it "waits for the server to shutdown when there is one" do
daemon.server = server
server.expects(:wait_for_shutdown)
daemon.start
end
end
describe "when stopping" do
before do
Puppet::Util::Log.stubs(:close_all)
# to make the global safe to mock, set it to a subclass of itself,
# then restore it in an after pass
without_warnings { Puppet::Application = Class.new(Puppet::Application) }
end
after do
# restore from the superclass so we lose the stub garbage
without_warnings { Puppet::Application = Puppet::Application.superclass }
end
it "should stop its server if one is configured" do
server.expects(:stop)
daemon.server = server
expect { daemon.stop }.to exit_with 0
end
it 'should request a stop from Puppet::Application' do
Puppet::Application.expects(:stop!)
expect { daemon.stop }.to exit_with 0
end
it "should remove its pidfile" do
pidfile.expects(:unlock)
expect { daemon.stop }.to exit_with 0
end
it "should close all logs" do
Puppet::Util::Log.expects(:close_all)
expect { daemon.stop }.to exit_with 0
end
it "should exit unless called with ':exit => false'" do
expect { daemon.stop }.to exit_with 0
end
it "should not exit if called with ':exit => false'" do
daemon.stop :exit => false
end
end
describe "when reloading" do
it "should do nothing if no agent is configured" do
daemon.reload
end
it "should do nothing if the agent is running" do
agent.expects(:running?).returns true
daemon.agent = agent
daemon.reload
end
it "should run the agent if one is available and it is not running" do
agent.expects(:running?).returns false
agent.expects(:run).with({:splay => false})
daemon.agent = agent
daemon.reload
end
end
describe "when restarting" do
before do
without_warnings { Puppet::Application = Class.new(Puppet::Application) }
end
after do
without_warnings { Puppet::Application = Puppet::Application.superclass }
end
it 'should set Puppet::Application.restart!' do
Puppet::Application.expects(:restart!)
daemon.stubs(:reexec)
daemon.restart
end
it "should reexec itself if no agent is available" do
daemon.expects(:reexec)
daemon.restart
end
it "should reexec itself if the agent is not running" do
agent.expects(:running?).returns false
daemon.agent = agent
daemon.expects(:reexec)
daemon.restart
end
end
describe "when reexecing it self" do
before do
daemon.stubs(:exec)
daemon.stubs(:stop)
end
it "should fail if no argv values are available" do
daemon.expects(:argv).returns nil
- lambda { daemon.reexec }.should raise_error(Puppet::DevError)
+ expect { daemon.reexec }.to raise_error(Puppet::DevError)
end
it "should shut down without exiting" do
daemon.argv = %w{foo}
daemon.expects(:stop).with(:exit => false)
daemon.reexec
end
it "should call 'exec' with the original executable and arguments" do
daemon.argv = %w{foo}
daemon.expects(:exec).with($0 + " foo")
daemon.reexec
end
end
end
diff --git a/spec/unit/data_binding_spec.rb b/spec/unit/data_binding_spec.rb
index 3713d2301..77635f36b 100644
--- a/spec/unit/data_binding_spec.rb
+++ b/spec/unit/data_binding_spec.rb
@@ -1,11 +1,11 @@
require 'spec_helper'
require 'puppet/data_binding'
describe Puppet::DataBinding do
describe "when indirecting" do
it "should default to the 'hiera' data_binding terminus" do
Puppet::DataBinding.indirection.reset_terminus_class
- Puppet::DataBinding.indirection.terminus_class.should == :hiera
+ expect(Puppet::DataBinding.indirection.terminus_class).to eq(:hiera)
end
end
end
diff --git a/spec/unit/defaults_spec.rb b/spec/unit/defaults_spec.rb
index 0d141d91c..e8e568dee 100644
--- a/spec/unit/defaults_spec.rb
+++ b/spec/unit/defaults_spec.rb
@@ -1,74 +1,74 @@
require 'spec_helper'
require 'puppet/settings'
describe "Defaults" do
describe ".default_diffargs" do
describe "on AIX" do
before(:each) do
Facter.stubs(:value).with(:kernel).returns("AIX")
end
describe "on 5.3" do
before(:each) do
Facter.stubs(:value).with(:kernelmajversion).returns("5300")
end
it "should be empty" do
- Puppet.default_diffargs.should == ""
+ expect(Puppet.default_diffargs).to eq("")
end
end
[ "",
nil,
"6300",
"7300",
].each do |kernel_version|
describe "on kernel version #{kernel_version.inspect}" do
before(:each) do
Facter.stubs(:value).with(:kernelmajversion).returns(kernel_version)
end
it "should be '-u'" do
- Puppet.default_diffargs.should == "-u"
+ expect(Puppet.default_diffargs).to eq("-u")
end
end
end
end
describe "on everything else" do
before(:each) do
Facter.stubs(:value).with(:kernel).returns("NOT_AIX")
end
it "should be '-u'" do
- Puppet.default_diffargs.should == "-u"
+ expect(Puppet.default_diffargs).to eq("-u")
end
end
end
describe 'cfacter' do
before :each do
Facter.reset
end
it 'should default to false' do
- Puppet.settings[:cfacter].should be_false
+ expect(Puppet.settings[:cfacter]).to be_falsey
end
it 'should raise an error if cfacter is not installed' do
Puppet.features.stubs(:cfacter?).returns false
- lambda { Puppet.settings[:cfacter] = true }.should raise_exception ArgumentError, 'cfacter version 0.2.0 or later is not installed.'
+ expect { Puppet.settings[:cfacter] = true }.to raise_exception ArgumentError, 'cfacter version 0.2.0 or later is not installed.'
end
it 'should raise an error if facter has already evaluated facts' do
Facter[:facterversion]
Puppet.features.stubs(:cfacter?).returns true
- lambda { Puppet.settings[:cfacter] = true }.should raise_exception ArgumentError, 'facter has already evaluated facts.'
+ expect { Puppet.settings[:cfacter] = true }.to raise_exception ArgumentError, 'facter has already evaluated facts.'
end
it 'should initialize cfacter when set to true' do
Puppet.features.stubs(:cfacter?).returns true
CFacter = mock
CFacter.stubs(:initialize)
Puppet.settings[:cfacter] = true
end
end
end
diff --git a/spec/unit/environments_spec.rb b/spec/unit/environments_spec.rb
index ca2e403c4..149811ffe 100644
--- a/spec/unit/environments_spec.rb
+++ b/spec/unit/environments_spec.rb
@@ -1,655 +1,655 @@
require 'spec_helper'
require 'puppet/environments'
require 'puppet/file_system'
require 'matchers/include'
require 'matchers/include_in_order'
module PuppetEnvironments
describe Puppet::Environments do
include Matchers::Include
FS = Puppet::FileSystem
before(:each) do
Puppet.settings.initialize_global_settings
Puppet[:environment_timeout] = "unlimited"
end
let(:directory_tree) do
FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_regular_file_containing("ignored_file", ''),
FS::MemoryFile.a_directory("an_environment", [
FS::MemoryFile.a_missing_file("environment.conf"),
FS::MemoryFile.a_directory("modules"),
FS::MemoryFile.a_directory("manifests"),
]),
FS::MemoryFile.a_directory("another_environment", [
FS::MemoryFile.a_missing_file("environment.conf"),
]),
FS::MemoryFile.a_missing_file("doesnotexist"),
])
end
describe "directories loader" do
it "lists environments" do
global_path_1_location = File.expand_path("global_path_1")
global_path_2_location = File.expand_path("global_path_2")
global_path_1 = FS::MemoryFile.a_directory(global_path_1_location)
global_path_2 = FS::MemoryFile.a_directory(global_path_2_location)
loader_from(:filesystem => [directory_tree, global_path_1, global_path_2],
:directory => directory_tree,
:modulepath => [global_path_1_location, global_path_2_location]) do |loader|
expect(loader.list).to include_in_any_order(
environment(:an_environment).
with_manifest("#{FS.path_string(directory_tree)}/an_environment/manifests").
with_modulepath(["#{FS.path_string(directory_tree)}/an_environment/modules",
global_path_1_location,
global_path_2_location]),
environment(:another_environment))
end
end
it "has search_paths" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree) do |loader|
expect(loader.search_paths).to eq(["file://#{directory_tree}"])
end
end
it "ignores directories that are not valid env names (alphanumeric and _)" do
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory(".foo"),
FS::MemoryFile.a_directory("bar-thing"),
FS::MemoryFile.a_directory("with spaces"),
FS::MemoryFile.a_directory("some.thing"),
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_missing_file("environment.conf"),
]),
FS::MemoryFile.a_directory("env2", [
FS::MemoryFile.a_missing_file("environment.conf"),
]),
])
loader_from(:filesystem => [envdir],
:directory => envdir) do |loader|
expect(loader.list).to include_in_any_order(environment(:env1), environment(:env2))
end
end
it "gets a particular environment" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree) do |loader|
expect(loader.get("an_environment")).to environment(:an_environment)
end
end
it "raises error when environment not found" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree) do |loader|
expect do
loader.get!("doesnotexist")
end.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
end
it "returns nil if an environment can't be found" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree) do |loader|
expect(loader.get("doesnotexist")).to be_nil
end
end
context "with an environment.conf" do
let(:envdir) do
FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
]),
])
end
let(:manifestdir) { FS::MemoryFile.a_directory(File.expand_path("/some/manifest/path")) }
let(:modulepath) do
[
FS::MemoryFile.a_directory(File.expand_path("/some/module/path")),
FS::MemoryFile.a_directory(File.expand_path("/some/other/path")),
]
end
let(:content) do
<<-EOF
manifest=#{manifestdir}
modulepath=#{modulepath.join(File::PATH_SEPARATOR)}
config_version=/some/script
EOF
end
it "reads environment.conf settings" do
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path))
end
end
it "does not append global_module_path to environment.conf modulepath setting" do
global_path_location = File.expand_path("global_path")
global_path = FS::MemoryFile.a_directory(global_path_location)
loader_from(:filesystem => [envdir, manifestdir, modulepath, global_path].flatten,
:directory => envdir,
:modulepath => [global_path]) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path))
end
end
it "reads config_version setting" do
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script'))
end
end
it "accepts an empty environment.conf without warning" do
content = nil
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
]),
])
manifestdir = FS::MemoryFile.a_directory(File.join(envdir, "env1", "manifests"))
modulesdir = FS::MemoryFile.a_directory(File.join(envdir, "env1", "modules"))
global_path_location = File.expand_path("global_path")
global_path = FS::MemoryFile.a_directory(global_path_location)
loader_from(:filesystem => [envdir, manifestdir, modulesdir, global_path].flatten,
:directory => envdir,
:modulepath => [global_path]) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest("#{FS.path_string(envdir)}/env1/manifests").
with_modulepath(["#{FS.path_string(envdir)}/env1/modules", global_path_location]).
with_config_version(nil)
end
expect(@logs).to be_empty
end
it "logs a warning, but processes the main settings if there are extraneous sections" do
content << "[foo]"
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script'))
end
expect(@logs.map(&:to_s).join).to match(/Invalid.*at.*\/env1.*may not have sections.*ignored: 'foo'/)
end
it "logs a warning, but processes the main settings if there are any extraneous settings" do
content << "dog=arf\n"
content << "cat=mew\n"
content << "[ignored]\n"
content << "cow=moo\n"
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script'))
end
expect(@logs.map(&:to_s).join).to match(/Invalid.*at.*\/env1.*unknown setting.*dog, cat/)
end
it "interpretes relative paths from the environment's directory" do
content = <<-EOF
manifest=relative/manifest
modulepath=relative/modules
config_version=relative/script
EOF
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
FS::MemoryFile.a_missing_file("modules"),
FS::MemoryFile.a_directory('relative', [
FS::MemoryFile.a_directory('modules'),
]),
]),
])
loader_from(:filesystem => [envdir],
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(File.join(envdir, 'env1', 'relative', 'manifest')).
with_modulepath([File.join(envdir, 'env1', 'relative', 'modules')]).
with_config_version(File.join(envdir, 'env1', 'relative', 'script'))
end
end
it "interpolates other setting values correctly" do
modulepath = [
File.expand_path('/some/absolute'),
'$basemodulepath',
'modules'
].join(File::PATH_SEPARATOR)
content = <<-EOF
manifest=$confdir/whackymanifests
modulepath=#{modulepath}
config_version=$vardir/random/scripts
EOF
some_absolute_dir = FS::MemoryFile.a_directory(File.expand_path('/some/absolute'))
base_module_dirs = Puppet[:basemodulepath].split(File::PATH_SEPARATOR).map do |path|
FS::MemoryFile.a_directory(path)
end
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
FS::MemoryFile.a_directory("modules"),
]),
])
loader_from(:filesystem => [envdir, some_absolute_dir, base_module_dirs].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(File.join(Puppet[:confdir], 'whackymanifests')).
with_modulepath([some_absolute_dir.path,
base_module_dirs.map { |d| d.path },
File.join(envdir, 'env1', 'modules')].flatten).
with_config_version(File.join(Puppet[:vardir], 'random', 'scripts'))
end
end
it "uses environment.conf settings regardless of existence of modules and manifests subdirectories" do
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
FS::MemoryFile.a_directory("modules"),
FS::MemoryFile.a_directory("manifests"),
]),
])
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script'))
end
end
it "should update environment settings if environment.conf has changed and timeout has expired" do
base_dir = File.expand_path("envdir")
original_envdir = FS::MemoryFile.a_directory(base_dir, [
FS::MemoryFile.a_directory("env3", [
FS::MemoryFile.a_regular_file_containing("environment.conf", <<-EOF)
manifest=/manifest_orig
modulepath=/modules_orig
environment_timeout=0
EOF
]),
])
FS.overlay(original_envdir) do
dir_loader = Puppet::Environments::Directories.new(original_envdir, [])
loader = Puppet::Environments::Cached.new(dir_loader)
Puppet.override(:environments => loader) do
original_env = loader.get("env3") # force the environment.conf to be read
changed_envdir = FS::MemoryFile.a_directory(base_dir, [
FS::MemoryFile.a_directory("env3", [
FS::MemoryFile.a_regular_file_containing("environment.conf", <<-EOF)
manifest=/manifest_changed
modulepath=/modules_changed
environment_timeout=0
EOF
]),
])
FS.overlay(changed_envdir) do
changed_env = loader.get("env3")
expect(original_env).to environment(:env3).
with_manifest(File.expand_path("/manifest_orig")).
with_full_modulepath([File.expand_path("/modules_orig")])
expect(changed_env).to environment(:env3).
with_manifest(File.expand_path("/manifest_changed")).
with_full_modulepath([File.expand_path("/modules_changed")])
end
end
end
end
context "custom cache expiration service" do
it "consults the custom service to expire the cache" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree) do |loader|
service = ReplayExpirationService.new([true])
using_expiration_service(service) do
cached = Puppet::Environments::Cached.new(loader)
cached.get(:an_environment)
cached.get(:an_environment)
expect(service.created_envs).to include(:an_environment)
expect(service.expired_envs).to include(:an_environment)
expect(service.evicted_envs).to include(:an_environment)
end
end
end
end
end
end
describe "static loaders" do
let(:static1) { Puppet::Node::Environment.create(:static1, []) }
let(:static2) { Puppet::Node::Environment.create(:static2, []) }
let(:loader) { Puppet::Environments::Static.new(static1, static2) }
it "lists environments" do
expect(loader.list).to eq([static1, static2])
end
it "has search_paths" do
expect(loader.search_paths).to eq(["data:text/plain,internal"])
end
it "gets an environment" do
expect(loader.get(:static2)).to eq(static2)
end
it "returns nil if env not found" do
expect(loader.get(:doesnotexist)).to be_nil
end
it "raises error if environment is not found" do
expect do
loader.get!(:doesnotexist)
end.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
it "gets a basic conf" do
conf = loader.get_conf(:static1)
expect(conf.modulepath).to eq('')
expect(conf.manifest).to eq(:no_manifest)
expect(conf.config_version).to be_nil
end
it "returns nil if you request a configuration from an env that doesn't exist" do
expect(loader.get_conf(:doesnotexist)).to be_nil
end
context "that are private" do
let(:private_env) { Puppet::Node::Environment.create(:private, []) }
let(:loader) { Puppet::Environments::StaticPrivate.new(private_env) }
it "lists nothing" do
expect(loader.list).to eq([])
end
end
end
describe "combined loaders" do
let(:static1) { Puppet::Node::Environment.create(:static1, []) }
let(:static2) { Puppet::Node::Environment.create(:static2, []) }
let(:static_loader) { Puppet::Environments::Static.new(static1, static2) }
let(:directory_tree) do
FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("an_environment", [
FS::MemoryFile.a_missing_file("environment.conf"),
FS::MemoryFile.a_directory("modules"),
FS::MemoryFile.a_directory("manifests"),
]),
FS::MemoryFile.a_missing_file("env_does_not_exist"),
FS::MemoryFile.a_missing_file("static2"),
])
end
it "lists environments" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
envs = Puppet::Environments::Combined.new(loader, static_loader).list
expect(envs[0]).to environment(:an_environment)
expect(envs[1]).to environment(:static1)
expect(envs[2]).to environment(:static2)
end
end
it "has search_paths" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Combined.new(loader, static_loader).search_paths).to eq(["file://#{directory_tree}","data:text/plain,internal"])
end
end
it "gets an environment" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Combined.new(loader, static_loader).get(:an_environment)).to environment(:an_environment)
expect(Puppet::Environments::Combined.new(loader, static_loader).get(:static2)).to environment(:static2)
end
end
it "returns nil if env not found" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Combined.new(loader, static_loader).get(:env_does_not_exist)).to be_nil
end
end
it "raises an error if environment is not found" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect do
Puppet::Environments::Combined.new(loader, static_loader).get!(:env_does_not_exist)
end.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
end
it "gets an environment.conf" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Combined.new(loader, static_loader).get_conf(:an_environment)).to match_environment_conf(:an_environment).
with_env_path(directory_tree).
with_global_module_path([])
end
end
end
describe "cached loaders" do
it "lists environments" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Cached.new(loader).list).to include_in_any_order(
environment(:an_environment),
environment(:another_environment))
end
end
it "has search_paths" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Cached.new(loader).search_paths).to eq(["file://#{directory_tree}"])
end
end
context "#get" do
it "gets an environment" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Cached.new(loader).get(:an_environment)).to environment(:an_environment)
end
end
it "does not reload the environment if it isn't expired" do
env = Puppet::Node::Environment.create(:cached, [])
mocked_loader = mock('loader')
mocked_loader.expects(:get).with(:cached).returns(env).once
mocked_loader.expects(:get_conf).with(:cached).returns(Puppet::Settings::EnvironmentConf.static_for(env, 20)).once
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get(:cached)
cached.get(:cached)
end
it "returns nil if env not found" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Cached.new(loader).get(:doesnotexist)).to be_nil
end
end
end
context "#get!" do
it "gets an environment" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Cached.new(loader).get!(:an_environment)).to environment(:an_environment)
end
end
it "does not reload the environment if it isn't expired" do
env = Puppet::Node::Environment.create(:cached, [])
mocked_loader = mock('loader')
mocked_loader.expects(:get).with(:cached).returns(env).once
mocked_loader.expects(:get_conf).with(:cached).returns(Puppet::Settings::EnvironmentConf.static_for(env, 20)).once
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get!(:cached)
cached.get!(:cached)
end
it "raises error if environment is not found" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect do
Puppet::Environments::Cached.new(loader).get!(:doesnotexist)
end.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
end
end
it "gets an environment.conf" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Cached.new(loader).get_conf(:an_environment)).to match_environment_conf(:an_environment).
with_env_path(directory_tree).
with_global_module_path([])
end
end
end
RSpec::Matchers.define :environment do |name|
match do |env|
env.name == name &&
(!@manifest || @manifest == env.manifest) &&
(!@modulepath || @modulepath == env.modulepath) &&
(!@full_modulepath || @full_modulepath == env.full_modulepath) &&
(!@config_version || @config_version == env.config_version)
end
chain :with_manifest do |manifest|
@manifest = manifest
end
chain :with_modulepath do |modulepath|
@modulepath = modulepath
end
chain :with_full_modulepath do |full_modulepath|
@full_modulepath = full_modulepath
end
chain :with_config_version do |config_version|
@config_version = config_version
end
description do
"environment #{expected}" +
(@manifest ? " with manifest #{@manifest}" : "") +
(@modulepath ? " with modulepath [#{@modulepath.join(', ')}]" : "") +
(@full_modulepath ? " with full_modulepath [#{@full_modulepath.join(', ')}]" : "") +
(@config_version ? " with config_version #{@config_version}" : "")
end
- failure_message_for_should do |env|
+ failure_message do |env|
"expected <#{env.name}: modulepath = [#{env.full_modulepath.join(', ')}], manifest = #{env.manifest}, config_version = #{env.config_version}> to be #{description}"
end
end
RSpec::Matchers.define :match_environment_conf do |env_name|
match do |env_conf|
env_conf.path_to_env =~ /#{env_name}$/ &&
(!@env_path || File.join(@env_path,env_name.to_s) == env_conf.path_to_env) &&
(!@global_modulepath || @global_module_path == env_conf.global_module_path)
end
chain :with_env_path do |env_path|
@env_path = env_path.to_s
end
chain :with_global_module_path do |global_module_path|
@global_module_path = global_module_path
end
description do
"EnvironmentConf #{expected}" +
" with path_to_env: #{@env_path ? @env_path : "*"}/#{env_name}" +
(@global_module_path ? " with global_module_path [#{@global_module_path.join(', ')}]" : "")
end
- failure_message_for_should do |env_conf|
+ failure_message do |env_conf|
"expected #{env_conf.inspect} to be #{description}"
end
end
def loader_from(options, &block)
FS.overlay(*options[:filesystem]) do
environments = Puppet::Environments::Directories.new(
options[:directory],
options[:modulepath] || []
)
Puppet.override(:environments => environments) do
yield environments
end
end
end
def using_expiration_service(service)
begin
orig_svc = Puppet::Environments::Cached.cache_expiration_service
Puppet::Environments::Cached.cache_expiration_service = service
yield
ensure
Puppet::Environments::Cached.cache_expiration_service = orig_svc
end
end
class ReplayExpirationService
attr_reader :created_envs, :expired_envs, :evicted_envs
def initialize(expiration_sequence)
@created_envs = []
@expired_envs = []
@evicted_envs = []
@expiration_sequence = expiration_sequence
end
def created(env)
@created_envs << env.name
end
def expired?(env_name)
@expired_envs << env_name
@expiration_sequence.pop
end
def evicted(env_name)
@evicted_envs << env_name
end
end
end
end
diff --git a/spec/unit/external/pson_spec.rb b/spec/unit/external/pson_spec.rb
index cf76b8ffc..61cfdd942 100755
--- a/spec/unit/external/pson_spec.rb
+++ b/spec/unit/external/pson_spec.rb
@@ -1,61 +1,61 @@
#! /usr/bin/env ruby
# Encoding: UTF-8
require 'spec_helper'
require 'puppet/external/pson/common'
describe PSON do
{
'foo' => '"foo"',
1 => '1',
"\x80" => "\"\x80\"",
[] => '[]'
}.each do |str, expect|
it "should be able to encode #{str.inspect}" do
got = str.to_pson
if got.respond_to? :force_encoding
- got.force_encoding('binary').should == expect.force_encoding('binary')
+ expect(got.force_encoding('binary')).to eq(expect.force_encoding('binary'))
else
- got.should == expect
+ expect(got).to eq(expect)
end
end
end
it "should be able to handle arbitrary binary data" do
bin_string = (1..20000).collect { |i| ((17*i+13*i*i) % 255).chr }.join
parsed = PSON.parse(%Q{{ "type": "foo", "data": #{bin_string.to_pson} }})["data"]
if parsed.respond_to? :force_encoding
parsed.force_encoding('binary')
bin_string.force_encoding('binary')
end
- parsed.should == bin_string
+ expect(parsed).to eq(bin_string)
end
it "should be able to handle UTF8 that isn't a real unicode character" do
s = ["\355\274\267"]
- PSON.parse( [s].to_pson ).should == [s]
+ expect(PSON.parse( [s].to_pson )).to eq([s])
end
it "should be able to handle UTF8 for \\xFF" do
s = ["\xc3\xbf"]
- PSON.parse( [s].to_pson ).should == [s]
+ expect(PSON.parse( [s].to_pson )).to eq([s])
end
it "should be able to handle invalid UTF8 bytes" do
s = ["\xc3\xc3"]
- PSON.parse( [s].to_pson ).should == [s]
+ expect(PSON.parse( [s].to_pson )).to eq([s])
end
it "should be able to parse JSON containing UTF-8 characters in strings" do
s = '{ "foö": "bár" }'
- lambda { PSON.parse s }.should_not raise_error
+ expect { PSON.parse s }.not_to raise_error
end
it 'ignores "document_type" during parsing' do
text = '{"data":{},"document_type":"Node"}'
expect(PSON.parse(text)).to eq({"data" => {}, "document_type" => "Node"})
end
end
diff --git a/spec/unit/face/certificate_spec.rb b/spec/unit/face/certificate_spec.rb
index 2fa5e3ea7..594043d36 100755
--- a/spec/unit/face/certificate_spec.rb
+++ b/spec/unit/face/certificate_spec.rb
@@ -1,223 +1,223 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/face'
require 'puppet/ssl/host'
describe Puppet::Face[:certificate, '0.0.1'] do
include PuppetSpec::Files
let(:ca) { Puppet::SSL::CertificateAuthority.instance }
before :each do
Puppet[:confdir] = tmpdir('conf')
Puppet::SSL::CertificateAuthority.stubs(:ca?).returns true
Puppet::SSL::Host.ca_location = :local
# We can't cache the CA between tests, because each one has its own SSL dir.
ca = Puppet::SSL::CertificateAuthority.new
Puppet::SSL::CertificateAuthority.stubs(:new).returns ca
Puppet::SSL::CertificateAuthority.stubs(:instance).returns ca
end
it "should have a ca-location option" do
- subject.should be_option :ca_location
+ expect(subject).to be_option :ca_location
end
it "should set the ca location when invoked" do
Puppet::SSL::Host.expects(:ca_location=).with(:local)
ca.expects(:sign).with do |name,options|
name == "hello, friend"
end
subject.sign "hello, friend", :ca_location => :local
end
it "(#7059) should set the ca location when an inherited action is invoked" do
Puppet::SSL::Host.expects(:ca_location=).with(:local)
subject.indirection.expects(:find)
subject.find "hello, friend", :ca_location => :local
end
it "should validate the option as required" do
expect do
subject.find 'hello, friend'
end.to raise_exception ArgumentError, /required/i
end
it "should validate the option as a supported value" do
expect do
subject.find 'hello, friend', :ca_location => :foo
end.to raise_exception ArgumentError, /valid values/i
end
describe "#generate" do
let(:options) { {:ca_location => 'local'} }
let(:host) { Puppet::SSL::Host.new(hostname) }
let(:csr) { host.certificate_request }
before :each do
Puppet[:autosign] = false
end
describe "for the current host" do
let(:hostname) { Puppet[:certname] }
it "should generate a CSR for this host" do
subject.generate(hostname, options)
- csr.content.subject.to_s.should == "/CN=#{Puppet[:certname]}"
- csr.name.should == Puppet[:certname]
+ expect(csr.content.subject.to_s).to eq("/CN=#{Puppet[:certname]}")
+ expect(csr.name).to eq(Puppet[:certname])
end
it "should add dns_alt_names from the global config if not otherwise specified" do
Puppet[:dns_alt_names] = 'from,the,config'
subject.generate(hostname, options)
expected = %W[DNS:from DNS:the DNS:config DNS:#{hostname}]
- csr.subject_alt_names.should =~ expected
+ expect(csr.subject_alt_names).to match_array(expected)
end
it "should add the provided dns_alt_names if they are specified" do
Puppet[:dns_alt_names] = 'from,the,config'
subject.generate(hostname, options.merge(:dns_alt_names => 'explicit,alt,names'))
expected = %W[DNS:explicit DNS:alt DNS:names DNS:#{hostname}]
- csr.subject_alt_names.should =~ expected
+ expect(csr.subject_alt_names).to match_array(expected)
end
end
describe "for another host" do
let(:hostname) { Puppet[:certname] + 'different' }
it "should generate a CSR for the specified host" do
subject.generate(hostname, options)
- csr.content.subject.to_s.should == "/CN=#{hostname}"
- csr.name.should == hostname
+ expect(csr.content.subject.to_s).to eq("/CN=#{hostname}")
+ expect(csr.name).to eq(hostname)
end
it "should fail if a CSR already exists for the host" do
subject.generate(hostname, options)
expect do
subject.generate(hostname, options)
end.to raise_error(RuntimeError, /#{hostname} already has a requested certificate; ignoring certificate request/)
end
it "should add not dns_alt_names from the config file" do
Puppet[:dns_alt_names] = 'from,the,config'
subject.generate(hostname, options)
- csr.subject_alt_names.should be_empty
+ expect(csr.subject_alt_names).to be_empty
end
it "should add the provided dns_alt_names if they are specified" do
Puppet[:dns_alt_names] = 'from,the,config'
subject.generate(hostname, options.merge(:dns_alt_names => 'explicit,alt,names'))
expected = %W[DNS:explicit DNS:alt DNS:names DNS:#{hostname}]
- csr.subject_alt_names.should =~ expected
+ expect(csr.subject_alt_names).to match_array(expected)
end
it "should use the global setting if set by CLI" do
Puppet.settings.patch_value(:dns_alt_names, 'from,the,cli', :cli)
subject.generate(hostname, options)
expected = %W[DNS:from DNS:the DNS:cli DNS:#{hostname}]
- csr.subject_alt_names.should =~ expected
+ expect(csr.subject_alt_names).to match_array(expected)
end
it "should generate an error if both set on CLI" do
Puppet.settings.patch_value(:dns_alt_names, 'from,the,cli', :cli)
expect do
subject.generate(hostname, options.merge(:dns_alt_names => 'explicit,alt,names'))
end.to raise_error ArgumentError, /Can't specify both/
end
end
end
describe "#sign" do
let(:options) { {:ca_location => 'local'} }
let(:host) { Puppet::SSL::Host.new(hostname) }
let(:hostname) { "foobar" }
it "should sign the certificate request if one is waiting", :unless => Puppet.features.microsoft_windows? do
subject.generate(hostname, options)
subject.sign(hostname, options)
- host.certificate_request.should be_nil
- host.certificate.should be_a(Puppet::SSL::Certificate)
- host.state.should == 'signed'
+ expect(host.certificate_request).to be_nil
+ expect(host.certificate).to be_a(Puppet::SSL::Certificate)
+ expect(host.state).to eq('signed')
end
it "should fail if there is no waiting certificate request" do
expect do
subject.sign(hostname, options)
end.to raise_error(ArgumentError, /Could not find certificate request for #{hostname}/)
end
describe "when ca_location is local", :unless => Puppet.features.microsoft_windows? do
describe "when the request has dns alt names" do
before :each do
subject.generate(hostname, options.merge(:dns_alt_names => 'some,alt,names'))
end
it "should refuse to sign the request if allow_dns_alt_names is not set" do
expect do
subject.sign(hostname, options)
end.to raise_error(Puppet::SSL::CertificateAuthority::CertificateSigningError,
/CSR '#{hostname}' contains subject alternative names \(.*?\), which are disallowed. Use `puppet cert --allow-dns-alt-names sign #{hostname}` to sign this request./i)
- host.state.should == 'requested'
+ expect(host.state).to eq('requested')
end
it "should sign the request if allow_dns_alt_names is set" do
expect do
subject.sign(hostname, options.merge(:allow_dns_alt_names => true))
end.not_to raise_error
- host.state.should == 'signed'
+ expect(host.state).to eq('signed')
end
end
describe "when the request has no dns alt names" do
before :each do
subject.generate(hostname, options)
end
it "should sign the request if allow_dns_alt_names is set" do
expect { subject.sign(hostname, options.merge(:allow_dns_alt_names => true)) }.not_to raise_error
- host.state.should == 'signed'
+ expect(host.state).to eq('signed')
end
it "should sign the request if allow_dns_alt_names is not set" do
expect { subject.sign(hostname, options) }.not_to raise_error
- host.state.should == 'signed'
+ expect(host.state).to eq('signed')
end
end
end
describe "when ca_location is remote" do
let(:options) { {:ca_location => :remote} }
it "should fail if allow-dns-alt-names is specified" do
expect do
subject.sign(hostname, options.merge(:allow_dns_alt_names => true))
end
end
end
end
end
diff --git a/spec/unit/face/facts_spec.rb b/spec/unit/face/facts_spec.rb
index 853b8ff93..09e823cc6 100755
--- a/spec/unit/face/facts_spec.rb
+++ b/spec/unit/face/facts_spec.rb
@@ -1,9 +1,9 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/face'
describe Puppet::Face[:facts, '0.0.1'] do
describe "#find" do
- it { should be_action :find }
+ it { is_expected.to be_action :find }
end
end
diff --git a/spec/unit/face/file_spec.rb b/spec/unit/face/file_spec.rb
index cef1141ff..2d8526143 100755
--- a/spec/unit/face/file_spec.rb
+++ b/spec/unit/face/file_spec.rb
@@ -1,10 +1,10 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/face'
describe Puppet::Face[:file, '0.0.1'] do
[:download, :store, :find, :info, :save].each do |action|
- it { should be_action action }
- it { should respond_to action }
+ it { is_expected.to be_action action }
+ it { is_expected.to respond_to action }
end
end
diff --git a/spec/unit/face/help_spec.rb b/spec/unit/face/help_spec.rb
index d81031ee3..417b81a72 100755
--- a/spec/unit/face/help_spec.rb
+++ b/spec/unit/face/help_spec.rb
@@ -1,144 +1,145 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/face'
describe Puppet::Face[:help, '0.0.1'] do
it "has a help action" do
- subject.should be_action :help
+ expect(subject).to be_action :help
end
it "has a default action of help" do
- subject.get_action('help').should be_default
+ expect(subject.get_action('help')).to be_default
end
it "accepts a call with no arguments" do
expect {
subject.help()
}.to_not raise_error
end
it "accepts a face name" do
expect { subject.help(:help) }.to_not raise_error
end
it "accepts a face and action name" do
expect { subject.help(:help, :help) }.to_not raise_error
end
it "fails if more than a face and action are given" do
expect { subject.help(:help, :help, :for_the_love_of_god) }.
to raise_error ArgumentError
end
it "treats :current and 'current' identically" do
- subject.help(:help, :version => :current).should ==
+ expect(subject.help(:help, :version => :current)).to eq(
subject.help(:help, :version => 'current')
+ )
end
it "raises an error when the face is unavailable" do
expect {
subject.help(:huzzah, :bar, :version => '17.0.0')
}.to raise_error(ArgumentError, /Could not find version 17\.0\.0/)
end
it "finds a face by version" do
face = Puppet::Face[:huzzah, :current]
- subject.help(:huzzah, :version => face.version).
- should == subject.help(:huzzah, :version => :current)
+ expect(subject.help(:huzzah, :version => face.version)).
+ to eq(subject.help(:huzzah, :version => :current))
end
context "when listing subcommands" do
subject { Puppet::Face[:help, :current].help }
RSpec::Matchers.define :have_a_summary do
match do |instance|
instance.summary.is_a?(String)
end
end
# Check a precondition for the next block; if this fails you have
# something odd in your set of face, and we skip testing things that
# matter. --daniel 2011-04-10
it "has at least one face with a summary" do
- Puppet::Face.faces.should be_any do |name|
+ expect(Puppet::Face.faces).to be_any do |name|
Puppet::Face[name, :current].summary
end
end
it "lists all faces which are runnable from the command line" do
help_face = Puppet::Face[:help, :current]
# The main purpose of the help face is to provide documentation for
# command line users. It shouldn't show documentation for faces
# that can't be run from the command line, so, rather than iterating
# over all available faces, we need to iterate over the subcommands
# that are available from the command line.
Puppet::Application.available_application_names.each do |name|
next unless help_face.is_face_app?(name)
next if help_face.exclude_from_docs?(name)
face = Puppet::Face[name, :current]
summary = face.summary
- subject.should =~ %r{ #{name} }
- summary and subject.should =~ %r{ #{name} +#{summary}}
+ expect(subject).to match(%r{ #{name} })
+ summary and expect(subject).to match(%r{ #{name} +#{summary}})
end
end
context "face summaries" do
it "can generate face summaries" do
faces = Puppet::Face.faces
- faces.length.should > 0
+ expect(faces.length).to be > 0
faces.each do |name|
- Puppet::Face[name, :current].should have_a_summary
+ expect(Puppet::Face[name, :current]).to have_a_summary
end
end
end
it "lists all legacy applications" do
Puppet::Face[:help, :current].legacy_applications.each do |appname|
- subject.should =~ %r{ #{appname} }
+ expect(subject).to match(%r{ #{appname} })
summary = Puppet::Face[:help, :current].horribly_extract_summary_from(appname)
- summary and subject.should =~ %r{ #{summary}\b}
+ summary and expect(subject).to match(%r{ #{summary}\b})
end
end
end
context "#legacy_applications" do
subject { Puppet::Face[:help, :current].legacy_applications }
# If we don't, these tests are ... less than useful, because they assume
# it. When this breaks you should consider ditching the entire feature
# and tests, but if not work out how to fake one. --daniel 2011-04-11
- it { should have_at_least(1).item }
+ it { is_expected.to have_at_least(1).item }
# Meh. This is nasty, but we can't control the other list; the specific
# bug that caused these to be listed is annoyingly subtle and has a nasty
# fix, so better to have a "fail if you do something daft" trigger in
# place here, I think. --daniel 2011-04-11
%w{face_base indirection_base}.each do |name|
- it { should_not include name }
+ it { is_expected.not_to include name }
end
end
context "help for legacy applications" do
subject { Puppet::Face[:help, :current] }
let :appname do subject.legacy_applications.first end
# This test is purposely generic, so that as we eliminate legacy commands
# we don't get into a loop where we either test a face-based replacement
# and fail to notice breakage, or where we have to constantly rewrite this
# test and all. --daniel 2011-04-11
it "returns the legacy help when given the subcommand" do
help = subject.help(appname)
- help.should =~ /puppet-#{appname}/
+ expect(help).to match(/puppet-#{appname}/)
%w{SYNOPSIS USAGE DESCRIPTION OPTIONS COPYRIGHT}.each do |heading|
- help.should =~ /^#{heading}$/
+ expect(help).to match(/^#{heading}$/)
end
end
it "fails when asked for an action on a legacy command" do
expect { subject.help(appname, :whatever) }.
to raise_error ArgumentError, /Legacy subcommands don't take actions/
end
end
end
diff --git a/spec/unit/face/module/list_spec.rb b/spec/unit/face/module/list_spec.rb
index fa7a5521e..a73ac3e61 100644
--- a/spec/unit/face/module/list_spec.rb
+++ b/spec/unit/face/module/list_spec.rb
@@ -1,241 +1,241 @@
# encoding: UTF-8
require 'spec_helper'
require 'puppet/face'
require 'puppet/module_tool'
require 'puppet_spec/modules'
describe "puppet module list" do
include PuppetSpec::Files
around do |example|
dir = tmpdir("deep_path")
FileUtils.mkdir_p(@modpath1 = File.join(dir, "modpath1"))
FileUtils.mkdir_p(@modpath2 = File.join(dir, "modpath2"))
FileUtils.mkdir_p(@modpath3 = File.join(dir, "modpath3"))
env = Puppet::Node::Environment.create(:env, [@modpath1, @modpath2])
Puppet.override(:current_environment => env) do
example.run
end
end
it "should return an empty list per dir in path if there are no modules" do
- Puppet::Face[:module, :current].list[:modules_by_path].should == {
+ expect(Puppet::Face[:module, :current].list[:modules_by_path]).to eq({
@modpath1 => [],
@modpath2 => []
- }
+ })
end
it "should include modules separated by the environment's modulepath" do
foomod1 = PuppetSpec::Modules.create('foo', @modpath1)
barmod1 = PuppetSpec::Modules.create('bar', @modpath1)
foomod2 = PuppetSpec::Modules.create('foo', @modpath2)
usedenv = Puppet::Node::Environment.create(:useme, [@modpath1, @modpath2, @modpath3])
Puppet.override(:environments => Puppet::Environments::Static.new(usedenv)) do
- Puppet::Face[:module, :current].list(:environment => 'useme')[:modules_by_path].should == {
+ expect(Puppet::Face[:module, :current].list(:environment => 'useme')[:modules_by_path]).to eq({
@modpath1 => [
Puppet::Module.new('bar', barmod1.path, usedenv),
Puppet::Module.new('foo', foomod1.path, usedenv)
],
@modpath2 => [Puppet::Module.new('foo', foomod2.path, usedenv)],
@modpath3 => [],
- }
+ })
end
end
it "should use the specified environment" do
foomod = PuppetSpec::Modules.create('foo', @modpath1)
barmod = PuppetSpec::Modules.create('bar', @modpath1)
usedenv = Puppet::Node::Environment.create(:useme, [@modpath1, @modpath2, @modpath3])
Puppet.override(:environments => Puppet::Environments::Static.new(usedenv)) do
- Puppet::Face[:module, :current].list(:environment => 'useme')[:modules_by_path].should == {
+ expect(Puppet::Face[:module, :current].list(:environment => 'useme')[:modules_by_path]).to eq({
@modpath1 => [
Puppet::Module.new('bar', barmod.path, usedenv),
Puppet::Module.new('foo', foomod.path, usedenv)
],
@modpath2 => [],
@modpath3 => [],
- }
+ })
end
end
it "should use the specified modulepath" do
foomod = PuppetSpec::Modules.create('foo', @modpath1)
barmod = PuppetSpec::Modules.create('bar', @modpath2)
modules = Puppet::Face[:module, :current].list(:modulepath => "#{@modpath1}#{File::PATH_SEPARATOR}#{@modpath2}")[:modules_by_path]
expect(modules[@modpath1].first.name).to eq('foo')
expect(modules[@modpath1].first.path).to eq(foomod.path)
expect(modules[@modpath1].first.environment.modulepath).to eq([@modpath1, @modpath2])
expect(modules[@modpath2].first.name).to eq('bar')
expect(modules[@modpath2].first.path).to eq(barmod.path)
expect(modules[@modpath2].first.environment.modulepath).to eq([@modpath1, @modpath2])
end
it "prefers a given modulepath over the modulepath from the given environment" do
foomod = PuppetSpec::Modules.create('foo', @modpath1)
barmod = PuppetSpec::Modules.create('bar', @modpath2)
env = Puppet::Node::Environment.create(:myenv, ['/tmp/notused'])
modules = Puppet::Face[:module, :current].list(:environment => 'myenv', :modulepath => "#{@modpath1}#{File::PATH_SEPARATOR}#{@modpath2}")[:modules_by_path]
expect(modules[@modpath1].first.name).to eq('foo')
expect(modules[@modpath1].first.path).to eq(foomod.path)
expect(modules[@modpath1].first.environment.modulepath).to eq([@modpath1, @modpath2])
expect(modules[@modpath1].first.environment.name).to_not eq(:myenv)
expect(modules[@modpath2].first.name).to eq('bar')
expect(modules[@modpath2].first.path).to eq(barmod.path)
expect(modules[@modpath2].first.environment.modulepath).to eq([@modpath1, @modpath2])
expect(modules[@modpath2].first.environment.name).to_not eq(:myenv)
end
describe "inline documentation" do
subject { Puppet::Face[:module, :current].get_action(:list) }
its(:summary) { should =~ /list.*module/im }
its(:description) { should =~ /list.*module/im }
its(:returns) { should =~ /hash of paths to module objects/i }
its(:examples) { should_not be_empty }
end
describe "when rendering to console" do
let(:face) { Puppet::Face[:module, :current] }
let(:action) { face.get_action(:list) }
def console_output(options={})
result = face.list(options)
action.when_rendering(:console).call(result, options)
end
it "should explicitly state when a modulepath is empty" do
empty_modpath = tmpdir('empty')
expected = <<-HEREDOC.gsub(' ', '')
#{empty_modpath} (no modules installed)
HEREDOC
- console_output(:modulepath => empty_modpath).should == expected
+ expect(console_output(:modulepath => empty_modpath)).to eq(expected)
end
it "should print both modules with and without metadata" do
modpath = tmpdir('modpath')
PuppetSpec::Modules.create('nometadata', modpath)
PuppetSpec::Modules.create('metadata', modpath, :metadata => {:author => 'metaman'})
env = Puppet::Node::Environment.create(:environ, [modpath])
Puppet.override(:current_environment => env) do
expected = <<-HEREDOC.gsub(' ', '')
#{modpath}
├── metaman-metadata (\e[0;36mv9.9.9\e[0m)
└── nometadata (\e[0;36m???\e[0m)
HEREDOC
- console_output.should == expected
+ expect(console_output).to eq(expected)
end
end
it "should print the modulepaths in the order they are in the modulepath setting" do
path1 = tmpdir('b')
path2 = tmpdir('c')
path3 = tmpdir('a')
env = Puppet::Node::Environment.create(:environ, [path1, path2, path3])
Puppet.override(:current_environment => env) do
expected = <<-HEREDOC.gsub(' ', '')
#{path1} (no modules installed)
#{path2} (no modules installed)
#{path3} (no modules installed)
HEREDOC
- console_output.should == expected
+ expect(console_output).to eq(expected)
end
end
it "should print dependencies as a tree" do
PuppetSpec::Modules.create('dependable', @modpath1, :metadata => { :version => '0.0.5'})
PuppetSpec::Modules.create(
'other_mod',
@modpath1,
:metadata => {
:version => '1.0.0',
:dependencies => [{
"version_requirement" => ">= 0.0.5",
"name" => "puppetlabs/dependable"
}]
}
)
expected = <<-HEREDOC.gsub(' ', '')
#{@modpath1}
└─┬ puppetlabs-other_mod (\e[0;36mv1.0.0\e[0m)
└── puppetlabs-dependable (\e[0;36mv0.0.5\e[0m)
#{@modpath2} (no modules installed)
HEREDOC
- console_output(:tree => true).should == expected
+ expect(console_output(:tree => true)).to eq(expected)
end
it "should print both modules with and without metadata as a tree" do
PuppetSpec::Modules.create('nometadata', @modpath1)
PuppetSpec::Modules.create('metadata', @modpath1, :metadata => {:author => 'metaman'})
expected = <<-HEREDOC.gsub(' ', '')
#{@modpath1}
├── metaman-metadata (\e[0;36mv9.9.9\e[0m)
└── nometadata (\e[0;36m???\e[0m)
#{@modpath2} (no modules installed)
HEREDOC
- console_output.should == expected
+ expect(console_output).to eq(expected)
end
it "should warn about missing dependencies" do
PuppetSpec::Modules.create('depender', @modpath1, :metadata => {
:version => '1.0.0',
:dependencies => [{
"version_requirement" => ">= 0.0.5",
"name" => "puppetlabs/dependable"
}]
})
warning_expectations = [
regexp_matches(/Missing dependency 'puppetlabs-dependable'/),
regexp_matches(/'puppetlabs-depender' \(v1\.0\.0\) requires 'puppetlabs-dependable' \(>= 0\.0\.5\)/)
]
Puppet.expects(:warning).with(all_of(*warning_expectations))
console_output(:tree => true)
end
it "should warn about out of range dependencies" do
PuppetSpec::Modules.create('dependable', @modpath1, :metadata => { :version => '0.0.1'})
PuppetSpec::Modules.create('depender', @modpath1, :metadata => {
:version => '1.0.0',
:dependencies => [{
"version_requirement" => ">= 0.0.5",
"name" => "puppetlabs/dependable"
}]
})
warning_expectations = [
regexp_matches(/Module 'puppetlabs-dependable' \(v0\.0\.1\) fails to meet some dependencies/),
regexp_matches(/'puppetlabs-depender' \(v1\.0\.0\) requires 'puppetlabs-dependable' \(>= 0\.0\.5\)/)
]
Puppet.expects(:warning).with(all_of(*warning_expectations))
console_output(:tree => true)
end
end
end
diff --git a/spec/unit/face/module/search_spec.rb b/spec/unit/face/module/search_spec.rb
index 4771bbdc9..0d9df956b 100644
--- a/spec/unit/face/module/search_spec.rb
+++ b/spec/unit/face/module/search_spec.rb
@@ -1,201 +1,201 @@
require 'spec_helper'
require 'puppet/face'
require 'puppet/application/module'
require 'puppet/module_tool'
describe "puppet module search" do
subject { Puppet::Face[:module, :current] }
let(:options) do
{}
end
describe Puppet::Application::Module do
subject do
app = Puppet::Application::Module.new
app.stubs(:action).returns(Puppet::Face.find_action(:module, :search))
app
end
before { subject.render_as = :console }
before { Puppet::Util::Terminal.stubs(:width).returns(100) }
it 'should output nothing when receiving an empty dataset' do
- subject.render({:answers => [], :result => :success}, ['apache', {}]).should == "No results found for 'apache'."
+ expect(subject.render({:answers => [], :result => :success}, ['apache', {}])).to eq("No results found for 'apache'.")
end
it 'should return error and exit when error returned' do
results = {
:result => :failure,
:error => {
:oneline => 'Something failed',
:multiline => 'Something failed',
}
}
expect { subject.render(results, ['apache', {}]) }.to raise_error 'Something failed'
end
it 'should output a header when receiving a non-empty dataset' do
results = {
:result => :success,
:answers => [
{'full_name' => '', 'author' => '', 'desc' => '', 'tag_list' => [] },
],
}
- subject.render(results, ['apache', {}]).should =~ /NAME/
- subject.render(results, ['apache', {}]).should =~ /DESCRIPTION/
- subject.render(results, ['apache', {}]).should =~ /AUTHOR/
- subject.render(results, ['apache', {}]).should =~ /KEYWORDS/
+ expect(subject.render(results, ['apache', {}])).to match(/NAME/)
+ expect(subject.render(results, ['apache', {}])).to match(/DESCRIPTION/)
+ expect(subject.render(results, ['apache', {}])).to match(/AUTHOR/)
+ expect(subject.render(results, ['apache', {}])).to match(/KEYWORDS/)
end
it 'should output the relevant fields when receiving a non-empty dataset' do
results = {
:result => :success,
:answers => [
{'full_name' => 'Name', 'author' => 'Author', 'desc' => 'Summary', 'tag_list' => ['tag1', 'tag2'] },
]
}
- subject.render(results, ['apache', {}]).should =~ /Name/
- subject.render(results, ['apache', {}]).should =~ /Author/
- subject.render(results, ['apache', {}]).should =~ /Summary/
- subject.render(results, ['apache', {}]).should =~ /tag1/
- subject.render(results, ['apache', {}]).should =~ /tag2/
+ expect(subject.render(results, ['apache', {}])).to match(/Name/)
+ expect(subject.render(results, ['apache', {}])).to match(/Author/)
+ expect(subject.render(results, ['apache', {}])).to match(/Summary/)
+ expect(subject.render(results, ['apache', {}])).to match(/tag1/)
+ expect(subject.render(results, ['apache', {}])).to match(/tag2/)
end
it 'should elide really long descriptions' do
results = {
:result => :success,
:answers => [
{
'full_name' => 'Name',
'author' => 'Author',
'desc' => 'This description is really too long to fit in a single data table, guys -- we should probably set about truncating it',
'tag_list' => ['tag1', 'tag2'],
},
]
}
- subject.render(results, ['apache', {}]).should =~ /\.{3} @Author/
+ expect(subject.render(results, ['apache', {}])).to match(/\.{3} @Author/)
end
it 'should never truncate the module name' do
results = {
:result => :success,
:answers => [
{
'full_name' => 'This-module-has-a-really-really-long-name',
'author' => 'Author',
'desc' => 'Description',
'tag_list' => ['tag1', 'tag2'],
},
]
}
- subject.render(results, ['apache', {}]).should =~ /This-module-has-a-really-really-long-name/
+ expect(subject.render(results, ['apache', {}])).to match(/This-module-has-a-really-really-long-name/)
end
it 'should never truncate the author name' do
results = {
:result => :success,
:answers => [
{
'full_name' => 'Name',
'author' => 'This-author-has-a-really-really-long-name',
'desc' => 'Description',
'tag_list' => ['tag1', 'tag2'],
},
]
}
- subject.render(results, ['apache', {}]).should =~ /@This-author-has-a-really-really-long-name/
+ expect(subject.render(results, ['apache', {}])).to match(/@This-author-has-a-really-really-long-name/)
end
it 'should never remove tags that match the search term' do
results = {
:results => :success,
:answers => [
{
'full_name' => 'Name',
'author' => 'Author',
'desc' => 'Description',
'tag_list' => ['Supercalifragilisticexpialidocious'] + (1..100).map { |i| "tag#{i}" },
},
]
}
- subject.render(results, ['Supercalifragilisticexpialidocious', {}]).should =~ /Supercalifragilisticexpialidocious/
- subject.render(results, ['Supercalifragilisticexpialidocious', {}]).should_not =~ /tag/
+ expect(subject.render(results, ['Supercalifragilisticexpialidocious', {}])).to match(/Supercalifragilisticexpialidocious/)
+ expect(subject.render(results, ['Supercalifragilisticexpialidocious', {}])).not_to match(/tag/)
end
{
100 => "NAME DESCRIPTION AUTHOR KEYWORDS#{' '*15}\n"\
"Name This description is really too long to fit ... @JohnnyApples tag1 tag2 taggitty3#{' '*4}\n",
70 => "NAME DESCRIPTION AUTHOR KEYWORDS#{' '*5}\n"\
"Name This description is rea... @JohnnyApples tag1 tag2#{' '*4}\n",
80 => "NAME DESCRIPTION AUTHOR KEYWORDS#{' '*8}\n"\
"Name This description is really too... @JohnnyApples tag1 tag2#{' '*7}\n",
200 => "NAME DESCRIPTION AUTHOR KEYWORDS#{' '*48}\n"\
"Name This description is really too long to fit in a single data table, guys -- we should probably set about trunca... @JohnnyApples tag1 tag2 taggitty3#{' '*37}\n"
}.each do |width, expectation|
it "should resize the table to fit the screen, when #{width} columns" do
results = {
:result => :success,
:answers => [
{
'full_name' => 'Name',
'author' => 'JohnnyApples',
'desc' => 'This description is really too long to fit in a single data table, guys -- we should probably set about truncating it',
'tag_list' => ['tag1', 'tag2', 'taggitty3'],
},
]
}
Puppet::Util::Terminal.expects(:width).returns(width)
result = subject.render(results, ['apache', {}])
- result.lines.sort_by(&:length).last.chomp.length.should <= width
- result.should == expectation
+ expect(result.lines.sort_by(&:length).last.chomp.length).to be <= width
+ expect(result).to eq(expectation)
end
end
end
describe "option validation" do
context "without any options" do
it "should require a search term" do
pattern = /wrong number of arguments/
expect { subject.search }.to raise_error ArgumentError, pattern
end
end
it "should accept the --module-repository option" do
forge = mock("Puppet::Forge")
searcher = mock("Searcher")
options[:module_repository] = "http://forge.example.com"
Puppet::Forge.expects(:new).with().returns(forge)
Puppet::ModuleTool::Applications::Searcher.expects(:new).with("puppetlabs-apache", forge, has_entries(options)).returns(searcher)
searcher.expects(:run)
subject.search("puppetlabs-apache", options)
end
end
describe "inline documentation" do
subject { Puppet::Face[:module, :current].get_action :search }
its(:summary) { should =~ /search.*module/im }
its(:description) { should =~ /search.*module/im }
its(:returns) { should =~ /array/i }
its(:examples) { should_not be_empty }
%w{ license copyright summary description returns examples }.each do |doc|
context "of the" do
its(doc.to_sym) { should_not =~ /(FIXME|REVISIT|TODO)/ }
end
end
end
end
diff --git a/spec/unit/face/node_spec.rb b/spec/unit/face/node_spec.rb
index 2e53c026b..559ce7ef3 100755
--- a/spec/unit/face/node_spec.rb
+++ b/spec/unit/face/node_spec.rb
@@ -1,154 +1,154 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/face'
describe Puppet::Face[:node, '0.0.1'] do
after :all do
Puppet::SSL::Host.ca_location = :none
end
describe '#cleanup' do
it "should clean everything" do
{
"cert" => ['hostname'],
"cached_facts" => ['hostname'],
"cached_node" => ['hostname'],
"reports" => ['hostname'],
}.each { |k, v| subject.expects("clean_#{k}".to_sym).with(*v) }
subject.cleanup('hostname')
end
end
describe 'when running #clean' do
before :each do
Puppet::Node::Facts.indirection.stubs(:terminus_class=)
Puppet::Node::Facts.indirection.stubs(:cache_class=)
Puppet::Node.stubs(:terminus_class=)
Puppet::Node.stubs(:cache_class=)
end
it 'should invoke #cleanup' do
subject.expects(:cleanup).with('hostname', nil)
subject.clean('hostname')
end
end
describe "clean action" do
before :each do
Puppet::Node::Facts.indirection.stubs(:terminus_class=)
Puppet::Node::Facts.indirection.stubs(:cache_class=)
Puppet::Node.stubs(:terminus_class=)
Puppet::Node.stubs(:cache_class=)
subject.stubs(:cleanup)
end
it "should have a clean action" do
- subject.should be_action :clean
+ expect(subject).to be_action :clean
end
it "should not accept a call with no arguments" do
expect { subject.clean() }.to raise_error
end
it "should accept a node name" do
expect { subject.clean('hostname') }.to_not raise_error
end
it "should accept more than one node name" do
expect do
subject.clean('hostname', 'hostname2', {})
end.to_not raise_error
expect do
subject.clean('hostname', 'hostname2', 'hostname3')
end.to_not raise_error
end
context "clean action" do
subject { Puppet::Face[:node, :current] }
before :each do
Puppet::Util::Log.stubs(:newdestination)
Puppet::Util::Log.stubs(:level=)
end
describe "during setup" do
it "should set facts terminus and cache class to yaml" do
Puppet::Node::Facts.indirection.expects(:terminus_class=).with(:yaml)
Puppet::Node::Facts.indirection.expects(:cache_class=).with(:yaml)
subject.clean('hostname')
end
it "should run in master mode" do
subject.clean('hostname')
- Puppet.run_mode.should be_master
+ expect(Puppet.run_mode).to be_master
end
it "should set node cache as yaml" do
Puppet::Node.indirection.expects(:terminus_class=).with(:yaml)
Puppet::Node.indirection.expects(:cache_class=).with(:yaml)
subject.clean('hostname')
end
it "should manage the certs if the host is a CA" do
Puppet::SSL::CertificateAuthority.stubs(:ca?).returns(true)
Puppet::SSL::Host.expects(:ca_location=).with(:local)
subject.clean('hostname')
end
it "should not manage the certs if the host is not a CA" do
Puppet::SSL::CertificateAuthority.stubs(:ca?).returns(false)
Puppet::SSL::Host.expects(:ca_location=).with(:none)
subject.clean('hostname')
end
end
describe "when cleaning certificate" do
before :each do
Puppet::SSL::Host.stubs(:destroy)
@ca = mock()
Puppet::SSL::CertificateAuthority.stubs(:instance).returns(@ca)
end
it "should send the :destroy order to the ca if we are a CA" do
Puppet::SSL::CertificateAuthority.stubs(:ca?).returns(true)
@ca.expects(:revoke).with(@host)
@ca.expects(:destroy).with(@host)
subject.clean_cert(@host)
end
it "should not destroy the certs if we are not a CA" do
Puppet::SSL::CertificateAuthority.stubs(:ca?).returns(false)
@ca.expects(:revoke).never
@ca.expects(:destroy).never
subject.clean_cert(@host)
end
end
describe "when cleaning cached facts" do
it "should destroy facts" do
@host = 'node'
Puppet::Node::Facts.indirection.expects(:destroy).with(@host)
subject.clean_cached_facts(@host)
end
end
describe "when cleaning cached node" do
it "should destroy the cached node" do
Puppet::Node.indirection.expects(:destroy).with(@host)
subject.clean_cached_node(@host)
end
end
describe "when cleaning archived reports" do
it "should tell the reports to remove themselves" do
Puppet::Transaction::Report.indirection.stubs(:destroy).with(@host)
subject.clean_reports(@host)
end
end
end
end
end
diff --git a/spec/unit/face/plugin_spec.rb b/spec/unit/face/plugin_spec.rb
index a417c3adf..2d4b9af66 100755
--- a/spec/unit/face/plugin_spec.rb
+++ b/spec/unit/face/plugin_spec.rb
@@ -1,10 +1,10 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/face'
describe Puppet::Face[:plugin, '0.0.1'] do
[:download].each do |action|
- it { should be_action action }
- it { should respond_to action }
+ it { is_expected.to be_action action }
+ it { is_expected.to respond_to action }
end
end
diff --git a/spec/unit/file_bucket/dipper_spec.rb b/spec/unit/file_bucket/dipper_spec.rb
index f80e048c0..b0b06fd89 100755
--- a/spec/unit/file_bucket/dipper_spec.rb
+++ b/spec/unit/file_bucket/dipper_spec.rb
@@ -1,176 +1,176 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'pathname'
require 'puppet/file_bucket/dipper'
require 'puppet/indirector/file_bucket_file/rest'
require 'puppet/indirector/file_bucket_file/file'
require 'puppet/util/checksums'
shared_examples_for "a restorable file" do
let(:dest) { tmpfile('file_bucket_dest') }
describe "restoring the file" do
with_digest_algorithms do
it "should restore the file" do
request = nil
klass.any_instance.expects(:find).with { |r| request = r }.returns(Puppet::FileBucket::File.new(plaintext))
- dipper.restore(dest, checksum).should == checksum
- digest(Puppet::FileSystem.binread(dest)).should == checksum
+ expect(dipper.restore(dest, checksum)).to eq(checksum)
+ expect(digest(Puppet::FileSystem.binread(dest))).to eq(checksum)
- request.key.should == "#{digest_algorithm}/#{checksum}"
- request.server.should == server
- request.port.should == port
+ expect(request.key).to eq("#{digest_algorithm}/#{checksum}")
+ expect(request.server).to eq(server)
+ expect(request.port).to eq(port)
end
it "should skip restoring if existing file has the same checksum" do
File.open(dest, 'wb') {|f| f.print(plaintext) }
dipper.expects(:getfile).never
- dipper.restore(dest, checksum).should be_nil
+ expect(dipper.restore(dest, checksum)).to be_nil
end
it "should overwrite existing file if it has different checksum" do
klass.any_instance.expects(:find).returns(Puppet::FileBucket::File.new(plaintext))
File.open(dest, 'wb') {|f| f.print('other contents') }
- dipper.restore(dest, checksum).should == checksum
+ expect(dipper.restore(dest, checksum)).to eq(checksum)
end
end
end
end
describe Puppet::FileBucket::Dipper, :uses_checksums => true do
include PuppetSpec::Files
def make_tmp_file(contents)
file = tmpfile("file_bucket_file")
File.open(file, 'wb') { |f| f.write(contents) }
file
end
it "should fail in an informative way when there are failures checking for the file on the server" do
@dipper = Puppet::FileBucket::Dipper.new(:Path => make_absolute("/my/bucket"))
file = make_tmp_file('contents')
Puppet::FileBucket::File.indirection.expects(:head).raises ArgumentError
- lambda { @dipper.backup(file) }.should raise_error(Puppet::Error)
+ expect { @dipper.backup(file) }.to raise_error(Puppet::Error)
end
it "should fail in an informative way when there are failures backing up to the server" do
@dipper = Puppet::FileBucket::Dipper.new(:Path => make_absolute("/my/bucket"))
file = make_tmp_file('contents')
Puppet::FileBucket::File.indirection.expects(:head).returns false
Puppet::FileBucket::File.indirection.expects(:save).raises ArgumentError
- lambda { @dipper.backup(file) }.should raise_error(Puppet::Error)
+ expect { @dipper.backup(file) }.to raise_error(Puppet::Error)
end
describe "backing up and retrieving local files" do
with_digest_algorithms do
it "should backup files to a local bucket" do
Puppet[:bucketdir] = "/non/existent/directory"
file_bucket = tmpdir("bucket")
@dipper = Puppet::FileBucket::Dipper.new(:Path => file_bucket)
file = make_tmp_file(plaintext)
- digest(plaintext).should == checksum
+ expect(digest(plaintext)).to eq(checksum)
- @dipper.backup(file).should == checksum
- Puppet::FileSystem.exist?("#{file_bucket}/#{bucket_dir}/contents").should == true
+ expect(@dipper.backup(file)).to eq(checksum)
+ expect(Puppet::FileSystem.exist?("#{file_bucket}/#{bucket_dir}/contents")).to eq(true)
end
it "should not backup a file that is already in the bucket" do
@dipper = Puppet::FileBucket::Dipper.new(:Path => "/my/bucket")
file = make_tmp_file(plaintext)
Puppet::FileBucket::File.indirection.expects(:head).returns true
Puppet::FileBucket::File.indirection.expects(:save).never
- @dipper.backup(file).should == checksum
+ expect(@dipper.backup(file)).to eq(checksum)
end
it "should retrieve files from a local bucket" do
@dipper = Puppet::FileBucket::Dipper.new(:Path => "/my/bucket")
request = nil
Puppet::FileBucketFile::File.any_instance.expects(:find).with{ |r| request = r }.once.returns(Puppet::FileBucket::File.new(plaintext))
- @dipper.getfile(checksum).should == plaintext
+ expect(@dipper.getfile(checksum)).to eq(plaintext)
- request.key.should == "#{digest_algorithm}/#{checksum}"
+ expect(request.key).to eq("#{digest_algorithm}/#{checksum}")
end
end
end
describe "backing up and retrieving remote files" do
with_digest_algorithms do
it "should backup files to a remote server" do
@dipper = Puppet::FileBucket::Dipper.new(:Server => "puppetmaster", :Port => "31337")
file = make_tmp_file(plaintext)
real_path = Pathname.new(file).realpath
request1 = nil
request2 = nil
Puppet::FileBucketFile::Rest.any_instance.expects(:head).with { |r| request1 = r }.once.returns(nil)
Puppet::FileBucketFile::Rest.any_instance.expects(:save).with { |r| request2 = r }.once
- @dipper.backup(file).should == checksum
+ expect(@dipper.backup(file)).to eq(checksum)
[request1, request2].each do |r|
- r.server.should == 'puppetmaster'
- r.port.should == 31337
- r.key.should == "#{digest_algorithm}/#{checksum}/#{real_path}"
+ expect(r.server).to eq('puppetmaster')
+ expect(r.port).to eq(31337)
+ expect(r.key).to eq("#{digest_algorithm}/#{checksum}/#{real_path}")
end
end
it "should retrieve files from a remote server" do
@dipper = Puppet::FileBucket::Dipper.new(:Server => "puppetmaster", :Port => "31337")
request = nil
Puppet::FileBucketFile::Rest.any_instance.expects(:find).with { |r| request = r }.returns(Puppet::FileBucket::File.new(plaintext))
- @dipper.getfile(checksum).should == plaintext
+ expect(@dipper.getfile(checksum)).to eq(plaintext)
- request.server.should == 'puppetmaster'
- request.port.should == 31337
- request.key.should == "#{digest_algorithm}/#{checksum}"
+ expect(request.server).to eq('puppetmaster')
+ expect(request.port).to eq(31337)
+ expect(request.key).to eq("#{digest_algorithm}/#{checksum}")
end
end
end
describe "#restore" do
describe "when restoring from a remote server" do
let(:klass) { Puppet::FileBucketFile::Rest }
let(:server) { "puppetmaster" }
let(:port) { 31337 }
it_behaves_like "a restorable file" do
let (:dipper) { Puppet::FileBucket::Dipper.new(:Server => server, :Port => port.to_s) }
end
end
describe "when restoring from a local server" do
let(:klass) { Puppet::FileBucketFile::File }
let(:server) { nil }
let(:port) { nil }
it_behaves_like "a restorable file" do
let (:dipper) { Puppet::FileBucket::Dipper.new(:Path => "/my/bucket") }
end
end
end
end
diff --git a/spec/unit/file_bucket/file_spec.rb b/spec/unit/file_bucket/file_spec.rb
index 9b4e440b6..c3033a505 100755
--- a/spec/unit/file_bucket/file_spec.rb
+++ b/spec/unit/file_bucket/file_spec.rb
@@ -1,60 +1,60 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_bucket/file'
describe Puppet::FileBucket::File, :uses_checksums => true do
include PuppetSpec::Files
# this is the default from spec_helper, but it keeps getting reset at odd times
let(:bucketdir) { Puppet[:bucketdir] = tmpdir('bucket') }
it "defaults to serializing to `:s`" do
expect(Puppet::FileBucket::File.default_format).to eq(:s)
end
it "accepts s" do
expect(Puppet::FileBucket::File.supported_formats).to include(:s)
end
describe "making round trips through network formats" do
with_digest_algorithms do
it "can make a round trip through `s`" do
file = Puppet::FileBucket::File.new(plaintext)
tripped = Puppet::FileBucket::File.convert_from(:s, file.render)
expect(tripped.contents).to eq(plaintext)
end
end
end
it "should require contents to be a string" do
expect { Puppet::FileBucket::File.new(5) }.to raise_error(ArgumentError, /contents must be a String or Pathname, got a Fixnum$/)
end
it "should complain about options other than :bucket_path" do
expect {
Puppet::FileBucket::File.new('5', :crazy_option => 'should not be passed')
}.to raise_error(ArgumentError, /Unknown option\(s\): crazy_option/)
end
with_digest_algorithms do
it "it uses #{metadata[:digest_algorithm]} as the configured digest algorithm" do
file = Puppet::FileBucket::File.new(plaintext)
- file.contents.should == plaintext
- file.checksum_type.should == digest_algorithm
- file.checksum.should == "{#{digest_algorithm}}#{checksum}"
- file.name.should == "#{digest_algorithm}/#{checksum}"
+ expect(file.contents).to eq(plaintext)
+ expect(file.checksum_type).to eq(digest_algorithm)
+ expect(file.checksum).to eq("{#{digest_algorithm}}#{checksum}")
+ expect(file.name).to eq("#{digest_algorithm}/#{checksum}")
end
end
describe "when using back-ends" do
it "should redirect using Puppet::Indirector" do
- Puppet::Indirector::Indirection.instance(:file_bucket_file).model.should equal(Puppet::FileBucket::File)
+ expect(Puppet::Indirector::Indirection.instance(:file_bucket_file).model).to equal(Puppet::FileBucket::File)
end
it "should have a :save instance method" do
- Puppet::FileBucket::File.indirection.should respond_to(:save)
+ expect(Puppet::FileBucket::File.indirection).to respond_to(:save)
end
end
end
diff --git a/spec/unit/file_serving/base_spec.rb b/spec/unit/file_serving/base_spec.rb
index 5b9794211..47cd6ad2f 100755
--- a/spec/unit/file_serving/base_spec.rb
+++ b/spec/unit/file_serving/base_spec.rb
@@ -1,168 +1,168 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_serving/base'
describe Puppet::FileServing::Base do
let(:path) { File.expand_path('/module/dir/file') }
let(:file) { File.expand_path('/my/file') }
it "should accept a path" do
- Puppet::FileServing::Base.new(path).path.should == path
+ expect(Puppet::FileServing::Base.new(path).path).to eq(path)
end
it "should require that paths be fully qualified" do
- lambda { Puppet::FileServing::Base.new("module/dir/file") }.should raise_error(ArgumentError)
+ expect { Puppet::FileServing::Base.new("module/dir/file") }.to raise_error(ArgumentError)
end
it "should allow specification of whether links should be managed" do
- Puppet::FileServing::Base.new(path, :links => :manage).links.should == :manage
+ expect(Puppet::FileServing::Base.new(path, :links => :manage).links).to eq(:manage)
end
it "should have a :source attribute" do
file = Puppet::FileServing::Base.new(path)
- file.should respond_to(:source)
- file.should respond_to(:source=)
+ expect(file).to respond_to(:source)
+ expect(file).to respond_to(:source=)
end
it "should consider :ignore links equivalent to :manage links" do
- Puppet::FileServing::Base.new(path, :links => :ignore).links.should == :manage
+ expect(Puppet::FileServing::Base.new(path, :links => :ignore).links).to eq(:manage)
end
it "should fail if :links is set to anything other than :manage, :follow, or :ignore" do
- proc { Puppet::FileServing::Base.new(path, :links => :else) }.should raise_error(ArgumentError)
+ expect { Puppet::FileServing::Base.new(path, :links => :else) }.to raise_error(ArgumentError)
end
it "should allow links values to be set as strings" do
- Puppet::FileServing::Base.new(path, :links => "follow").links.should == :follow
+ expect(Puppet::FileServing::Base.new(path, :links => "follow").links).to eq(:follow)
end
it "should default to :manage for :links" do
- Puppet::FileServing::Base.new(path).links.should == :manage
+ expect(Puppet::FileServing::Base.new(path).links).to eq(:manage)
end
it "should allow specification of a path" do
Puppet::FileSystem.stubs(:exist?).returns(true)
- Puppet::FileServing::Base.new(path, :path => file).path.should == file
+ expect(Puppet::FileServing::Base.new(path, :path => file).path).to eq(file)
end
it "should allow specification of a relative path" do
Puppet::FileSystem.stubs(:exist?).returns(true)
- Puppet::FileServing::Base.new(path, :relative_path => "my/file").relative_path.should == "my/file"
+ expect(Puppet::FileServing::Base.new(path, :relative_path => "my/file").relative_path).to eq("my/file")
end
it "should have a means of determining if the file exists" do
- Puppet::FileServing::Base.new(file).should respond_to(:exist?)
+ expect(Puppet::FileServing::Base.new(file)).to respond_to(:exist?)
end
it "should correctly indicate if the file is present" do
Puppet::FileSystem.expects(:lstat).with(file).returns stub('stat')
- Puppet::FileServing::Base.new(file).exist?.should be_true
+ expect(Puppet::FileServing::Base.new(file).exist?).to be_truthy
end
it "should correctly indicate if the file is absent" do
Puppet::FileSystem.expects(:lstat).with(file).raises RuntimeError
- Puppet::FileServing::Base.new(file).exist?.should be_false
+ expect(Puppet::FileServing::Base.new(file).exist?).to be_falsey
end
describe "when setting the relative path" do
it "should require that the relative path be unqualified" do
@file = Puppet::FileServing::Base.new(path)
Puppet::FileSystem.stubs(:exist?).returns(true)
- proc { @file.relative_path = File.expand_path("/qualified/file") }.should raise_error(ArgumentError)
+ expect { @file.relative_path = File.expand_path("/qualified/file") }.to raise_error(ArgumentError)
end
end
describe "when determining the full file path" do
let(:path) { File.expand_path('/this/file') }
let(:file) { Puppet::FileServing::Base.new(path) }
it "should return the path if there is no relative path" do
- file.full_path.should == path
+ expect(file.full_path).to eq(path)
end
it "should return the path if the relative_path is set to ''" do
file.relative_path = ""
- file.full_path.should == path
+ expect(file.full_path).to eq(path)
end
it "should return the path if the relative_path is set to '.'" do
file.relative_path = "."
- file.full_path.should == path
+ expect(file.full_path).to eq(path)
end
it "should return the path joined with the relative path if there is a relative path and it is not set to '/' or ''" do
file.relative_path = "not/qualified"
- file.full_path.should == File.join(path, "not/qualified")
+ expect(file.full_path).to eq(File.join(path, "not/qualified"))
end
it "should strip extra slashes" do
file = Puppet::FileServing::Base.new(File.join(File.expand_path('/'), "//this//file"))
- file.full_path.should == path
+ expect(file.full_path).to eq(path)
end
end
describe "when handling a UNC file path on Windows" do
let(:path) { '//server/share/filename' }
let(:file) { Puppet::FileServing::Base.new(path) }
it "should preserve double slashes at the beginning of the path" do
Puppet.features.stubs(:microsoft_windows?).returns(true)
- file.full_path.should == path
+ expect(file.full_path).to eq(path)
end
it "should strip double slashes not at the beginning of the path" do
Puppet.features.stubs(:microsoft_windows?).returns(true)
file = Puppet::FileServing::Base.new('//server//share//filename')
- file.full_path.should == path
+ expect(file.full_path).to eq(path)
end
end
describe "when stat'ing files" do
let(:path) { File.expand_path('/this/file') }
let(:file) { Puppet::FileServing::Base.new(path) }
let(:stat) { stub('stat', :ftype => 'file' ) }
let(:stubbed_file) { stub(path, :stat => stat, :lstat => stat)}
it "should stat the file's full path" do
Puppet::FileSystem.expects(:lstat).with(path).returns stat
file.stat
end
it "should fail if the file does not exist" do
Puppet::FileSystem.expects(:lstat).with(path).raises(Errno::ENOENT)
- proc { file.stat }.should raise_error(Errno::ENOENT)
+ expect { file.stat }.to raise_error(Errno::ENOENT)
end
it "should use :lstat if :links is set to :manage" do
Puppet::FileSystem.expects(:lstat).with(path).returns stubbed_file
file.stat
end
it "should use :stat if :links is set to :follow" do
Puppet::FileSystem.expects(:stat).with(path).returns stubbed_file
file.links = :follow
file.stat
end
end
describe "#absolute?" do
it "should be accept POSIX paths" do
- Puppet::FileServing::Base.should be_absolute('/')
+ expect(Puppet::FileServing::Base).to be_absolute('/')
end
it "should accept Windows paths on Windows" do
Puppet.features.stubs(:microsoft_windows?).returns(true)
Puppet.features.stubs(:posix?).returns(false)
- Puppet::FileServing::Base.should be_absolute('c:/foo')
+ expect(Puppet::FileServing::Base).to be_absolute('c:/foo')
end
it "should reject Windows paths on POSIX" do
Puppet.features.stubs(:microsoft_windows?).returns(false)
- Puppet::FileServing::Base.should_not be_absolute('c:/foo')
+ expect(Puppet::FileServing::Base).not_to be_absolute('c:/foo')
end
end
end
diff --git a/spec/unit/file_serving/configuration/parser_spec.rb b/spec/unit/file_serving/configuration/parser_spec.rb
index d9d712999..c8a3802db 100755
--- a/spec/unit/file_serving/configuration/parser_spec.rb
+++ b/spec/unit/file_serving/configuration/parser_spec.rb
@@ -1,186 +1,186 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_serving/configuration/parser'
module FSConfigurationParserTesting
def write_config_file(content)
# We want an array, but we actually want our carriage returns on all of it.
File.open(@path, 'w') {|f| f.puts content}
end
end
describe Puppet::FileServing::Configuration::Parser do
include PuppetSpec::Files
before :each do
@path = tmpfile('fileserving_config')
FileUtils.touch(@path)
@parser = Puppet::FileServing::Configuration::Parser.new(@path)
end
describe Puppet::FileServing::Configuration::Parser, " when parsing" do
include FSConfigurationParserTesting
it "should allow comments" do
write_config_file("# this is a comment\n")
- proc { @parser.parse }.should_not raise_error
+ expect { @parser.parse }.not_to raise_error
end
it "should allow blank lines" do
write_config_file("\n")
- proc { @parser.parse }.should_not raise_error
+ expect { @parser.parse }.not_to raise_error
end
it "should create a new mount for each section in the configuration" do
mount1 = mock 'one', :validate => true
mount2 = mock 'two', :validate => true
Puppet::FileServing::Mount::File.expects(:new).with("one").returns(mount1)
Puppet::FileServing::Mount::File.expects(:new).with("two").returns(mount2)
write_config_file "[one]\n[two]\n"
@parser.parse
end
# This test is almost the exact same as the previous one.
it "should return a hash of the created mounts" do
mount1 = mock 'one', :validate => true
mount2 = mock 'two', :validate => true
Puppet::FileServing::Mount::File.expects(:new).with("one").returns(mount1)
Puppet::FileServing::Mount::File.expects(:new).with("two").returns(mount2)
write_config_file "[one]\n[two]\n"
result = @parser.parse
- result["one"].should equal(mount1)
- result["two"].should equal(mount2)
+ expect(result["one"]).to equal(mount1)
+ expect(result["two"]).to equal(mount2)
end
it "should only allow mount names that are alphanumeric plus dashes" do
write_config_file "[a*b]\n"
- proc { @parser.parse }.should raise_error(ArgumentError)
+ expect { @parser.parse }.to raise_error(ArgumentError)
end
it "should fail if the value for path/allow/deny starts with an equals sign" do
write_config_file "[one]\npath = /testing"
- proc { @parser.parse }.should raise_error(ArgumentError)
+ expect { @parser.parse }.to raise_error(ArgumentError)
end
it "should validate each created mount" do
mount1 = mock 'one'
Puppet::FileServing::Mount::File.expects(:new).with("one").returns(mount1)
write_config_file "[one]\n"
mount1.expects(:validate)
@parser.parse
end
it "should fail if any mount does not pass validation" do
mount1 = mock 'one'
Puppet::FileServing::Mount::File.expects(:new).with("one").returns(mount1)
write_config_file "[one]\n"
mount1.expects(:validate).raises RuntimeError
- lambda { @parser.parse }.should raise_error(RuntimeError)
+ expect { @parser.parse }.to raise_error(RuntimeError)
end
it "should return comprehensible error message, if invalid line detected" do
write_config_file "[one]\n\n\x01path /etc/puppet/files\n\x01allow *\n"
- proc { @parser.parse }.should raise_error(ArgumentError, /Invalid line.*in.*, line 3/)
+ expect { @parser.parse }.to raise_error(ArgumentError, /Invalid line.*in.*, line 3/)
end
end
describe Puppet::FileServing::Configuration::Parser, " when parsing mount attributes" do
include FSConfigurationParserTesting
before do
@mount = stub 'testmount', :name => "one", :validate => true
Puppet::FileServing::Mount::File.expects(:new).with("one").returns(@mount)
@parser.stubs(:add_modules_mount)
end
it "should set the mount path to the path attribute from that section" do
write_config_file "[one]\npath /some/path\n"
@mount.expects(:path=).with("/some/path")
@parser.parse
end
it "should tell the mount to allow any allow values from the section" do
write_config_file "[one]\nallow something\n"
@mount.expects(:info)
@mount.expects(:allow).with("something")
@parser.parse
end
it "should support inline comments" do
write_config_file "[one]\nallow something \# will it work?\n"
@mount.expects(:info)
@mount.expects(:allow).with("something")
@parser.parse
end
it "should tell the mount to deny any deny values from the section" do
write_config_file "[one]\ndeny something\n"
@mount.expects(:info)
@mount.expects(:deny).with("something")
@parser.parse
end
it "should return comprehensible error message, if failed on invalid attribute" do
write_config_file "[one]\ndo something\n"
- proc { @parser.parse }.should raise_error(ArgumentError, /Invalid argument 'do' in .*, line 2/)
+ expect { @parser.parse }.to raise_error(ArgumentError, /Invalid argument 'do' in .*, line 2/)
end
end
describe Puppet::FileServing::Configuration::Parser, " when parsing the modules mount" do
include FSConfigurationParserTesting
before do
@mount = stub 'modulesmount', :name => "modules", :validate => true
end
it "should create an instance of the Modules Mount class" do
write_config_file "[modules]\n"
Puppet::FileServing::Mount::Modules.expects(:new).with("modules").returns @mount
@parser.parse
end
it "should warn if a path is set" do
write_config_file "[modules]\npath /some/path\n"
Puppet::FileServing::Mount::Modules.expects(:new).with("modules").returns(@mount)
Puppet.expects(:warning)
@parser.parse
end
end
describe Puppet::FileServing::Configuration::Parser, " when parsing the plugins mount" do
include FSConfigurationParserTesting
before do
@mount = stub 'pluginsmount', :name => "plugins", :validate => true
end
it "should create an instance of the Plugins Mount class" do
write_config_file "[plugins]\n"
Puppet::FileServing::Mount::Plugins.expects(:new).with("plugins").returns @mount
@parser.parse
end
it "should warn if a path is set" do
write_config_file "[plugins]\npath /some/path\n"
Puppet.expects(:warning)
@parser.parse
end
end
end
diff --git a/spec/unit/file_serving/configuration_spec.rb b/spec/unit/file_serving/configuration_spec.rb
index a2c808051..f006d49ea 100755
--- a/spec/unit/file_serving/configuration_spec.rb
+++ b/spec/unit/file_serving/configuration_spec.rb
@@ -1,231 +1,231 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_serving/configuration'
describe Puppet::FileServing::Configuration do
include PuppetSpec::Files
before :each do
@path = make_absolute("/path/to/configuration/file.conf")
Puppet[:trace] = false
Puppet[:fileserverconfig] = @path
end
after :each do
Puppet::FileServing::Configuration.instance_variable_set(:@configuration, nil)
end
it "should make :new a private method" do
expect { Puppet::FileServing::Configuration.new }.to raise_error
end
it "should return the same configuration each time 'configuration' is called" do
- Puppet::FileServing::Configuration.configuration.should equal(Puppet::FileServing::Configuration.configuration)
+ expect(Puppet::FileServing::Configuration.configuration).to equal(Puppet::FileServing::Configuration.configuration)
end
describe "when initializing" do
it "should work without a configuration file" do
Puppet::FileSystem.stubs(:exist?).with(@path).returns(false)
expect { Puppet::FileServing::Configuration.configuration }.to_not raise_error
end
it "should parse the configuration file if present" do
Puppet::FileSystem.stubs(:exist?).with(@path).returns(true)
@parser = mock 'parser'
@parser.expects(:parse).returns({})
Puppet::FileServing::Configuration::Parser.stubs(:new).returns(@parser)
Puppet::FileServing::Configuration.configuration
end
it "should determine the path to the configuration file from the Puppet settings" do
Puppet::FileServing::Configuration.configuration
end
end
describe "when parsing the configuration file" do
before do
Puppet::FileSystem.stubs(:exist?).with(@path).returns(true)
@parser = mock 'parser'
Puppet::FileServing::Configuration::Parser.stubs(:new).returns(@parser)
end
it "should set the mount list to the results of parsing" do
@parser.expects(:parse).returns("one" => mock("mount"))
config = Puppet::FileServing::Configuration.configuration
- config.mounted?("one").should be_true
+ expect(config.mounted?("one")).to be_truthy
end
it "should not raise exceptions" do
@parser.expects(:parse).raises(ArgumentError)
expect { Puppet::FileServing::Configuration.configuration }.to_not raise_error
end
it "should replace the existing mount list with the results of reparsing" do
@parser.expects(:parse).returns("one" => mock("mount"))
config = Puppet::FileServing::Configuration.configuration
- config.mounted?("one").should be_true
+ expect(config.mounted?("one")).to be_truthy
# Now parse again
@parser.expects(:parse).returns("two" => mock('other'))
config.send(:readconfig, false)
- config.mounted?("one").should be_false
- config.mounted?("two").should be_true
+ expect(config.mounted?("one")).to be_falsey
+ expect(config.mounted?("two")).to be_truthy
end
it "should not replace the mount list until the file is entirely parsed successfully" do
@parser.expects(:parse).returns("one" => mock("mount"))
@parser.expects(:parse).raises(ArgumentError)
config = Puppet::FileServing::Configuration.configuration
# Now parse again, so the exception gets thrown
config.send(:readconfig, false)
- config.mounted?("one").should be_true
+ expect(config.mounted?("one")).to be_truthy
end
it "should add modules and plugins mounts even if the file does not exist" do
Puppet::FileSystem.expects(:exist?).returns false # the file doesn't exist
config = Puppet::FileServing::Configuration.configuration
- config.mounted?("modules").should be_true
- config.mounted?("plugins").should be_true
+ expect(config.mounted?("modules")).to be_truthy
+ expect(config.mounted?("plugins")).to be_truthy
end
it "should allow all access to modules and plugins if no fileserver.conf exists" do
Puppet::FileSystem.expects(:exist?).returns false # the file doesn't exist
modules = stub 'modules', :empty? => true
Puppet::FileServing::Mount::Modules.stubs(:new).returns(modules)
modules.expects(:allow).with('*')
plugins = stub 'plugins', :empty? => true
Puppet::FileServing::Mount::Plugins.stubs(:new).returns(plugins)
plugins.expects(:allow).with('*')
Puppet::FileServing::Configuration.configuration
end
it "should not allow access from all to modules and plugins if the fileserver.conf provided some rules" do
Puppet::FileSystem.expects(:exist?).returns false # the file doesn't exist
modules = stub 'modules', :empty? => false
Puppet::FileServing::Mount::Modules.stubs(:new).returns(modules)
modules.expects(:allow).with('*').never
plugins = stub 'plugins', :empty? => false
Puppet::FileServing::Mount::Plugins.stubs(:new).returns(plugins)
plugins.expects(:allow).with('*').never
Puppet::FileServing::Configuration.configuration
end
it "should add modules and plugins mounts even if they are not returned by the parser" do
@parser.expects(:parse).returns("one" => mock("mount"))
Puppet::FileSystem.expects(:exist?).returns true # the file doesn't exist
config = Puppet::FileServing::Configuration.configuration
- config.mounted?("modules").should be_true
- config.mounted?("plugins").should be_true
+ expect(config.mounted?("modules")).to be_truthy
+ expect(config.mounted?("plugins")).to be_truthy
end
end
describe "when finding the specified mount" do
it "should choose the named mount if one exists" do
config = Puppet::FileServing::Configuration.configuration
config.expects(:mounts).returns("one" => "foo")
- config.find_mount("one", mock('env')).should == "foo"
+ expect(config.find_mount("one", mock('env'))).to eq("foo")
end
it "should return nil if there is no such named mount" do
config = Puppet::FileServing::Configuration.configuration
env = mock 'environment'
mount = mock 'mount'
config.stubs(:mounts).returns("modules" => mount)
- config.find_mount("foo", env).should be_nil
+ expect(config.find_mount("foo", env)).to be_nil
end
end
describe "#split_path" do
let(:config) { Puppet::FileServing::Configuration.configuration }
let(:request) { stub 'request', :key => "foo/bar/baz", :options => {}, :node => nil, :environment => mock("env") }
before do
config.stubs(:find_mount)
end
it "should reread the configuration" do
config.expects(:readconfig)
config.split_path(request)
end
it "should treat the first field of the URI path as the mount name" do
config.expects(:find_mount).with { |name, node| name == "foo" }
config.split_path(request)
end
it "should fail if the mount name is not alpha-numeric" do
request.expects(:key).returns "foo&bar/asdf"
expect { config.split_path(request) }.to raise_error(ArgumentError)
end
it "should support dashes in the mount name" do
request.expects(:key).returns "foo-bar/asdf"
expect { config.split_path(request) }.to_not raise_error
end
it "should use the mount name and environment to find the mount" do
config.expects(:find_mount).with { |name, env| name == "foo" and env == request.environment }
request.stubs(:node).returns("mynode")
config.split_path(request)
end
it "should return nil if the mount cannot be found" do
config.expects(:find_mount).returns nil
- config.split_path(request).should be_nil
+ expect(config.split_path(request)).to be_nil
end
it "should return the mount and the relative path if the mount is found" do
mount = stub 'mount', :name => "foo"
config.expects(:find_mount).returns mount
- config.split_path(request).should == [mount, "bar/baz"]
+ expect(config.split_path(request)).to eq([mount, "bar/baz"])
end
it "should remove any double slashes" do
request.stubs(:key).returns "foo/bar//baz"
mount = stub 'mount', :name => "foo"
config.expects(:find_mount).returns mount
- config.split_path(request).should == [mount, "bar/baz"]
+ expect(config.split_path(request)).to eq([mount, "bar/baz"])
end
it "should fail if the path contains .." do
request.stubs(:key).returns 'module/foo/../../bar'
expect do
config.split_path(request)
end.to raise_error(ArgumentError, /Invalid relative path/)
end
it "should return the relative path as nil if it is an empty string" do
request.expects(:key).returns "foo"
mount = stub 'mount', :name => "foo"
config.expects(:find_mount).returns mount
- config.split_path(request).should == [mount, nil]
+ expect(config.split_path(request)).to eq([mount, nil])
end
it "should add 'modules/' to the relative path if the modules mount is used but not specified, for backward compatibility" do
request.expects(:key).returns "foo/bar"
mount = stub 'mount', :name => "modules"
config.expects(:find_mount).returns mount
- config.split_path(request).should == [mount, "foo/bar"]
+ expect(config.split_path(request)).to eq([mount, "foo/bar"])
end
end
end
diff --git a/spec/unit/file_serving/content_spec.rb b/spec/unit/file_serving/content_spec.rb
index 168ef9292..079902b42 100755
--- a/spec/unit/file_serving/content_spec.rb
+++ b/spec/unit/file_serving/content_spec.rb
@@ -1,112 +1,112 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_serving/content'
describe Puppet::FileServing::Content do
let(:path) { File.expand_path('/path') }
it "should be a subclass of Base" do
- Puppet::FileServing::Content.superclass.should equal(Puppet::FileServing::Base)
+ expect(Puppet::FileServing::Content.superclass).to equal(Puppet::FileServing::Base)
end
it "should indirect file_content" do
- Puppet::FileServing::Content.indirection.name.should == :file_content
+ expect(Puppet::FileServing::Content.indirection.name).to eq(:file_content)
end
it "should only support the raw format" do
- Puppet::FileServing::Content.supported_formats.should == [:raw]
+ expect(Puppet::FileServing::Content.supported_formats).to eq([:raw])
end
it "should have a method for collecting its attributes" do
- Puppet::FileServing::Content.new(path).should respond_to(:collect)
+ expect(Puppet::FileServing::Content.new(path)).to respond_to(:collect)
end
it "should not retrieve and store its contents when its attributes are collected if the file is a normal file" do
content = Puppet::FileServing::Content.new(path)
result = "foo"
Puppet::FileSystem.expects(:lstat).with(path).returns stub('stat', :ftype => "file")
File.expects(:read).with(path).never
content.collect
- content.instance_variable_get("@content").should be_nil
+ expect(content.instance_variable_get("@content")).to be_nil
end
it "should not attempt to retrieve its contents if the file is a directory" do
content = Puppet::FileServing::Content.new(path)
result = "foo"
Puppet::FileSystem.expects(:lstat).with(path).returns stub('stat', :ftype => "directory")
File.expects(:read).with(path).never
content.collect
- content.instance_variable_get("@content").should be_nil
+ expect(content.instance_variable_get("@content")).to be_nil
end
it "should have a method for setting its content" do
content = Puppet::FileServing::Content.new(path)
- content.should respond_to(:content=)
+ expect(content).to respond_to(:content=)
end
it "should make content available when set externally" do
content = Puppet::FileServing::Content.new(path)
content.content = "foo/bar"
- content.content.should == "foo/bar"
+ expect(content.content).to eq("foo/bar")
end
it "should be able to create a content instance from raw file contents" do
- Puppet::FileServing::Content.should respond_to(:from_raw)
+ expect(Puppet::FileServing::Content).to respond_to(:from_raw)
end
it "should create an instance with a fake file name and correct content when converting from raw" do
instance = mock 'instance'
Puppet::FileServing::Content.expects(:new).with("/this/is/a/fake/path").returns instance
instance.expects(:content=).with "foo/bar"
- Puppet::FileServing::Content.from_raw("foo/bar").should equal(instance)
+ expect(Puppet::FileServing::Content.from_raw("foo/bar")).to equal(instance)
end
it "should return an opened File when converted to raw" do
content = Puppet::FileServing::Content.new(path)
File.expects(:new).with(path, "rb").returns :file
- content.to_raw.should == :file
+ expect(content.to_raw).to eq(:file)
end
end
describe Puppet::FileServing::Content, "when returning the contents" do
let(:path) { File.expand_path('/my/path') }
let(:content) { Puppet::FileServing::Content.new(path, :links => :follow) }
it "should fail if the file is a symlink and links are set to :manage" do
content.links = :manage
Puppet::FileSystem.expects(:lstat).with(path).returns stub("stat", :ftype => "symlink")
- proc { content.content }.should raise_error(ArgumentError)
+ expect { content.content }.to raise_error(ArgumentError)
end
it "should fail if a path is not set" do
- proc { content.content }.should raise_error(Errno::ENOENT)
+ expect { content.content }.to raise_error(Errno::ENOENT)
end
it "should raise Errno::ENOENT if the file is absent" do
content.path = File.expand_path("/there/is/absolutely/no/chance/that/this/path/exists")
- proc { content.content }.should raise_error(Errno::ENOENT)
+ expect { content.content }.to raise_error(Errno::ENOENT)
end
it "should return the contents of the path if the file exists" do
Puppet::FileSystem.expects(:stat).with(path).returns(stub('stat', :ftype => 'file'))
Puppet::FileSystem.expects(:binread).with(path).returns(:mycontent)
- content.content.should == :mycontent
+ expect(content.content).to eq(:mycontent)
end
it "should cache the returned contents" do
Puppet::FileSystem.expects(:stat).with(path).returns(stub('stat', :ftype => 'file'))
Puppet::FileSystem.expects(:binread).with(path).returns(:mycontent)
content.content
# The second run would throw a failure if the content weren't being cached.
content.content
end
end
diff --git a/spec/unit/file_serving/fileset_spec.rb b/spec/unit/file_serving/fileset_spec.rb
index e4df5c93d..bd5809604 100755
--- a/spec/unit/file_serving/fileset_spec.rb
+++ b/spec/unit/file_serving/fileset_spec.rb
@@ -1,354 +1,353 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_serving/fileset'
describe Puppet::FileServing::Fileset do
include PuppetSpec::Files
let(:somefile) { make_absolute("/some/file") }
context "when initializing" do
it "requires a path" do
expect { Puppet::FileServing::Fileset.new }.to raise_error(ArgumentError)
end
it "fails if its path is not fully qualified" do
expect { Puppet::FileServing::Fileset.new("some/file") }.to raise_error(ArgumentError, "Fileset paths must be fully qualified: some/file")
end
it "removes a trailing file path separator" do
path_with_separator = "#{somefile}#{File::SEPARATOR}"
Puppet::FileSystem.expects(:lstat).with(somefile).returns stub('stat')
fileset = Puppet::FileServing::Fileset.new(path_with_separator)
- fileset.path.should == somefile
+ expect(fileset.path).to eq(somefile)
end
it "can be created from the root directory" do
path = File.expand_path(File::SEPARATOR)
Puppet::FileSystem.expects(:lstat).with(path).returns stub('stat')
fileset = Puppet::FileServing::Fileset.new(path)
- fileset.path.should == path
+ expect(fileset.path).to eq(path)
end
it "fails if its path does not exist" do
Puppet::FileSystem.expects(:lstat).with(somefile).raises(Errno::ENOENT)
expect { Puppet::FileServing::Fileset.new(somefile) }.to raise_error(ArgumentError, "Fileset paths must exist")
end
it "accepts a 'recurse' option" do
Puppet::FileSystem.expects(:lstat).with(somefile).returns stub('stat')
set = Puppet::FileServing::Fileset.new(somefile, :recurse => true)
- set.recurse.should be_true
+ expect(set.recurse).to be_truthy
end
it "accepts a 'recurselimit' option" do
Puppet::FileSystem.expects(:lstat).with(somefile).returns stub('stat')
set = Puppet::FileServing::Fileset.new(somefile, :recurselimit => 3)
- set.recurselimit.should == 3
+ expect(set.recurselimit).to eq(3)
end
it "accepts an 'ignore' option" do
Puppet::FileSystem.expects(:lstat).with(somefile).returns stub('stat')
set = Puppet::FileServing::Fileset.new(somefile, :ignore => ".svn")
- set.ignore.should == [".svn"]
+ expect(set.ignore).to eq([".svn"])
end
it "accepts a 'links' option" do
Puppet::FileSystem.expects(:lstat).with(somefile).returns stub('stat')
set = Puppet::FileServing::Fileset.new(somefile, :links => :manage)
- set.links.should == :manage
+ expect(set.links).to eq(:manage)
end
it "accepts a 'checksum_type' option" do
Puppet::FileSystem.expects(:lstat).with(somefile).returns stub('stat')
set = Puppet::FileServing::Fileset.new(somefile, :checksum_type => :test)
- set.checksum_type.should == :test
+ expect(set.checksum_type).to eq(:test)
end
it "fails if 'links' is set to anything other than :manage or :follow" do
expect { Puppet::FileServing::Fileset.new(somefile, :links => :whatever) }.to raise_error(ArgumentError, "Invalid :links value 'whatever'")
end
it "defaults to 'false' for recurse" do
Puppet::FileSystem.expects(:lstat).with(somefile).returns stub('stat')
- Puppet::FileServing::Fileset.new(somefile).recurse.should == false
+ expect(Puppet::FileServing::Fileset.new(somefile).recurse).to eq(false)
end
it "defaults to :infinite for recurselimit" do
Puppet::FileSystem.expects(:lstat).with(somefile).returns stub('stat')
- Puppet::FileServing::Fileset.new(somefile).recurselimit.should == :infinite
+ expect(Puppet::FileServing::Fileset.new(somefile).recurselimit).to eq(:infinite)
end
it "defaults to an empty ignore list" do
Puppet::FileSystem.expects(:lstat).with(somefile).returns stub('stat')
- Puppet::FileServing::Fileset.new(somefile).ignore.should == []
+ expect(Puppet::FileServing::Fileset.new(somefile).ignore).to eq([])
end
it "defaults to :manage for links" do
Puppet::FileSystem.expects(:lstat).with(somefile).returns stub('stat')
- Puppet::FileServing::Fileset.new(somefile).links.should == :manage
+ expect(Puppet::FileServing::Fileset.new(somefile).links).to eq(:manage)
end
describe "using an indirector request" do
let(:values) { { :links => :manage, :ignore => %w{a b}, :recurse => true, :recurselimit => 1234 } }
- let(:stub_file) { stub(somefile, :lstat => stub('stat')) }
before :each do
Puppet::FileSystem.expects(:lstat).with(somefile).returns stub('stat')
end
[:recurse, :recurselimit, :ignore, :links].each do |option|
it "passes the #{option} option on to the fileset if present" do
request = Puppet::Indirector::Request.new(:file_serving, :find, "foo", nil, {option => values[option]})
- Puppet::FileServing::Fileset.new(somefile, request).send(option).should == values[option]
+ expect(Puppet::FileServing::Fileset.new(somefile, request).send(option)).to eq(values[option])
end
end
it "converts the integer as a string to their integer counterpart when setting options" do
request = Puppet::Indirector::Request.new(:file_serving, :find, "foo", nil,
{:recurselimit => "1234"})
- Puppet::FileServing::Fileset.new(somefile, request).recurselimit.should == 1234
+ expect(Puppet::FileServing::Fileset.new(somefile, request).recurselimit).to eq(1234)
end
it "converts the string 'true' to the boolean true when setting options" do
request = Puppet::Indirector::Request.new(:file_serving, :find, "foo", nil,
{:recurse => "true"})
- Puppet::FileServing::Fileset.new(somefile, request).recurse.should == true
+ expect(Puppet::FileServing::Fileset.new(somefile, request).recurse).to eq(true)
end
it "converts the string 'false' to the boolean false when setting options" do
request = Puppet::Indirector::Request.new(:file_serving, :find, "foo", nil,
{:recurse => "false"})
- Puppet::FileServing::Fileset.new(somefile, request).recurse.should == false
+ expect(Puppet::FileServing::Fileset.new(somefile, request).recurse).to eq(false)
end
end
end
context "when recursing" do
before do
@path = make_absolute("/my/path")
Puppet::FileSystem.stubs(:lstat).with(@path).returns stub('stat', :directory? => true)
@fileset = Puppet::FileServing::Fileset.new(@path)
@dirstat = stub 'dirstat', :directory? => true
@filestat = stub 'filestat', :directory? => false
end
def mock_dir_structure(path, stat_method = :lstat)
Puppet::FileSystem.stubs(stat_method).with(path).returns @dirstat
# Keep track of the files we're stubbing.
@files = %w{.}
top_names = %w{one two .svn CVS}
sub_names = %w{file1 file2 .svn CVS 0 false}
Dir.stubs(:entries).with(path).returns(top_names)
top_names.each do |subdir|
@files << subdir # relative path
subpath = File.join(path, subdir)
Puppet::FileSystem.stubs(stat_method).with(subpath).returns @dirstat
Dir.stubs(:entries).with(subpath).returns(sub_names)
sub_names.each do |file|
@files << File.join(subdir, file) # relative path
subfile_path = File.join(subpath, file)
Puppet::FileSystem.stubs(stat_method).with(subfile_path).returns(@filestat)
end
end
end
MockStat = Struct.new(:path, :directory) do
# struct doesn't support thing ending in ?
def directory?
directory
end
end
MockDirectory = Struct.new(:name, :entries) do
def mock(base_path)
extend Mocha::API
path = File.join(base_path, name)
Puppet::FileSystem.stubs(:lstat).with(path).returns MockStat.new(path, true)
Dir.stubs(:entries).with(path).returns(['.', '..'] + entries.map(&:name))
entries.each do |entry|
entry.mock(path)
end
end
end
MockFile = Struct.new(:name) do
def mock(base_path)
extend Mocha::API
path = File.join(base_path, name)
Puppet::FileSystem.stubs(:lstat).with(path).returns MockStat.new(path, false)
end
end
it "doesn't ignore pending directories when the last entry at the top level is a file" do
structure = MockDirectory.new('path',
[MockDirectory.new('dir1',
[MockDirectory.new('a', [MockFile.new('f')])]),
MockFile.new('file')])
structure.mock(make_absolute('/your'))
fileset = Puppet::FileServing::Fileset.new(make_absolute('/your/path'))
fileset.recurse = true
fileset.links = :manage
- fileset.files.should == [".", "dir1", "file", "dir1/a", "dir1/a/f"]
+ expect(fileset.files).to eq([".", "dir1", "file", "dir1/a", "dir1/a/f"])
end
it "recurses through the whole file tree if :recurse is set to 'true'" do
mock_dir_structure(@path)
@fileset.recurse = true
- @fileset.files.sort.should == @files.sort
+ expect(@fileset.files.sort).to eq(@files.sort)
end
it "does not recurse if :recurse is set to 'false'" do
mock_dir_structure(@path)
@fileset.recurse = false
- @fileset.files.should == %w{.}
+ expect(@fileset.files).to eq(%w{.})
end
it "recurses to the level set by :recurselimit" do
mock_dir_structure(@path)
@fileset.recurse = true
@fileset.recurselimit = 1
- @fileset.files.should == %w{. one two .svn CVS}
+ expect(@fileset.files).to eq(%w{. one two .svn CVS})
end
it "ignores the '.' and '..' directories in subdirectories" do
mock_dir_structure(@path)
@fileset.recurse = true
- @fileset.files.sort.should == @files.sort
+ expect(@fileset.files.sort).to eq(@files.sort)
end
it "does not fail if the :ignore value provided is nil" do
mock_dir_structure(@path)
@fileset.recurse = true
@fileset.ignore = nil
expect { @fileset.files }.to_not raise_error
end
it "ignores files that match a single pattern in the ignore list" do
mock_dir_structure(@path)
@fileset.recurse = true
@fileset.ignore = ".svn"
- @fileset.files.find { |file| file.include?(".svn") }.should be_nil
+ expect(@fileset.files.find { |file| file.include?(".svn") }).to be_nil
end
it "ignores files that match any of multiple patterns in the ignore list" do
mock_dir_structure(@path)
@fileset.recurse = true
@fileset.ignore = %w{.svn CVS}
- @fileset.files.find { |file| file.include?(".svn") or file.include?("CVS") }.should be_nil
+ expect(@fileset.files.find { |file| file.include?(".svn") or file.include?("CVS") }).to be_nil
end
it "ignores files that match a pattern given as a number" do
mock_dir_structure(@path)
@fileset.recurse = true
@fileset.ignore = [0]
- @fileset.files.find { |file| file.include?("0") }.should be_nil
+ expect(@fileset.files.find { |file| file.include?("0") }).to be_nil
end
it "ignores files that match a pattern given as a boolean" do
mock_dir_structure(@path)
@fileset.recurse = true
@fileset.ignore = [false]
- @fileset.files.find { |file| file.include?("false") }.should be_nil
+ expect(@fileset.files.find { |file| file.include?("false") }).to be_nil
end
it "uses Puppet::FileSystem#stat if :links is set to :follow" do
mock_dir_structure(@path, :stat)
@fileset.recurse = true
@fileset.links = :follow
- @fileset.files.sort.should == @files.sort
+ expect(@fileset.files.sort).to eq(@files.sort)
end
it "uses Puppet::FileSystem#lstat if :links is set to :manage" do
mock_dir_structure(@path, :lstat)
@fileset.recurse = true
@fileset.links = :manage
- @fileset.files.sort.should == @files.sort
+ expect(@fileset.files.sort).to eq(@files.sort)
end
it "works when paths have regexp significant characters" do
@path = make_absolute("/my/path/rV1x2DafFr0R6tGG+1bbk++++TM")
stat = stub('dir_stat', :directory? => true)
stub_file = stub(@path, :stat => stat, :lstat => stat)
Puppet::FileSystem.expects(:lstat).with(@path).returns stub(@path, :stat => stat, :lstat => stat)
@fileset = Puppet::FileServing::Fileset.new(@path)
mock_dir_structure(@path)
@fileset.recurse = true
- @fileset.files.sort.should == @files.sort
+ expect(@fileset.files.sort).to eq(@files.sort)
end
end
it "manages the links to missing files" do
path = make_absolute("/my/path")
stat = stub 'stat', :directory? => true
Puppet::FileSystem.expects(:stat).with(path).returns stat
Puppet::FileSystem.expects(:lstat).with(path).returns stat
link_path = File.join(path, "mylink")
Puppet::FileSystem.expects(:stat).with(link_path).raises(Errno::ENOENT)
Dir.stubs(:entries).with(path).returns(["mylink"])
fileset = Puppet::FileServing::Fileset.new(path)
fileset.links = :follow
fileset.recurse = true
- fileset.files.sort.should == %w{. mylink}.sort
+ expect(fileset.files.sort).to eq(%w{. mylink}.sort)
end
context "when merging other filesets" do
before do
@paths = [make_absolute("/first/path"), make_absolute("/second/path"), make_absolute("/third/path")]
Puppet::FileSystem.stubs(:lstat).returns stub('stat', :directory? => false)
@filesets = @paths.collect do |path|
Puppet::FileSystem.stubs(:lstat).with(path).returns stub('stat', :directory? => true)
Puppet::FileServing::Fileset.new(path, :recurse => true)
end
Dir.stubs(:entries).returns []
end
it "returns a hash of all files in each fileset with the value being the base path" do
Dir.expects(:entries).with(make_absolute("/first/path")).returns(%w{one uno})
Dir.expects(:entries).with(make_absolute("/second/path")).returns(%w{two dos})
Dir.expects(:entries).with(make_absolute("/third/path")).returns(%w{three tres})
- Puppet::FileServing::Fileset.merge(*@filesets).should == {
+ expect(Puppet::FileServing::Fileset.merge(*@filesets)).to eq({
"." => make_absolute("/first/path"),
"one" => make_absolute("/first/path"),
"uno" => make_absolute("/first/path"),
"two" => make_absolute("/second/path"),
"dos" => make_absolute("/second/path"),
"three" => make_absolute("/third/path"),
"tres" => make_absolute("/third/path"),
- }
+ })
end
it "includes the base directory from the first fileset" do
Dir.expects(:entries).with(make_absolute("/first/path")).returns(%w{one})
Dir.expects(:entries).with(make_absolute("/second/path")).returns(%w{two})
- Puppet::FileServing::Fileset.merge(*@filesets)["."].should == make_absolute("/first/path")
+ expect(Puppet::FileServing::Fileset.merge(*@filesets)["."]).to eq(make_absolute("/first/path"))
end
it "uses the base path of the first found file when relative file paths conflict" do
Dir.expects(:entries).with(make_absolute("/first/path")).returns(%w{one})
Dir.expects(:entries).with(make_absolute("/second/path")).returns(%w{one})
- Puppet::FileServing::Fileset.merge(*@filesets)["one"].should == make_absolute("/first/path")
+ expect(Puppet::FileServing::Fileset.merge(*@filesets)["one"]).to eq(make_absolute("/first/path"))
end
end
end
diff --git a/spec/unit/file_serving/metadata_spec.rb b/spec/unit/file_serving/metadata_spec.rb
index 0478d281b..0d1e31f01 100755
--- a/spec/unit/file_serving/metadata_spec.rb
+++ b/spec/unit/file_serving/metadata_spec.rb
@@ -1,462 +1,462 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_serving/metadata'
require 'matchers/json'
describe Puppet::FileServing::Metadata do
let(:foobar) { File.expand_path('/foo/bar') }
it "should be a subclass of Base" do
- Puppet::FileServing::Metadata.superclass.should equal(Puppet::FileServing::Base)
+ expect(Puppet::FileServing::Metadata.superclass).to equal(Puppet::FileServing::Base)
end
it "should indirect file_metadata" do
- Puppet::FileServing::Metadata.indirection.name.should == :file_metadata
+ expect(Puppet::FileServing::Metadata.indirection.name).to eq(:file_metadata)
end
it "should have a method that triggers attribute collection" do
- Puppet::FileServing::Metadata.new(foobar).should respond_to(:collect)
+ expect(Puppet::FileServing::Metadata.new(foobar)).to respond_to(:collect)
end
it "should support pson serialization" do
- Puppet::FileServing::Metadata.new(foobar).should respond_to(:to_pson)
+ expect(Puppet::FileServing::Metadata.new(foobar)).to respond_to(:to_pson)
end
it "should support deserialization" do
- Puppet::FileServing::Metadata.should respond_to(:from_data_hash)
+ expect(Puppet::FileServing::Metadata).to respond_to(:from_data_hash)
end
describe "when serializing" do
let(:metadata) { Puppet::FileServing::Metadata.new(foobar) }
it "the data should include the path, relative_path, links, owner, group, mode, checksum, type, and destination" do
- metadata.to_data_hash.keys.sort.should == %w{ path relative_path links owner group mode checksum type destination }.sort
+ expect(metadata.to_data_hash.keys.sort).to eq(%w{ path relative_path links owner group mode checksum type destination }.sort)
end
it "should pass the path in the hash verbatim" do
- metadata.to_data_hash['path'].should == metadata.path
+ expect(metadata.to_data_hash['path']).to eq(metadata.path)
end
it "should pass the relative_path in the hash verbatim" do
- metadata.to_data_hash['relative_path'].should == metadata.relative_path
+ expect(metadata.to_data_hash['relative_path']).to eq(metadata.relative_path)
end
it "should pass the links in the hash verbatim" do
- metadata.to_data_hash['links'].should == metadata.links
+ expect(metadata.to_data_hash['links']).to eq(metadata.links)
end
it "should pass the path owner in the hash verbatim" do
- metadata.to_data_hash['owner'].should == metadata.owner
+ expect(metadata.to_data_hash['owner']).to eq(metadata.owner)
end
it "should pass the group in the hash verbatim" do
- metadata.to_data_hash['group'].should == metadata.group
+ expect(metadata.to_data_hash['group']).to eq(metadata.group)
end
it "should pass the mode in the hash verbatim" do
- metadata.to_data_hash['mode'].should == metadata.mode
+ expect(metadata.to_data_hash['mode']).to eq(metadata.mode)
end
it "should pass the ftype in the hash verbatim as the 'type'" do
- metadata.to_data_hash['type'].should == metadata.ftype
+ expect(metadata.to_data_hash['type']).to eq(metadata.ftype)
end
it "should pass the destination verbatim" do
- metadata.to_data_hash['destination'].should == metadata.destination
+ expect(metadata.to_data_hash['destination']).to eq(metadata.destination)
end
it "should pass the checksum in the hash as a nested hash" do
- metadata.to_data_hash['checksum'].should be_is_a(Hash)
+ expect(metadata.to_data_hash['checksum']).to be_is_a(Hash)
end
it "should pass the checksum_type in the hash verbatim as the checksum's type" do
- metadata.to_data_hash['checksum']['type'].should == metadata.checksum_type
+ expect(metadata.to_data_hash['checksum']['type']).to eq(metadata.checksum_type)
end
it "should pass the checksum in the hash verbatim as the checksum's value" do
- metadata.to_data_hash['checksum']['value'].should == metadata.checksum
+ expect(metadata.to_data_hash['checksum']['value']).to eq(metadata.checksum)
end
end
end
describe Puppet::FileServing::Metadata, :uses_checksums => true do
include JSONMatchers
include PuppetSpec::Files
shared_examples_for "metadata collector" do
let(:metadata) do
data = described_class.new(path)
data.collect
data
end
describe "when collecting attributes" do
describe "when managing files" do
let(:path) { tmpfile('file_serving_metadata') }
before :each do
FileUtils.touch(path)
end
describe "checksumming" do
with_digest_algorithms do
before :each do
File.open(path, "wb") {|f| f.print(plaintext)}
end
it "should default to a checksum of the proper type with the file's current checksum" do
- metadata.checksum.should == "{#{digest_algorithm}}#{checksum}"
+ expect(metadata.checksum).to eq("{#{digest_algorithm}}#{checksum}")
end
it "should give a mtime checksum when checksum_type is set" do
time = Time.now
metadata.checksum_type = "mtime"
metadata.expects(:mtime_file).returns(@time)
metadata.collect
- metadata.checksum.should == "{mtime}#{@time}"
+ expect(metadata.checksum).to eq("{mtime}#{@time}")
end
end
end
it "should validate against the schema" do
expect(metadata.to_pson).to validate_against('api/schemas/file_metadata.json')
end
end
describe "when managing directories" do
let(:path) { tmpdir('file_serving_metadata_dir') }
let(:time) { Time.now }
before :each do
metadata.expects(:ctime_file).returns(time)
end
it "should only use checksums of type 'ctime' for directories" do
metadata.collect
- metadata.checksum.should == "{ctime}#{time}"
+ expect(metadata.checksum).to eq("{ctime}#{time}")
end
it "should only use checksums of type 'ctime' for directories even if checksum_type set" do
metadata.checksum_type = "mtime"
metadata.expects(:mtime_file).never
metadata.collect
- metadata.checksum.should == "{ctime}#{time}"
+ expect(metadata.checksum).to eq("{ctime}#{time}")
end
it "should validate against the schema" do
metadata.collect
expect(metadata.to_pson).to validate_against('api/schemas/file_metadata.json')
end
end
end
end
describe "WindowsStat", :if => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
it "should return default owner, group and mode when the given path has an invalid DACL (such as a non-NTFS volume)" do
invalid_error = Puppet::Util::Windows::Error.new('Invalid DACL', 1336)
path = tmpfile('foo')
FileUtils.touch(path)
Puppet::Util::Windows::Security.stubs(:get_owner).with(path).raises(invalid_error)
Puppet::Util::Windows::Security.stubs(:get_group).with(path).raises(invalid_error)
Puppet::Util::Windows::Security.stubs(:get_mode).with(path).raises(invalid_error)
stat = Puppet::FileSystem.stat(path)
win_stat = Puppet::FileServing::Metadata::WindowsStat.new(stat, path)
- win_stat.owner.should == 'S-1-5-32-544'
- win_stat.group.should == 'S-1-0-0'
- win_stat.mode.should == 0644
+ expect(win_stat.owner).to eq('S-1-5-32-544')
+ expect(win_stat.group).to eq('S-1-0-0')
+ expect(win_stat.mode).to eq(0644)
end
it "should still raise errors that are not the result of an 'Invalid DACL'" do
invalid_error = ArgumentError.new('bar')
path = tmpfile('bar')
FileUtils.touch(path)
Puppet::Util::Windows::Security.stubs(:get_owner).with(path, :use).raises(invalid_error)
Puppet::Util::Windows::Security.stubs(:get_group).with(path, :use).raises(invalid_error)
Puppet::Util::Windows::Security.stubs(:get_mode).with(path, :use).raises(invalid_error)
stat = Puppet::FileSystem.stat(path)
expect { Puppet::FileServing::Metadata::WindowsStat.new(stat, path, :use) }.to raise_error("Unsupported Windows source permissions option use")
end
end
shared_examples_for "metadata collector symlinks" do
let(:metadata) do
data = described_class.new(path)
data.collect
data
end
describe "when collecting attributes" do
describe "when managing links" do
# 'path' is a link that points to 'target'
let(:path) { tmpfile('file_serving_metadata_link') }
let(:target) { tmpfile('file_serving_metadata_target') }
let(:fmode) { Puppet::FileSystem.lstat(path).mode & 0777 }
before :each do
File.open(target, "wb") {|f| f.print('some content')}
set_mode(0644, target)
Puppet::FileSystem.symlink(target, path)
end
it "should read links instead of returning their checksums" do
- metadata.destination.should == target
+ expect(metadata.destination).to eq(target)
end
it "should validate against the schema" do
expect(metadata.to_pson).to validate_against('api/schemas/file_metadata.json')
end
end
end
describe Puppet::FileServing::Metadata, " when finding the file to use for setting attributes" do
let(:path) { tmpfile('file_serving_metadata_find_file') }
before :each do
File.open(path, "wb") {|f| f.print('some content')}
set_mode(0755, path)
end
it "should accept a base path to which the file should be relative" do
dir = tmpdir('metadata_dir')
metadata = described_class.new(dir)
metadata.relative_path = 'relative_path'
FileUtils.touch(metadata.full_path)
metadata.collect
end
it "should use the set base path if one is not provided" do
metadata.collect
end
it "should raise an exception if the file does not exist" do
File.delete(path)
- proc { metadata.collect}.should raise_error(Errno::ENOENT)
+ expect { metadata.collect}.to raise_error(Errno::ENOENT)
end
it "should validate against the schema" do
expect(metadata.to_pson).to validate_against('api/schemas/file_metadata.json')
end
end
end
describe "on POSIX systems", :if => Puppet.features.posix? do
let(:owner) {10}
let(:group) {20}
before :each do
File::Stat.any_instance.stubs(:uid).returns owner
File::Stat.any_instance.stubs(:gid).returns group
end
describe "when collecting attributes when managing files" do
let(:metadata) do
data = described_class.new(path)
data.collect
data
end
let(:path) { tmpfile('file_serving_metadata') }
before :each do
FileUtils.touch(path)
end
it "should set the owner to the Process's current owner" do
- metadata.owner.should == Process.euid
+ expect(metadata.owner).to eq(Process.euid)
end
it "should set the group to the Process's current group" do
- metadata.group.should == Process.egid
+ expect(metadata.group).to eq(Process.egid)
end
it "should set the mode to the default mode" do
set_mode(33261, path)
- metadata.mode.should == 0644
+ expect(metadata.mode).to eq(0644)
end
end
it_should_behave_like "metadata collector"
it_should_behave_like "metadata collector symlinks"
def set_mode(mode, path)
File.chmod(mode, path)
end
end
describe "on Windows systems", :if => Puppet.features.microsoft_windows? do
let(:owner) {'S-1-1-50'}
let(:group) {'S-1-1-51'}
before :each do
require 'puppet/util/windows/security'
Puppet::Util::Windows::Security.stubs(:get_owner).returns owner
Puppet::Util::Windows::Security.stubs(:get_group).returns group
end
describe "when collecting attributes when managing files" do
let(:metadata) do
data = described_class.new(path)
data.collect
data
end
let(:path) { tmpfile('file_serving_metadata') }
before :each do
FileUtils.touch(path)
end
it "should set the owner to the Process's current owner" do
- metadata.owner.should == "S-1-5-32-544"
+ expect(metadata.owner).to eq("S-1-5-32-544")
end
it "should set the group to the Process's current group" do
- metadata.group.should == "S-1-0-0"
+ expect(metadata.group).to eq("S-1-0-0")
end
it "should set the mode to the default mode" do
set_mode(33261, path)
- metadata.mode.should == 0644
+ expect(metadata.mode).to eq(0644)
end
end
it_should_behave_like "metadata collector"
it_should_behave_like "metadata collector symlinks" if Puppet.features.manages_symlinks?
describe "if ACL metadata cannot be collected" do
let(:path) { tmpdir('file_serving_metadata_acl') }
let(:metadata) do
data = described_class.new(path)
data.collect
data
end
let (:invalid_dacl_error) do
Puppet::Util::Windows::Error.new('Invalid DACL', 1336)
end
it "should default owner" do
Puppet::Util::Windows::Security.stubs(:get_owner).returns nil
- metadata.owner.should == 'S-1-5-32-544'
+ expect(metadata.owner).to eq('S-1-5-32-544')
end
it "should default group" do
Puppet::Util::Windows::Security.stubs(:get_group).returns nil
- metadata.group.should == 'S-1-0-0'
+ expect(metadata.group).to eq('S-1-0-0')
end
it "should default mode" do
Puppet::Util::Windows::Security.stubs(:get_mode).returns nil
- metadata.mode.should == 0644
+ expect(metadata.mode).to eq(0644)
end
describe "when the path raises an Invalid ACL error" do
# these simulate the behavior of a symlink file whose target does not support ACLs
it "should default owner" do
Puppet::Util::Windows::Security.stubs(:get_owner).raises(invalid_dacl_error)
- metadata.owner.should == 'S-1-5-32-544'
+ expect(metadata.owner).to eq('S-1-5-32-544')
end
it "should default group" do
Puppet::Util::Windows::Security.stubs(:get_group).raises(invalid_dacl_error)
- metadata.group.should == 'S-1-0-0'
+ expect(metadata.group).to eq('S-1-0-0')
end
it "should default mode" do
Puppet::Util::Windows::Security.stubs(:get_mode).raises(invalid_dacl_error)
- metadata.mode.should == 0644
+ expect(metadata.mode).to eq(0644)
end
end
end
def set_mode(mode, path)
Puppet::Util::Windows::Security.set_mode(mode, path)
end
end
end
describe Puppet::FileServing::Metadata, " when pointing to a link", :if => Puppet.features.manages_symlinks?, :uses_checksums => true do
with_digest_algorithms do
describe "when links are managed" do
before do
path = "/base/path/my/file"
@file = Puppet::FileServing::Metadata.new(path, :links => :manage)
stat = stub("stat", :uid => 1, :gid => 2, :ftype => "link", :mode => 0755)
stub_file = stub(:readlink => "/some/other/path", :lstat => stat)
Puppet::FileSystem.expects(:lstat).with(path).at_least_once.returns stat
Puppet::FileSystem.expects(:readlink).with(path).at_least_once.returns "/some/other/path"
@file.stubs("#{digest_algorithm}_file".intern).returns(checksum) # Remove these when :managed links are no longer checksumed.
if Puppet.features.microsoft_windows?
win_stat = stub('win_stat', :owner => 'snarf', :group => 'thundercats',
:ftype => 'link', :mode => 0755)
Puppet::FileServing::Metadata::WindowsStat.stubs(:new).returns win_stat
end
end
it "should store the destination of the link in :destination if links are :manage" do
@file.collect
- @file.destination.should == "/some/other/path"
+ expect(@file.destination).to eq("/some/other/path")
end
pending "should not collect the checksum if links are :manage" do
# We'd like this to be true, but we need to always collect the checksum because in the server/client/server round trip we lose the distintion between manage and follow.
@file.collect
- @file.checksum.should be_nil
+ expect(@file.checksum).to be_nil
end
it "should collect the checksum if links are :manage" do # see pending note above
@file.collect
- @file.checksum.should == "{#{digest_algorithm}}#{checksum}"
+ expect(@file.checksum).to eq("{#{digest_algorithm}}#{checksum}")
end
end
describe "when links are followed" do
before do
path = "/base/path/my/file"
@file = Puppet::FileServing::Metadata.new(path, :links => :follow)
stat = stub("stat", :uid => 1, :gid => 2, :ftype => "file", :mode => 0755)
Puppet::FileSystem.expects(:stat).with(path).at_least_once.returns stat
Puppet::FileSystem.expects(:readlink).never
if Puppet.features.microsoft_windows?
win_stat = stub('win_stat', :owner => 'snarf', :group => 'thundercats',
:ftype => 'file', :mode => 0755)
Puppet::FileServing::Metadata::WindowsStat.stubs(:new).returns win_stat
end
@file.stubs("#{digest_algorithm}_file".intern).returns(checksum)
end
it "should not store the destination of the link in :destination if links are :follow" do
@file.collect
- @file.destination.should be_nil
+ expect(@file.destination).to be_nil
end
it "should collect the checksum if links are :follow" do
@file.collect
- @file.checksum.should == "{#{digest_algorithm}}#{checksum}"
+ expect(@file.checksum).to eq("{#{digest_algorithm}}#{checksum}")
end
end
end
end
diff --git a/spec/unit/file_serving/mount/file_spec.rb b/spec/unit/file_serving/mount/file_spec.rb
index f889b8eb1..5026067b2 100755
--- a/spec/unit/file_serving/mount/file_spec.rb
+++ b/spec/unit/file_serving/mount/file_spec.rb
@@ -1,189 +1,189 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_serving/mount/file'
module FileServingMountTesting
def stub_facter(hostname)
Facter.stubs(:value).with("hostname").returns(hostname.sub(/\..+/, ''))
Facter.stubs(:value).with("domain").returns(hostname.sub(/^[^.]+\./, ''))
end
end
describe Puppet::FileServing::Mount::File do
it "should be invalid if it does not have a path" do
expect { Puppet::FileServing::Mount::File.new("foo").validate }.to raise_error(ArgumentError)
end
it "should be valid if it has a path" do
FileTest.stubs(:directory?).returns true
FileTest.stubs(:readable?).returns true
mount = Puppet::FileServing::Mount::File.new("foo")
mount.path = "/foo"
expect { mount.validate }.not_to raise_error
end
describe "when setting the path" do
before do
@mount = Puppet::FileServing::Mount::File.new("test")
@dir = "/this/path/does/not/exist"
end
it "should fail if the path is not a directory" do
FileTest.expects(:directory?).returns(false)
expect { @mount.path = @dir }.to raise_error(ArgumentError)
end
it "should fail if the path is not readable" do
FileTest.expects(:directory?).returns(true)
FileTest.expects(:readable?).returns(false)
expect { @mount.path = @dir }.to raise_error(ArgumentError)
end
end
describe "when substituting hostnames and ip addresses into file paths" do
include FileServingMountTesting
before do
FileTest.stubs(:directory?).returns(true)
FileTest.stubs(:readable?).returns(true)
@mount = Puppet::FileServing::Mount::File.new("test")
@host = "host.domain.com"
end
after :each do
Puppet::FileServing::Mount::File.instance_variable_set(:@localmap, nil)
end
it "should replace incidences of %h in the path with the client's short name" do
@mount.path = "/dir/%h/yay"
- @mount.path(@host).should == "/dir/host/yay"
+ expect(@mount.path(@host)).to eq("/dir/host/yay")
end
it "should replace incidences of %H in the path with the client's fully qualified name" do
@mount.path = "/dir/%H/yay"
- @mount.path(@host).should == "/dir/host.domain.com/yay"
+ expect(@mount.path(@host)).to eq("/dir/host.domain.com/yay")
end
it "should replace incidences of %d in the path with the client's domain name" do
@mount.path = "/dir/%d/yay"
- @mount.path(@host).should == "/dir/domain.com/yay"
+ expect(@mount.path(@host)).to eq("/dir/domain.com/yay")
end
it "should perform all necessary replacements" do
@mount.path = "/%h/%d/%H"
- @mount.path(@host).should == "/host/domain.com/host.domain.com"
+ expect(@mount.path(@host)).to eq("/host/domain.com/host.domain.com")
end
it "should use local host information if no client data is provided" do
stub_facter("myhost.mydomain.com")
@mount.path = "/%h/%d/%H"
- @mount.path.should == "/myhost/mydomain.com/myhost.mydomain.com"
+ expect(@mount.path).to eq("/myhost/mydomain.com/myhost.mydomain.com")
end
end
describe "when determining the complete file path" do
include FileServingMountTesting
before do
Puppet::FileSystem.stubs(:exist?).returns(true)
FileTest.stubs(:directory?).returns(true)
FileTest.stubs(:readable?).returns(true)
@mount = Puppet::FileServing::Mount::File.new("test")
@mount.path = "/mount"
stub_facter("myhost.mydomain.com")
@host = "host.domain.com"
end
it "should return nil if the file is absent" do
Puppet::FileSystem.stubs(:exist?).returns(false)
- @mount.complete_path("/my/path", nil).should be_nil
+ expect(@mount.complete_path("/my/path", nil)).to be_nil
end
it "should write a log message if the file is absent" do
Puppet::FileSystem.stubs(:exist?).returns(false)
Puppet.expects(:info).with("File does not exist or is not accessible: /mount/my/path")
@mount.complete_path("/my/path", nil)
end
it "should return the file path if the file is present" do
Puppet::FileSystem.stubs(:exist?).with("/my/path").returns(true)
- @mount.complete_path("/my/path", nil).should == "/mount/my/path"
+ expect(@mount.complete_path("/my/path", nil)).to eq("/mount/my/path")
end
it "should treat a nil file name as the path to the mount itself" do
Puppet::FileSystem.stubs(:exist?).returns(true)
- @mount.complete_path(nil, nil).should == "/mount"
+ expect(@mount.complete_path(nil, nil)).to eq("/mount")
end
it "should use the client host name if provided in the options" do
@mount.path = "/mount/%h"
- @mount.complete_path("/my/path", @host).should == "/mount/host/my/path"
+ expect(@mount.complete_path("/my/path", @host)).to eq("/mount/host/my/path")
end
it "should perform replacements on the base path" do
@mount.path = "/blah/%h"
- @mount.complete_path("/my/stuff", @host).should == "/blah/host/my/stuff"
+ expect(@mount.complete_path("/my/stuff", @host)).to eq("/blah/host/my/stuff")
end
it "should not perform replacements on the per-file path" do
@mount.path = "/blah"
- @mount.complete_path("/%h/stuff", @host).should == "/blah/%h/stuff"
+ expect(@mount.complete_path("/%h/stuff", @host)).to eq("/blah/%h/stuff")
end
it "should look for files relative to its base directory" do
- @mount.complete_path("/my/stuff", @host).should == "/mount/my/stuff"
+ expect(@mount.complete_path("/my/stuff", @host)).to eq("/mount/my/stuff")
end
end
describe "when finding files" do
include FileServingMountTesting
before do
Puppet::FileSystem.stubs(:exist?).returns(true)
FileTest.stubs(:directory?).returns(true)
FileTest.stubs(:readable?).returns(true)
@mount = Puppet::FileServing::Mount::File.new("test")
@mount.path = "/mount"
stub_facter("myhost.mydomain.com")
@host = "host.domain.com"
@request = stub 'request', :node => "foo"
end
it "should return the results of the complete file path" do
Puppet::FileSystem.stubs(:exist?).returns(false)
@mount.expects(:complete_path).with("/my/path", "foo").returns "eh"
- @mount.find("/my/path", @request).should == "eh"
+ expect(@mount.find("/my/path", @request)).to eq("eh")
end
end
describe "when searching for files" do
include FileServingMountTesting
before do
Puppet::FileSystem.stubs(:exist?).returns(true)
FileTest.stubs(:directory?).returns(true)
FileTest.stubs(:readable?).returns(true)
@mount = Puppet::FileServing::Mount::File.new("test")
@mount.path = "/mount"
stub_facter("myhost.mydomain.com")
@host = "host.domain.com"
@request = stub 'request', :node => "foo"
end
it "should return the results of the complete file path as an array" do
Puppet::FileSystem.stubs(:exist?).returns(false)
@mount.expects(:complete_path).with("/my/path", "foo").returns "eh"
- @mount.search("/my/path", @request).should == ["eh"]
+ expect(@mount.search("/my/path", @request)).to eq(["eh"])
end
it "should return nil if the complete path is nil" do
Puppet::FileSystem.stubs(:exist?).returns(false)
@mount.expects(:complete_path).with("/my/path", "foo").returns nil
- @mount.search("/my/path", @request).should be_nil
+ expect(@mount.search("/my/path", @request)).to be_nil
end
end
end
diff --git a/spec/unit/file_serving/mount/modules_spec.rb b/spec/unit/file_serving/mount/modules_spec.rb
index 7851a3c2b..b03fd8a69 100755
--- a/spec/unit/file_serving/mount/modules_spec.rb
+++ b/spec/unit/file_serving/mount/modules_spec.rb
@@ -1,70 +1,70 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_serving/mount/modules'
describe Puppet::FileServing::Mount::Modules do
before do
@mount = Puppet::FileServing::Mount::Modules.new("modules")
@environment = stub 'environment', :module => nil
@request = stub 'request', :environment => @environment
end
describe "when finding files" do
it "should fail if no module is specified" do
expect { @mount.find("", @request) }.to raise_error(/No module specified/)
end
it "should use the provided environment to find the module" do
@environment.expects(:module)
@mount.find("foo", @request)
end
it "should treat the first field of the relative path as the module name" do
@environment.expects(:module).with("foo")
@mount.find("foo/bar/baz", @request)
end
it "should return nil if the specified module does not exist" do
@environment.expects(:module).with("foo").returns nil
@mount.find("foo/bar/baz", @request)
end
it "should return the file path from the module" do
mod = mock 'module'
mod.expects(:file).with("bar/baz").returns "eh"
@environment.expects(:module).with("foo").returns mod
- @mount.find("foo/bar/baz", @request).should == "eh"
+ expect(@mount.find("foo/bar/baz", @request)).to eq("eh")
end
end
describe "when searching for files" do
it "should fail if no module is specified" do
expect { @mount.find("", @request) }.to raise_error(/No module specified/)
end
it "should use the node's environment to search the module" do
@environment.expects(:module)
@mount.search("foo", @request)
end
it "should treat the first field of the relative path as the module name" do
@environment.expects(:module).with("foo")
@mount.search("foo/bar/baz", @request)
end
it "should return nil if the specified module does not exist" do
@environment.expects(:module).with("foo").returns nil
@mount.search("foo/bar/baz", @request)
end
it "should return the file path as an array from the module" do
mod = mock 'module'
mod.expects(:file).with("bar/baz").returns "eh"
@environment.expects(:module).with("foo").returns mod
- @mount.search("foo/bar/baz", @request).should == ["eh"]
+ expect(@mount.search("foo/bar/baz", @request)).to eq(["eh"])
end
end
end
diff --git a/spec/unit/file_serving/mount/pluginfacts_spec.rb b/spec/unit/file_serving/mount/pluginfacts_spec.rb
index a54e45e4c..2c178fb21 100755
--- a/spec/unit/file_serving/mount/pluginfacts_spec.rb
+++ b/spec/unit/file_serving/mount/pluginfacts_spec.rb
@@ -1,73 +1,73 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_serving/mount/pluginfacts'
describe Puppet::FileServing::Mount::PluginFacts do
before do
@mount = Puppet::FileServing::Mount::PluginFacts.new("pluginfacts")
@environment = stub 'environment', :module => nil
@options = { :recurse => true }
@request = stub 'request', :environment => @environment, :options => @options
end
describe "when finding files" do
it "should use the provided environment to find the modules" do
@environment.expects(:modules).returns []
@mount.find("foo", @request)
end
it "should return nil if no module can be found with a matching plugin" do
mod = mock 'module'
mod.stubs(:pluginfact).with("foo/bar").returns nil
@environment.stubs(:modules).returns [mod]
- @mount.find("foo/bar", @request).should be_nil
+ expect(@mount.find("foo/bar", @request)).to be_nil
end
it "should return the file path from the module" do
mod = mock 'module'
mod.stubs(:pluginfact).with("foo/bar").returns "eh"
@environment.stubs(:modules).returns [mod]
- @mount.find("foo/bar", @request).should == "eh"
+ expect(@mount.find("foo/bar", @request)).to eq("eh")
end
end
describe "when searching for files" do
it "should use the node's environment to find the modules" do
@environment.expects(:modules).at_least_once.returns []
@environment.stubs(:modulepath).returns ["/tmp/modules"]
@mount.search("foo", @request)
end
it "should return modulepath if no modules can be found that have plugins" do
mod = mock 'module'
mod.stubs(:pluginfacts?).returns false
@environment.stubs(:modules).returns []
@environment.stubs(:modulepath).returns ["/"]
@options.expects(:[]=).with(:recurse, false)
- @mount.search("foo/bar", @request).should == ["/"]
+ expect(@mount.search("foo/bar", @request)).to eq(["/"])
end
it "should return nil if no modules can be found that have plugins and modulepath is invalid" do
mod = mock 'module'
mod.stubs(:pluginfacts?).returns false
@environment.stubs(:modules).returns []
@environment.stubs(:modulepath).returns []
- @mount.search("foo/bar", @request).should be_nil
+ expect(@mount.search("foo/bar", @request)).to be_nil
end
it "should return the plugin paths for each module that has plugins" do
one = stub 'module', :pluginfacts? => true, :plugin_fact_directory => "/one"
two = stub 'module', :pluginfacts? => true, :plugin_fact_directory => "/two"
@environment.stubs(:modules).returns [one, two]
- @mount.search("foo/bar", @request).should == %w{/one /two}
+ expect(@mount.search("foo/bar", @request)).to eq(%w{/one /two})
end
end
end
diff --git a/spec/unit/file_serving/mount/plugins_spec.rb b/spec/unit/file_serving/mount/plugins_spec.rb
index f0fc7ea1d..17427f447 100755
--- a/spec/unit/file_serving/mount/plugins_spec.rb
+++ b/spec/unit/file_serving/mount/plugins_spec.rb
@@ -1,73 +1,73 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_serving/mount/plugins'
describe Puppet::FileServing::Mount::Plugins do
before do
@mount = Puppet::FileServing::Mount::Plugins.new("plugins")
@environment = stub 'environment', :module => nil
@options = { :recurse => true }
@request = stub 'request', :environment => @environment, :options => @options
end
describe "when finding files" do
it "should use the provided environment to find the modules" do
@environment.expects(:modules).returns []
@mount.find("foo", @request)
end
it "should return nil if no module can be found with a matching plugin" do
mod = mock 'module'
mod.stubs(:plugin).with("foo/bar").returns nil
@environment.stubs(:modules).returns [mod]
- @mount.find("foo/bar", @request).should be_nil
+ expect(@mount.find("foo/bar", @request)).to be_nil
end
it "should return the file path from the module" do
mod = mock 'module'
mod.stubs(:plugin).with("foo/bar").returns "eh"
@environment.stubs(:modules).returns [mod]
- @mount.find("foo/bar", @request).should == "eh"
+ expect(@mount.find("foo/bar", @request)).to eq("eh")
end
end
describe "when searching for files" do
it "should use the node's environment to find the modules" do
@environment.expects(:modules).at_least_once.returns []
@environment.stubs(:modulepath).returns ["/tmp/modules"]
@mount.search("foo", @request)
end
it "should return modulepath if no modules can be found that have plugins" do
mod = mock 'module'
mod.stubs(:plugins?).returns false
@environment.stubs(:modules).returns []
@environment.stubs(:modulepath).returns ["/"]
@options.expects(:[]=).with(:recurse, false)
- @mount.search("foo/bar", @request).should == ["/"]
+ expect(@mount.search("foo/bar", @request)).to eq(["/"])
end
it "should return nil if no modules can be found that have plugins and modulepath is invalid" do
mod = mock 'module'
mod.stubs(:plugins?).returns false
@environment.stubs(:modules).returns []
@environment.stubs(:modulepath).returns []
- @mount.search("foo/bar", @request).should be_nil
+ expect(@mount.search("foo/bar", @request)).to be_nil
end
it "should return the plugin paths for each module that has plugins" do
one = stub 'module', :plugins? => true, :plugin_directory => "/one"
two = stub 'module', :plugins? => true, :plugin_directory => "/two"
@environment.stubs(:modules).returns [one, two]
- @mount.search("foo/bar", @request).should == %w{/one /two}
+ expect(@mount.search("foo/bar", @request)).to eq(%w{/one /two})
end
end
end
diff --git a/spec/unit/file_serving/mount_spec.rb b/spec/unit/file_serving/mount_spec.rb
index 1119d3141..baa4b9c98 100755
--- a/spec/unit/file_serving/mount_spec.rb
+++ b/spec/unit/file_serving/mount_spec.rb
@@ -1,31 +1,31 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_serving/mount'
describe Puppet::FileServing::Mount do
it "should use 'mount[$name]' as its string form" do
- Puppet::FileServing::Mount.new("foo").to_s.should == "mount[foo]"
+ expect(Puppet::FileServing::Mount.new("foo").to_s).to eq("mount[foo]")
end
end
describe Puppet::FileServing::Mount, " when initializing" do
it "should fail on non-alphanumeric name" do
- proc { Puppet::FileServing::Mount.new("non alpha") }.should raise_error(ArgumentError)
+ expect { Puppet::FileServing::Mount.new("non alpha") }.to raise_error(ArgumentError)
end
it "should allow dashes in its name" do
- Puppet::FileServing::Mount.new("non-alpha").name.should == "non-alpha"
+ expect(Puppet::FileServing::Mount.new("non-alpha").name).to eq("non-alpha")
end
end
describe Puppet::FileServing::Mount, " when finding files" do
it "should fail" do
- lambda { Puppet::FileServing::Mount.new("test").find("foo", :one => "two") }.should raise_error(NotImplementedError)
+ expect { Puppet::FileServing::Mount.new("test").find("foo", :one => "two") }.to raise_error(NotImplementedError)
end
end
describe Puppet::FileServing::Mount, " when searching for files" do
it "should fail" do
- lambda { Puppet::FileServing::Mount.new("test").search("foo", :one => "two") }.should raise_error(NotImplementedError)
+ expect { Puppet::FileServing::Mount.new("test").search("foo", :one => "two") }.to raise_error(NotImplementedError)
end
end
diff --git a/spec/unit/file_serving/terminus_selector_spec.rb b/spec/unit/file_serving/terminus_selector_spec.rb
index 9ece7063f..938059bb8 100755
--- a/spec/unit/file_serving/terminus_selector_spec.rb
+++ b/spec/unit/file_serving/terminus_selector_spec.rb
@@ -1,58 +1,58 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_serving/terminus_selector'
describe Puppet::FileServing::TerminusSelector do
before do
@object = Object.new
@object.extend(Puppet::FileServing::TerminusSelector)
@request = stub 'request', :key => "mymod/myfile", :options => {:node => "whatever"}, :server => nil, :protocol => nil
end
describe "when being used to select termini" do
it "should return :file if the request key is fully qualified" do
@request.expects(:key).returns File.expand_path('/foo')
- @object.select(@request).should == :file
+ expect(@object.select(@request)).to eq(:file)
end
it "should return :file if the URI protocol is set to 'file'" do
@request.expects(:protocol).returns "file"
- @object.select(@request).should == :file
+ expect(@object.select(@request)).to eq(:file)
end
it "should fail when a protocol other than :puppet or :file is used" do
@request.stubs(:protocol).returns "http"
- proc { @object.select(@request) }.should raise_error(ArgumentError)
+ expect { @object.select(@request) }.to raise_error(ArgumentError)
end
describe "and the protocol is 'puppet'" do
before do
@request.stubs(:protocol).returns "puppet"
end
it "should choose :rest when a server is specified" do
@request.stubs(:protocol).returns "puppet"
@request.expects(:server).returns "foo"
- @object.select(@request).should == :rest
+ expect(@object.select(@request)).to eq(:rest)
end
# This is so a given file location works when bootstrapping with no server.
it "should choose :rest when default_file_terminus is rest" do
@request.stubs(:protocol).returns "puppet"
Puppet[:server] = 'localhost'
- @object.select(@request).should == :rest
+ expect(@object.select(@request)).to eq(:rest)
end
it "should choose :file_server when default_file_terminus is file_server and no server is specified on the request" do
modules = mock 'modules'
@request.expects(:protocol).returns "puppet"
@request.expects(:server).returns nil
Puppet[:default_file_terminus] = 'file_server'
- @object.select(@request).should == :file_server
+ expect(@object.select(@request)).to eq(:file_server)
end
end
end
end
diff --git a/spec/unit/file_system/uniquefile_spec.rb b/spec/unit/file_system/uniquefile_spec.rb
index 1268581fa..724f5b0e5 100644
--- a/spec/unit/file_system/uniquefile_spec.rb
+++ b/spec/unit/file_system/uniquefile_spec.rb
@@ -1,184 +1,184 @@
require 'spec_helper'
describe Puppet::FileSystem::Uniquefile do
it "makes the name of the file available" do
Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
expect(file.path).to match(/foo/)
end
end
it "provides a writeable file" do
Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
file.write("stuff")
file.flush
expect(Puppet::FileSystem.read(file.path)).to eq("stuff")
end
end
it "returns the value of the block" do
the_value = Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
"my value"
end
expect(the_value).to eq("my value")
end
it "unlinks the temporary file" do
filename = Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
file.path
end
- expect(Puppet::FileSystem.exist?(filename)).to be_false
+ expect(Puppet::FileSystem.exist?(filename)).to be_falsey
end
it "unlinks the temporary file even if the block raises an error" do
filename = nil
begin
Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
filename = file.path
raise "error!"
end
rescue
end
- expect(Puppet::FileSystem.exist?(filename)).to be_false
+ expect(Puppet::FileSystem.exist?(filename)).to be_falsey
end
context "Ruby 1.9.3 Tempfile tests" do
# the remaining tests in this file are ported directly from the ruby 1.9.3 source,
# since most of this file was ported from there
# see: https://github.com/ruby/ruby/blob/v1_9_3_547/test/test_tempfile.rb
def tempfile(*args, &block)
t = Puppet::FileSystem::Uniquefile.new(*args, &block)
@tempfile = (t unless block)
end
after(:each) do
if @tempfile
@tempfile.close!
end
end
it "creates tempfiles" do
t = tempfile("foo")
path = t.path
t.write("hello world")
t.close
expect(File.read(path)).to eq("hello world")
end
it "saves in tmpdir by default" do
t = tempfile("foo")
expect(Dir.tmpdir).to eq(File.dirname(t.path))
end
it "saves in given directory" do
subdir = File.join(Dir.tmpdir, "tempfile-test-#{rand}")
Dir.mkdir(subdir)
begin
tempfile = Tempfile.new("foo", subdir)
tempfile.close
begin
expect(subdir).to eq(File.dirname(tempfile.path))
ensure
tempfile.unlink
end
ensure
Dir.rmdir(subdir)
end
end
it "supports basename" do
t = tempfile("foo")
expect(File.basename(t.path)).to match(/^foo/)
end
it "supports basename with suffix" do
t = tempfile(["foo", ".txt"])
expect(File.basename(t.path)).to match(/^foo/)
expect(File.basename(t.path)).to match(/\.txt$/)
end
it "supports unlink" do
t = tempfile("foo")
path = t.path
t.close
expect(File.exist?(path)).to eq(true)
t.unlink
expect(File.exist?(path)).to eq(false)
expect(t.path).to eq(nil)
end
it "supports closing" do
t = tempfile("foo")
expect(t.closed?).to eq(false)
t.close
expect(t.closed?).to eq(true)
end
it "supports closing and unlinking via boolean argument" do
t = tempfile("foo")
path = t.path
t.close(true)
expect(t.closed?).to eq(true)
expect(t.path).to eq(nil)
expect(File.exist?(path)).to eq(false)
end
context "on unix platforms", :unless => Puppet.features.microsoft_windows? do
it "close doesn't unlink if already unlinked" do
t = tempfile("foo")
path = t.path
t.unlink
File.open(path, "w").close
begin
t.close(true)
expect(File.exist?(path)).to eq(true)
ensure
File.unlink(path) rescue nil
end
end
end
it "supports close!" do
t = tempfile("foo")
path = t.path
t.close!
expect(t.closed?).to eq(true)
expect(t.path).to eq(nil)
expect(File.exist?(path)).to eq(false)
end
context "on unix platforms", :unless => Puppet.features.microsoft_windows? do
it "close! doesn't unlink if already unlinked" do
t = tempfile("foo")
path = t.path
t.unlink
File.open(path, "w").close
begin
t.close!
expect(File.exist?(path)).to eq(true)
ensure
File.unlink(path) rescue nil
end
end
end
it "close does not make path nil" do
t = tempfile("foo")
t.close
expect(t.path.nil?).to eq(false)
end
it "close flushes buffer" do
t = tempfile("foo")
t.write("hello")
t.close
expect(File.size(t.path)).to eq(5)
end
end
end
diff --git a/spec/unit/file_system_spec.rb b/spec/unit/file_system_spec.rb
index 90d943bbf..cd6be8e1f 100644
--- a/spec/unit/file_system_spec.rb
+++ b/spec/unit/file_system_spec.rb
@@ -1,508 +1,508 @@
require 'spec_helper'
require 'puppet/file_system'
require 'puppet/util/platform'
describe "Puppet::FileSystem" do
include PuppetSpec::Files
context "#exclusive_open" do
it "opens ands allows updating of an existing file" do
file = file_containing("file_to_update", "the contents")
Puppet::FileSystem.exclusive_open(file, 0660, 'r+') do |fh|
old = fh.read
fh.truncate(0)
fh.rewind
fh.write("updated #{old}")
end
expect(Puppet::FileSystem.read(file)).to eq("updated the contents")
end
it "opens, creates ands allows updating of a new file" do
file = tmpfile("file_to_update")
Puppet::FileSystem.exclusive_open(file, 0660, 'w') do |fh|
fh.write("updated new file")
end
expect(Puppet::FileSystem.read(file)).to eq("updated new file")
end
it "excludes other processes from updating at the same time", :unless => Puppet::Util::Platform.windows? do
file = file_containing("file_to_update", "0")
increment_counter_in_multiple_processes(file, 5, 'r+')
expect(Puppet::FileSystem.read(file)).to eq("5")
end
it "excludes other processes from updating at the same time even when creating the file", :unless => Puppet::Util::Platform.windows? do
file = tmpfile("file_to_update")
increment_counter_in_multiple_processes(file, 5, 'a+')
expect(Puppet::FileSystem.read(file)).to eq("5")
end
it "times out if the lock cannot be acquired in a specified amount of time", :unless => Puppet::Util::Platform.windows? do
file = tmpfile("file_to_update")
child = spawn_process_that_locks(file)
expect do
Puppet::FileSystem.exclusive_open(file, 0666, 'a', 0.1) do |f|
end
end.to raise_error(Timeout::Error)
Process.kill(9, child)
end
def spawn_process_that_locks(file)
read, write = IO.pipe
child = Kernel.fork do
read.close
Puppet::FileSystem.exclusive_open(file, 0666, 'a') do |fh|
write.write(true)
write.close
sleep 10
end
end
write.close
read.read
read.close
child
end
def increment_counter_in_multiple_processes(file, num_procs, options)
children = []
num_procs.times do
children << Kernel.fork do
Puppet::FileSystem.exclusive_open(file, 0660, options) do |fh|
fh.rewind
contents = (fh.read || 0).to_i
fh.truncate(0)
fh.rewind
fh.write((contents + 1).to_s)
end
exit(0)
end
end
children.each { |pid| Process.wait(pid) }
end
end
describe "symlink",
:if => ! Puppet.features.manages_symlinks? &&
Puppet.features.microsoft_windows? do
let(:file) { tmpfile("somefile") }
let(:missing_file) { tmpfile("missingfile") }
let(:expected_msg) { "This version of Windows does not support symlinks. Windows Vista / 2008 or higher is required." }
before :each do
FileUtils.touch(file)
end
it "should raise an error when trying to create a symlink" do
expect { Puppet::FileSystem.symlink(file, 'foo') }.to raise_error(Puppet::Util::Windows::Error)
end
it "should return false when trying to check if a path is a symlink" do
- Puppet::FileSystem.symlink?(file).should be_false
+ expect(Puppet::FileSystem.symlink?(file)).to be_falsey
end
it "should raise an error when trying to read a symlink" do
expect { Puppet::FileSystem.readlink(file) }.to raise_error(Puppet::Util::Windows::Error)
end
it "should return a File::Stat instance when calling stat on an existing file" do
- Puppet::FileSystem.stat(file).should be_instance_of(File::Stat)
+ expect(Puppet::FileSystem.stat(file)).to be_instance_of(File::Stat)
end
it "should raise Errno::ENOENT when calling stat on a missing file" do
expect { Puppet::FileSystem.stat(missing_file) }.to raise_error(Errno::ENOENT)
end
it "should fall back to stat when trying to lstat a file" do
Puppet::Util::Windows::File.expects(:stat).with(Puppet::FileSystem.assert_path(file))
Puppet::FileSystem.lstat(file)
end
end
describe "symlink", :if => Puppet.features.manages_symlinks? do
let(:file) { tmpfile("somefile") }
let(:missing_file) { tmpfile("missingfile") }
let(:dir) { tmpdir("somedir") }
before :each do
FileUtils.touch(file)
end
it "should return true for exist? on a present file" do
- Puppet::FileSystem.exist?(file).should be_true
+ expect(Puppet::FileSystem.exist?(file)).to be_truthy
end
it "should return true for file? on a present file" do
- Puppet::FileSystem.file?(file).should be_true
+ expect(Puppet::FileSystem.file?(file)).to be_truthy
end
it "should return false for exist? on a non-existent file" do
- Puppet::FileSystem.exist?(missing_file).should be_false
+ expect(Puppet::FileSystem.exist?(missing_file)).to be_falsey
end
it "should return true for exist? on a present directory" do
- Puppet::FileSystem.exist?(dir).should be_true
+ expect(Puppet::FileSystem.exist?(dir)).to be_truthy
end
it "should return false for exist? on a dangling symlink" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(missing_file, symlink)
- Puppet::FileSystem.exist?(missing_file).should be_false
- Puppet::FileSystem.exist?(symlink).should be_false
+ expect(Puppet::FileSystem.exist?(missing_file)).to be_falsey
+ expect(Puppet::FileSystem.exist?(symlink)).to be_falsey
end
it "should return true for exist? on valid symlinks" do
[file, dir].each do |target|
symlink = tmpfile("#{Puppet::FileSystem.basename(target).to_s}_link")
Puppet::FileSystem.symlink(target, symlink)
- Puppet::FileSystem.exist?(target).should be_true
- Puppet::FileSystem.exist?(symlink).should be_true
+ expect(Puppet::FileSystem.exist?(target)).to be_truthy
+ expect(Puppet::FileSystem.exist?(symlink)).to be_truthy
end
end
it "should not create a symlink when the :noop option is specified" do
[file, dir].each do |target|
symlink = tmpfile("#{Puppet::FileSystem.basename(target)}_link")
Puppet::FileSystem.symlink(target, symlink, { :noop => true })
- Puppet::FileSystem.exist?(target).should be_true
- Puppet::FileSystem.exist?(symlink).should be_false
+ expect(Puppet::FileSystem.exist?(target)).to be_truthy
+ expect(Puppet::FileSystem.exist?(symlink)).to be_falsey
end
end
it "should raise Errno::EEXIST if trying to create a file / directory symlink when the symlink path already exists as a file" do
existing_file = tmpfile("#{Puppet::FileSystem.basename(file)}_link")
FileUtils.touch(existing_file)
[file, dir].each do |target|
expect { Puppet::FileSystem.symlink(target, existing_file) }.to raise_error(Errno::EEXIST)
- Puppet::FileSystem.exist?(existing_file).should be_true
- Puppet::FileSystem.symlink?(existing_file).should be_false
+ expect(Puppet::FileSystem.exist?(existing_file)).to be_truthy
+ expect(Puppet::FileSystem.symlink?(existing_file)).to be_falsey
end
end
it "should silently fail if trying to create a file / directory symlink when the symlink path already exists as a directory" do
existing_dir = tmpdir("#{Puppet::FileSystem.basename(file)}_dir")
[file, dir].each do |target|
- Puppet::FileSystem.symlink(target, existing_dir).should == 0
+ expect(Puppet::FileSystem.symlink(target, existing_dir)).to eq(0)
- Puppet::FileSystem.exist?(existing_dir).should be_true
- File.directory?(existing_dir).should be_true
- Puppet::FileSystem.symlink?(existing_dir).should be_false
+ expect(Puppet::FileSystem.exist?(existing_dir)).to be_truthy
+ expect(File.directory?(existing_dir)).to be_truthy
+ expect(Puppet::FileSystem.symlink?(existing_dir)).to be_falsey
end
end
it "should silently fail to modify an existing directory symlink to reference a new file or directory" do
[file, dir].each do |target|
existing_dir = tmpdir("#{Puppet::FileSystem.basename(target)}_dir")
symlink = tmpfile("#{Puppet::FileSystem.basename(existing_dir)}_link")
Puppet::FileSystem.symlink(existing_dir, symlink)
- Puppet::FileSystem.readlink(symlink).should == Puppet::FileSystem.path_string(existing_dir)
+ expect(Puppet::FileSystem.readlink(symlink)).to eq(Puppet::FileSystem.path_string(existing_dir))
# now try to point it at the new target, no error raised, but file system unchanged
- Puppet::FileSystem.symlink(target, symlink).should == 0
- Puppet::FileSystem.readlink(symlink).should == existing_dir.to_s
+ expect(Puppet::FileSystem.symlink(target, symlink)).to eq(0)
+ expect(Puppet::FileSystem.readlink(symlink)).to eq(existing_dir.to_s)
end
end
it "should raise Errno::EEXIST if trying to modify a file symlink to reference a new file or directory" do
symlink = tmpfile("#{Puppet::FileSystem.basename(file)}_link")
file_2 = tmpfile("#{Puppet::FileSystem.basename(file)}_2")
FileUtils.touch(file_2)
# symlink -> file_2
Puppet::FileSystem.symlink(file_2, symlink)
[file, dir].each do |target|
expect { Puppet::FileSystem.symlink(target, symlink) }.to raise_error(Errno::EEXIST)
- Puppet::FileSystem.readlink(symlink).should == file_2.to_s
+ expect(Puppet::FileSystem.readlink(symlink)).to eq(file_2.to_s)
end
end
it "should delete the existing file when creating a file / directory symlink with :force when the symlink path exists as a file" do
[file, dir].each do |target|
existing_file = tmpfile("#{Puppet::FileSystem.basename(target)}_existing")
FileUtils.touch(existing_file)
- Puppet::FileSystem.symlink?(existing_file).should be_false
+ expect(Puppet::FileSystem.symlink?(existing_file)).to be_falsey
Puppet::FileSystem.symlink(target, existing_file, { :force => true })
- Puppet::FileSystem.symlink?(existing_file).should be_true
- Puppet::FileSystem.readlink(existing_file).should == target.to_s
+ expect(Puppet::FileSystem.symlink?(existing_file)).to be_truthy
+ expect(Puppet::FileSystem.readlink(existing_file)).to eq(target.to_s)
end
end
it "should modify an existing file symlink when using :force to reference a new file or directory" do
[file, dir].each do |target|
existing_file = tmpfile("#{Puppet::FileSystem.basename(target)}_existing")
FileUtils.touch(existing_file)
existing_symlink = tmpfile("#{Puppet::FileSystem.basename(existing_file)}_link")
Puppet::FileSystem.symlink(existing_file, existing_symlink)
- Puppet::FileSystem.readlink(existing_symlink).should == existing_file.to_s
+ expect(Puppet::FileSystem.readlink(existing_symlink)).to eq(existing_file.to_s)
Puppet::FileSystem.symlink(target, existing_symlink, { :force => true })
- Puppet::FileSystem.readlink(existing_symlink).should == target.to_s
+ expect(Puppet::FileSystem.readlink(existing_symlink)).to eq(target.to_s)
end
end
it "should silently fail if trying to overwrite an existing directory with a new symlink when using :force to reference a file or directory" do
[file, dir].each do |target|
existing_dir = tmpdir("#{Puppet::FileSystem.basename(target)}_existing")
- Puppet::FileSystem.symlink(target, existing_dir, { :force => true }).should == 0
+ expect(Puppet::FileSystem.symlink(target, existing_dir, { :force => true })).to eq(0)
- Puppet::FileSystem.symlink?(existing_dir).should be_false
+ expect(Puppet::FileSystem.symlink?(existing_dir)).to be_falsey
end
end
it "should silently fail if trying to modify an existing directory symlink when using :force to reference a new file or directory" do
[file, dir].each do |target|
existing_dir = tmpdir("#{Puppet::FileSystem.basename(target)}_existing")
existing_symlink = tmpfile("#{Puppet::FileSystem.basename(existing_dir)}_link")
Puppet::FileSystem.symlink(existing_dir, existing_symlink)
- Puppet::FileSystem.readlink(existing_symlink).should == existing_dir.to_s
+ expect(Puppet::FileSystem.readlink(existing_symlink)).to eq(existing_dir.to_s)
- Puppet::FileSystem.symlink(target, existing_symlink, { :force => true }).should == 0
+ expect(Puppet::FileSystem.symlink(target, existing_symlink, { :force => true })).to eq(0)
- Puppet::FileSystem.readlink(existing_symlink).should == existing_dir.to_s
+ expect(Puppet::FileSystem.readlink(existing_symlink)).to eq(existing_dir.to_s)
end
end
it "should accept a string, Pathname or object with to_str (Puppet::Util::WatchedFile) for exist?" do
[ tmpfile('bogus1'),
Pathname.new(tmpfile('bogus2')),
Puppet::Util::WatchedFile.new(tmpfile('bogus3'))
- ].each { |f| Puppet::FileSystem.exist?(f).should be_false }
+ ].each { |f| expect(Puppet::FileSystem.exist?(f)).to be_falsey }
end
it "should return a File::Stat instance when calling stat on an existing file" do
- Puppet::FileSystem.stat(file).should be_instance_of(File::Stat)
+ expect(Puppet::FileSystem.stat(file)).to be_instance_of(File::Stat)
end
it "should raise Errno::ENOENT when calling stat on a missing file" do
expect { Puppet::FileSystem.stat(missing_file) }.to raise_error(Errno::ENOENT)
end
it "should be able to create a symlink, and verify it with symlink?" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
- Puppet::FileSystem.symlink?(symlink).should be_true
+ expect(Puppet::FileSystem.symlink?(symlink)).to be_truthy
end
it "should report symlink? as false on file, directory and missing files" do
[file, dir, missing_file].each do |f|
- Puppet::FileSystem.symlink?(f).should be_false
+ expect(Puppet::FileSystem.symlink?(f)).to be_falsey
end
end
it "should return a File::Stat with ftype 'link' when calling lstat on a symlink pointing to existing file" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
stat = Puppet::FileSystem.lstat(symlink)
- stat.should be_instance_of(File::Stat)
- stat.ftype.should == 'link'
+ expect(stat).to be_instance_of(File::Stat)
+ expect(stat.ftype).to eq('link')
end
it "should return a File::Stat of ftype 'link' when calling lstat on a symlink pointing to missing file" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(missing_file, symlink)
stat = Puppet::FileSystem.lstat(symlink)
- stat.should be_instance_of(File::Stat)
- stat.ftype.should == 'link'
+ expect(stat).to be_instance_of(File::Stat)
+ expect(stat.ftype).to eq('link')
end
it "should return a File::Stat of ftype 'file' when calling stat on a symlink pointing to existing file" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
stat = Puppet::FileSystem.stat(symlink)
- stat.should be_instance_of(File::Stat)
- stat.ftype.should == 'file'
+ expect(stat).to be_instance_of(File::Stat)
+ expect(stat.ftype).to eq('file')
end
it "should return a File::Stat of ftype 'directory' when calling stat on a symlink pointing to existing directory" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(dir, symlink)
stat = Puppet::FileSystem.stat(symlink)
- stat.should be_instance_of(File::Stat)
- stat.ftype.should == 'directory'
+ expect(stat).to be_instance_of(File::Stat)
+ expect(stat.ftype).to eq('directory')
# on Windows, this won't get cleaned up if still linked
Puppet::FileSystem.unlink(symlink)
end
it "should return a File::Stat of ftype 'file' when calling stat on a symlink pointing to another symlink" do
# point symlink -> file
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
# point symlink2 -> symlink
symlink2 = tmpfile("somefile_link2")
Puppet::FileSystem.symlink(symlink, symlink2)
- Puppet::FileSystem.stat(symlink2).ftype.should == 'file'
+ expect(Puppet::FileSystem.stat(symlink2).ftype).to eq('file')
end
it "should raise Errno::ENOENT when calling stat on a dangling symlink" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(missing_file, symlink)
expect { Puppet::FileSystem.stat(symlink) }.to raise_error(Errno::ENOENT)
end
it "should be able to readlink to resolve the physical path to a symlink" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
- Puppet::FileSystem.exist?(file).should be_true
- Puppet::FileSystem.readlink(symlink).should == file.to_s
+ expect(Puppet::FileSystem.exist?(file)).to be_truthy
+ expect(Puppet::FileSystem.readlink(symlink)).to eq(file.to_s)
end
it "should not resolve entire symlink chain with readlink on a symlink'd symlink" do
# point symlink -> file
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
# point symlink2 -> symlink
symlink2 = tmpfile("somefile_link2")
Puppet::FileSystem.symlink(symlink, symlink2)
- Puppet::FileSystem.exist?(file).should be_true
- Puppet::FileSystem.readlink(symlink2).should == symlink.to_s
+ expect(Puppet::FileSystem.exist?(file)).to be_truthy
+ expect(Puppet::FileSystem.readlink(symlink2)).to eq(symlink.to_s)
end
it "should be able to readlink to resolve the physical path to a dangling symlink" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(missing_file, symlink)
- Puppet::FileSystem.exist?(missing_file).should be_false
- Puppet::FileSystem.readlink(symlink).should == missing_file.to_s
+ expect(Puppet::FileSystem.exist?(missing_file)).to be_falsey
+ expect(Puppet::FileSystem.readlink(symlink)).to eq(missing_file.to_s)
end
it "should delete only the symlink and not the target when calling unlink instance method" do
[file, dir].each do |target|
symlink = tmpfile("#{Puppet::FileSystem.basename(target)}_link")
Puppet::FileSystem.symlink(target, symlink)
- Puppet::FileSystem.exist?(target).should be_true
- Puppet::FileSystem.readlink(symlink).should == target.to_s
+ expect(Puppet::FileSystem.exist?(target)).to be_truthy
+ expect(Puppet::FileSystem.readlink(symlink)).to eq(target.to_s)
- Puppet::FileSystem.unlink(symlink).should == 1 # count of files
+ expect(Puppet::FileSystem.unlink(symlink)).to eq(1) # count of files
- Puppet::FileSystem.exist?(target).should be_true
- Puppet::FileSystem.exist?(symlink).should be_false
+ expect(Puppet::FileSystem.exist?(target)).to be_truthy
+ expect(Puppet::FileSystem.exist?(symlink)).to be_falsey
end
end
it "should delete only the symlink and not the target when calling unlink class method" do
[file, dir].each do |target|
symlink = tmpfile("#{Puppet::FileSystem.basename(target)}_link")
Puppet::FileSystem.symlink(target, symlink)
- Puppet::FileSystem.exist?(target).should be_true
- Puppet::FileSystem.readlink(symlink).should == target.to_s
+ expect(Puppet::FileSystem.exist?(target)).to be_truthy
+ expect(Puppet::FileSystem.readlink(symlink)).to eq(target.to_s)
- Puppet::FileSystem.unlink(symlink).should == 1 # count of files
+ expect(Puppet::FileSystem.unlink(symlink)).to eq(1) # count of files
- Puppet::FileSystem.exist?(target).should be_true
- Puppet::FileSystem.exist?(symlink).should be_false
+ expect(Puppet::FileSystem.exist?(target)).to be_truthy
+ expect(Puppet::FileSystem.exist?(symlink)).to be_falsey
end
end
describe "unlink" do
it "should delete files with unlink" do
- Puppet::FileSystem.exist?(file).should be_true
+ expect(Puppet::FileSystem.exist?(file)).to be_truthy
- Puppet::FileSystem.unlink(file).should == 1 # count of files
+ expect(Puppet::FileSystem.unlink(file)).to eq(1) # count of files
- Puppet::FileSystem.exist?(file).should be_false
+ expect(Puppet::FileSystem.exist?(file)).to be_falsey
end
it "should delete files with unlink class method" do
- Puppet::FileSystem.exist?(file).should be_true
+ expect(Puppet::FileSystem.exist?(file)).to be_truthy
- Puppet::FileSystem.unlink(file).should == 1 # count of files
+ expect(Puppet::FileSystem.unlink(file)).to eq(1) # count of files
- Puppet::FileSystem.exist?(file).should be_false
+ expect(Puppet::FileSystem.exist?(file)).to be_falsey
end
it "should delete multiple files with unlink class method" do
paths = (1..3).collect do |i|
f = tmpfile("somefile_#{i}")
FileUtils.touch(f)
- Puppet::FileSystem.exist?(f).should be_true
+ expect(Puppet::FileSystem.exist?(f)).to be_truthy
f.to_s
end
- Puppet::FileSystem.unlink(*paths).should == 3 # count of files
+ expect(Puppet::FileSystem.unlink(*paths)).to eq(3) # count of files
- paths.each { |p| Puppet::FileSystem.exist?(p).should be_false }
+ paths.each { |p| expect(Puppet::FileSystem.exist?(p)).to be_falsey }
end
it "should raise Errno::EPERM or Errno::EISDIR when trying to delete a directory with the unlink class method" do
- Puppet::FileSystem.exist?(dir).should be_true
+ expect(Puppet::FileSystem.exist?(dir)).to be_truthy
ex = nil
begin
Puppet::FileSystem.unlink(dir)
rescue Exception => e
ex = e
end
- [
+ expect([
Errno::EPERM, # Windows and OSX
Errno::EISDIR # Linux
- ].should include(ex.class)
+ ]).to include(ex.class)
- Puppet::FileSystem.exist?(dir).should be_true
+ expect(Puppet::FileSystem.exist?(dir)).to be_truthy
end
end
describe "exclusive_create" do
it "should create a file that doesn't exist" do
- Puppet::FileSystem.exist?(missing_file).should be_false
+ expect(Puppet::FileSystem.exist?(missing_file)).to be_falsey
Puppet::FileSystem.exclusive_create(missing_file, nil) {}
- Puppet::FileSystem.exist?(missing_file).should be_true
+ expect(Puppet::FileSystem.exist?(missing_file)).to be_truthy
end
it "should raise Errno::EEXIST creating a file that does exist" do
- Puppet::FileSystem.exist?(file).should be_true
+ expect(Puppet::FileSystem.exist?(file)).to be_truthy
expect do
Puppet::FileSystem.exclusive_create(file, nil) {}
end.to raise_error(Errno::EEXIST)
end
end
end
end
diff --git a/spec/unit/forge/errors_spec.rb b/spec/unit/forge/errors_spec.rb
index fc1ac1a0e..61253bb90 100644
--- a/spec/unit/forge/errors_spec.rb
+++ b/spec/unit/forge/errors_spec.rb
@@ -1,80 +1,80 @@
require 'spec_helper'
require 'puppet/forge'
describe Puppet::Forge::Errors do
describe 'SSLVerifyError' do
subject { Puppet::Forge::Errors::SSLVerifyError }
let(:exception) { subject.new(:uri => 'https://fake.com:1111') }
it 'should return a valid single line error' do
- exception.message.should == 'Unable to verify the SSL certificate at https://fake.com:1111'
+ expect(exception.message).to eq('Unable to verify the SSL certificate at https://fake.com:1111')
end
it 'should return a valid multiline error' do
- exception.multiline.should == <<-EOS.chomp
+ expect(exception.multiline).to eq <<-EOS.chomp
Could not connect via HTTPS to https://fake.com:1111
Unable to verify the SSL certificate
The certificate may not be signed by a valid CA
The CA bundle included with OpenSSL may not be valid or up to date
EOS
end
end
describe 'CommunicationError' do
subject { Puppet::Forge::Errors::CommunicationError }
let(:socket_exception) { SocketError.new('There was a problem') }
let(:exception) { subject.new(:uri => 'http://fake.com:1111', :original => socket_exception) }
it 'should return a valid single line error' do
- exception.message.should == 'Unable to connect to the server at http://fake.com:1111. Detail: There was a problem.'
+ expect(exception.message).to eq('Unable to connect to the server at http://fake.com:1111. Detail: There was a problem.')
end
it 'should return a valid multiline error' do
- exception.multiline.should == <<-EOS.chomp
+ expect(exception.multiline).to eq <<-EOS.chomp
Could not connect to http://fake.com:1111
There was a network communications problem
The error we caught said 'There was a problem'
Check your network connection and try again
EOS
end
end
describe 'ResponseError' do
subject { Puppet::Forge::Errors::ResponseError }
let(:response) { stub(:body => '{}', :code => '404', :message => "not found") }
context 'without message' do
let(:exception) { subject.new(:uri => 'http://fake.com:1111', :response => response, :input => 'user/module') }
it 'should return a valid single line error' do
- exception.message.should == 'Request to Puppet Forge failed. Detail: 404 not found.'
+ expect(exception.message).to eq('Request to Puppet Forge failed. Detail: 404 not found.')
end
it 'should return a valid multiline error' do
- exception.multiline.should == <<-eos.chomp
+ expect(exception.multiline).to eq <<-eos.chomp
Request to Puppet Forge failed.
The server being queried was http://fake.com:1111
The HTTP response we received was '404 not found'
eos
end
end
context 'with message' do
let(:exception) { subject.new(:uri => 'http://fake.com:1111', :response => response, :input => 'user/module', :message => 'no such module') }
it 'should return a valid single line error' do
- exception.message.should == 'Request to Puppet Forge failed. Detail: no such module / 404 not found.'
+ expect(exception.message).to eq('Request to Puppet Forge failed. Detail: no such module / 404 not found.')
end
it 'should return a valid multiline error' do
- exception.multiline.should == <<-eos.chomp
+ expect(exception.multiline).to eq <<-eos.chomp
Request to Puppet Forge failed.
The server being queried was http://fake.com:1111
The HTTP response we received was '404 not found'
The message we received said 'no such module'
eos
end
end
end
end
diff --git a/spec/unit/forge/module_release_spec.rb b/spec/unit/forge/module_release_spec.rb
index ce00b27e9..bf4383332 100644
--- a/spec/unit/forge/module_release_spec.rb
+++ b/spec/unit/forge/module_release_spec.rb
@@ -1,218 +1,218 @@
# encoding: utf-8
require 'spec_helper'
require 'puppet/forge'
require 'net/http'
require 'puppet/module_tool'
describe Puppet::Forge::ModuleRelease do
let(:agent) { "Test/1.0" }
let(:repository) { Puppet::Forge::Repository.new('http://fake.com', agent) }
let(:ssl_repository) { Puppet::Forge::Repository.new('https://fake.com', agent) }
let(:api_version) { "v3" }
let(:module_author) { "puppetlabs" }
let(:module_name) { "stdlib" }
let(:module_version) { "4.1.0" }
let(:module_full_name) { "#{module_author}-#{module_name}" }
let(:module_full_name_versioned) { "#{module_full_name}-#{module_version}" }
let(:module_md5) { "bbf919d7ee9d278d2facf39c25578bf8" }
let(:uri) { " "}
let(:release) { Puppet::Forge::ModuleRelease.new(ssl_repository, JSON.parse(release_json)) }
let(:mock_file) {
mock_io = StringIO.new
mock_io.stubs(:path).returns('/dev/null')
mock_io
}
let(:mock_dir) { '/tmp' }
shared_examples 'a module release' do
def mock_digest_file_with_md5(md5)
Digest::MD5.stubs(:file).returns(stub(:hexdigest => md5))
end
describe '#prepare' do
before :each do
release.stubs(:tmpfile).returns(mock_file)
release.stubs(:tmpdir).returns(mock_dir)
end
it 'should call sub methods with correct params' do
release.expects(:download).with("/#{api_version}/files/#{module_full_name_versioned}.tar.gz", mock_file)
release.expects(:validate_checksum).with(mock_file, module_md5)
release.expects(:unpack).with(mock_file, mock_dir)
release.prepare
end
end
describe '#tmpfile' do
it 'should be opened in binary mode' do
Puppet::Forge::Cache.stubs(:base_path).returns(Dir.tmpdir)
- release.send(:tmpfile).binmode?.should be_true
+ expect(release.send(:tmpfile).binmode?).to be_truthy
end
end
describe '#download' do
it 'should call make_http_request with correct params' do
# valid URI comes from file_uri in JSON blob above
ssl_repository.expects(:make_http_request).with("/#{api_version}/files/#{module_full_name_versioned}.tar.gz", mock_file).returns(stub(:body => '{}', :code => '200'))
release.send(:download, "/#{api_version}/files/#{module_full_name_versioned}.tar.gz", mock_file)
end
it 'should raise a response error when it receives an error from forge' do
ssl_repository.stubs(:make_http_request).returns(stub(:body => '{"errors": ["error"]}', :code => '500', :message => 'server error'))
expect { release.send(:download, "/some/path", mock_file)}. to raise_error Puppet::Forge::Errors::ResponseError
end
end
describe '#verify_checksum' do
it 'passes md5 check when valid' do
# valid hash comes from file_md5 in JSON blob above
mock_digest_file_with_md5(module_md5)
release.send(:validate_checksum, mock_file, module_md5)
end
it 'fails md5 check when invalid' do
mock_digest_file_with_md5('ffffffffffffffffffffffffffffffff')
expect { release.send(:validate_checksum, mock_file, module_md5) }.to raise_error(RuntimeError, /did not match expected checksum/)
end
end
describe '#unpack' do
it 'should call unpacker with correct params' do
Puppet::ModuleTool::Applications::Unpacker.expects(:unpack).with(mock_file.path, mock_dir).returns(true)
release.send(:unpack, mock_file, mock_dir)
end
end
end
context 'standard forge module' do
let(:release_json) do %Q{
{
"uri": "/#{api_version}/releases/#{module_full_name_versioned}",
"module": {
"uri": "/#{api_version}/modules/#{module_full_name}",
"name": "#{module_name}",
"owner": {
"uri": "/#{api_version}/users/#{module_author}",
"username": "#{module_author}",
"gravatar_id": "fdd009b7c1ec96e088b389f773e87aec"
}
},
"version": "#{module_version}",
"metadata": {
"types": [ ],
"license": "Apache 2.0",
"checksums": { },
"version": "#{module_version}",
"description": "Standard Library for Puppet Modules",
"source": "git://github.com/puppetlabs/puppetlabs-stdlib.git",
"project_page": "https://github.com/puppetlabs/puppetlabs-stdlib",
"summary": "Puppet Module Standard Library",
"dependencies": [
],
"author": "#{module_author}",
"name": "#{module_full_name}"
},
"tags": [
"puppetlabs",
"library",
"stdlib",
"standard",
"stages"
],
"file_uri": "/#{api_version}/files/#{module_full_name_versioned}.tar.gz",
"file_size": 67586,
"file_md5": "#{module_md5}",
"downloads": 610751,
"readme": "",
"changelog": "",
"license": "",
"created_at": "2013-05-13 08:31:19 -0700",
"updated_at": "2013-05-13 08:31:19 -0700",
"deleted_at": null
}
}
end
it_behaves_like 'a module release'
end
context 'forge module with no dependencies field' do
let(:release_json) do %Q{
{
"uri": "/#{api_version}/releases/#{module_full_name_versioned}",
"module": {
"uri": "/#{api_version}/modules/#{module_full_name}",
"name": "#{module_name}",
"owner": {
"uri": "/#{api_version}/users/#{module_author}",
"username": "#{module_author}",
"gravatar_id": "fdd009b7c1ec96e088b389f773e87aec"
}
},
"version": "#{module_version}",
"metadata": {
"types": [ ],
"license": "Apache 2.0",
"checksums": { },
"version": "#{module_version}",
"description": "Standard Library for Puppet Modules",
"source": "git://github.com/puppetlabs/puppetlabs-stdlib.git",
"project_page": "https://github.com/puppetlabs/puppetlabs-stdlib",
"summary": "Puppet Module Standard Library",
"author": "#{module_author}",
"name": "#{module_full_name}"
},
"tags": [
"puppetlabs",
"library",
"stdlib",
"standard",
"stages"
],
"file_uri": "/#{api_version}/files/#{module_full_name_versioned}.tar.gz",
"file_size": 67586,
"file_md5": "#{module_md5}",
"downloads": 610751,
"readme": "",
"changelog": "",
"license": "",
"created_at": "2013-05-13 08:31:19 -0700",
"updated_at": "2013-05-13 08:31:19 -0700",
"deleted_at": null
}
}
end
it_behaves_like 'a module release'
end
context 'forge module with the minimal set of fields' do
let(:release_json) do %Q{
{
"uri": "/#{api_version}/releases/#{module_full_name_versioned}",
"module": {
"uri": "/#{api_version}/modules/#{module_full_name}",
"name": "#{module_name}"
},
"metadata": {
"version": "#{module_version}",
"name": "#{module_full_name}"
},
"file_uri": "/#{api_version}/files/#{module_full_name_versioned}.tar.gz",
"file_size": 67586,
"file_md5": "#{module_md5}"
}
}
end
it_behaves_like 'a module release'
end
end
diff --git a/spec/unit/forge/repository_spec.rb b/spec/unit/forge/repository_spec.rb
index 2dc9dd1f9..1e2c1b5e4 100644
--- a/spec/unit/forge/repository_spec.rb
+++ b/spec/unit/forge/repository_spec.rb
@@ -1,224 +1,224 @@
# encoding: utf-8
require 'spec_helper'
require 'net/http'
require 'puppet/forge/repository'
require 'puppet/forge/cache'
require 'puppet/forge/errors'
describe Puppet::Forge::Repository do
let(:agent) { "Test/1.0" }
let(:repository) { Puppet::Forge::Repository.new('http://fake.com', agent) }
let(:ssl_repository) { Puppet::Forge::Repository.new('https://fake.com', agent) }
it "retrieve accesses the cache" do
path = '/module/foo.tar.gz'
repository.cache.expects(:retrieve)
repository.retrieve(path)
end
it "retrieve merges forge URI and path specified" do
host = 'http://fake.com/test'
path = '/module/foo.tar.gz'
uri = [ host, path ].join('')
repository = Puppet::Forge::Repository.new(host, agent)
repository.cache.expects(:retrieve).with(uri)
repository.retrieve(path)
end
describe "making a request" do
before :each do
proxy_settings_of("proxy", 1234)
end
it "returns the result object from the request" do
result = "#{Object.new}"
performs_an_http_request result do |http|
http.expects(:request).with(responds_with(:path, "the_path"))
end
- repository.make_http_request("the_path").should == result
+ expect(repository.make_http_request("the_path")).to eq(result)
end
it 'returns the result object from a request with ssl' do
result = "#{Object.new}"
performs_an_https_request result do |http|
http.expects(:request).with(responds_with(:path, "the_path"))
end
- ssl_repository.make_http_request("the_path").should == result
+ expect(ssl_repository.make_http_request("the_path")).to eq(result)
end
it 'return a valid exception when there is an SSL verification problem' do
performs_an_https_request "#{Object.new}" do |http|
http.expects(:request).with(responds_with(:path, "the_path")).raises OpenSSL::SSL::SSLError.new("certificate verify failed")
end
expect { ssl_repository.make_http_request("the_path") }.to raise_error Puppet::Forge::Errors::SSLVerifyError, 'Unable to verify the SSL certificate at https://fake.com'
end
it 'return a valid exception when there is a communication problem' do
performs_an_http_request "#{Object.new}" do |http|
http.expects(:request).with(responds_with(:path, "the_path")).raises SocketError
end
expect { repository.make_http_request("the_path") }.
to raise_error Puppet::Forge::Errors::CommunicationError,
'Unable to connect to the server at http://fake.com. Detail: SocketError.'
end
it "sets the user agent for the request" do
path = 'the_path'
request = repository.get_request_object(path)
- request['User-Agent'].should =~ /\b#{agent}\b/
- request['User-Agent'].should =~ /\bPuppet\b/
- request['User-Agent'].should =~ /\bRuby\b/
+ expect(request['User-Agent']).to match(/\b#{agent}\b/)
+ expect(request['User-Agent']).to match(/\bPuppet\b/)
+ expect(request['User-Agent']).to match(/\bRuby\b/)
end
it "Does not set Authorization header by default" do
Puppet.features.stubs(:pe_license?).returns(false)
Puppet[:forge_authorization] = nil
request = repository.get_request_object("the_path")
- request['Authorization'].should == nil
+ expect(request['Authorization']).to eq(nil)
end
it "Sets Authorization header from config" do
token = 'bearer some token'
Puppet[:forge_authorization] = token
request = repository.get_request_object("the_path")
- request['Authorization'].should == token
+ expect(request['Authorization']).to eq(token)
end
it "escapes the received URI" do
unescaped_uri = "héllo world !! ç à"
performs_an_http_request do |http|
http.expects(:request).with(responds_with(:path, URI.escape(unescaped_uri)))
end
repository.make_http_request(unescaped_uri)
end
def performs_an_http_request(result = nil, &block)
proxy_args = ["proxy", 1234, nil, nil]
mock_proxy(80, proxy_args, result, &block)
end
def performs_an_https_request(result = nil, &block)
proxy_args = ["proxy", 1234, nil, nil]
proxy = mock_proxy(443, proxy_args, result, &block)
proxy.expects(:use_ssl=).with(true)
proxy.expects(:cert_store=)
proxy.expects(:verify_mode=).with(OpenSSL::SSL::VERIFY_PEER)
end
end
describe "making a request against an authentiated proxy" do
before :each do
authenticated_proxy_settings_of("proxy", 1234, 'user1', 'password')
end
it "returns the result object from the request" do
result = "#{Object.new}"
performs_an_authenticated_http_request result do |http|
http.expects(:request).with(responds_with(:path, "the_path"))
end
- repository.make_http_request("the_path").should == result
+ expect(repository.make_http_request("the_path")).to eq(result)
end
it 'returns the result object from a request with ssl' do
result = "#{Object.new}"
performs_an_authenticated_https_request result do |http|
http.expects(:request).with(responds_with(:path, "the_path"))
end
- ssl_repository.make_http_request("the_path").should == result
+ expect(ssl_repository.make_http_request("the_path")).to eq(result)
end
it 'return a valid exception when there is an SSL verification problem' do
performs_an_authenticated_https_request "#{Object.new}" do |http|
http.expects(:request).with(responds_with(:path, "the_path")).raises OpenSSL::SSL::SSLError.new("certificate verify failed")
end
expect { ssl_repository.make_http_request("the_path") }.to raise_error Puppet::Forge::Errors::SSLVerifyError, 'Unable to verify the SSL certificate at https://fake.com'
end
it 'return a valid exception when there is a communication problem' do
performs_an_authenticated_http_request "#{Object.new}" do |http|
http.expects(:request).with(responds_with(:path, "the_path")).raises SocketError
end
expect { repository.make_http_request("the_path") }.
to raise_error Puppet::Forge::Errors::CommunicationError,
'Unable to connect to the server at http://fake.com. Detail: SocketError.'
end
it "sets the user agent for the request" do
path = 'the_path'
request = repository.get_request_object(path)
- request['User-Agent'].should =~ /\b#{agent}\b/
- request['User-Agent'].should =~ /\bPuppet\b/
- request['User-Agent'].should =~ /\bRuby\b/
+ expect(request['User-Agent']).to match(/\b#{agent}\b/)
+ expect(request['User-Agent']).to match(/\bPuppet\b/)
+ expect(request['User-Agent']).to match(/\bRuby\b/)
end
it "escapes the received URI" do
unescaped_uri = "héllo world !! ç à"
performs_an_authenticated_http_request do |http|
http.expects(:request).with(responds_with(:path, URI.escape(unescaped_uri)))
end
repository.make_http_request(unescaped_uri)
end
def performs_an_authenticated_http_request(result = nil, &block)
proxy_args = ["proxy", 1234, 'user1', 'password']
mock_proxy(80, proxy_args, result, &block)
end
def performs_an_authenticated_https_request(result = nil, &block)
proxy_args = ["proxy", 1234, 'user1', 'password']
proxy = mock_proxy(443, proxy_args, result, &block)
proxy.expects(:use_ssl=).with(true)
proxy.expects(:cert_store=)
proxy.expects(:verify_mode=).with(OpenSSL::SSL::VERIFY_PEER)
end
end
def proxy_settings_of(host, port)
Puppet[:http_proxy_host] = host
Puppet[:http_proxy_port] = port
end
def authenticated_proxy_settings_of(host, port, user, password)
Puppet[:http_proxy_host] = host
Puppet[:http_proxy_port] = port
Puppet[:http_proxy_user] = user
Puppet[:http_proxy_password] = password
end
def mock_proxy(port, proxy_args, result, &block)
http = mock("http client")
proxy = mock("http proxy")
proxy_class = mock("http proxy class")
Net::HTTP.expects(:Proxy).with(*proxy_args).returns(proxy_class)
proxy_class.expects(:new).with("fake.com", port).returns(proxy)
proxy.expects(:open_timeout=)
proxy.expects(:read_timeout=)
proxy.expects(:start).yields(http).returns(result)
yield http
proxy
end
end
diff --git a/spec/unit/forge_spec.rb b/spec/unit/forge_spec.rb
index eb7c56a3e..72a91a374 100644
--- a/spec/unit/forge_spec.rb
+++ b/spec/unit/forge_spec.rb
@@ -1,172 +1,172 @@
require 'spec_helper'
require 'puppet/forge'
require 'net/http'
require 'puppet/module_tool'
describe Puppet::Forge do
let(:http_response) do
<<-EOF
{
"pagination": {
"limit": 1,
"offset": 0,
"first": "/v3/modules?limit=1&offset=0",
"previous": null,
"current": "/v3/modules?limit=1&offset=0",
"next": null,
"total": 1832
},
"results": [
{
"uri": "/v3/modules/puppetlabs-bacula",
"name": "bacula",
"downloads": 640274,
"created_at": "2011-05-24 18:34:58 -0700",
"updated_at": "2013-12-03 15:24:20 -0800",
"owner": {
"uri": "/v3/users/puppetlabs",
"username": "puppetlabs",
"gravatar_id": "fdd009b7c1ec96e088b389f773e87aec"
},
"current_release": {
"uri": "/v3/releases/puppetlabs-bacula-0.0.2",
"module": {
"uri": "/v3/modules/puppetlabs-bacula",
"name": "bacula",
"owner": {
"uri": "/v3/users/puppetlabs",
"username": "puppetlabs",
"gravatar_id": "fdd009b7c1ec96e088b389f773e87aec"
}
},
"version": "0.0.2",
"metadata": {
"types": [],
"license": "Apache 2.0",
"checksums": { },
"version": "0.0.2",
"source": "git://github.com/puppetlabs/puppetlabs-bacula.git",
"project_page": "https://github.com/puppetlabs/puppetlabs-bacula",
"summary": "bacula",
"dependencies": [ ],
"author": "puppetlabs",
"name": "puppetlabs-bacula"
},
"tags": [
"backup",
"bacula"
],
"file_uri": "/v3/files/puppetlabs-bacula-0.0.2.tar.gz",
"file_size": 67586,
"file_md5": "bbf919d7ee9d278d2facf39c25578bf8",
"downloads": 565041,
"readme": "",
"changelog": "",
"license": "",
"created_at": "2013-05-13 08:31:19 -0700",
"updated_at": "2013-05-13 08:31:19 -0700",
"deleted_at": null
},
"releases": [
{
"uri": "/v3/releases/puppetlabs-bacula-0.0.2",
"version": "0.0.2"
},
{
"uri": "/v3/releases/puppetlabs-bacula-0.0.1",
"version": "0.0.1"
}
],
"homepage_url": "https://github.com/puppetlabs/puppetlabs-bacula",
"issues_url": "https://projects.puppetlabs.com/projects/bacula/issues"
}
]
}
EOF
end
let(:search_results) do
JSON.parse(http_response)['results'].map do |hash|
hash.merge(
"author" => "puppetlabs",
"name" => "bacula",
"tag_list" => ["backup", "bacula"],
"full_name" => "puppetlabs/bacula",
"version" => "0.0.2",
"project_url" => "https://github.com/puppetlabs/puppetlabs-bacula",
"desc" => "bacula"
)
end
end
let(:forge) { Puppet::Forge.new }
def repository_responds_with(response)
Puppet::Forge::Repository.any_instance.stubs(:make_http_request).returns(response)
end
it "returns a list of matches from the forge when there are matches for the search term" do
repository_responds_with(stub(:body => http_response, :code => '200'))
- forge.search('bacula').should == search_results
+ expect(forge.search('bacula')).to eq(search_results)
end
context "when module_groups are defined" do
let(:release_response) do
releases = JSON.parse(http_response)
releases['results'] = []
JSON.dump(releases)
end
before :each do
repository_responds_with(stub(:body => release_response, :code => '200')).with {|uri| uri =~ /module_groups=foo/}
Puppet[:module_groups] = "foo"
end
it "passes module_groups with search" do
forge.search('bacula')
end
it "passes module_groups with fetch" do
forge.fetch('puppetlabs-bacula')
end
end
context "when the connection to the forge fails" do
before :each do
repository_responds_with(stub(:body => '{}', :code => '404', :message => "not found"))
end
it "raises an error for search" do
expect { forge.search('bacula') }.to raise_error Puppet::Forge::Errors::ResponseError, "Request to Puppet Forge failed. Detail: 404 not found."
end
it "raises an error for fetch" do
expect { forge.fetch('puppetlabs/bacula') }.to raise_error Puppet::Forge::Errors::ResponseError, "Request to Puppet Forge failed. Detail: 404 not found."
end
end
context "when the API responds with an error" do
before :each do
repository_responds_with(stub(:body => '{"error":"invalid module"}', :code => '410', :message => "Gone"))
end
it "raises an error for fetch" do
expect { forge.fetch('puppetlabs/bacula') }.to raise_error Puppet::Forge::Errors::ResponseError, "Request to Puppet Forge failed. Detail: 410 Gone."
end
end
context "when the forge returns a module with unparseable dependencies" do
before :each do
response = JSON.parse(http_response)
release = response['results'][0]['current_release']
release['metadata']['dependencies'] = [{'name' => 'broken-garbage >= 1.0.0', 'version_requirement' => 'banana'}]
response['results'] = [release]
repository_responds_with(stub(:body => JSON.dump(response), :code => '200'))
end
it "ignores modules with unparseable dependencies" do
expect { result = forge.fetch('puppetlabs/bacula') }.to_not raise_error
expect { result.to be_empty }
end
end
end
diff --git a/spec/unit/functions/each_spec.rb b/spec/unit/functions/each_spec.rb
index b8d3289ac..bd6d9a1c5 100644
--- a/spec/unit/functions/each_spec.rb
+++ b/spec/unit/functions/each_spec.rb
@@ -1,107 +1,107 @@
require 'puppet'
require 'spec_helper'
require 'puppet_spec/compiler'
require 'shared_behaviours/iterative_functions'
describe 'the each method' do
include PuppetSpec::Compiler
context "should be callable as" do
it 'each on an array selecting each value' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [1,2,3]
$a.each |$v| {
file { "/file_$v": ensure => present }
}
MANIFEST
- catalog.resource(:file, "/file_1")['ensure'].should == 'present'
- catalog.resource(:file, "/file_2")['ensure'].should == 'present'
- catalog.resource(:file, "/file_3")['ensure'].should == 'present'
+ expect(catalog.resource(:file, "/file_1")['ensure']).to eq('present')
+ expect(catalog.resource(:file, "/file_2")['ensure']).to eq('present')
+ expect(catalog.resource(:file, "/file_3")['ensure']).to eq('present')
end
it 'each on an array selecting each value - function call style' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [1,2,3]
each ($a) |$index, $v| {
file { "/file_$v": ensure => present }
}
MANIFEST
- catalog.resource(:file, "/file_1")['ensure'].should == 'present'
- catalog.resource(:file, "/file_2")['ensure'].should == 'present'
- catalog.resource(:file, "/file_3")['ensure'].should == 'present'
+ expect(catalog.resource(:file, "/file_1")['ensure']).to eq('present')
+ expect(catalog.resource(:file, "/file_2")['ensure']).to eq('present')
+ expect(catalog.resource(:file, "/file_3")['ensure']).to eq('present')
end
it 'each on an array with index' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [present, absent, present]
$a.each |$k,$v| {
file { "/file_${$k+1}": ensure => $v }
}
MANIFEST
- catalog.resource(:file, "/file_1")['ensure'].should == 'present'
- catalog.resource(:file, "/file_2")['ensure'].should == 'absent'
- catalog.resource(:file, "/file_3")['ensure'].should == 'present'
+ expect(catalog.resource(:file, "/file_1")['ensure']).to eq('present')
+ expect(catalog.resource(:file, "/file_2")['ensure']).to eq('absent')
+ expect(catalog.resource(:file, "/file_3")['ensure']).to eq('present')
end
it 'each on a hash selecting entries' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'a'=>'present','b'=>'absent','c'=>'present'}
$a.each |$e| {
file { "/file_${e[0]}": ensure => $e[1] }
}
MANIFEST
- catalog.resource(:file, "/file_a")['ensure'].should == 'present'
- catalog.resource(:file, "/file_b")['ensure'].should == 'absent'
- catalog.resource(:file, "/file_c")['ensure'].should == 'present'
+ expect(catalog.resource(:file, "/file_a")['ensure']).to eq('present')
+ expect(catalog.resource(:file, "/file_b")['ensure']).to eq('absent')
+ expect(catalog.resource(:file, "/file_c")['ensure']).to eq('present')
end
it 'each on a hash selecting key and value' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'a'=>present,'b'=>absent,'c'=>present}
$a.each |$k, $v| {
file { "/file_$k": ensure => $v }
}
MANIFEST
- catalog.resource(:file, "/file_a")['ensure'].should == 'present'
- catalog.resource(:file, "/file_b")['ensure'].should == 'absent'
- catalog.resource(:file, "/file_c")['ensure'].should == 'present'
+ expect(catalog.resource(:file, "/file_a")['ensure']).to eq('present')
+ expect(catalog.resource(:file, "/file_b")['ensure']).to eq('absent')
+ expect(catalog.resource(:file, "/file_c")['ensure']).to eq('present')
end
it 'each on a hash selecting key and value (using captures-last parameter)' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'a'=>present,'b'=>absent,'c'=>present}
$a.each |*$kv| {
file { "/file_${kv[0]}": ensure => $kv[1] }
}
MANIFEST
- catalog.resource(:file, "/file_a")['ensure'].should == 'present'
- catalog.resource(:file, "/file_b")['ensure'].should == 'absent'
- catalog.resource(:file, "/file_c")['ensure'].should == 'present'
+ expect(catalog.resource(:file, "/file_a")['ensure']).to eq('present')
+ expect(catalog.resource(:file, "/file_b")['ensure']).to eq('absent')
+ expect(catalog.resource(:file, "/file_c")['ensure']).to eq('present')
end
end
context "should produce receiver" do
it 'each checking produced value using single expression' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [1, 3, 2]
$b = $a.each |$x| { "unwanted" }
file { "/file_${b[1]}":
ensure => present
}
MANIFEST
- catalog.resource(:file, "/file_3")['ensure'].should == 'present'
+ expect(catalog.resource(:file, "/file_3")['ensure']).to eq('present')
end
end
it_should_behave_like 'all iterative functions argument checks', 'each'
it_should_behave_like 'all iterative functions hash handling', 'each'
end
diff --git a/spec/unit/functions/epp_spec.rb b/spec/unit/functions/epp_spec.rb
index 4586d664c..819ea14a8 100644
--- a/spec/unit/functions/epp_spec.rb
+++ b/spec/unit/functions/epp_spec.rb
@@ -1,146 +1,146 @@
require 'spec_helper'
describe "the epp function" do
include PuppetSpec::Files
let :node do Puppet::Node.new('localhost') end
let :compiler do Puppet::Parser::Compiler.new(node) end
let :scope do Puppet::Parser::Scope.new(compiler) end
context "when accessing scope variables as $ variables" do
it "looks up the value from the scope" do
scope["what"] = "are belong"
- eval_template("all your base <%= $what %> to us").should == "all your base are belong to us"
+ expect(eval_template("all your base <%= $what %> to us")).to eq("all your base are belong to us")
end
it "get nil accessing a variable that does not exist" do
- eval_template("<%= $kryptonite == undef %>").should == "true"
+ expect(eval_template("<%= $kryptonite == undef %>")).to eq("true")
end
it "get nil accessing a variable that is undef" do
scope['undef_var'] = nil
- eval_template("<%= $undef_var == undef %>").should == "true"
+ expect(eval_template("<%= $undef_var == undef %>")).to eq("true")
end
it "gets shadowed variable if args are given" do
scope['phantom'] = 'of the opera'
- eval_template_with_args("<%= $phantom == dragos %>", 'phantom' => 'dragos').should == "true"
+ expect(eval_template_with_args("<%= $phantom == dragos %>", 'phantom' => 'dragos')).to eq("true")
end
it "can use values from the enclosing scope for defaults" do
scope['phantom'] = 'of the opera'
- eval_template("<%- |$phantom = $phantom| -%><%= $phantom %>").should == "of the opera"
+ expect(eval_template("<%- |$phantom = $phantom| -%><%= $phantom %>")).to eq("of the opera")
end
it "uses the default value if the given value is undef/nil" do
- eval_template_with_args("<%- |$phantom = 'inside your mind'| -%><%= $phantom %>", 'phantom' => nil).should == "inside your mind"
+ expect(eval_template_with_args("<%- |$phantom = 'inside your mind'| -%><%= $phantom %>", 'phantom' => nil)).to eq("inside your mind")
end
it "gets shadowed variable if args are given and parameters are specified" do
scope['x'] = 'wrong one'
- eval_template_with_args("<%- |$x| -%><%= $x == correct %>", 'x' => 'correct').should == "true"
+ expect(eval_template_with_args("<%- |$x| -%><%= $x == correct %>", 'x' => 'correct')).to eq("true")
end
it "raises an error if required variable is not given" do
scope['x'] = 'wrong one'
expect do
eval_template_with_args("<%-| $x |-%><%= $x == correct %>", 'y' => 'correct')
end.to raise_error(/no value given for required parameters x/)
end
it "raises an error if too many arguments are given" do
scope['x'] = 'wrong one'
expect do
eval_template_with_args("<%-| $x |-%><%= $x == correct %>", 'x' => 'correct', 'y' => 'surplus')
end.to raise_error(/Too many arguments: 2 for 1/)
end
end
context "when given an empty template" do
it "allows the template file to be empty" do
expect(eval_template("")).to eq("")
end
it "allows the template to have empty body after parameters" do
expect(eval_template_with_args("<%-|$x|%>", 'x'=>1)).to eq("")
end
end
context "when using typed parameters" do
it "allows a passed value that matches the parameter's type" do
expect(eval_template_with_args("<%-|String $x|-%><%= $x == correct %>", 'x' => 'correct')).to eq("true")
end
it "does not allow slurped parameters" do
expect do
eval_template_with_args("<%-|*$x|-%><%= $x %>", 'x' => 'incorrect')
end.to raise_error(/'captures rest' - not supported in an Epp Template/)
end
it "raises an error when the passed value does not match the parameter's type" do
expect do
eval_template_with_args("<%-|Integer $x|-%><%= $x %>", 'x' => 'incorrect')
end.to raise_error(/expected.*Integer.*actual.*String/m)
end
it "raises an error when the default value does not match the parameter's type" do
expect do
eval_template("<%-|Integer $x = 'nope'|-%><%= $x %>")
end.to raise_error(/expected.*Integer.*actual.*String/m)
end
it "allows an parameter to default to undef" do
expect(eval_template("<%-|Optional[Integer] $x = undef|-%><%= $x == undef %>")).to eq("true")
end
end
# although never a problem with epp
it "is not interfered with by having a variable named 'string' (#14093)" do
scope['string'] = "this output should not be seen"
- eval_template("some text that is static").should == "some text that is static"
+ expect(eval_template("some text that is static")).to eq("some text that is static")
end
it "has access to a variable named 'string' (#14093)" do
scope['string'] = "the string value"
- eval_template("string was: <%= $string %>").should == "string was: the string value"
+ expect(eval_template("string was: <%= $string %>")).to eq("string was: the string value")
end
describe 'when loading from modules' do
include PuppetSpec::Files
it 'an epp template is found' do
modules_dir = dir_containing('modules', {
'testmodule' => {
'templates' => {
'the_x.epp' => 'The x is <%= $x %>'
}
}})
Puppet.override({:current_environment => (env = Puppet::Node::Environment.create(:testload, [ modules_dir ]))}, "test") do
node.environment = env
expect(epp_function.call(scope, 'testmodule/the_x.epp', { 'x' => '3'} )).to eql("The x is 3")
end
end
end
def eval_template_with_args(content, args_hash)
file_path = tmpdir('epp_spec_content')
filename = File.join(file_path, "template.epp")
File.open(filename, "w+") { |f| f.write(content) }
Puppet::Parser::Files.stubs(:find_template).returns(filename)
epp_function.call(scope, 'template', args_hash)
end
def eval_template(content)
file_path = tmpdir('epp_spec_content')
filename = File.join(file_path, "template.epp")
File.open(filename, "w+") { |f| f.write(content) }
Puppet::Parser::Files.stubs(:find_template).returns(filename)
epp_function.call(scope, 'template')
end
def epp_function()
epp_func = scope.compiler.loaders.public_environment_loader.load(:function, 'epp')
end
end
diff --git a/spec/unit/functions/inline_epp_spec.rb b/spec/unit/functions/inline_epp_spec.rb
index f428e3895..838f5ef2f 100644
--- a/spec/unit/functions/inline_epp_spec.rb
+++ b/spec/unit/functions/inline_epp_spec.rb
@@ -1,89 +1,89 @@
require 'spec_helper'
describe "the inline_epp function" do
include PuppetSpec::Files
let :node do Puppet::Node.new('localhost') end
let :compiler do Puppet::Parser::Compiler.new(node) end
let :scope do Puppet::Parser::Scope.new(compiler) end
context "when accessing scope variables as $ variables" do
it "looks up the value from the scope" do
scope["what"] = "are belong"
- eval_template("all your base <%= $what %> to us").should == "all your base are belong to us"
+ expect(eval_template("all your base <%= $what %> to us")).to eq("all your base are belong to us")
end
it "get nil accessing a variable that does not exist" do
- eval_template("<%= $kryptonite == undef %>").should == "true"
+ expect(eval_template("<%= $kryptonite == undef %>")).to eq("true")
end
it "get nil accessing a variable that is undef" do
scope['undef_var'] = :undef
- eval_template("<%= $undef_var == undef %>").should == "true"
+ expect(eval_template("<%= $undef_var == undef %>")).to eq("true")
end
it "gets shadowed variable if args are given" do
scope['phantom'] = 'of the opera'
- eval_template_with_args("<%= $phantom == dragos %>", 'phantom' => 'dragos').should == "true"
+ expect(eval_template_with_args("<%= $phantom == dragos %>", 'phantom' => 'dragos')).to eq("true")
end
it "gets shadowed variable if args are given and parameters are specified" do
scope['x'] = 'wrong one'
- eval_template_with_args("<%-| $x |-%><%= $x == correct %>", 'x' => 'correct').should == "true"
+ expect(eval_template_with_args("<%-| $x |-%><%= $x == correct %>", 'x' => 'correct')).to eq("true")
end
it "raises an error if required variable is not given" do
scope['x'] = 'wrong one'
expect {
eval_template_with_args("<%-| $x |-%><%= $x == correct %>", 'y' => 'correct')
}.to raise_error(/no value given for required parameters x/)
end
it "raises an error if too many arguments are given" do
scope['x'] = 'wrong one'
expect {
eval_template_with_args("<%-| $x |-%><%= $x == correct %>", 'x' => 'correct', 'y' => 'surplus')
}.to raise_error(/Too many arguments: 2 for 1/)
end
end
context "when given an empty template" do
it "allows the template file to be empty" do
expect(eval_template("")).to eq("")
end
it "allows the template to have empty body after parameters" do
expect(eval_template_with_args("<%-|$x|%>", 'x'=>1)).to eq("")
end
end
it "renders a block expression" do
- eval_template_with_args("<%= { $y = $x $x + 1} %>", 'x' => 2).should == "3"
+ expect(eval_template_with_args("<%= { $y = $x $x + 1} %>", 'x' => 2)).to eq("3")
end
# although never a problem with epp
it "is not interfered with by having a variable named 'string' (#14093)" do
scope['string'] = "this output should not be seen"
- eval_template("some text that is static").should == "some text that is static"
+ expect(eval_template("some text that is static")).to eq("some text that is static")
end
it "has access to a variable named 'string' (#14093)" do
scope['string'] = "the string value"
- eval_template("string was: <%= $string %>").should == "string was: the string value"
+ expect(eval_template("string was: <%= $string %>")).to eq("string was: the string value")
end
def eval_template_with_args(content, args_hash)
epp_function.call(scope, content, args_hash)
end
def eval_template(content)
epp_function.call(scope, content)
end
def epp_function()
epp_func = scope.compiler.loaders.public_environment_loader.load(:function, 'inline_epp')
end
end
diff --git a/spec/unit/functions4_spec.rb b/spec/unit/functions4_spec.rb
index bdf012ffa..eaa42a1e9 100644
--- a/spec/unit/functions4_spec.rb
+++ b/spec/unit/functions4_spec.rb
@@ -1,660 +1,660 @@
require 'spec_helper'
require 'puppet/pops'
require 'puppet/loaders'
require 'puppet_spec/pops'
require 'puppet_spec/scope'
module FunctionAPISpecModule
class TestDuck
end
class TestFunctionLoader < Puppet::Pops::Loader::StaticLoader
def initialize
@functions = {}
end
def add_function(name, function)
typed_name = Puppet::Pops::Loader::Loader::TypedName.new(:function, name)
entry = Puppet::Pops::Loader::Loader::NamedEntry.new(typed_name, function, __FILE__)
@functions[typed_name] = entry
end
# override StaticLoader
def load_constant(typed_name)
@functions[typed_name]
end
end
end
describe 'the 4x function api' do
include FunctionAPISpecModule
include PuppetSpec::Pops
include PuppetSpec::Scope
let(:loader) { FunctionAPISpecModule::TestFunctionLoader.new }
it 'allows a simple function to be created without dispatch declaration' do
f = Puppet::Functions.create_function('min') do
def min(x,y)
x <= y ? x : y
end
end
# the produced result is a Class inheriting from Function
expect(f.class).to be(Class)
expect(f.superclass).to be(Puppet::Functions::Function)
# and this class had the given name (not a real Ruby class name)
expect(f.name).to eql('min')
end
it 'refuses to create functions that are not based on the Function class' do
expect do
Puppet::Functions.create_function('testing', Object) {}
end.to raise_error(ArgumentError, 'Functions must be based on Puppet::Pops::Functions::Function. Got Object')
end
it 'refuses to create functions with parameters that are not named with a symbol' do
expect do
Puppet::Functions.create_function('testing') do
dispatch :test do
param 'Integer', 'not_symbol'
end
def test(x)
end
end
end.to raise_error(ArgumentError, /Parameter name argument must be a Symbol/)
end
it 'a function without arguments can be defined and called without dispatch declaration' do
f = create_noargs_function_class()
func = f.new(:closure_scope, :loader)
expect(func.call({})).to eql(10)
end
it 'an error is raised when calling a no arguments function with arguments' do
f = create_noargs_function_class()
func = f.new(:closure_scope, :loader)
expect{func.call({}, 'surprise')}.to raise_error(ArgumentError, "function 'test' called with mis-matched arguments
expected:
test() - arg count {0}
actual:
test(String) - arg count {1}")
end
it 'a simple function can be called' do
f = create_min_function_class()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
- expect(func.is_a?(Puppet::Functions::Function)).to be_true
+ expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect(func.call({}, 10,20)).to eql(10)
end
it 'an error is raised if called with too few arguments' do
f = create_min_function_class()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
- expect(func.is_a?(Puppet::Functions::Function)).to be_true
+ expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
signature = 'Any x, Any y'
expect do
func.call({}, 10)
end.to raise_error(ArgumentError, "function 'min' called with mis-matched arguments
expected:
min(#{signature}) - arg count {2}
actual:
min(Integer) - arg count {1}")
end
it 'an error is raised if called with too many arguments' do
f = create_min_function_class()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
- expect(func.is_a?(Puppet::Functions::Function)).to be_true
+ expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
signature = 'Any x, Any y'
expect do
func.call({}, 10, 10, 10)
end.to raise_error(ArgumentError, Regexp.new(Regexp.escape(
"function 'min' called with mis-matched arguments
expected:
min(#{signature}) - arg count {2}
actual:
min(Integer, Integer, Integer) - arg count {3}")))
end
it 'an error is raised if simple function-name and method are not matched' do
expect do
f = create_badly_named_method_function_class()
end.to raise_error(ArgumentError, /Function Creation Error, cannot create a default dispatcher for function 'mix', no method with this name found/)
end
it 'the implementation separates dispatchers for different functions' do
# this tests that meta programming / construction puts class attributes in the correct class
f1 = create_min_function_class()
f2 = create_max_function_class()
d1 = f1.dispatcher
d2 = f2.dispatcher
expect(d1).to_not eql(d2)
expect(d1.dispatchers[0]).to_not eql(d2.dispatchers[0])
end
context 'when using regular dispatch' do
it 'a function can be created using dispatch and called' do
f = create_min_function_class_using_dispatch()
func = f.new(:closure_scope, :loader)
expect(func.call({}, 3,4)).to eql(3)
end
it 'an error is raised with reference to given parameter names when called with mis-matched arguments' do
f = create_min_function_class_using_dispatch()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
- expect(func.is_a?(Puppet::Functions::Function)).to be_true
+ expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect do
func.call({}, 10, 10, 10)
end.to raise_error(ArgumentError, Regexp.new(Regexp.escape(
"function 'min' called with mis-matched arguments
expected:
min(Numeric a, Numeric b) - arg count {2}
actual:
min(Integer, Integer, Integer) - arg count {3}")))
end
it 'an error includes optional indicators and count for last element' do
f = create_function_with_optionals_and_varargs()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
- expect(func.is_a?(Puppet::Functions::Function)).to be_true
+ expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
signature = 'Any x, Any y, Any a?, Any b?, Any c{0,}'
expect do
func.call({}, 10)
end.to raise_error(ArgumentError,
"function 'min' called with mis-matched arguments
expected:
min(#{signature}) - arg count {2,}
actual:
min(Integer) - arg count {1}")
end
it 'an error includes optional indicators and count for last element when defined via dispatch' do
f = create_function_with_optionals_and_varargs_via_dispatch()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
- expect(func.is_a?(Puppet::Functions::Function)).to be_true
+ expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect do
func.call({}, 10)
end.to raise_error(ArgumentError,
"function 'min' called with mis-matched arguments
expected:
min(Numeric x, Numeric y, Numeric a?, Numeric b?, Numeric c{0,}) - arg count {2,}
actual:
min(Integer) - arg count {1}")
end
it 'a function can be created using dispatch and called' do
f = create_min_function_class_disptaching_to_two_methods()
func = f.new(:closure_scope, :loader)
expect(func.call({}, 3,4)).to eql(3)
expect(func.call({}, 'Apple', 'Banana')).to eql('Apple')
end
it 'an error is raised with reference to multiple methods when called with mis-matched arguments' do
f = create_min_function_class_disptaching_to_two_methods()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
- expect(func.is_a?(Puppet::Functions::Function)).to be_true
+ expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect do
func.call({}, 10, 10, 10)
end.to raise_error(ArgumentError,
"function 'min' called with mis-matched arguments
expected one of:
min(Numeric a, Numeric b) - arg count {2}
min(String s1, String s2) - arg count {2}
actual:
min(Integer, Integer, Integer) - arg count {3}")
end
context 'can use injection' do
before :all do
injector = Puppet::Pops::Binder::Injector.create('test') do
bind.name('a_string').to('evoe')
bind.name('an_int').to(42)
end
Puppet.push_context({:injector => injector}, "injector for testing function API")
end
after :all do
Puppet.pop_context()
end
it 'attributes can be injected' do
f1 = create_function_with_class_injection()
f = f1.new(:closure_scope, :loader)
expect(f.test_attr2()).to eql("evoe")
expect(f.serial().produce(nil)).to eql(42)
expect(f.test_attr().class.name).to eql("FunctionAPISpecModule::TestDuck")
end
it 'parameters can be injected and woven with regular dispatch' do
f1 = create_function_with_param_injection_regular()
f = f1.new(:closure_scope, :loader)
expect(f.call(nil, 10, 20)).to eql("evoe! 10, and 20 < 42 = true")
expect(f.call(nil, 50, 20)).to eql("evoe! 50, and 20 < 42 = false")
end
end
context 'when requesting a type' do
it 'responds with a Callable for a single signature' do
tf = Puppet::Pops::Types::TypeFactory
fc = create_min_function_class_using_dispatch()
t = fc.dispatcher.to_type
expect(t.class).to be(Puppet::Pops::Types::PCallableType)
expect(t.param_types.class).to be(Puppet::Pops::Types::PTupleType)
expect(t.param_types.types).to eql([tf.numeric(), tf.numeric()])
expect(t.block_type).to be_nil
end
it 'responds with a Variant[Callable...] for multiple signatures' do
tf = Puppet::Pops::Types::TypeFactory
fc = create_min_function_class_disptaching_to_two_methods()
t = fc.dispatcher.to_type
expect(t.class).to be(Puppet::Pops::Types::PVariantType)
expect(t.types.size).to eql(2)
t1 = t.types[0]
expect(t1.param_types.class).to be(Puppet::Pops::Types::PTupleType)
expect(t1.param_types.types).to eql([tf.numeric(), tf.numeric()])
expect(t1.block_type).to be_nil
t2 = t.types[1]
expect(t2.param_types.class).to be(Puppet::Pops::Types::PTupleType)
expect(t2.param_types.types).to eql([tf.string(), tf.string()])
expect(t2.block_type).to be_nil
end
end
context 'supports lambdas' do
it 'such that, a required block can be defined and given as an argument' do
# use a Function as callable
the_callable = create_min_function_class().new(:closure_scope, :loader)
the_function = create_function_with_required_block_all_defaults().new(:closure_scope, :loader)
result = the_function.call({}, 10, the_callable)
expect(result).to be(the_callable)
end
it 'such that, a missing required block when called raises an error' do
# use a Function as callable
the_function = create_function_with_required_block_all_defaults().new(:closure_scope, :loader)
expect do
the_function.call({}, 10)
end.to raise_error(ArgumentError,
"function 'test' called with mis-matched arguments
expected:
test(Integer x, Callable block) - arg count {2}
actual:
test(Integer) - arg count {1}")
end
it 'such that, an optional block can be defined and given as an argument' do
# use a Function as callable
the_callable = create_min_function_class().new(:closure_scope, :loader)
the_function = create_function_with_optional_block_all_defaults().new(:closure_scope, :loader)
result = the_function.call({}, 10, the_callable)
expect(result).to be(the_callable)
end
it 'such that, an optional block can be omitted when called and gets the value nil' do
# use a Function as callable
the_function = create_function_with_optional_block_all_defaults().new(:closure_scope, :loader)
expect(the_function.call({}, 10)).to be_nil
end
end
context 'provides signature information' do
it 'about capture rest (varargs)' do
fc = create_function_with_optionals_and_varargs
signatures = fc.signatures
expect(signatures.size).to eql(1)
signature = signatures[0]
- expect(signature.last_captures_rest?).to be_true
+ expect(signature.last_captures_rest?).to be_truthy
end
it 'about optional and required parameters' do
fc = create_function_with_optionals_and_varargs
signature = fc.signatures[0]
expect(signature.args_range).to eql( [2, Float::INFINITY ] )
- expect(signature.infinity?(signature.args_range[1])).to be_true
+ expect(signature.infinity?(signature.args_range[1])).to be_truthy
end
it 'about block not being allowed' do
fc = create_function_with_optionals_and_varargs
signature = fc.signatures[0]
expect(signature.block_range).to eql( [ 0, 0 ] )
expect(signature.block_type).to be_nil
end
it 'about required block' do
fc = create_function_with_required_block_all_defaults
signature = fc.signatures[0]
expect(signature.block_range).to eql( [ 1, 1 ] )
expect(signature.block_type).to_not be_nil
end
it 'about optional block' do
fc = create_function_with_optional_block_all_defaults
signature = fc.signatures[0]
expect(signature.block_range).to eql( [ 0, 1 ] )
expect(signature.block_type).to_not be_nil
end
it 'about the type' do
fc = create_function_with_optional_block_all_defaults
signature = fc.signatures[0]
expect(signature.type.class).to be(Puppet::Pops::Types::PCallableType)
end
it 'about parameter names obtained from ruby introspection' do
fc = create_min_function_class
signature = fc.signatures[0]
expect(signature.parameter_names).to eql(['x', 'y'])
end
it 'about parameter names specified with dispatch' do
fc = create_min_function_class_using_dispatch
signature = fc.signatures[0]
expect(signature.parameter_names).to eql([:a, :b])
end
it 'about block_name when it is *not* given in the definition' do
# neither type, nor name
fc = create_function_with_required_block_all_defaults
signature = fc.signatures[0]
expect(signature.block_name).to eql(:block)
# no name given, only type
fc = create_function_with_required_block_given_type
signature = fc.signatures[0]
expect(signature.block_name).to eql(:block)
end
it 'about block_name when it *is* given in the definition' do
# neither type, nor name
fc = create_function_with_required_block_default_type
signature = fc.signatures[0]
expect(signature.block_name).to eql(:the_block)
# no name given, only type
fc = create_function_with_required_block_fully_specified
signature = fc.signatures[0]
expect(signature.block_name).to eql(:the_block)
end
end
context 'supports calling other functions' do
before(:all) do
Puppet.push_context( {:loaders => Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, []))})
end
after(:all) do
Puppet.pop_context()
end
it 'such that, other functions are callable by name' do
fc = Puppet::Functions.create_function('test') do
def test()
# Call a function available in the puppet system
call_function('assert_type', 'Integer', 10)
end
end
# initiate the function the same way the loader initiates it
f = fc.new(:closure_scope, Puppet.lookup(:loaders).puppet_system_loader)
expect(f.call({})).to eql(10)
end
it 'such that, calling a non existing function raises an error' do
fc = Puppet::Functions.create_function('test') do
def test()
# Call a function not available in the puppet system
call_function('no_such_function', 'Integer', 'hello')
end
end
# initiate the function the same way the loader initiates it
f = fc.new(:closure_scope, Puppet.lookup(:loaders).puppet_system_loader)
expect{f.call({})}.to raise_error(ArgumentError, "Function test(): cannot call function 'no_such_function' - not found")
end
end
context 'supports calling ruby functions with lambda from puppet' do
before(:all) do
Puppet.push_context( {:loaders => Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, []))})
end
after(:all) do
Puppet.pop_context()
end
before(:each) do
Puppet[:strict_variables] = true
end
let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new }
let(:node) { 'node.example.com' }
let(:scope) { s = create_test_scope_for_node(node); s }
it 'function with required block can be called' do
# construct ruby function to call
fc = Puppet::Functions.create_function('testing::test') do
dispatch :test do
param 'Integer', :x
# block called 'the_block', and using "all_callables"
required_block_param #(all_callables(), 'the_block')
end
def test(x, block)
# call the block with x
block.call(x)
end
end
# add the function to the loader (as if it had been loaded from somewhere)
the_loader = loader()
f = fc.new({}, the_loader)
loader.add_function('testing::test', f)
# evaluate a puppet call
source = "testing::test(10) |$x| { $x+1 }"
program = parser.parse_string(source, __FILE__)
Puppet::Pops::Adapters::LoaderAdapter.adapt(program.model).loader = the_loader
expect(parser.evaluate(scope, program)).to eql(11)
end
end
end
def create_noargs_function_class
f = Puppet::Functions.create_function('test') do
def test()
10
end
end
end
def create_min_function_class
f = Puppet::Functions.create_function('min') do
def min(x,y)
x <= y ? x : y
end
end
end
def create_max_function_class
f = Puppet::Functions.create_function('max') do
def max(x,y)
x >= y ? x : y
end
end
end
def create_badly_named_method_function_class
f = Puppet::Functions.create_function('mix') do
def mix_up(x,y)
x <= y ? x : y
end
end
end
def create_min_function_class_using_dispatch
f = Puppet::Functions.create_function('min') do
dispatch :min do
param 'Numeric', :a
param 'Numeric', :b
end
def min(x,y)
x <= y ? x : y
end
end
end
def create_min_function_class_disptaching_to_two_methods
f = Puppet::Functions.create_function('min') do
dispatch :min do
param 'Numeric', :a
param 'Numeric', :b
end
dispatch :min_s do
param 'String', :s1
param 'String', :s2
end
def min(x,y)
x <= y ? x : y
end
def min_s(x,y)
cmp = (x.downcase <=> y.downcase)
cmp <= 0 ? x : y
end
end
end
def create_function_with_optionals_and_varargs
f = Puppet::Functions.create_function('min') do
def min(x,y,a=1, b=1, *c)
x <= y ? x : y
end
end
end
def create_function_with_optionals_and_varargs_via_dispatch
f = Puppet::Functions.create_function('min') do
dispatch :min do
param 'Numeric', :x
param 'Numeric', :y
param 'Numeric', :a
param 'Numeric', :b
param 'Numeric', :c
arg_count 2, :default
end
def min(x,y,a=1, b=1, *c)
x <= y ? x : y
end
end
end
def create_function_with_class_injection
f = Puppet::Functions.create_function('test', Puppet::Functions::InternalFunction) do
attr_injected Puppet::Pops::Types::TypeFactory.type_of(FunctionAPISpecModule::TestDuck), :test_attr
attr_injected Puppet::Pops::Types::TypeFactory.string(), :test_attr2, "a_string"
attr_injected_producer Puppet::Pops::Types::TypeFactory.integer(), :serial, "an_int"
def test(x,y,a=1, b=1, *c)
x <= y ? x : y
end
end
end
def create_function_with_param_injection_regular
f = Puppet::Functions.create_function('test', Puppet::Functions::InternalFunction) do
attr_injected Puppet::Pops::Types::TypeFactory.type_of(FunctionAPISpecModule::TestDuck), :test_attr
attr_injected Puppet::Pops::Types::TypeFactory.string(), :test_attr2, "a_string"
attr_injected_producer Puppet::Pops::Types::TypeFactory.integer(), :serial, "an_int"
dispatch :test do
injected_param Puppet::Pops::Types::TypeFactory.string, :x, 'a_string'
injected_producer_param Puppet::Pops::Types::TypeFactory.integer, :y, 'an_int'
param 'Scalar', :a
param 'Scalar', :b
end
def test(x,y,a,b)
y_produced = y.produce(nil)
"#{x}! #{a}, and #{b} < #{y_produced} = #{ !!(a < y_produced && b < y_produced)}"
end
end
end
def create_function_with_required_block_all_defaults
f = Puppet::Functions.create_function('test') do
dispatch :test do
param 'Integer', :x
# use defaults, any callable, name is 'block'
required_block_param
end
def test(x, block)
# returns the block to make it easy to test what it got when called
block
end
end
end
def create_function_with_required_block_default_type
f = Puppet::Functions.create_function('test') do
dispatch :test do
param 'Integer', :x
# use defaults, any callable, name is 'block'
required_block_param :the_block
end
def test(x, block)
# returns the block to make it easy to test what it got when called
block
end
end
end
def create_function_with_required_block_given_type
f = Puppet::Functions.create_function('test') do
dispatch :test do
param 'Integer', :x
required_block_param
end
def test(x, block)
# returns the block to make it easy to test what it got when called
block
end
end
end
def create_function_with_required_block_fully_specified
f = Puppet::Functions.create_function('test') do
dispatch :test do
param 'Integer', :x
# use defaults, any callable, name is 'block'
required_block_param('Callable', :the_block)
end
def test(x, block)
# returns the block to make it easy to test what it got when called
block
end
end
end
def create_function_with_optional_block_all_defaults
f = Puppet::Functions.create_function('test') do
dispatch :test do
param 'Integer', :x
# use defaults, any callable, name is 'block'
optional_block_param
end
def test(x, block=nil)
# returns the block to make it easy to test what it got when called
# a default of nil must be used or the call will fail with a missing parameter
block
end
end
end
end
diff --git a/spec/unit/graph/rb_tree_map_spec.rb b/spec/unit/graph/rb_tree_map_spec.rb
index e1ac7d9b2..af4028105 100644
--- a/spec/unit/graph/rb_tree_map_spec.rb
+++ b/spec/unit/graph/rb_tree_map_spec.rb
@@ -1,572 +1,572 @@
#!/usr/bin/env ruby
require 'spec_helper'
require 'puppet/graph'
describe Puppet::Graph::RbTreeMap do
describe "#push" do
it "should allow a new element to be added" do
subject[5] = 'foo'
- subject.size.should == 1
+ expect(subject.size).to eq(1)
- subject[5].should == 'foo'
+ expect(subject[5]).to eq('foo')
end
it "should replace the old value if the key is in tree already" do
subject[0] = 10
subject[0] = 20
- subject[0].should == 20
- subject.size.should == 1
+ expect(subject[0]).to eq(20)
+ expect(subject.size).to eq(1)
end
it "should be able to add a large number of elements" do
(1..1000).each {|i| subject[i] = i.to_s}
- subject.size.should == 1000
+ expect(subject.size).to eq(1000)
end
it "should create a root node if the tree was empty" do
- subject.instance_variable_get(:@root).should be_nil
+ expect(subject.instance_variable_get(:@root)).to be_nil
subject[5] = 'foo'
- subject.instance_variable_get(:@root).should be_a(Puppet::Graph::RbTreeMap::Node)
+ expect(subject.instance_variable_get(:@root)).to be_a(Puppet::Graph::RbTreeMap::Node)
end
end
describe "#size" do
it "should be 0 for en empty tree" do
- subject.size.should == 0
+ expect(subject.size).to eq(0)
end
it "should correctly report the size for a non-empty tree" do
(1..10).each {|i| subject[i] = i.to_s}
- subject.size.should == 10
+ expect(subject.size).to eq(10)
end
end
describe "#has_key?" do
it "should be true if the tree contains the key" do
subject[1] = 2
- subject.should be_has_key(1)
+ expect(subject).to be_has_key(1)
end
it "should be true if the tree contains the key and its value is nil" do
subject[0] = nil
- subject.should be_has_key(0)
+ expect(subject).to be_has_key(0)
end
it "should be false if the tree does not contain the key" do
subject[1] = 2
- subject.should_not be_has_key(2)
+ expect(subject).not_to be_has_key(2)
end
it "should be false if the tree is empty" do
- subject.should_not be_has_key(5)
+ expect(subject).not_to be_has_key(5)
end
end
describe "#get" do
it "should return the value at the key" do
subject[1] = 2
subject[3] = 4
- subject.get(1).should == 2
- subject.get(3).should == 4
+ expect(subject.get(1)).to eq(2)
+ expect(subject.get(3)).to eq(4)
end
it "should return nil if the tree is empty" do
- subject[1].should be_nil
+ expect(subject[1]).to be_nil
end
it "should return nil if the key is not in the tree" do
subject[1] = 2
- subject[3].should be_nil
+ expect(subject[3]).to be_nil
end
it "should return nil if the value at the key is nil" do
subject[1] = nil
- subject[1].should be_nil
+ expect(subject[1]).to be_nil
end
end
describe "#min_key" do
it "should return the smallest key in the tree" do
[4,8,12,3,6,2,-4,7].each do |i|
subject[i] = i.to_s
end
- subject.min_key.should == -4
+ expect(subject.min_key).to eq(-4)
end
it "should return nil if the tree is empty" do
- subject.min_key.should be_nil
+ expect(subject.min_key).to be_nil
end
end
describe "#max_key" do
it "should return the largest key in the tree" do
[4,8,12,3,6,2,-4,7].each do |i|
subject[i] = i.to_s
end
- subject.max_key.should == 12
+ expect(subject.max_key).to eq(12)
end
it "should return nil if the tree is empty" do
- subject.max_key.should be_nil
+ expect(subject.max_key).to be_nil
end
end
describe "#delete" do
before :each do
subject[1] = '1'
subject[0] = '0'
subject[2] = '2'
end
it "should return the value at the key deleted" do
- subject.delete(0).should == '0'
- subject.delete(1).should == '1'
- subject.delete(2).should == '2'
- subject.size.should == 0
+ expect(subject.delete(0)).to eq('0')
+ expect(subject.delete(1)).to eq('1')
+ expect(subject.delete(2)).to eq('2')
+ expect(subject.size).to eq(0)
end
it "should be able to delete the last node" do
tree = described_class.new
tree[1] = '1'
- tree.delete(1).should == '1'
- tree.should be_empty
+ expect(tree.delete(1)).to eq('1')
+ expect(tree).to be_empty
end
it "should be able to delete the root node" do
- subject.delete(1).should == '1'
+ expect(subject.delete(1)).to eq('1')
- subject.size.should == 2
+ expect(subject.size).to eq(2)
- subject.to_hash.should == {
+ expect(subject.to_hash).to eq({
:node => {
:key => 2,
:value => '2',
:color => :black,
},
:left => {
:node => {
:key => 0,
:value => '0',
:color => :red,
}
}
- }
+ })
end
it "should be able to delete the left child" do
- subject.delete(0).should == '0'
+ expect(subject.delete(0)).to eq('0')
- subject.size.should == 2
+ expect(subject.size).to eq(2)
- subject.to_hash.should == {
+ expect(subject.to_hash).to eq({
:node => {
:key => 2,
:value => '2',
:color => :black,
},
:left => {
:node => {
:key => 1,
:value => '1',
:color => :red,
}
}
- }
+ })
end
it "should be able to delete the right child" do
- subject.delete(2).should == '2'
+ expect(subject.delete(2)).to eq('2')
- subject.size.should == 2
+ expect(subject.size).to eq(2)
- subject.to_hash.should == {
+ expect(subject.to_hash).to eq({
:node => {
:key => 1,
:value => '1',
:color => :black,
},
:left => {
:node => {
:key => 0,
:value => '0',
:color => :red,
}
}
- }
+ })
end
it "should be able to delete the left child if it is a subtree" do
(3..6).each {|i| subject[i] = i.to_s}
- subject.delete(1).should == '1'
+ expect(subject.delete(1)).to eq('1')
- subject.to_hash.should == {
+ expect(subject.to_hash).to eq({
:node => {
:key => 5,
:value => '5',
:color => :black,
},
:left => {
:node => {
:key => 3,
:value => '3',
:color => :red,
},
:left => {
:node => {
:key => 2,
:value => '2',
:color => :black,
},
:left => {
:node => {
:key => 0,
:value => '0',
:color => :red,
},
},
},
:right => {
:node => {
:key => 4,
:value => '4',
:color => :black,
},
},
},
:right => {
:node => {
:key => 6,
:value => '6',
:color => :black,
},
},
- }
+ })
end
it "should be able to delete the right child if it is a subtree" do
(3..6).each {|i| subject[i] = i.to_s}
- subject.delete(5).should == '5'
+ expect(subject.delete(5)).to eq('5')
- subject.to_hash.should == {
+ expect(subject.to_hash).to eq({
:node => {
:key => 3,
:value => '3',
:color => :black,
},
:left => {
:node => {
:key => 1,
:value => '1',
:color => :red,
},
:left => {
:node => {
:key => 0,
:value => '0',
:color => :black,
},
},
:right => {
:node => {
:key => 2,
:value => '2',
:color => :black,
},
},
},
:right => {
:node => {
:key => 6,
:value => '6',
:color => :black,
},
:left => {
:node => {
:key => 4,
:value => '4',
:color => :red,
},
},
},
- }
+ })
end
it "should return nil if the tree is empty" do
tree = described_class.new
- tree.delete(14).should be_nil
+ expect(tree.delete(14)).to be_nil
- tree.size.should == 0
+ expect(tree.size).to eq(0)
end
it "should return nil if the key is not in the tree" do
(0..4).each {|i| subject[i] = i.to_s}
- subject.delete(2.5).should be_nil
- subject.size.should == 5
+ expect(subject.delete(2.5)).to be_nil
+ expect(subject.size).to eq(5)
end
it "should return nil if the key is larger than the maximum key" do
- subject.delete(100).should be_nil
- subject.size.should == 3
+ expect(subject.delete(100)).to be_nil
+ expect(subject.size).to eq(3)
end
it "should return nil if the key is smaller than the minimum key" do
- subject.delete(-1).should be_nil
- subject.size.should == 3
+ expect(subject.delete(-1)).to be_nil
+ expect(subject.size).to eq(3)
end
end
describe "#empty?" do
it "should return true if the tree is empty" do
- subject.should be_empty
+ expect(subject).to be_empty
end
it "should return false if the tree is not empty" do
subject[5] = 10
- subject.should_not be_empty
+ expect(subject).not_to be_empty
end
end
describe "#delete_min" do
it "should delete the smallest element of the tree" do
(1..15).each {|i| subject[i] = i.to_s}
- subject.delete_min.should == '1'
- subject.size.should == 14
+ expect(subject.delete_min).to eq('1')
+ expect(subject.size).to eq(14)
end
it "should return nil if the tree is empty" do
- subject.delete_min.should be_nil
+ expect(subject.delete_min).to be_nil
end
end
describe "#delete_max" do
it "should delete the largest element of the tree" do
(1..15).each {|i| subject[i] = i.to_s}
- subject.delete_max.should == '15'
- subject.size.should == 14
+ expect(subject.delete_max).to eq('15')
+ expect(subject.size).to eq(14)
end
it "should return nil if the tree is empty" do
- subject.delete_max.should be_nil
+ expect(subject.delete_max).to be_nil
end
end
describe "#each" do
it "should yield each pair in the tree in order if a block is provided" do
# Insert in reverse to demonstrate they aren't being yielded in insertion order
(1..5).to_a.reverse.each {|i| subject[i] = i.to_s}
nodes = []
subject.each do |key,value|
nodes << [key,value]
end
- nodes.should == (1..5).map {|i| [i, i.to_s]}
+ expect(nodes).to eq((1..5).map {|i| [i, i.to_s]})
end
it "should do nothing if the tree is empty" do
subject.each do |key,value|
raise "each on an empty tree incorrectly yielded #{key}, #{value}"
end
end
end
describe "#isred" do
it "should return true if the node is red" do
node = Puppet::Graph::RbTreeMap::Node.new(1,2)
node.color = :red
- subject.send(:isred, node).should == true
+ expect(subject.send(:isred, node)).to eq(true)
end
it "should return false if the node is black" do
node = Puppet::Graph::RbTreeMap::Node.new(1,2)
node.color = :black
- subject.send(:isred, node).should == false
+ expect(subject.send(:isred, node)).to eq(false)
end
it "should return false if the node is nil" do
- subject.send(:isred, nil).should == false
+ expect(subject.send(:isred, nil)).to eq(false)
end
end
end
describe Puppet::Graph::RbTreeMap::Node do
let(:tree) { Puppet::Graph::RbTreeMap.new }
let(:subject) { tree.instance_variable_get(:@root) }
before :each do
(1..3).each {|i| tree[i] = i.to_s}
end
describe "#red?" do
it "should return true if the node is red" do
subject.color = :red
- subject.should be_red
+ expect(subject).to be_red
end
it "should return false if the node is black" do
subject.color = :black
- subject.should_not be_red
+ expect(subject).not_to be_red
end
end
describe "#colorflip" do
it "should switch the color of the node and its children" do
- subject.color.should == :black
- subject.left.color.should == :black
- subject.right.color.should == :black
+ expect(subject.color).to eq(:black)
+ expect(subject.left.color).to eq(:black)
+ expect(subject.right.color).to eq(:black)
subject.colorflip
- subject.color.should == :red
- subject.left.color.should == :red
- subject.right.color.should == :red
+ expect(subject.color).to eq(:red)
+ expect(subject.left.color).to eq(:red)
+ expect(subject.right.color).to eq(:red)
end
end
describe "#rotate_left" do
it "should rotate the tree once to the left" do
(4..7).each {|i| tree[i] = i.to_s}
root = tree.instance_variable_get(:@root)
root.rotate_left
- tree.to_hash.should == {
+ expect(tree.to_hash).to eq({
:node => {
:key => 6,
:value => '6',
:color => :black,
},
:left => {
:node => {
:key => 4,
:value => '4',
:color => :red,
},
:left => {
:node => {
:key => 2,
:value => '2',
:color => :black,
},
:left => {
:node => {
:key => 1,
:value => '1',
:color => :black,
},
},
:right => {
:node => {
:key => 3,
:value => '3',
:color => :black,
},
},
},
:right => {
:node => {
:key => 5,
:value => '5',
:color => :black,
},
},
},
:right => {
:node => {
:key => 7,
:value => '7',
:color => :black,
},
},
- }
+ })
end
end
describe "#rotate_right" do
it "should rotate the tree once to the right" do
(4..7).each {|i| tree[i] = i.to_s}
root = tree.instance_variable_get(:@root)
root.rotate_right
- tree.to_hash.should == {
+ expect(tree.to_hash).to eq({
:node => {
:key => 2,
:value => '2',
:color => :black,
},
:left => {
:node => {
:key => 1,
:value => '1',
:color => :black,
},
},
:right => {
:node => {
:key => 4,
:value => '4',
:color => :red,
},
:left => {
:node => {
:key => 3,
:value => '3',
:color => :black,
},
},
:right => {
:node => {
:key => 6,
:value => '6',
:color => :black,
},
:left => {
:node => {
:key => 5,
:value => '5',
:color => :black,
},
},
:right => {
:node => {
:key => 7,
:value => '7',
:color => :black,
},
},
},
},
- }
+ })
end
end
end
diff --git a/spec/unit/graph/relationship_graph_spec.rb b/spec/unit/graph/relationship_graph_spec.rb
index 8bd35de4d..d96be87a4 100755
--- a/spec/unit/graph/relationship_graph_spec.rb
+++ b/spec/unit/graph/relationship_graph_spec.rb
@@ -1,387 +1,387 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/graph'
require 'puppet_spec/compiler'
require 'matchers/include_in_order'
require 'matchers/relationship_graph_matchers'
describe Puppet::Graph::RelationshipGraph do
include PuppetSpec::Files
include PuppetSpec::Compiler
include RelationshipGraphMatchers
let(:graph) { Puppet::Graph::RelationshipGraph.new(Puppet::Graph::SequentialPrioritizer.new) }
it "allows adding a new vertex with a specific priority" do
vertex = stub_vertex('something')
graph.add_vertex(vertex, 2)
expect(graph.resource_priority(vertex)).to eq(2)
end
it "returns resource priority based on the order added" do
# strings chosen so the old hex digest method would put these in the
# wrong order
first = stub_vertex('aa')
second = stub_vertex('b')
graph.add_vertex(first)
graph.add_vertex(second)
expect(graph.resource_priority(first)).to be < graph.resource_priority(second)
end
it "retains the first priority when a resource is added more than once" do
first = stub_vertex(1)
second = stub_vertex(2)
graph.add_vertex(first)
graph.add_vertex(second)
graph.add_vertex(first)
expect(graph.resource_priority(first)).to be < graph.resource_priority(second)
end
it "forgets the priority of a removed resource" do
vertex = stub_vertex(1)
graph.add_vertex(vertex)
graph.remove_vertex!(vertex)
expect(graph.resource_priority(vertex)).to be_nil
end
it "does not give two resources the same priority" do
first = stub_vertex(1)
second = stub_vertex(2)
third = stub_vertex(3)
graph.add_vertex(first)
graph.add_vertex(second)
graph.remove_vertex!(first)
graph.add_vertex(third)
expect(graph.resource_priority(second)).to be < graph.resource_priority(third)
end
context "order of traversal" do
it "traverses independent resources in the order they are added" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
notify { "first": }
notify { "second": }
notify { "third": }
notify { "fourth": }
notify { "fifth": }
MANIFEST
expect(order_resources_traversed_in(relationships)).to(
include_in_order("Notify[first]",
"Notify[second]",
"Notify[third]",
"Notify[fourth]",
"Notify[fifth]"))
end
it "traverses resources generated during catalog creation in the order inserted" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
create_resources(notify, { "first" => {} })
create_resources(notify, { "second" => {} })
notify{ "third": }
create_resources(notify, { "fourth" => {} })
create_resources(notify, { "fifth" => {} })
MANIFEST
expect(order_resources_traversed_in(relationships)).to(
include_in_order("Notify[first]",
"Notify[second]",
"Notify[third]",
"Notify[fourth]",
"Notify[fifth]"))
end
it "traverses all independent resources before traversing dependent ones" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
notify { "first": require => Notify[third] }
notify { "second": }
notify { "third": }
MANIFEST
expect(order_resources_traversed_in(relationships)).to(
include_in_order("Notify[second]", "Notify[third]", "Notify[first]"))
end
it "traverses all independent resources before traversing dependent ones (with a backwards require)" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
notify { "first": }
notify { "second": }
notify { "third": require => Notify[second] }
notify { "fourth": }
MANIFEST
expect(order_resources_traversed_in(relationships)).to(
include_in_order("Notify[first]", "Notify[second]", "Notify[third]", "Notify[fourth]"))
end
it "traverses resources in classes in the order they are added" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
class c1 {
notify { "a": }
notify { "b": }
}
class c2 {
notify { "c": require => Notify[b] }
}
class c3 {
notify { "d": }
}
include c2
include c1
include c3
MANIFEST
expect(order_resources_traversed_in(relationships)).to(
include_in_order("Notify[a]", "Notify[b]", "Notify[c]", "Notify[d]"))
end
it "traverses resources in defines in the order they are added" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
define d1() {
notify { "a": }
notify { "b": }
}
define d2() {
notify { "c": require => Notify[b]}
}
define d3() {
notify { "d": }
}
d2 { "c": }
d1 { "d": }
d3 { "e": }
MANIFEST
expect(order_resources_traversed_in(relationships)).to(
include_in_order("Notify[a]", "Notify[b]", "Notify[c]", "Notify[d]"))
end
end
describe "when interrupting traversal" do
def collect_canceled_resources(relationships, trigger_on)
continue = true
continue_while = lambda { continue }
canceled_resources = []
canceled_resource_handler = lambda { |resource| canceled_resources << resource.ref }
relationships.traverse(:while => continue_while,
:canceled_resource_handler => canceled_resource_handler) do |resource|
if resource.ref == trigger_on
continue = false
end
end
canceled_resources
end
it "enumerates the remaining resources" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
notify { "a": }
notify { "b": }
notify { "c": }
MANIFEST
resources = collect_canceled_resources(relationships, 'Notify[b]')
expect(resources).to include('Notify[c]')
end
it "enumerates the remaining blocked resources" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
notify { "a": }
notify { "b": }
notify { "c": }
notify { "d": require => Notify["c"] }
MANIFEST
resources = collect_canceled_resources(relationships, 'Notify[b]')
expect(resources).to include('Notify[d]')
end
end
describe "when constructing dependencies" do
let(:child) { make_absolute('/a/b') }
let(:parent) { make_absolute('/a') }
it "does not create an automatic relationship that would interfere with a manual relationship" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
file { "#{child}": }
file { "#{parent}": require => File["#{child}"] }
MANIFEST
- relationship_graph.should enforce_order_with_edge("File[#{child}]", "File[#{parent}]")
+ expect(relationship_graph).to enforce_order_with_edge("File[#{child}]", "File[#{parent}]")
end
it "creates automatic relationships defined by the type" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
file { "#{child}": }
file { "#{parent}": }
MANIFEST
- relationship_graph.should enforce_order_with_edge("File[#{parent}]", "File[#{child}]")
+ expect(relationship_graph).to enforce_order_with_edge("File[#{parent}]", "File[#{child}]")
end
end
describe "when reconstructing containment relationships" do
def admissible_sentinel_of(ref)
"Admissible_#{ref}"
end
def completed_sentinel_of(ref)
"Completed_#{ref}"
end
it "an empty container's completed sentinel should depend on its admissible sentinel" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a { }
include a
MANIFEST
- relationship_graph.should enforce_order_with_edge(
+ expect(relationship_graph).to enforce_order_with_edge(
admissible_sentinel_of("class[A]"),
completed_sentinel_of("class[A]"))
end
it "a container with children does not directly connect the completed sentinel to its admissible sentinel" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a { notify { "a": } }
include a
MANIFEST
- relationship_graph.should_not enforce_order_with_edge(
+ expect(relationship_graph).not_to enforce_order_with_edge(
admissible_sentinel_of("class[A]"),
completed_sentinel_of("class[A]"))
end
it "all contained objects should depend on their container's admissible sentinel" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a {
notify { "class a": }
}
include a
MANIFEST
- relationship_graph.should enforce_order_with_edge(
+ expect(relationship_graph).to enforce_order_with_edge(
admissible_sentinel_of("class[A]"),
"Notify[class a]")
end
it "completed sentinels should depend on their container's contents" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a {
notify { "class a": }
}
include a
MANIFEST
- relationship_graph.should enforce_order_with_edge(
+ expect(relationship_graph).to enforce_order_with_edge(
"Notify[class a]",
completed_sentinel_of("class[A]"))
end
it "should remove all Component objects from the dependency graph" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a {
notify { "class a": }
}
define b() {
notify { "define b": }
}
include a
b { "testing": }
MANIFEST
- relationship_graph.vertices.find_all { |v| v.is_a?(Puppet::Type.type(:component)) }.should be_empty
+ expect(relationship_graph.vertices.find_all { |v| v.is_a?(Puppet::Type.type(:component)) }).to be_empty
end
it "should remove all Stage resources from the dependency graph" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
notify { "class a": }
MANIFEST
- relationship_graph.vertices.find_all { |v| v.is_a?(Puppet::Type.type(:stage)) }.should be_empty
+ expect(relationship_graph.vertices.find_all { |v| v.is_a?(Puppet::Type.type(:stage)) }).to be_empty
end
it "should retain labels on non-containment edges" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a {
notify { "class a": }
}
define b() {
notify { "define b": }
}
include a
Class[a] ~> b { "testing": }
MANIFEST
- relationship_graph.edges_between(
+ expect(relationship_graph.edges_between(
vertex_called(relationship_graph, completed_sentinel_of("class[A]")),
- vertex_called(relationship_graph, admissible_sentinel_of("b[testing]")))[0].label.
- should == {:callback => :refresh, :event => :ALL_EVENTS}
+ vertex_called(relationship_graph, admissible_sentinel_of("b[testing]")))[0].label).
+ to eq({:callback => :refresh, :event => :ALL_EVENTS})
end
it "should not add labels to edges that have none" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a {
notify { "class a": }
}
define b() {
notify { "define b": }
}
include a
Class[a] -> b { "testing": }
MANIFEST
- relationship_graph.edges_between(
+ expect(relationship_graph.edges_between(
vertex_called(relationship_graph, completed_sentinel_of("class[A]")),
- vertex_called(relationship_graph, admissible_sentinel_of("b[testing]")))[0].label.
- should be_empty
+ vertex_called(relationship_graph, admissible_sentinel_of("b[testing]")))[0].label).
+ to be_empty
end
it "should copy notification labels to all created edges" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a {
notify { "class a": }
}
define b() {
notify { "define b": }
}
include a
Class[a] ~> b { "testing": }
MANIFEST
- relationship_graph.edges_between(
+ expect(relationship_graph.edges_between(
vertex_called(relationship_graph, admissible_sentinel_of("b[testing]")),
- vertex_called(relationship_graph, "Notify[define b]"))[0].label.
- should == {:callback => :refresh, :event => :ALL_EVENTS}
+ vertex_called(relationship_graph, "Notify[define b]"))[0].label).
+ to eq({:callback => :refresh, :event => :ALL_EVENTS})
end
end
def vertex_called(graph, name)
graph.vertices.find { |v| v.ref =~ /#{Regexp.escape(name)}/ }
end
def stub_vertex(name)
stub "vertex #{name}", :ref => name
end
end
diff --git a/spec/unit/graph/simple_graph_spec.rb b/spec/unit/graph/simple_graph_spec.rb
index a6ae4d9c4..e9f492528 100755
--- a/spec/unit/graph/simple_graph_spec.rb
+++ b/spec/unit/graph/simple_graph_spec.rb
@@ -1,717 +1,717 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/graph'
describe Puppet::Graph::SimpleGraph do
it "should return the number of its vertices as its length" do
@graph = Puppet::Graph::SimpleGraph.new
@graph.add_vertex("one")
@graph.add_vertex("two")
- @graph.size.should == 2
+ expect(@graph.size).to eq(2)
end
it "should consider itself a directed graph" do
- Puppet::Graph::SimpleGraph.new.directed?.should be_true
+ expect(Puppet::Graph::SimpleGraph.new.directed?).to be_truthy
end
it "should provide a method for reversing the graph" do
@graph = Puppet::Graph::SimpleGraph.new
@graph.add_edge(:one, :two)
- @graph.reversal.edge?(:two, :one).should be_true
+ expect(@graph.reversal.edge?(:two, :one)).to be_truthy
end
it "should be able to produce a dot graph" do
@graph = Puppet::Graph::SimpleGraph.new
class FauxVertex
def ref
"never mind"
end
end
v1 = FauxVertex.new
v2 = FauxVertex.new
@graph.add_edge(v1, v2)
expect { @graph.to_dot_graph }.to_not raise_error
end
describe "when managing vertices" do
before do
@graph = Puppet::Graph::SimpleGraph.new
end
it "should provide a method to add a vertex" do
@graph.add_vertex(:test)
- @graph.vertex?(:test).should be_true
+ expect(@graph.vertex?(:test)).to be_truthy
end
it "should reset its reversed graph when vertices are added" do
rev = @graph.reversal
@graph.add_vertex(:test)
- @graph.reversal.should_not equal(rev)
+ expect(@graph.reversal).not_to equal(rev)
end
it "should ignore already-present vertices when asked to add a vertex" do
@graph.add_vertex(:test)
expect { @graph.add_vertex(:test) }.to_not raise_error
end
it "should return true when asked if a vertex is present" do
@graph.add_vertex(:test)
- @graph.vertex?(:test).should be_true
+ expect(@graph.vertex?(:test)).to be_truthy
end
it "should return false when asked if a non-vertex is present" do
- @graph.vertex?(:test).should be_false
+ expect(@graph.vertex?(:test)).to be_falsey
end
it "should return all set vertices when asked" do
@graph.add_vertex(:one)
@graph.add_vertex(:two)
- @graph.vertices.length.should == 2
- @graph.vertices.should include(:one)
- @graph.vertices.should include(:two)
+ expect(@graph.vertices.length).to eq(2)
+ expect(@graph.vertices).to include(:one)
+ expect(@graph.vertices).to include(:two)
end
it "should remove a given vertex when asked" do
@graph.add_vertex(:one)
@graph.remove_vertex!(:one)
- @graph.vertex?(:one).should be_false
+ expect(@graph.vertex?(:one)).to be_falsey
end
it "should do nothing when a non-vertex is asked to be removed" do
expect { @graph.remove_vertex!(:one) }.to_not raise_error
end
end
describe "when managing edges" do
before do
@graph = Puppet::Graph::SimpleGraph.new
end
it "should provide a method to test whether a given vertex pair is an edge" do
- @graph.should respond_to(:edge?)
+ expect(@graph).to respond_to(:edge?)
end
it "should reset its reversed graph when edges are added" do
rev = @graph.reversal
@graph.add_edge(:one, :two)
- @graph.reversal.should_not equal(rev)
+ expect(@graph.reversal).not_to equal(rev)
end
it "should provide a method to add an edge as an instance of the edge class" do
edge = Puppet::Relationship.new(:one, :two)
@graph.add_edge(edge)
- @graph.edge?(:one, :two).should be_true
+ expect(@graph.edge?(:one, :two)).to be_truthy
end
it "should provide a method to add an edge by specifying the two vertices" do
@graph.add_edge(:one, :two)
- @graph.edge?(:one, :two).should be_true
+ expect(@graph.edge?(:one, :two)).to be_truthy
end
it "should provide a method to add an edge by specifying the two vertices and a label" do
@graph.add_edge(:one, :two, :callback => :awesome)
- @graph.edge?(:one, :two).should be_true
+ expect(@graph.edge?(:one, :two)).to be_truthy
end
describe "when retrieving edges between two nodes" do
it "should handle the case of nodes not in the graph" do
- @graph.edges_between(:one, :two).should == []
+ expect(@graph.edges_between(:one, :two)).to eq([])
end
it "should handle the case of nodes with no edges between them" do
@graph.add_vertex(:one)
@graph.add_vertex(:two)
- @graph.edges_between(:one, :two).should == []
+ expect(@graph.edges_between(:one, :two)).to eq([])
end
it "should handle the case of nodes connected by a single edge" do
edge = Puppet::Relationship.new(:one, :two)
@graph.add_edge(edge)
- @graph.edges_between(:one, :two).length.should == 1
- @graph.edges_between(:one, :two)[0].should equal(edge)
+ expect(@graph.edges_between(:one, :two).length).to eq(1)
+ expect(@graph.edges_between(:one, :two)[0]).to equal(edge)
end
it "should handle the case of nodes connected by multiple edges" do
edge1 = Puppet::Relationship.new(:one, :two, :callback => :foo)
edge2 = Puppet::Relationship.new(:one, :two, :callback => :bar)
@graph.add_edge(edge1)
@graph.add_edge(edge2)
- Set.new(@graph.edges_between(:one, :two)).should == Set.new([edge1, edge2])
+ expect(Set.new(@graph.edges_between(:one, :two))).to eq(Set.new([edge1, edge2]))
end
end
it "should add the edge source as a vertex if it is not already" do
edge = Puppet::Relationship.new(:one, :two)
@graph.add_edge(edge)
- @graph.vertex?(:one).should be_true
+ expect(@graph.vertex?(:one)).to be_truthy
end
it "should add the edge target as a vertex if it is not already" do
edge = Puppet::Relationship.new(:one, :two)
@graph.add_edge(edge)
- @graph.vertex?(:two).should be_true
+ expect(@graph.vertex?(:two)).to be_truthy
end
it "should return all edges as edge instances when asked" do
one = Puppet::Relationship.new(:one, :two)
two = Puppet::Relationship.new(:two, :three)
@graph.add_edge(one)
@graph.add_edge(two)
edges = @graph.edges
- edges.should be_instance_of(Array)
- edges.length.should == 2
- edges.should include(one)
- edges.should include(two)
+ expect(edges).to be_instance_of(Array)
+ expect(edges.length).to eq(2)
+ expect(edges).to include(one)
+ expect(edges).to include(two)
end
it "should remove an edge when asked" do
edge = Puppet::Relationship.new(:one, :two)
@graph.add_edge(edge)
@graph.remove_edge!(edge)
- @graph.edge?(edge.source, edge.target).should be_false
+ expect(@graph.edge?(edge.source, edge.target)).to be_falsey
end
it "should remove all related edges when a vertex is removed" do
one = Puppet::Relationship.new(:one, :two)
two = Puppet::Relationship.new(:two, :three)
@graph.add_edge(one)
@graph.add_edge(two)
@graph.remove_vertex!(:two)
- @graph.edge?(:one, :two).should be_false
- @graph.edge?(:two, :three).should be_false
- @graph.edges.length.should == 0
+ expect(@graph.edge?(:one, :two)).to be_falsey
+ expect(@graph.edge?(:two, :three)).to be_falsey
+ expect(@graph.edges.length).to eq(0)
end
end
describe "when finding adjacent vertices" do
before do
@graph = Puppet::Graph::SimpleGraph.new
@one_two = Puppet::Relationship.new(:one, :two)
@two_three = Puppet::Relationship.new(:two, :three)
@one_three = Puppet::Relationship.new(:one, :three)
@graph.add_edge(@one_two)
@graph.add_edge(@one_three)
@graph.add_edge(@two_three)
end
it "should return adjacent vertices" do
adj = @graph.adjacent(:one)
- adj.should be_include(:three)
- adj.should be_include(:two)
+ expect(adj).to be_include(:three)
+ expect(adj).to be_include(:two)
end
it "should default to finding :out vertices" do
- @graph.adjacent(:two).should == [:three]
+ expect(@graph.adjacent(:two)).to eq([:three])
end
it "should support selecting :in vertices" do
- @graph.adjacent(:two, :direction => :in).should == [:one]
+ expect(@graph.adjacent(:two, :direction => :in)).to eq([:one])
end
it "should default to returning the matching vertices as an array of vertices" do
- @graph.adjacent(:two).should == [:three]
+ expect(@graph.adjacent(:two)).to eq([:three])
end
it "should support returning an array of matching edges" do
- @graph.adjacent(:two, :type => :edges).should == [@two_three]
+ expect(@graph.adjacent(:two, :type => :edges)).to eq([@two_three])
end
# Bug #2111
it "should not consider a vertex adjacent just because it was asked about previously" do
@graph = Puppet::Graph::SimpleGraph.new
@graph.add_vertex("a")
@graph.add_vertex("b")
@graph.edge?("a", "b")
- @graph.adjacent("a").should == []
+ expect(@graph.adjacent("a")).to eq([])
end
end
describe "when clearing" do
before do
@graph = Puppet::Graph::SimpleGraph.new
one = Puppet::Relationship.new(:one, :two)
two = Puppet::Relationship.new(:two, :three)
@graph.add_edge(one)
@graph.add_edge(two)
@graph.clear
end
it "should remove all vertices" do
- @graph.vertices.should be_empty
+ expect(@graph.vertices).to be_empty
end
it "should remove all edges" do
- @graph.edges.should be_empty
+ expect(@graph.edges).to be_empty
end
end
describe "when reversing graphs" do
before do
@graph = Puppet::Graph::SimpleGraph.new
end
it "should provide a method for reversing the graph" do
@graph.add_edge(:one, :two)
- @graph.reversal.edge?(:two, :one).should be_true
+ expect(@graph.reversal.edge?(:two, :one)).to be_truthy
end
it "should add all vertices to the reversed graph" do
@graph.add_edge(:one, :two)
- @graph.vertex?(:one).should be_true
- @graph.vertex?(:two).should be_true
+ expect(@graph.vertex?(:one)).to be_truthy
+ expect(@graph.vertex?(:two)).to be_truthy
end
it "should retain labels on edges" do
@graph.add_edge(:one, :two, :callback => :awesome)
edge = @graph.reversal.edges_between(:two, :one)[0]
- edge.label.should == {:callback => :awesome}
+ expect(edge.label).to eq({:callback => :awesome})
end
end
describe "when reporting cycles in the graph" do
before do
@graph = Puppet::Graph::SimpleGraph.new
end
# This works with `add_edges` to auto-vivify the resource instances.
let :vertex do
Hash.new do |hash, key|
hash[key] = Puppet::Type.type(:notify).new(:name => key.to_s)
end
end
def add_edges(hash)
hash.each do |a,b|
@graph.add_edge(vertex[a], vertex[b])
end
end
def simplify(cycles)
cycles.map do |cycle|
cycle.map do |resource|
resource.name
end
end
end
it "should fail on two-vertex loops" do
add_edges :a => :b, :b => :a
expect { @graph.report_cycles_in_graph }.to raise_error(Puppet::Error)
end
it "should fail on multi-vertex loops" do
add_edges :a => :b, :b => :c, :c => :a
expect { @graph.report_cycles_in_graph }.to raise_error(Puppet::Error)
end
it "should fail when a larger tree contains a small cycle" do
add_edges :a => :b, :b => :a, :c => :a, :d => :c
expect { @graph.report_cycles_in_graph }.to raise_error(Puppet::Error)
end
it "should succeed on trees with no cycles" do
add_edges :a => :b, :b => :e, :c => :a, :d => :c
expect { @graph.report_cycles_in_graph }.to_not raise_error
end
it "should produce the correct relationship text" do
add_edges :a => :b, :b => :a
# cycle detection starts from a or b randomly
# so we need to check for either ordering in the error message
want = %r{Found 1 dependency cycle:\n\((Notify\[a\] => Notify\[b\] => Notify\[a\]|Notify\[b\] => Notify\[a\] => Notify\[b\])\)\nTry}
expect { @graph.report_cycles_in_graph }.to raise_error(Puppet::Error, want)
end
it "cycle discovery should be the minimum cycle for a simple graph" do
add_edges "a" => "b"
add_edges "b" => "a"
add_edges "b" => "c"
- simplify(@graph.find_cycles_in_graph).should be == [["a", "b"]]
+ expect(simplify(@graph.find_cycles_in_graph)).to eq([["a", "b"]])
end
it "cycle discovery handles a self-loop cycle" do
add_edges :a => :a
- simplify(@graph.find_cycles_in_graph).should be == [["a"]]
+ expect(simplify(@graph.find_cycles_in_graph)).to eq([["a"]])
end
it "cycle discovery should handle two distinct cycles" do
add_edges "a" => "a1", "a1" => "a"
add_edges "b" => "b1", "b1" => "b"
- simplify(@graph.find_cycles_in_graph).should be == [["a1", "a"], ["b1", "b"]]
+ expect(simplify(@graph.find_cycles_in_graph)).to eq([["a1", "a"], ["b1", "b"]])
end
it "cycle discovery should handle two cycles in a connected graph" do
add_edges "a" => "b", "b" => "c", "c" => "d"
add_edges "a" => "a1", "a1" => "a"
add_edges "c" => "c1", "c1" => "c2", "c2" => "c3", "c3" => "c"
- simplify(@graph.find_cycles_in_graph).should be == [%w{a1 a}, %w{c1 c2 c3 c}]
+ expect(simplify(@graph.find_cycles_in_graph)).to eq([%w{a1 a}, %w{c1 c2 c3 c}])
end
it "cycle discovery should handle a complicated cycle" do
add_edges "a" => "b", "b" => "c"
add_edges "a" => "c"
add_edges "c" => "c1", "c1" => "a"
add_edges "c" => "c2", "c2" => "b"
- simplify(@graph.find_cycles_in_graph).should be == [%w{a b c1 c2 c}]
+ expect(simplify(@graph.find_cycles_in_graph)).to eq([%w{a b c1 c2 c}])
end
it "cycle discovery should not fail with large data sets" do
limit = 3000
(1..(limit - 1)).each do |n| add_edges n.to_s => (n+1).to_s end
- simplify(@graph.find_cycles_in_graph).should be == []
+ expect(simplify(@graph.find_cycles_in_graph)).to eq([])
end
it "path finding should work with a simple cycle" do
add_edges "a" => "b", "b" => "c", "c" => "a"
cycles = @graph.find_cycles_in_graph
paths = @graph.paths_in_cycle(cycles.first, 100)
- simplify(paths).should be == [%w{a b c a}]
+ expect(simplify(paths)).to eq([%w{a b c a}])
end
it "path finding should work with two independent cycles" do
add_edges "a" => "b1"
add_edges "a" => "b2"
add_edges "b1" => "a", "b2" => "a"
cycles = @graph.find_cycles_in_graph
- cycles.length.should be == 1
+ expect(cycles.length).to eq(1)
paths = @graph.paths_in_cycle(cycles.first, 100)
- simplify(paths).should be == [%w{a b1 a}, %w{a b2 a}]
+ expect(simplify(paths)).to eq([%w{a b1 a}, %w{a b2 a}])
end
it "path finding should prefer shorter paths in cycles" do
add_edges "a" => "b", "b" => "c", "c" => "a"
add_edges "b" => "a"
cycles = @graph.find_cycles_in_graph
- cycles.length.should be == 1
+ expect(cycles.length).to eq(1)
paths = @graph.paths_in_cycle(cycles.first, 100)
- simplify(paths).should be == [%w{a b a}, %w{a b c a}]
+ expect(simplify(paths)).to eq([%w{a b a}, %w{a b c a}])
end
it "path finding should respect the max_path value" do
(1..20).each do |n| add_edges "a" => "b#{n}", "b#{n}" => "a" end
cycles = @graph.find_cycles_in_graph
- cycles.length.should be == 1
+ expect(cycles.length).to eq(1)
(1..20).each do |n|
paths = @graph.paths_in_cycle(cycles.first, n)
- paths.length.should be == n
+ expect(paths.length).to eq(n)
end
paths = @graph.paths_in_cycle(cycles.first, 21)
- paths.length.should be == 20
+ expect(paths.length).to eq(20)
end
end
describe "when writing dot files" do
before do
@graph = Puppet::Graph::SimpleGraph.new
@name = :test
@file = File.join(Puppet[:graphdir], @name.to_s + ".dot")
end
it "should only write when graphing is enabled" do
File.expects(:open).with(@file).never
Puppet[:graph] = false
@graph.write_graph(@name)
end
it "should write a dot file based on the passed name" do
File.expects(:open).with(@file, "w").yields(stub("file", :puts => nil))
@graph.expects(:to_dot).with("name" => @name.to_s.capitalize)
Puppet[:graph] = true
@graph.write_graph(@name)
end
end
describe Puppet::Graph::SimpleGraph do
before do
@graph = Puppet::Graph::SimpleGraph.new
end
it "should correctly clear vertices and edges when asked" do
@graph.add_edge("a", "b")
@graph.add_vertex "c"
@graph.clear
- @graph.vertices.should be_empty
- @graph.edges.should be_empty
+ expect(@graph.vertices).to be_empty
+ expect(@graph.edges).to be_empty
end
end
describe "when matching edges" do
before do
@graph = Puppet::Graph::SimpleGraph.new
# Resource is a String here although not for realz. Stub [] to always return nil
# because indexing a String with a non-Integer throws an exception (and none of
# these tests need anything meaningful from []).
resource = "a"
resource.stubs(:[])
@event = Puppet::Transaction::Event.new(:name => :yay, :resource => resource)
@none = Puppet::Transaction::Event.new(:name => :NONE, :resource => resource)
@edges = {}
@edges["a/b"] = Puppet::Relationship.new("a", "b", {:event => :yay, :callback => :refresh})
@edges["a/c"] = Puppet::Relationship.new("a", "c", {:event => :yay, :callback => :refresh})
@graph.add_edge(@edges["a/b"])
end
it "should match edges whose source matches the source of the event" do
- @graph.matching_edges(@event).should == [@edges["a/b"]]
+ expect(@graph.matching_edges(@event)).to eq([@edges["a/b"]])
end
it "should match always match nothing when the event is :NONE" do
- @graph.matching_edges(@none).should be_empty
+ expect(@graph.matching_edges(@none)).to be_empty
end
it "should match multiple edges" do
@graph.add_edge(@edges["a/c"])
edges = @graph.matching_edges(@event)
- edges.should be_include(@edges["a/b"])
- edges.should be_include(@edges["a/c"])
+ expect(edges).to be_include(@edges["a/b"])
+ expect(edges).to be_include(@edges["a/c"])
end
end
describe "when determining dependencies" do
before do
@graph = Puppet::Graph::SimpleGraph.new
@graph.add_edge("a", "b")
@graph.add_edge("a", "c")
@graph.add_edge("b", "d")
end
it "should find all dependents when they are on multiple levels" do
- @graph.dependents("a").sort.should == %w{b c d}.sort
+ expect(@graph.dependents("a").sort).to eq(%w{b c d}.sort)
end
it "should find single dependents" do
- @graph.dependents("b").sort.should == %w{d}.sort
+ expect(@graph.dependents("b").sort).to eq(%w{d}.sort)
end
it "should return an empty array when there are no dependents" do
- @graph.dependents("c").sort.should == [].sort
+ expect(@graph.dependents("c").sort).to eq([].sort)
end
it "should find all dependencies when they are on multiple levels" do
- @graph.dependencies("d").sort.should == %w{a b}
+ expect(@graph.dependencies("d").sort).to eq(%w{a b})
end
it "should find single dependencies" do
- @graph.dependencies("c").sort.should == %w{a}
+ expect(@graph.dependencies("c").sort).to eq(%w{a})
end
it "should return an empty array when there are no dependencies" do
- @graph.dependencies("a").sort.should == []
+ expect(@graph.dependencies("a").sort).to eq([])
end
end
it "should serialize to YAML using the old format by default" do
- Puppet::Graph::SimpleGraph.use_new_yaml_format.should == false
+ expect(Puppet::Graph::SimpleGraph.use_new_yaml_format).to eq(false)
end
describe "(yaml tests)" do
def empty_graph(graph)
end
def one_vertex_graph(graph)
graph.add_vertex(:a)
end
def graph_without_edges(graph)
[:a, :b, :c].each { |x| graph.add_vertex(x) }
end
def one_edge_graph(graph)
graph.add_edge(:a, :b)
end
def many_edge_graph(graph)
graph.add_edge(:a, :b)
graph.add_edge(:a, :c)
graph.add_edge(:b, :d)
graph.add_edge(:c, :d)
end
def labeled_edge_graph(graph)
graph.add_edge(:a, :b, :callback => :foo, :event => :bar)
end
def overlapping_edge_graph(graph)
graph.add_edge(:a, :b, :callback => :foo, :event => :bar)
graph.add_edge(:a, :b, :callback => :biz, :event => :baz)
end
def self.all_test_graphs
[:empty_graph, :one_vertex_graph, :graph_without_edges, :one_edge_graph, :many_edge_graph, :labeled_edge_graph,
:overlapping_edge_graph]
end
def object_ids(enumerable)
# Return a sorted list of the object id's of the elements of an
# enumerable.
enumerable.collect { |x| x.object_id }.sort
end
def graph_to_yaml(graph, which_format)
previous_use_new_yaml_format = Puppet::Graph::SimpleGraph.use_new_yaml_format
Puppet::Graph::SimpleGraph.use_new_yaml_format = (which_format == :new)
YAML.dump(graph)
ensure
Puppet::Graph::SimpleGraph.use_new_yaml_format = previous_use_new_yaml_format
end
# Test serialization of graph to YAML.
[:old, :new].each do |which_format|
all_test_graphs.each do |graph_to_test|
it "should be able to serialize #{graph_to_test} to YAML (#{which_format} format)" do
graph = Puppet::Graph::SimpleGraph.new
send(graph_to_test, graph)
yaml_form = graph_to_yaml(graph, which_format)
# Hack the YAML so that objects in the Puppet namespace get
# changed to YAML::DomainType objects. This lets us inspect
# the serialized objects easily without invoking any
# yaml_initialize hooks.
yaml_form.gsub!('!ruby/object:Puppet::', '!hack/object:Puppet::')
serialized_object = YAML.load(yaml_form)
# Check that the object contains instance variables @edges and
# @vertices only. @reversal is also permitted, but we don't
# check it, because it is going to be phased out.
- serialized_object.keys.reject { |x| x == 'reversal' }.sort.should == ['edges', 'vertices']
+ expect(serialized_object.keys.reject { |x| x == 'reversal' }.sort).to eq(['edges', 'vertices'])
# Check edges by forming a set of tuples (source, target,
# callback, event) based on the graph and the YAML and make sure
# they match.
edges = serialized_object['edges']
- edges.should be_a(Array)
+ expect(edges).to be_a(Array)
expected_edge_tuples = graph.edges.collect { |edge| [edge.source, edge.target, edge.callback, edge.event] }
actual_edge_tuples = edges.collect do |edge|
- %w{source target}.each { |x| edge.keys.should include(x) }
- edge.keys.each { |x| ['source', 'target', 'callback', 'event'].should include(x) }
+ %w{source target}.each { |x| expect(edge.keys).to include(x) }
+ edge.keys.each { |x| expect(['source', 'target', 'callback', 'event']).to include(x) }
%w{source target callback event}.collect { |x| edge[x] }
end
- Set.new(actual_edge_tuples).should == Set.new(expected_edge_tuples)
- actual_edge_tuples.length.should == expected_edge_tuples.length
+ expect(Set.new(actual_edge_tuples)).to eq(Set.new(expected_edge_tuples))
+ expect(actual_edge_tuples.length).to eq(expected_edge_tuples.length)
# Check vertices one by one.
vertices = serialized_object['vertices']
if which_format == :old
- vertices.should be_a(Hash)
- Set.new(vertices.keys).should == Set.new(graph.vertices)
+ expect(vertices).to be_a(Hash)
+ expect(Set.new(vertices.keys)).to eq(Set.new(graph.vertices))
vertices.each do |key, value|
- value.keys.sort.should == %w{adjacencies vertex}
- value['vertex'].should equal(key)
+ expect(value.keys.sort).to eq(%w{adjacencies vertex})
+ expect(value['vertex']).to equal(key)
adjacencies = value['adjacencies']
- adjacencies.should be_a(Hash)
- Set.new(adjacencies.keys).should == Set.new([:in, :out])
+ expect(adjacencies).to be_a(Hash)
+ expect(Set.new(adjacencies.keys)).to eq(Set.new([:in, :out]))
[:in, :out].each do |direction|
- adjacencies[direction].should be_a(Hash)
+ expect(adjacencies[direction]).to be_a(Hash)
expected_adjacent_vertices = Set.new(graph.adjacent(key, :direction => direction, :type => :vertices))
- Set.new(adjacencies[direction].keys).should == expected_adjacent_vertices
+ expect(Set.new(adjacencies[direction].keys)).to eq(expected_adjacent_vertices)
adjacencies[direction].each do |adj_key, adj_value|
# Since we already checked edges, just check consistency
# with edges.
desired_source = direction == :in ? adj_key : key
desired_target = direction == :in ? key : adj_key
expected_edges = edges.select do |edge|
edge['source'] == desired_source && edge['target'] == desired_target
end
- adj_value.should be_a(Set)
+ expect(adj_value).to be_a(Set)
if object_ids(adj_value) != object_ids(expected_edges)
raise "For vertex #{key.inspect}, direction #{direction.inspect}: expected adjacencies #{expected_edges.inspect} but got #{adj_value.inspect}"
end
end
end
end
else
- vertices.should be_a(Array)
- Set.new(vertices).should == Set.new(graph.vertices)
- vertices.length.should == graph.vertices.length
+ expect(vertices).to be_a(Array)
+ expect(Set.new(vertices)).to eq(Set.new(graph.vertices))
+ expect(vertices.length).to eq(graph.vertices.length)
end
end
end
# Test deserialization of graph from YAML. This presumes the
# correctness of serialization to YAML, which has already been
# tested.
all_test_graphs.each do |graph_to_test|
it "should be able to deserialize #{graph_to_test} from YAML (#{which_format} format)" do
reference_graph = Puppet::Graph::SimpleGraph.new
send(graph_to_test, reference_graph)
yaml_form = graph_to_yaml(reference_graph, which_format)
recovered_graph = YAML.load(yaml_form)
# Test that the recovered vertices match the vertices in the
# reference graph.
expected_vertices = reference_graph.vertices.to_a
recovered_vertices = recovered_graph.vertices.to_a
- Set.new(recovered_vertices).should == Set.new(expected_vertices)
- recovered_vertices.length.should == expected_vertices.length
+ expect(Set.new(recovered_vertices)).to eq(Set.new(expected_vertices))
+ expect(recovered_vertices.length).to eq(expected_vertices.length)
# Test that the recovered edges match the edges in the
# reference graph.
expected_edge_tuples = reference_graph.edges.collect do |edge|
[edge.source, edge.target, edge.callback, edge.event]
end
recovered_edge_tuples = recovered_graph.edges.collect do |edge|
[edge.source, edge.target, edge.callback, edge.event]
end
- Set.new(recovered_edge_tuples).should == Set.new(expected_edge_tuples)
- recovered_edge_tuples.length.should == expected_edge_tuples.length
+ expect(Set.new(recovered_edge_tuples)).to eq(Set.new(expected_edge_tuples))
+ expect(recovered_edge_tuples.length).to eq(expected_edge_tuples.length)
# We ought to test that the recovered graph is self-consistent
# too. But we're not going to bother with that yet because
# the internal representation of the graph is about to change.
end
end
it "should be able to serialize a graph where the vertices contain backreferences to the graph (#{which_format} format)" do
reference_graph = Puppet::Graph::SimpleGraph.new
vertex = Object.new
vertex.instance_eval { @graph = reference_graph }
reference_graph.add_edge(vertex, :other_vertex)
yaml_form = graph_to_yaml(reference_graph, which_format)
recovered_graph = YAML.load(yaml_form)
- recovered_graph.vertices.length.should == 2
+ expect(recovered_graph.vertices.length).to eq(2)
recovered_vertex = recovered_graph.vertices.reject { |x| x.is_a?(Symbol) }[0]
- recovered_vertex.instance_eval { @graph }.should equal(recovered_graph)
- recovered_graph.edges.length.should == 1
+ expect(recovered_vertex.instance_eval { @graph }).to equal(recovered_graph)
+ expect(recovered_graph.edges.length).to eq(1)
recovered_edge = recovered_graph.edges[0]
- recovered_edge.source.should equal(recovered_vertex)
- recovered_edge.target.should == :other_vertex
+ expect(recovered_edge.source).to equal(recovered_vertex)
+ expect(recovered_edge.target).to eq(:other_vertex)
end
end
it "should serialize properly when used as a base class" do
class Puppet::TestDerivedClass < Puppet::Graph::SimpleGraph
attr_accessor :foo
end
derived = Puppet::TestDerivedClass.new
derived.add_edge(:a, :b)
derived.foo = 1234
recovered_derived = YAML.load(YAML.dump(derived))
- recovered_derived.class.should equal(Puppet::TestDerivedClass)
- recovered_derived.edges.length.should == 1
- recovered_derived.edges[0].source.should == :a
- recovered_derived.edges[0].target.should == :b
- recovered_derived.vertices.length.should == 2
- recovered_derived.foo.should == 1234
+ expect(recovered_derived.class).to equal(Puppet::TestDerivedClass)
+ expect(recovered_derived.edges.length).to eq(1)
+ expect(recovered_derived.edges[0].source).to eq(:a)
+ expect(recovered_derived.edges[0].target).to eq(:b)
+ expect(recovered_derived.vertices.length).to eq(2)
+ expect(recovered_derived.foo).to eq(1234)
end
end
end
diff --git a/spec/unit/hiera/backend/puppet_backend_spec.rb b/spec/unit/hiera/backend/puppet_backend_spec.rb
index 4e87430c6..04699ecc4 100644
--- a/spec/unit/hiera/backend/puppet_backend_spec.rb
+++ b/spec/unit/hiera/backend/puppet_backend_spec.rb
@@ -1,148 +1,148 @@
require 'spec_helper'
require 'hiera/backend/puppet_backend'
require 'hiera/scope'
require 'hiera/config'
describe Hiera::Backend::Puppet_backend do
before do
Hiera.stubs(:warn)
Hiera.stubs(:debug)
Hiera::Backend.stubs(:datasources).yields([])
Puppet::Parser::Functions.stubs(:function).with(:include)
@mockresource = mock
@mockresource.stubs(:name).returns("ntp::config")
@mockscope = mock
@mockscope.stubs(:resource).returns(@mockresource)
@scope = Hiera::Scope.new(@mockscope)
@backend = Hiera::Backend::Puppet_backend.new
end
describe "#hierarchy" do
it "should use the configured datasource" do
with_config(:puppet => {:datasource => "rspec"},
:hierarchy => nil)
- @backend.hierarchy(@scope, nil).should == ["rspec::ntp::config", "rspec::ntp", "ntp::config::rspec", "ntp::rspec"]
+ expect(@backend.hierarchy(@scope, nil)).to eq(["rspec::ntp::config", "rspec::ntp", "ntp::config::rspec", "ntp::rspec"])
end
it "should not include empty class names" do
with_config(:puppet => {:datasource => "rspec"},
:hierarchy => ["%{foo}", "common"])
@mockscope.expects(:lookupvar).with("foo").returns(nil)
- @backend.hierarchy(@scope, nil).should == ["rspec::common", "ntp::config::rspec", "ntp::rspec"]
+ expect(@backend.hierarchy(@scope, nil)).to eq(["rspec::common", "ntp::config::rspec", "ntp::rspec"])
end
it "should allow for an override data source" do
with_config(:puppet => {:datasource => "rspec"},
:hierarchy => nil)
- @backend.hierarchy(@scope, "override").should == ["rspec::override", "rspec::ntp::config", "rspec::ntp", "ntp::config::rspec", "ntp::rspec"]
+ expect(@backend.hierarchy(@scope, "override")).to eq(["rspec::override", "rspec::ntp::config", "rspec::ntp", "ntp::config::rspec", "ntp::rspec"])
end
end
describe "#lookup" do
it "should attempt to load data from unincluded classes" do
with_config(:puppet => {:datasource => "rspec"},
:hierarchy => ["rspec"])
catalog = mock
catalog.expects(:classes).returns([])
@mockscope.expects(:catalog).returns(catalog)
@mockscope.expects(:function_include).with(["rspec::rspec"])
@mockscope.expects(:lookupvar).with("rspec::rspec::key").returns("rspec")
- @backend.lookup("key", @scope, nil, nil).should == "rspec"
+ expect(@backend.lookup("key", @scope, nil, nil)).to eq("rspec")
end
it "should not load loaded classes" do
with_config(:puppet => {:datasource => "rspec"},
:hierarchy => ["rspec"])
catalog = mock
catalog.expects(:classes).returns(["rspec::rspec"])
@mockscope.expects(:catalog).returns(catalog)
@mockscope.expects(:function_include).never
@mockscope.expects(:lookupvar).with("rspec::rspec::key").returns("rspec")
- @backend.lookup("key", @scope, nil, nil).should == "rspec"
+ expect(@backend.lookup("key", @scope, nil, nil)).to eq("rspec")
end
it "should return the first found data" do
with_config(:puppet => {:datasource => "rspec"},
:hierarchy => ["override", "rspec"])
catalog = mock
catalog.expects(:classes).returns(["rspec::override", "override::override"])
@mockscope.expects(:catalog).returns(catalog)
@mockscope.expects(:function_include).never
@mockscope.expects(:lookupvar).with("rspec::override::key").returns("rspec")
@mockscope.expects(:lookupvar).with("rspec::rspec::key").never
- @backend.lookup("key", @scope, "override", nil).should == "rspec"
+ expect(@backend.lookup("key", @scope, "override", nil)).to eq("rspec")
end
it "should consider a value of false to be a real value" do
with_config(:puppet => {:datasource => "rspec"},
:hierarchy => ["override", "rspec"])
expected_answer = false
catalog = mock
catalog.expects(:classes).returns(["rspec::override", "override::override"])
@mockscope.expects(:catalog).returns(catalog)
@mockscope.expects(:lookupvar).with("rspec::override::key").returns(expected_answer)
@mockscope.expects(:lookupvar).with("rspec::rspec::key").never
- @backend.lookup("key", @scope, "override", nil).should == expected_answer
+ expect(@backend.lookup("key", @scope, "override", nil)).to eq(expected_answer)
end
it "should return an array of found data for array searches" do
catalog = mock
catalog.expects(:classes).returns(["rspec", "test"])
@mockscope.expects(:catalog).returns(catalog)
@mockscope.expects(:function_include).never
@mockscope.expects(:lookupvar).with("rspec::key").returns("rspec::key")
@mockscope.expects(:lookupvar).with("test::key").returns("test::key")
@backend.expects(:hierarchy).with(@scope, nil).returns(["rspec", "test"])
- @backend.lookup("key", @scope, nil, :array).should == ["rspec::key", "test::key"]
+ expect(@backend.lookup("key", @scope, nil, :array)).to eq(["rspec::key", "test::key"])
end
it "should return a hash of found data for hash searches" do
catalog = mock
catalog.expects(:classes).returns(["rspec", "test"])
@mockscope.expects(:catalog).returns(catalog)
@mockscope.expects(:function_include).never
@mockscope.expects(:lookupvar).with("rspec::key").returns({'rspec'=>'key'})
@mockscope.expects(:lookupvar).with("test::key").returns({'test'=>'key'})
@backend.expects(:hierarchy).with(@scope, nil).returns(["rspec", "test"])
- @backend.lookup("key", @scope, nil, :hash).should == {'rspec'=>'key', 'test'=>'key'}
+ expect(@backend.lookup("key", @scope, nil, :hash)).to eq({'rspec'=>'key', 'test'=>'key'})
end
it "should return a merged hash of found data for hash searches" do
catalog = mock
catalog.expects(:classes).returns(["rspec", "test"])
@mockscope.expects(:catalog).returns(catalog)
@mockscope.expects(:function_include).never
@mockscope.expects(:lookupvar).with("rspec::key").returns({'rspec'=>'key', 'common'=>'rspec'})
@mockscope.expects(:lookupvar).with("test::key").returns({'test'=>'key', 'common'=>'rspec'})
@backend.expects(:hierarchy).with(@scope, nil).returns(["rspec", "test"])
- @backend.lookup("key", @scope, nil, :hash).should == {'rspec'=>'key', 'common'=>'rspec', 'test'=>'key'}
+ expect(@backend.lookup("key", @scope, nil, :hash)).to eq({'rspec'=>'key', 'common'=>'rspec', 'test'=>'key'})
end
end
def with_config(config)
config.each do |key, value|
Hiera::Config.expects("[]").with(key).returns(value)
end
end
end
diff --git a/spec/unit/hiera/scope_spec.rb b/spec/unit/hiera/scope_spec.rb
index a18823615..6af83c3d9 100644
--- a/spec/unit/hiera/scope_spec.rb
+++ b/spec/unit/hiera/scope_spec.rb
@@ -1,90 +1,90 @@
require 'spec_helper'
require 'hiera/scope'
require 'puppet_spec/scope'
describe Hiera::Scope do
include PuppetSpec::Scope
let(:real) { create_test_scope_for_node("test_node") }
let(:scope) { Hiera::Scope.new(real) }
describe "#initialize" do
it "should store the supplied puppet scope" do
- scope.real.should == real
+ expect(scope.real).to eq(real)
end
end
describe "#[]" do
it "should return nil when no value is found" do
- scope["foo"].should == nil
+ expect(scope["foo"]).to eq(nil)
end
it "should treat '' as nil" do
real["foo"] = ""
- scope["foo"].should == nil
+ expect(scope["foo"]).to eq(nil)
end
it "should return found data" do
real["foo"] = "bar"
- scope["foo"].should == "bar"
+ expect(scope["foo"]).to eq("bar")
end
it "preserves the case of a string that is found" do
real["foo"] = "CAPITAL!"
- scope["foo"].should == "CAPITAL!"
+ expect(scope["foo"]).to eq("CAPITAL!")
end
it "aliases $module_name as calling_module" do
real["module_name"] = "the_module"
- scope["calling_module"].should == "the_module"
+ expect(scope["calling_module"]).to eq("the_module")
end
it "uses the name of the of the scope's class as the calling_class" do
real.source = Puppet::Resource::Type.new(:hostclass,
"testing",
:module_name => "the_module")
- scope["calling_class"].should == "testing"
+ expect(scope["calling_class"]).to eq("testing")
end
it "downcases the calling_class" do
real.source = Puppet::Resource::Type.new(:hostclass,
"UPPER CASE",
:module_name => "the_module")
- scope["calling_class"].should == "upper case"
+ expect(scope["calling_class"]).to eq("upper case")
end
it "looks for the class which includes the defined type as the calling_class" do
parent = create_test_scope_for_node("parent")
real.parent = parent
parent.source = Puppet::Resource::Type.new(:hostclass,
"name_of_the_class_including_the_definition",
:module_name => "class_module")
real.source = Puppet::Resource::Type.new(:definition,
"definition_name",
:module_name => "definition_module")
- scope["calling_class"].should == "name_of_the_class_including_the_definition"
+ expect(scope["calling_class"]).to eq("name_of_the_class_including_the_definition")
end
end
describe "#include?" do
it "should correctly report missing data" do
real["foo"] = ""
- scope.include?("foo").should == false
+ expect(scope.include?("foo")).to eq(false)
end
it "should always return true for calling_class and calling_module" do
- scope.include?("calling_class").should == true
- scope.include?("calling_class_path").should == true
- scope.include?("calling_module").should == true
+ expect(scope.include?("calling_class")).to eq(true)
+ expect(scope.include?("calling_class_path")).to eq(true)
+ expect(scope.include?("calling_module")).to eq(true)
end
end
end
diff --git a/spec/unit/hiera_puppet_spec.rb b/spec/unit/hiera_puppet_spec.rb
index 221dfa9c6..d3a72b2a5 100644
--- a/spec/unit/hiera_puppet_spec.rb
+++ b/spec/unit/hiera_puppet_spec.rb
@@ -1,118 +1,118 @@
require 'spec_helper'
require 'hiera_puppet'
require 'puppet_spec/scope'
describe 'HieraPuppet' do
include PuppetSpec::Scope
after(:all) do
HieraPuppet.instance_variable_set(:@hiera, nil)
end
describe 'HieraPuppet#hiera_config' do
let(:hiera_config_data) do
{ :backend => 'yaml' }
end
context "when the hiera_config_file exists" do
before do
Hiera::Config.expects(:load).returns(hiera_config_data)
HieraPuppet.expects(:hiera_config_file).returns(true)
end
it "should return a configuration hash" do
expected_results = {
:backend => 'yaml',
:logger => 'puppet'
}
- HieraPuppet.send(:hiera_config).should == expected_results
+ expect(HieraPuppet.send(:hiera_config)).to eq(expected_results)
end
end
context "when the hiera_config_file does not exist" do
before do
Hiera::Config.expects(:load).never
HieraPuppet.expects(:hiera_config_file).returns(nil)
end
it "should return a configuration hash" do
- HieraPuppet.send(:hiera_config).should == { :logger => 'puppet' }
+ expect(HieraPuppet.send(:hiera_config)).to eq({ :logger => 'puppet' })
end
end
end
describe 'HieraPuppet#hiera_config_file' do
it "should return nil when we cannot derive the hiera config file from Puppet.settings" do
begin
Puppet.settings[:hiera_config] = nil
rescue ArgumentError => detail
raise unless detail.message =~ /unknown setting/
end
- HieraPuppet.send(:hiera_config_file).should be_nil
+ expect(HieraPuppet.send(:hiera_config_file)).to be_nil
end
it "should use Puppet.settings[:hiera_config] as the hiera config file" do
begin
Puppet.settings[:hiera_config] = "/dev/null/my_hiera.yaml"
rescue ArgumentError => detail
raise unless detail.message =~ /unknown setting/
pending("This example does not apply to Puppet #{Puppet.version} because it does not have this setting")
end
Puppet::FileSystem.stubs(:exist?).with(Puppet[:hiera_config]).returns(true)
- HieraPuppet.send(:hiera_config_file).should == Puppet[:hiera_config]
+ expect(HieraPuppet.send(:hiera_config_file)).to eq(Puppet[:hiera_config])
end
it "should use Puppet.settings[:confdir] as the base directory when hiera_config is not set" do
begin
Puppet.settings[:hiera_config] = nil
rescue ArgumentError => detail
raise unless detail.message =~ /unknown setting/
end
Puppet.settings[:confdir] = "/dev/null/puppet"
hiera_config = File.join(Puppet[:confdir], 'hiera.yaml')
Puppet::FileSystem.stubs(:exist?).with(hiera_config).returns(true)
- HieraPuppet.send(:hiera_config_file).should == hiera_config
+ expect(HieraPuppet.send(:hiera_config_file)).to eq(hiera_config)
end
end
describe 'HieraPuppet#lookup' do
let :scope do create_test_scope_for_node('foo') end
before :each do
Puppet[:hiera_config] = PuppetSpec::Files.tmpfile('hiera_config')
end
it "should return the value from Hiera" do
Hiera.any_instance.stubs(:lookup).returns('8080')
- HieraPuppet.lookup('port', nil, scope, nil, :priority).should == '8080'
+ expect(HieraPuppet.lookup('port', nil, scope, nil, :priority)).to eq('8080')
Hiera.any_instance.stubs(:lookup).returns(['foo', 'bar'])
- HieraPuppet.lookup('ntpservers', nil, scope, nil, :array).should == ['foo', 'bar']
+ expect(HieraPuppet.lookup('ntpservers', nil, scope, nil, :array)).to eq(['foo', 'bar'])
Hiera.any_instance.stubs(:lookup).returns({'uid' => '1000'})
- HieraPuppet.lookup('user', nil, scope, nil, :hash).should == {'uid' => '1000'}
+ expect(HieraPuppet.lookup('user', nil, scope, nil, :hash)).to eq({'uid' => '1000'})
end
it "should raise a useful error when the answer is nil" do
Hiera.any_instance.stubs(:lookup).returns(nil)
expect do
HieraPuppet.lookup('port', nil, scope, nil, :priority)
end.to raise_error(Puppet::ParseError,
/Could not find data item port in any Hiera data file and no default supplied/)
end
end
describe 'HieraPuppet#parse_args' do
it 'should return a 3 item array' do
args = ['foo', '8080', nil, nil]
- HieraPuppet.parse_args(args).should == ['foo', '8080', nil]
+ expect(HieraPuppet.parse_args(args)).to eq(['foo', '8080', nil])
end
it 'should raise a useful error when no key is supplied' do
expect { HieraPuppet.parse_args([]) }.to raise_error(Puppet::ParseError,
/Please supply a parameter to perform a Hiera lookup/)
end
end
end
diff --git a/spec/unit/indirector/catalog/compiler_spec.rb b/spec/unit/indirector/catalog/compiler_spec.rb
index 8ff228e6e..fe3cf7b3b 100755
--- a/spec/unit/indirector/catalog/compiler_spec.rb
+++ b/spec/unit/indirector/catalog/compiler_spec.rb
@@ -1,267 +1,267 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/catalog/compiler'
describe Puppet::Resource::Catalog::Compiler do
before do
Facter.stubs(:to_hash).returns({})
end
describe "when initializing" do
before do
Puppet.expects(:version).returns(1)
Facter.expects(:value).with('fqdn').returns("my.server.com")
Facter.expects(:value).with('ipaddress').returns("my.ip.address")
end
it "should gather data about itself" do
Puppet::Resource::Catalog::Compiler.new
end
it "should cache the server metadata and reuse it" do
Puppet[:node_terminus] = :memory
Puppet::Node.indirection.save(Puppet::Node.new("node1"))
Puppet::Node.indirection.save(Puppet::Node.new("node2"))
compiler = Puppet::Resource::Catalog::Compiler.new
compiler.stubs(:compile)
compiler.find(Puppet::Indirector::Request.new(:catalog, :find, 'node1', nil, :node => 'node1'))
compiler.find(Puppet::Indirector::Request.new(:catalog, :find, 'node2', nil, :node => 'node2'))
end
end
describe "when finding catalogs" do
before do
Facter.stubs(:value).returns("whatever")
@compiler = Puppet::Resource::Catalog::Compiler.new
@name = "me"
@node = Puppet::Node.new @name
@node.stubs(:merge)
Puppet::Node.indirection.stubs(:find).returns @node
@request = Puppet::Indirector::Request.new(:catalog, :find, @name, nil, :node => @name)
end
it "should directly use provided nodes for a local request" do
Puppet::Node.indirection.expects(:find).never
@compiler.expects(:compile).with(@node)
@request.stubs(:options).returns(:use_node => @node)
@request.stubs(:remote?).returns(false)
@compiler.find(@request)
end
it "rejects a provided node if the request is remote" do
@request.stubs(:options).returns(:use_node => @node)
@request.stubs(:remote?).returns(true)
expect {
@compiler.find(@request)
}.to raise_error Puppet::Error, /invalid option use_node/i
end
it "should use the authenticated node name if no request key is provided" do
@request.stubs(:key).returns(nil)
Puppet::Node.indirection.expects(:find).with(@name, anything).returns(@node)
@compiler.expects(:compile).with(@node)
@compiler.find(@request)
end
it "should use the provided node name by default" do
@request.expects(:key).returns "my_node"
Puppet::Node.indirection.expects(:find).with("my_node", anything).returns @node
@compiler.expects(:compile).with(@node)
@compiler.find(@request)
end
it "should fail if no node is passed and none can be found" do
Puppet::Node.indirection.stubs(:find).with(@name, anything).returns(nil)
- proc { @compiler.find(@request) }.should raise_error(ArgumentError)
+ expect { @compiler.find(@request) }.to raise_error(ArgumentError)
end
it "should fail intelligently when searching for a node raises an exception" do
Puppet::Node.indirection.stubs(:find).with(@name, anything).raises "eh"
- proc { @compiler.find(@request) }.should raise_error(Puppet::Error)
+ expect { @compiler.find(@request) }.to raise_error(Puppet::Error)
end
it "should pass the found node to the compiler for compiling" do
Puppet::Node.indirection.expects(:find).with(@name, anything).returns(@node)
config = mock 'config'
Puppet::Parser::Compiler.expects(:compile).with(@node)
@compiler.find(@request)
end
it "should extract and save any facts from the request" do
Puppet::Node.indirection.expects(:find).with(@name, anything).returns @node
@compiler.expects(:extract_facts_from_request).with(@request)
Puppet::Parser::Compiler.stubs(:compile)
@compiler.find(@request)
end
it "requires `facts_format` option if facts are passed in" do
facts = Puppet::Node::Facts.new("mynode", :afact => "avalue")
request = Puppet::Indirector::Request.new(:catalog, :find, "mynode", nil, :facts => facts)
expect {
@compiler.find(request)
}.to raise_error ArgumentError, /no fact format provided for mynode/
end
it "rejects facts in the request from a different node" do
facts = Puppet::Node::Facts.new("differentnode", :afact => "avalue")
request = Puppet::Indirector::Request.new(
:catalog, :find, "mynode", nil, :facts => facts, :facts_format => "unused"
)
expect {
@compiler.find(request)
}.to raise_error Puppet::Error, /fact definition for the wrong node/i
end
it "should return the results of compiling as the catalog" do
Puppet::Node.indirection.stubs(:find).returns(@node)
config = mock 'config'
result = mock 'result'
Puppet::Parser::Compiler.expects(:compile).returns result
- @compiler.find(@request).should equal(result)
+ expect(@compiler.find(@request)).to equal(result)
end
end
describe "when extracting facts from the request" do
before do
Puppet::Node::Facts.indirection.terminus_class = :memory
Facter.stubs(:value).returns "something"
@compiler = Puppet::Resource::Catalog::Compiler.new
@facts = Puppet::Node::Facts.new('hostname', "fact" => "value", "architecture" => "i386")
end
def a_request_that_contains(facts)
request = Puppet::Indirector::Request.new(:catalog, :find, "hostname", nil)
request.options[:facts_format] = "pson"
request.options[:facts] = CGI.escape(facts.render(:pson))
request
end
it "should do nothing if no facts are provided" do
request = Puppet::Indirector::Request.new(:catalog, :find, "hostname", nil)
request.options[:facts] = nil
- @compiler.extract_facts_from_request(request).should be_nil
+ expect(@compiler.extract_facts_from_request(request)).to be_nil
end
it "should deserialize the facts without changing the timestamp" do
time = Time.now
@facts.timestamp = time
request = a_request_that_contains(@facts)
facts = @compiler.extract_facts_from_request(request)
expect(facts.timestamp).to eq(time)
end
it "should convert the facts into a fact instance and save it" do
request = a_request_that_contains(@facts)
options = {
:environment => request.environment,
:transaction_uuid => request.options[:transaction_uuid],
}
Puppet::Node::Facts.indirection.expects(:save).with(equals(@facts), nil, options)
@compiler.extract_facts_from_request(request)
end
end
describe "when finding nodes" do
it "should look node information up via the Node class with the provided key" do
Facter.stubs(:value).returns("whatever")
node = Puppet::Node.new('node')
compiler = Puppet::Resource::Catalog::Compiler.new
request = Puppet::Indirector::Request.new(:catalog, :find, "me", nil)
compiler.stubs(:compile)
Puppet::Node.indirection.expects(:find).with("me", anything).returns(node)
compiler.find(request)
end
it "should pass the transaction_uuid to the node indirection" do
uuid = '793ff10d-89f8-4527-a645-3302cbc749f3'
node = Puppet::Node.new("thing")
compiler = Puppet::Resource::Catalog::Compiler.new
compiler.stubs(:compile)
request = Puppet::Indirector::Request.new(:catalog, :find, "thing",
nil, :transaction_uuid => uuid)
Puppet::Node.indirection.expects(:find).with(
"thing",
has_entries(:transaction_uuid => uuid)
).returns(node)
compiler.find(request)
end
end
describe "after finding nodes" do
before do
Puppet.expects(:version).returns(1)
Facter.expects(:value).with('fqdn').returns("my.server.com")
Facter.expects(:value).with('ipaddress').returns("my.ip.address")
@compiler = Puppet::Resource::Catalog::Compiler.new
@node = Puppet::Node.new("me")
@request = Puppet::Indirector::Request.new(:catalog, :find, "me", nil)
@compiler.stubs(:compile)
Puppet::Node.indirection.stubs(:find).with("me", anything).returns(@node)
end
it "should add the server's Puppet version to the node's parameters as 'serverversion'" do
@node.expects(:merge).with { |args| args["serverversion"] == "1" }
@compiler.find(@request)
end
it "should add the server's fqdn to the node's parameters as 'servername'" do
@node.expects(:merge).with { |args| args["servername"] == "my.server.com" }
@compiler.find(@request)
end
it "should add the server's IP address to the node's parameters as 'serverip'" do
@node.expects(:merge).with { |args| args["serverip"] == "my.ip.address" }
@compiler.find(@request)
end
end
describe "when filtering resources" do
before :each do
Facter.stubs(:value)
@compiler = Puppet::Resource::Catalog::Compiler.new
@catalog = stub_everything 'catalog'
@catalog.stubs(:respond_to?).with(:filter).returns(true)
end
it "should delegate to the catalog instance filtering" do
@catalog.expects(:filter)
@compiler.filter(@catalog)
end
it "should filter out virtual resources" do
resource = mock 'resource', :virtual? => true
@catalog.stubs(:filter).yields(resource)
@compiler.filter(@catalog)
end
it "should return the same catalog if it doesn't support filtering" do
@catalog.stubs(:respond_to?).with(:filter).returns(false)
- @compiler.filter(@catalog).should == @catalog
+ expect(@compiler.filter(@catalog)).to eq(@catalog)
end
it "should return the filtered catalog" do
catalog = stub 'filtered catalog'
@catalog.stubs(:filter).returns(catalog)
- @compiler.filter(@catalog).should == catalog
+ expect(@compiler.filter(@catalog)).to eq(catalog)
end
end
end
diff --git a/spec/unit/indirector/catalog/json_spec.rb b/spec/unit/indirector/catalog/json_spec.rb
index 223aaad10..59fe10627 100755
--- a/spec/unit/indirector/catalog/json_spec.rb
+++ b/spec/unit/indirector/catalog/json_spec.rb
@@ -1,12 +1,12 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/resource/catalog'
require 'puppet/indirector/catalog/json'
describe Puppet::Resource::Catalog::Json do
# This is it for local functionality: we don't *do* anything else.
it "should be registered with the catalog store indirection" do
- Puppet::Resource::Catalog.indirection.terminus(:json).
- should be_an_instance_of described_class
+ expect(Puppet::Resource::Catalog.indirection.terminus(:json)).
+ to be_an_instance_of described_class
end
end
diff --git a/spec/unit/indirector/catalog/msgpack_spec.rb b/spec/unit/indirector/catalog/msgpack_spec.rb
index f266c897d..ad636b2f4 100755
--- a/spec/unit/indirector/catalog/msgpack_spec.rb
+++ b/spec/unit/indirector/catalog/msgpack_spec.rb
@@ -1,12 +1,12 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/resource/catalog'
require 'puppet/indirector/catalog/msgpack'
describe Puppet::Resource::Catalog::Msgpack, :if => Puppet.features.msgpack? do
# This is it for local functionality: we don't *do* anything else.
it "should be registered with the catalog store indirection" do
- Puppet::Resource::Catalog.indirection.terminus(:msgpack).
- should be_an_instance_of described_class
+ expect(Puppet::Resource::Catalog.indirection.terminus(:msgpack)).
+ to be_an_instance_of described_class
end
end
diff --git a/spec/unit/indirector/catalog/rest_spec.rb b/spec/unit/indirector/catalog/rest_spec.rb
index 2d521726d..033d0ac25 100755
--- a/spec/unit/indirector/catalog/rest_spec.rb
+++ b/spec/unit/indirector/catalog/rest_spec.rb
@@ -1,10 +1,10 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/catalog/rest'
describe Puppet::Resource::Catalog::Rest do
it "should be a sublcass of Puppet::Indirector::REST" do
- Puppet::Resource::Catalog::Rest.superclass.should equal(Puppet::Indirector::REST)
+ expect(Puppet::Resource::Catalog::Rest.superclass).to equal(Puppet::Indirector::REST)
end
end
diff --git a/spec/unit/indirector/catalog/static_compiler_spec.rb b/spec/unit/indirector/catalog/static_compiler_spec.rb
index cf6bba3a0..d08f3402c 100644
--- a/spec/unit/indirector/catalog/static_compiler_spec.rb
+++ b/spec/unit/indirector/catalog/static_compiler_spec.rb
@@ -1,237 +1,237 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/catalog/static_compiler'
require 'puppet/file_serving/metadata'
require 'puppet/file_serving/content'
require 'yaml'
describe Puppet::Resource::Catalog::StaticCompiler do
before :all do
@num_file_resources = 10
end
before :each do
Facter.stubs(:loadfacts)
Facter.stubs(:to_hash).returns({})
Facter.stubs(:value)
end
around(:each) do |example|
Puppet.override({
:current_environment => Puppet::Node::Environment.create(:app, []),
},
"Ensure we are using an environment other than root"
) do
example.run
end
end
let(:request) do
Puppet::Indirector::Request.new(:the_indirection_named_foo,
:find,
"the-node-named-foo",
:environment => "production")
end
describe "#find" do
it "returns a catalog" do
- subject.find(request).should be_a_kind_of(Puppet::Resource::Catalog)
+ expect(subject.find(request)).to be_a_kind_of(Puppet::Resource::Catalog)
end
it "returns nil if there is no compiled catalog" do
subject.expects(:compile).returns(nil)
- subject.find(request).should be_nil
+ expect(subject.find(request)).to be_nil
end
describe "a catalog with file resources containing source parameters with puppet:// URIs" do
it "filters file resource source URI's to checksums" do
stub_the_compiler
resource_catalog = subject.find(request)
resource_catalog.resources.each do |resource|
next unless resource.type == "File"
- resource[:content].should == "{md5}361fadf1c712e812d198c4cab5712a79"
- resource[:source].should be_nil
+ expect(resource[:content]).to eq("{md5}361fadf1c712e812d198c4cab5712a79")
+ expect(resource[:source]).to be_nil
end
end
it "does not modify file resources with non-puppet:// URI's" do
uri = "/this/is/not/a/puppet/uri.txt"
stub_the_compiler(:source => uri)
resource_catalog = subject.find(request)
resource_catalog.resources.each do |resource|
next unless resource.type == "File"
- resource[:content].should be_nil
- resource[:source].should == uri
+ expect(resource[:content]).to be_nil
+ expect(resource[:source]).to eq(uri)
end
end
it "copies the owner, group and mode from the fileserer" do
stub_the_compiler
resource_catalog = subject.find(request)
resource_catalog.resources.each do |resource|
next unless resource.type == "File"
- resource[:owner].should == 0
- resource[:group].should == 0
- resource[:mode].should == 420
+ expect(resource[:owner]).to eq(0)
+ expect(resource[:group]).to eq(0)
+ expect(resource[:mode]).to eq(420)
end
end
end
end
describe "(#15193) when storing content to the filebucket" do
it "explicitly uses the indirection method" do
# We expect the content to be retrieved from the FileServer ...
fake_content = mock('FileServer Content')
fake_content.expects(:content).returns("HELLO WORLD")
# Mock the FileBucket to behave as if the file content does not exist.
# NOTE, we're simulating the first call returning false, indicating the
# file is not present, then all subsequent calls returning true. This
# mocked behavior is intended to replicate the real behavior of the same
# file being stored to the filebucket multiple times.
Puppet::FileBucket::File.indirection.
expects(:find).times(@num_file_resources).
returns(false).then.returns(true)
Puppet::FileServing::Content.indirection.
expects(:find).once.
returns(fake_content)
# Once retrived from the FileServer, we expect the file to be stored into
# the FileBucket only once. All of the file resources in the fake
# catalog have the same content.
Puppet::FileBucket::File.indirection.expects(:save).once.with do |file|
file.contents == "HELLO WORLD"
end
# Obtain the Static Catalog
subject.stubs(:compile).returns(build_catalog)
resource_catalog = subject.find(request)
# Ensure all of the file resources were filtered
resource_catalog.resources.each do |resource|
next unless resource.type == "File"
- resource[:content].should == "{md5}361fadf1c712e812d198c4cab5712a79"
- resource[:source].should be_nil
+ expect(resource[:content]).to eq("{md5}361fadf1c712e812d198c4cab5712a79")
+ expect(resource[:source]).to be_nil
end
end
end
# Spec helper methods
def stub_the_compiler(options = {:stub_methods => [:store_content]})
# Build a resource catalog suitable for specifying the behavior of the
# static compiler.
compiler = mock('indirection terminus compiler')
compiler.stubs(:find).returns(build_catalog(options))
subject.stubs(:compiler).returns(compiler)
# Mock the store content method to prevent copying the contents to the
# file bucket.
(options[:stub_methods] || []).each do |mthd|
subject.stubs(mthd)
end
end
def build_catalog(options = {})
options = options.dup
options[:source] ||= 'puppet:///modules/mymodule/config_file.txt'
options[:request] ||= request
# Build a catalog suitable for the static compiler to operate on
environment = Puppet::Node::Environment.remote(:testing)
catalog = Puppet::Resource::Catalog.new("#{options[:request].key}", environment)
# Mock out the fileserver, otherwise converting the catalog to a
fake_fileserver_metadata = fileserver_metadata(options)
# Stub the call to the FileServer metadata API so we don't have to have
# a real fileserver initialized for testing.
Puppet::FileServing::Metadata.
indirection.stubs(:find).with do |uri, opts|
expect(uri).to eq options[:source].sub('puppet:///','')
expect(opts[:links]).to eq :manage
expect(opts[:environment]).to eq environment
end.returns(fake_fileserver_metadata)
# I want a resource that all the file resources require and another
# that requires them.
resources = Array.new
resources << Puppet::Resource.new("notify", "alpha")
resources << Puppet::Resource.new("notify", "omega")
# Create some File resources with source parameters.
1.upto(@num_file_resources) do |idx|
parameters = {
:ensure => 'file',
:source => options[:source],
:require => "Notify[alpha]",
:before => "Notify[omega]"
}
# The static compiler does not operate on a RAL catalog, so we're
# using Puppet::Resource to produce a resource catalog.
agnostic_path = File.expand_path("/tmp/file_#{idx}.txt") # Windows Friendly
rsrc = Puppet::Resource.new("file", agnostic_path, :parameters => parameters)
rsrc.file = 'site.pp'
rsrc.line = idx
resources << rsrc
end
resources.each do |rsrc|
catalog.add_resource(rsrc)
end
# Return the resource catalog
catalog
end
describe "(#22744) when filtering resources" do
let(:catalog) { stub_everything 'catalog' }
it "should delegate to the catalog instance filtering" do
catalog.expects(:filter)
subject.filter(catalog)
end
it "should filter out virtual resources" do
resource = mock 'resource', :virtual? => true
catalog.stubs(:filter).yields(resource)
subject.filter(catalog)
end
it "should return the same catalog if it doesn't support filtering" do
catalog.stubs(:respond_to?).with(:filter)
- subject.filter(catalog).should == catalog
+ expect(subject.filter(catalog)).to eq(catalog)
end
it "should return the filtered catalog" do
filtered_catalog = stub 'filtered catalog'
catalog.stubs(:filter).returns(filtered_catalog)
- subject.filter(catalog).should == filtered_catalog
+ expect(subject.filter(catalog)).to eq(filtered_catalog)
end
end
def fileserver_metadata(options = {})
yaml = <<EOFILESERVERMETADATA
--- !ruby/object:Puppet::FileServing::Metadata
checksum: "{md5}361fadf1c712e812d198c4cab5712a79"
checksum_type: md5
destination:
expiration: #{Time.now + 1800}
ftype: file
group: 0
links: !ruby/sym manage
mode: 420
owner: 0
path: #{File.expand_path('/etc/puppet/modules/mymodule/files/config_file.txt')}
source: #{options[:source]}
stat_method: !ruby/sym lstat
EOFILESERVERMETADATA
# Return a deserialized metadata object suitable for returning from a stub.
YAML.load(yaml)
end
end
diff --git a/spec/unit/indirector/catalog/yaml_spec.rb b/spec/unit/indirector/catalog/yaml_spec.rb
index f540519ef..36d2ccf3f 100755
--- a/spec/unit/indirector/catalog/yaml_spec.rb
+++ b/spec/unit/indirector/catalog/yaml_spec.rb
@@ -1,24 +1,24 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/resource/catalog'
require 'puppet/indirector/catalog/yaml'
describe Puppet::Resource::Catalog::Yaml do
it "should be a subclass of the Yaml terminus" do
- Puppet::Resource::Catalog::Yaml.superclass.should equal(Puppet::Indirector::Yaml)
+ expect(Puppet::Resource::Catalog::Yaml.superclass).to equal(Puppet::Indirector::Yaml)
end
it "should have documentation" do
- Puppet::Resource::Catalog::Yaml.doc.should_not be_nil
+ expect(Puppet::Resource::Catalog::Yaml.doc).not_to be_nil
end
it "should be registered with the catalog store indirection" do
indirection = Puppet::Indirector::Indirection.instance(:catalog)
- Puppet::Resource::Catalog::Yaml.indirection.should equal(indirection)
+ expect(Puppet::Resource::Catalog::Yaml.indirection).to equal(indirection)
end
it "should have its name set to :yaml" do
- Puppet::Resource::Catalog::Yaml.name.should == :yaml
+ expect(Puppet::Resource::Catalog::Yaml.name).to eq(:yaml)
end
end
diff --git a/spec/unit/indirector/certificate/ca_spec.rb b/spec/unit/indirector/certificate/ca_spec.rb
index decc95592..5f800e35d 100755
--- a/spec/unit/indirector/certificate/ca_spec.rb
+++ b/spec/unit/indirector/certificate/ca_spec.rb
@@ -1,23 +1,23 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/certificate/ca'
describe Puppet::SSL::Certificate::Ca do
it "should have documentation" do
- Puppet::SSL::Certificate::Ca.doc.should be_instance_of(String)
+ expect(Puppet::SSL::Certificate::Ca.doc).to be_instance_of(String)
end
it "should use the :signeddir as the collection directory" do
Puppet[:signeddir] = File.expand_path("/cert/dir")
- Puppet::SSL::Certificate::Ca.collection_directory.should == Puppet[:signeddir]
+ expect(Puppet::SSL::Certificate::Ca.collection_directory).to eq(Puppet[:signeddir])
end
it "should store the ca certificate at the :cacert location" do
Puppet.settings.stubs(:use)
Puppet[:cacert] = File.expand_path("/ca/cert")
file = Puppet::SSL::Certificate::Ca.new
file.stubs(:ca?).returns true
- file.path("whatever").should == Puppet[:cacert]
+ expect(file.path("whatever")).to eq(Puppet[:cacert])
end
end
diff --git a/spec/unit/indirector/certificate/file_spec.rb b/spec/unit/indirector/certificate/file_spec.rb
index fff00ea3a..f6b72b226 100755
--- a/spec/unit/indirector/certificate/file_spec.rb
+++ b/spec/unit/indirector/certificate/file_spec.rb
@@ -1,23 +1,23 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/certificate/file'
describe Puppet::SSL::Certificate::File do
it "should have documentation" do
- Puppet::SSL::Certificate::File.doc.should be_instance_of(String)
+ expect(Puppet::SSL::Certificate::File.doc).to be_instance_of(String)
end
it "should use the :certdir as the collection directory" do
Puppet[:certdir] = File.expand_path("/cert/dir")
- Puppet::SSL::Certificate::File.collection_directory.should == Puppet[:certdir]
+ expect(Puppet::SSL::Certificate::File.collection_directory).to eq(Puppet[:certdir])
end
it "should store the ca certificate at the :localcacert location" do
Puppet.settings.stubs(:use)
Puppet[:localcacert] = File.expand_path("/ca/cert")
file = Puppet::SSL::Certificate::File.new
file.stubs(:ca?).returns true
- file.path("whatever").should == Puppet[:localcacert]
+ expect(file.path("whatever")).to eq(Puppet[:localcacert])
end
end
diff --git a/spec/unit/indirector/certificate/rest_spec.rb b/spec/unit/indirector/certificate/rest_spec.rb
index c8f304a67..281ec5826 100755
--- a/spec/unit/indirector/certificate/rest_spec.rb
+++ b/spec/unit/indirector/certificate/rest_spec.rb
@@ -1,63 +1,63 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/certificate/rest'
describe Puppet::SSL::Certificate::Rest do
before do
@searcher = Puppet::SSL::Certificate::Rest.new
end
it "should be a sublcass of Puppet::Indirector::REST" do
- Puppet::SSL::Certificate::Rest.superclass.should equal(Puppet::Indirector::REST)
+ expect(Puppet::SSL::Certificate::Rest.superclass).to equal(Puppet::Indirector::REST)
end
it "should set server_setting to :ca_server" do
- Puppet::SSL::Certificate::Rest.server_setting.should == :ca_server
+ expect(Puppet::SSL::Certificate::Rest.server_setting).to eq(:ca_server)
end
it "should set port_setting to :ca_port" do
- Puppet::SSL::Certificate::Rest.port_setting.should == :ca_port
+ expect(Puppet::SSL::Certificate::Rest.port_setting).to eq(:ca_port)
end
it "should use the :ca SRV service" do
- Puppet::SSL::Certificate::Rest.srv_service.should == :ca
+ expect(Puppet::SSL::Certificate::Rest.srv_service).to eq(:ca)
end
it "should make sure found certificates have their names set to the search string" do
terminus = Puppet::SSL::Certificate::Rest.new
# This has 'boo.com' in the CN
cert_string = "-----BEGIN CERTIFICATE-----
MIICPzCCAaigAwIBAgIBBDANBgkqhkiG9w0BAQUFADAWMRQwEgYDVQQDDAtidWNr
eS5sb2NhbDAeFw0wOTA5MTcxNzI1MzJaFw0xNDA5MTYxNzI1MzJaMBIxEDAOBgNV
BAMMB2Jvby5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAKG9B+DkTCNh
F5xHchNDfnbC9NzWKM600oxrr84pgUVAG6B2wAZcdfoEtXszhsY9Jzpwqkvxk4Mx
AbYqo9+TCi4UoiH6e+vAKOOJD3DHrlf+/RW4hGtyaI41DBhf4+B4/oFz5PH9mvKe
NSfHFI/yPW+1IXYjxKLQNwF9E7q3JbnzAgMBAAGjgaAwgZ0wOAYJYIZIAYb4QgEN
BCsWKVB1cHBldCBSdWJ5L09wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMAwG
A1UdEwEB/wQCMAAwHQYDVR0OBBYEFJOxEUeyf4cNOBmf9zIaE1JTuNdLMAsGA1Ud
DwQEAwIFoDAnBgNVHSUEIDAeBggrBgEFBQcDAQYIKwYBBQUHAwIGCCsGAQUFBwME
MA0GCSqGSIb3DQEBBQUAA4GBAFTJxKprMg6tfhGnvEvURPmlJrINn9c2b5Y4AGYp
tO86PFFkWw/EIJvvJzbj3s+Butr+eUo//+f1xxX7UCwwGqGxKqjtVS219oU/wkx8
h7rW4Xk7MrLl0auSS1p4wLcAMm+ZImf94+j8Cj+tkr8eGozZceRV13b8+EkdaE3S
rn/G
-----END CERTIFICATE-----
"
network = stub 'network'
terminus.stubs(:network).returns network
response = stub 'response', :code => "200", :body => cert_string
response.stubs(:[]).with('content-type').returns "text/plain"
response.stubs(:[]).with('content-encoding')
response.stubs(:[]).with(Puppet::Network::HTTP::HEADER_PUPPET_VERSION).returns(Puppet.version)
network.stubs(:verify_callback=)
network.expects(:get).returns response
request = Puppet::Indirector::Request.new(:certificate, :find, "foo.com", nil)
result = terminus.find(request)
- result.should_not be_nil
- result.name.should == "foo.com"
+ expect(result).not_to be_nil
+ expect(result.name).to eq("foo.com")
end
end
diff --git a/spec/unit/indirector/certificate_request/ca_spec.rb b/spec/unit/indirector/certificate_request/ca_spec.rb
index ac18974c5..42e9ee093 100755
--- a/spec/unit/indirector/certificate_request/ca_spec.rb
+++ b/spec/unit/indirector/certificate_request/ca_spec.rb
@@ -1,57 +1,57 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/host'
require 'puppet/indirector/certificate_request/ca'
describe Puppet::SSL::CertificateRequest::Ca, :unless => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
before :each do
Puppet[:ssldir] = tmpdir('ssl')
Puppet::SSL::Host.ca_location = :local
Puppet[:localcacert] = Puppet[:cacert]
@ca = Puppet::SSL::CertificateAuthority.new
end
after :all do
Puppet::SSL::Host.ca_location = :none
end
it "should have documentation" do
- Puppet::SSL::CertificateRequest::Ca.doc.should be_instance_of(String)
+ expect(Puppet::SSL::CertificateRequest::Ca.doc).to be_instance_of(String)
end
it "should use the :csrdir as the collection directory" do
Puppet[:csrdir] = File.expand_path("/request/dir")
- Puppet::SSL::CertificateRequest::Ca.collection_directory.should == Puppet[:csrdir]
+ expect(Puppet::SSL::CertificateRequest::Ca.collection_directory).to eq(Puppet[:csrdir])
end
it "should overwrite the previous certificate request if allow_duplicate_certs is true" do
Puppet[:allow_duplicate_certs] = true
host = Puppet::SSL::Host.new("foo")
host.generate_certificate_request
@ca.sign(host.name)
Puppet::SSL::Host.indirection.find("foo").generate_certificate_request
- Puppet::SSL::Certificate.indirection.find("foo").name.should == "foo"
- Puppet::SSL::CertificateRequest.indirection.find("foo").name.should == "foo"
- Puppet::SSL::Host.indirection.find("foo").state.should == "requested"
+ expect(Puppet::SSL::Certificate.indirection.find("foo").name).to eq("foo")
+ expect(Puppet::SSL::CertificateRequest.indirection.find("foo").name).to eq("foo")
+ expect(Puppet::SSL::Host.indirection.find("foo").state).to eq("requested")
end
it "should reject a new certificate request if allow_duplicate_certs is false" do
Puppet[:allow_duplicate_certs] = false
host = Puppet::SSL::Host.new("bar")
host.generate_certificate_request
@ca.sign(host.name)
expect { Puppet::SSL::Host.indirection.find("bar").generate_certificate_request }.to raise_error(/ignoring certificate request/)
- Puppet::SSL::Certificate.indirection.find("bar").name.should == "bar"
- Puppet::SSL::CertificateRequest.indirection.find("bar").should be_nil
- Puppet::SSL::Host.indirection.find("bar").state.should == "signed"
+ expect(Puppet::SSL::Certificate.indirection.find("bar").name).to eq("bar")
+ expect(Puppet::SSL::CertificateRequest.indirection.find("bar")).to be_nil
+ expect(Puppet::SSL::Host.indirection.find("bar").state).to eq("signed")
end
end
diff --git a/spec/unit/indirector/certificate_request/file_spec.rb b/spec/unit/indirector/certificate_request/file_spec.rb
index 9bfc94f9d..bba283995 100755
--- a/spec/unit/indirector/certificate_request/file_spec.rb
+++ b/spec/unit/indirector/certificate_request/file_spec.rb
@@ -1,15 +1,15 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/certificate_request/file'
describe Puppet::SSL::CertificateRequest::File do
it "should have documentation" do
- Puppet::SSL::CertificateRequest::File.doc.should be_instance_of(String)
+ expect(Puppet::SSL::CertificateRequest::File.doc).to be_instance_of(String)
end
it "should use the :requestdir as the collection directory" do
Puppet[:requestdir] = File.expand_path("/request/dir")
- Puppet::SSL::CertificateRequest::File.collection_directory.should == Puppet[:requestdir]
+ expect(Puppet::SSL::CertificateRequest::File.collection_directory).to eq(Puppet[:requestdir])
end
end
diff --git a/spec/unit/indirector/certificate_request/rest_spec.rb b/spec/unit/indirector/certificate_request/rest_spec.rb
index 4949bff76..f836308d2 100755
--- a/spec/unit/indirector/certificate_request/rest_spec.rb
+++ b/spec/unit/indirector/certificate_request/rest_spec.rb
@@ -1,26 +1,26 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/certificate_request/rest'
describe Puppet::SSL::CertificateRequest::Rest do
before do
@searcher = Puppet::SSL::CertificateRequest::Rest.new
end
it "should be a sublcass of Puppet::Indirector::REST" do
- Puppet::SSL::CertificateRequest::Rest.superclass.should equal(Puppet::Indirector::REST)
+ expect(Puppet::SSL::CertificateRequest::Rest.superclass).to equal(Puppet::Indirector::REST)
end
it "should set server_setting to :ca_server" do
- Puppet::SSL::CertificateRequest::Rest.server_setting.should == :ca_server
+ expect(Puppet::SSL::CertificateRequest::Rest.server_setting).to eq(:ca_server)
end
it "should set port_setting to :ca_port" do
- Puppet::SSL::CertificateRequest::Rest.port_setting.should == :ca_port
+ expect(Puppet::SSL::CertificateRequest::Rest.port_setting).to eq(:ca_port)
end
it "should use the :ca SRV service" do
- Puppet::SSL::CertificateRequest::Rest.srv_service.should == :ca
+ expect(Puppet::SSL::CertificateRequest::Rest.srv_service).to eq(:ca)
end
end
diff --git a/spec/unit/indirector/certificate_revocation_list/ca_spec.rb b/spec/unit/indirector/certificate_revocation_list/ca_spec.rb
index f3acd7668..9aac66e89 100755
--- a/spec/unit/indirector/certificate_revocation_list/ca_spec.rb
+++ b/spec/unit/indirector/certificate_revocation_list/ca_spec.rb
@@ -1,16 +1,16 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/certificate_revocation_list/ca'
describe Puppet::SSL::CertificateRevocationList::Ca do
it "should have documentation" do
- Puppet::SSL::CertificateRevocationList::Ca.doc.should be_instance_of(String)
+ expect(Puppet::SSL::CertificateRevocationList::Ca.doc).to be_instance_of(String)
end
it "should use the :cacrl setting as the crl location" do
Puppet.settings.stubs(:use)
Puppet[:cacrl] = File.expand_path("/request/dir")
- Puppet::SSL::CertificateRevocationList::Ca.new.path("whatever").should == Puppet[:cacrl]
+ expect(Puppet::SSL::CertificateRevocationList::Ca.new.path("whatever")).to eq(Puppet[:cacrl])
end
end
diff --git a/spec/unit/indirector/certificate_revocation_list/file_spec.rb b/spec/unit/indirector/certificate_revocation_list/file_spec.rb
index 9ba0380b8..be86a4b48 100755
--- a/spec/unit/indirector/certificate_revocation_list/file_spec.rb
+++ b/spec/unit/indirector/certificate_revocation_list/file_spec.rb
@@ -1,17 +1,17 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/certificate_revocation_list/file'
describe Puppet::SSL::CertificateRevocationList::File do
it "should have documentation" do
- Puppet::SSL::CertificateRevocationList::File.doc.should be_instance_of(String)
+ expect(Puppet::SSL::CertificateRevocationList::File.doc).to be_instance_of(String)
end
it "should always store the file to :hostcrl location" do
crl = File.expand_path("/host/crl")
Puppet[:hostcrl] = crl
Puppet.settings.stubs(:use)
- Puppet::SSL::CertificateRevocationList::File.file_location.should == crl
+ expect(Puppet::SSL::CertificateRevocationList::File.file_location).to eq(crl)
end
end
diff --git a/spec/unit/indirector/certificate_revocation_list/rest_spec.rb b/spec/unit/indirector/certificate_revocation_list/rest_spec.rb
index f8d37c341..c82b9f916 100755
--- a/spec/unit/indirector/certificate_revocation_list/rest_spec.rb
+++ b/spec/unit/indirector/certificate_revocation_list/rest_spec.rb
@@ -1,26 +1,26 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/certificate_revocation_list/rest'
describe Puppet::SSL::CertificateRevocationList::Rest do
before do
@searcher = Puppet::SSL::CertificateRevocationList::Rest.new
end
it "should be a sublcass of Puppet::Indirector::REST" do
- Puppet::SSL::CertificateRevocationList::Rest.superclass.should equal(Puppet::Indirector::REST)
+ expect(Puppet::SSL::CertificateRevocationList::Rest.superclass).to equal(Puppet::Indirector::REST)
end
it "should set server_setting to :ca_server" do
- Puppet::SSL::CertificateRevocationList::Rest.server_setting.should == :ca_server
+ expect(Puppet::SSL::CertificateRevocationList::Rest.server_setting).to eq(:ca_server)
end
it "should set port_setting to :ca_port" do
- Puppet::SSL::CertificateRevocationList::Rest.port_setting.should == :ca_port
+ expect(Puppet::SSL::CertificateRevocationList::Rest.port_setting).to eq(:ca_port)
end
it "should use the :ca SRV service" do
- Puppet::SSL::CertificateRevocationList::Rest.srv_service.should == :ca
+ expect(Puppet::SSL::CertificateRevocationList::Rest.srv_service).to eq(:ca)
end
end
diff --git a/spec/unit/indirector/certificate_status/file_spec.rb b/spec/unit/indirector/certificate_status/file_spec.rb
index 83d4de210..8bf10742d 100755
--- a/spec/unit/indirector/certificate_status/file_spec.rb
+++ b/spec/unit/indirector/certificate_status/file_spec.rb
@@ -1,191 +1,191 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/host'
require 'puppet/indirector/certificate_status'
require 'tempfile'
describe "Puppet::Indirector::CertificateStatus::File" do
include PuppetSpec::Files
before :all do
Puppet::SSL::Host.configure_indirection(:file)
end
before do
Puppet::SSL::CertificateAuthority.stubs(:ca?).returns true
@terminus = Puppet::SSL::Host.indirection.terminus(:file)
@tmpdir = tmpdir("certificate_status_ca_testing")
Puppet[:confdir] = @tmpdir
Puppet[:vardir] = @tmpdir
# localcacert is where each client stores the CA certificate
# cacert is where the master stores the CA certificate
# Since we need to play the role of both for testing we need them to be the same and exist
Puppet[:cacert] = Puppet[:localcacert]
end
def generate_csr(host)
host.generate_key
csr = Puppet::SSL::CertificateRequest.new(host.name)
csr.generate(host.key.content)
Puppet::SSL::CertificateRequest.indirection.save(csr)
end
def sign_csr(host)
host.desired_state = "signed"
@terminus.save(Puppet::Indirector::Request.new(:certificate_status, :save, host.name, host))
end
def generate_signed_cert(host)
generate_csr(host)
sign_csr(host)
@terminus.find(Puppet::Indirector::Request.new(:certificate_status, :find, host.name, host))
end
def generate_revoked_cert(host)
generate_signed_cert(host)
host.desired_state = "revoked"
@terminus.save(Puppet::Indirector::Request.new(:certificate_status, :save, host.name, host))
end
it "should be a terminus on SSL::Host" do
- @terminus.should be_instance_of(Puppet::Indirector::CertificateStatus::File)
+ expect(@terminus).to be_instance_of(Puppet::Indirector::CertificateStatus::File)
end
it "should create a CA instance if none is present" do
- @terminus.ca.should be_instance_of(Puppet::SSL::CertificateAuthority)
+ expect(@terminus.ca).to be_instance_of(Puppet::SSL::CertificateAuthority)
end
describe "when creating the CA" do
it "should fail if it is not a valid CA" do
Puppet::SSL::CertificateAuthority.expects(:ca?).returns false
- lambda { @terminus.ca }.should raise_error(ArgumentError, "This process is not configured as a certificate authority")
+ expect { @terminus.ca }.to raise_error(ArgumentError, "This process is not configured as a certificate authority")
end
end
it "should be indirected with the name 'certificate_status'" do
- Puppet::SSL::Host.indirection.name.should == :certificate_status
+ expect(Puppet::SSL::Host.indirection.name).to eq(:certificate_status)
end
describe "when finding" do
before do
@host = Puppet::SSL::Host.new("foo")
Puppet.settings.use(:main)
end
it "should return the Puppet::SSL::Host when a CSR exists for the host" do
generate_csr(@host)
request = Puppet::Indirector::Request.new(:certificate_status, :find, "foo", @host)
retrieved_host = @terminus.find(request)
- retrieved_host.name.should == @host.name
- retrieved_host.certificate_request.content.to_s.chomp.should == @host.certificate_request.content.to_s.chomp
+ expect(retrieved_host.name).to eq(@host.name)
+ expect(retrieved_host.certificate_request.content.to_s.chomp).to eq(@host.certificate_request.content.to_s.chomp)
end
it "should return the Puppet::SSL::Host when a public key exists for the host" do
generate_signed_cert(@host)
request = Puppet::Indirector::Request.new(:certificate_status, :find, "foo", @host)
retrieved_host = @terminus.find(request)
- retrieved_host.name.should == @host.name
- retrieved_host.certificate.content.to_s.chomp.should == @host.certificate.content.to_s.chomp
+ expect(retrieved_host.name).to eq(@host.name)
+ expect(retrieved_host.certificate.content.to_s.chomp).to eq(@host.certificate.content.to_s.chomp)
end
it "should return nil when neither a CSR nor public key exist for the host" do
request = Puppet::Indirector::Request.new(:certificate_status, :find, "foo", @host)
- @terminus.find(request).should == nil
+ expect(@terminus.find(request)).to eq(nil)
end
end
describe "when saving" do
before do
@host = Puppet::SSL::Host.new("foobar")
Puppet.settings.use(:main)
end
describe "when signing a cert" do
before do
@host.desired_state = "signed"
@request = Puppet::Indirector::Request.new(:certificate_status, :save, "foobar", @host)
end
it "should fail if no CSR is on disk" do
- lambda { @terminus.save(@request) }.should raise_error(Puppet::Error, /certificate request/)
+ expect { @terminus.save(@request) }.to raise_error(Puppet::Error, /certificate request/)
end
it "should sign the on-disk CSR when it is present" do
signed_host = generate_signed_cert(@host)
- signed_host.state.should == "signed"
- Puppet::SSL::Certificate.indirection.find("foobar").should be_instance_of(Puppet::SSL::Certificate)
+ expect(signed_host.state).to eq("signed")
+ expect(Puppet::SSL::Certificate.indirection.find("foobar")).to be_instance_of(Puppet::SSL::Certificate)
end
end
describe "when revoking a cert" do
before do
@request = Puppet::Indirector::Request.new(:certificate_status, :save, "foobar", @host)
end
it "should fail if no certificate is on disk" do
@host.desired_state = "revoked"
- lambda { @terminus.save(@request) }.should raise_error(Puppet::Error, /Cannot revoke/)
+ expect { @terminus.save(@request) }.to raise_error(Puppet::Error, /Cannot revoke/)
end
it "should revoke the certificate when it is present" do
generate_revoked_cert(@host)
- @host.state.should == 'revoked'
+ expect(@host.state).to eq('revoked')
end
end
end
describe "when deleting" do
before do
Puppet.settings.use(:main)
end
it "should not delete anything if no certificate, request, or key is on disk" do
host = Puppet::SSL::Host.new("clean_me")
request = Puppet::Indirector::Request.new(:certificate_status, :delete, "clean_me", host)
- @terminus.destroy(request).should == "Nothing was deleted"
+ expect(@terminus.destroy(request)).to eq("Nothing was deleted")
end
it "should clean certs, cert requests, keys" do
signed_host = Puppet::SSL::Host.new("clean_signed_cert")
generate_signed_cert(signed_host)
signed_request = Puppet::Indirector::Request.new(:certificate_status, :delete, "clean_signed_cert", signed_host)
- @terminus.destroy(signed_request).should == "Deleted for clean_signed_cert: Puppet::SSL::Certificate, Puppet::SSL::Key"
+ expect(@terminus.destroy(signed_request)).to eq("Deleted for clean_signed_cert: Puppet::SSL::Certificate, Puppet::SSL::Key")
requested_host = Puppet::SSL::Host.new("clean_csr")
generate_csr(requested_host)
csr_request = Puppet::Indirector::Request.new(:certificate_status, :delete, "clean_csr", requested_host)
- @terminus.destroy(csr_request).should == "Deleted for clean_csr: Puppet::SSL::CertificateRequest, Puppet::SSL::Key"
+ expect(@terminus.destroy(csr_request)).to eq("Deleted for clean_csr: Puppet::SSL::CertificateRequest, Puppet::SSL::Key")
end
end
describe "when searching" do
it "should return a list of all hosts with certificate requests, signed certs, or revoked certs" do
Puppet.settings.use(:main)
signed_host = Puppet::SSL::Host.new("signed_host")
generate_signed_cert(signed_host)
requested_host = Puppet::SSL::Host.new("requested_host")
generate_csr(requested_host)
revoked_host = Puppet::SSL::Host.new("revoked_host")
generate_revoked_cert(revoked_host)
retrieved_hosts = @terminus.search(Puppet::Indirector::Request.new(:certificate_status, :search, "all", signed_host))
results = retrieved_hosts.map {|h| [h.name, h.state]}.sort{ |h,i| h[0] <=> i[0] }
- results.should == [["ca","signed"],["requested_host","requested"],["revoked_host","revoked"],["signed_host","signed"]]
+ expect(results).to eq([["ca","signed"],["requested_host","requested"],["revoked_host","revoked"],["signed_host","signed"]])
end
end
end
diff --git a/spec/unit/indirector/certificate_status/rest_spec.rb b/spec/unit/indirector/certificate_status/rest_spec.rb
index 33dff7528..9d39c7d5a 100755
--- a/spec/unit/indirector/certificate_status/rest_spec.rb
+++ b/spec/unit/indirector/certificate_status/rest_spec.rb
@@ -1,18 +1,18 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/host'
require 'puppet/indirector/certificate_status'
describe "Puppet::CertificateStatus::Rest" do
before do
@terminus = Puppet::SSL::Host.indirection.terminus(:rest)
end
it "should be a terminus on Puppet::SSL::Host" do
- @terminus.should be_instance_of(Puppet::Indirector::CertificateStatus::Rest)
+ expect(@terminus).to be_instance_of(Puppet::Indirector::CertificateStatus::Rest)
end
it "should use the :ca SRV service" do
- Puppet::Indirector::CertificateStatus::Rest.srv_service.should == :ca
+ expect(Puppet::Indirector::CertificateStatus::Rest.srv_service).to eq(:ca)
end
end
diff --git a/spec/unit/indirector/code_spec.rb b/spec/unit/indirector/code_spec.rb
index a7a307287..05363f440 100755
--- a/spec/unit/indirector/code_spec.rb
+++ b/spec/unit/indirector/code_spec.rb
@@ -1,31 +1,31 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/code'
describe Puppet::Indirector::Code do
before :all do
Puppet::Indirector::Terminus.stubs(:register_terminus_class)
@model = mock 'model'
@indirection = stub 'indirection', :name => :mystuff, :register_terminus_type => nil, :model => @model
Puppet::Indirector::Indirection.stubs(:instance).returns(@indirection)
module Testing; end
@code_class = class Testing::MyCode < Puppet::Indirector::Code
self
end
@searcher = @code_class.new
end
it "should not have a find() method defined" do
- @searcher.should_not respond_to(:find)
+ expect(@searcher).not_to respond_to(:find)
end
it "should not have a save() method defined" do
- @searcher.should_not respond_to(:save)
+ expect(@searcher).not_to respond_to(:save)
end
it "should not have a destroy() method defined" do
- @searcher.should_not respond_to(:destroy)
+ expect(@searcher).not_to respond_to(:destroy)
end
end
diff --git a/spec/unit/indirector/data_binding/hiera_spec.rb b/spec/unit/indirector/data_binding/hiera_spec.rb
index 12572b174..9cda5aabe 100644
--- a/spec/unit/indirector/data_binding/hiera_spec.rb
+++ b/spec/unit/indirector/data_binding/hiera_spec.rb
@@ -1,19 +1,19 @@
require 'spec_helper'
require 'puppet/indirector/data_binding/hiera'
describe Puppet::DataBinding::Hiera do
it "should have documentation" do
- Puppet::DataBinding::Hiera.doc.should_not be_nil
+ 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)
- Puppet::DataBinding::Hiera.indirection.should equal(indirection)
+ expect(Puppet::DataBinding::Hiera.indirection).to equal(indirection)
end
it "should have its name set to :hiera" do
- Puppet::DataBinding::Hiera.name.should == :hiera
+ expect(Puppet::DataBinding::Hiera.name).to eq(:hiera)
end
it_should_behave_like "Hiera indirection", Puppet::DataBinding::Hiera, my_fixture_dir
end
diff --git a/spec/unit/indirector/data_binding/none_spec.rb b/spec/unit/indirector/data_binding/none_spec.rb
index ebd7d4b04..b924a56e1 100644
--- a/spec/unit/indirector/data_binding/none_spec.rb
+++ b/spec/unit/indirector/data_binding/none_spec.rb
@@ -1,28 +1,28 @@
require 'spec_helper'
require 'puppet/indirector/data_binding/none'
describe Puppet::DataBinding::None do
it "should be a subclass of the None terminus" do
- Puppet::DataBinding::None.superclass.should equal(Puppet::Indirector::None)
+ expect(Puppet::DataBinding::None.superclass).to equal(Puppet::Indirector::None)
end
it "should have documentation" do
- Puppet::DataBinding::None.doc.should_not be_nil
+ 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)
- Puppet::DataBinding::None.indirection.should equal(indirection)
+ expect(Puppet::DataBinding::None.indirection).to equal(indirection)
end
it "should have its name set to :none" do
- Puppet::DataBinding::None.name.should == :none
+ expect(Puppet::DataBinding::None.name).to eq(:none)
end
describe "the behavior of the find method" do
it "should just return nil" do
data_binding = Puppet::DataBinding::None.new
- data_binding.find('fake_request').should be_nil
+ expect(data_binding.find('fake_request')).to be_nil
end
end
end
diff --git a/spec/unit/indirector/direct_file_server_spec.rb b/spec/unit/indirector/direct_file_server_spec.rb
index b47b13a11..00764c3b9 100755
--- a/spec/unit/indirector/direct_file_server_spec.rb
+++ b/spec/unit/indirector/direct_file_server_spec.rb
@@ -1,80 +1,80 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/direct_file_server'
describe Puppet::Indirector::DirectFileServer do
before :all do
Puppet::Indirector::Terminus.stubs(:register_terminus_class)
@model = mock 'model'
@indirection = stub 'indirection', :name => :mystuff, :register_terminus_type => nil, :model => @model
Puppet::Indirector::Indirection.stubs(:instance).returns(@indirection)
module Testing; end
@direct_file_class = class Testing::Mytype < Puppet::Indirector::DirectFileServer
self
end
@server = @direct_file_class.new
@path = File.expand_path('/my/local')
@uri = Puppet::Util.path_to_uri(@path).to_s
@request = Puppet::Indirector::Request.new(:mytype, :find, @uri, nil)
end
describe Puppet::Indirector::DirectFileServer, "when finding a single file" do
it "should return nil if the file does not exist" do
Puppet::FileSystem.expects(:exist?).with(@path).returns false
- @server.find(@request).should be_nil
+ expect(@server.find(@request)).to be_nil
end
it "should return a Content instance created with the full path to the file if the file exists" do
Puppet::FileSystem.expects(:exist?).with(@path).returns true
@model.expects(:new).returns(:mycontent)
- @server.find(@request).should == :mycontent
+ expect(@server.find(@request)).to eq(:mycontent)
end
end
describe Puppet::Indirector::DirectFileServer, "when creating the instance for a single found file" do
before do
@data = mock 'content'
@data.stubs(:collect)
Puppet::FileSystem.expects(:exist?).with(@path).returns true
end
it "should pass the full path to the instance" do
@model.expects(:new).with { |key, options| key == @path }.returns(@data)
@server.find(@request)
end
it "should pass the :links setting on to the created Content instance if the file exists and there is a value for :links" do
@model.expects(:new).returns(@data)
@data.expects(:links=).with(:manage)
@request.stubs(:options).returns(:links => :manage)
@server.find(@request)
end
end
describe Puppet::Indirector::DirectFileServer, "when searching for multiple files" do
it "should return nil if the file does not exist" do
Puppet::FileSystem.expects(:exist?).with(@path).returns false
- @server.find(@request).should be_nil
+ expect(@server.find(@request)).to be_nil
end
it "should use :path2instances from the terminus_helper to return instances if the file exists" do
Puppet::FileSystem.expects(:exist?).with(@path).returns true
@server.expects(:path2instances)
@server.search(@request)
end
it "should pass the original request to :path2instances" do
Puppet::FileSystem.expects(:exist?).with(@path).returns true
@server.expects(:path2instances).with(@request, @path)
@server.search(@request)
end
end
end
diff --git a/spec/unit/indirector/envelope_spec.rb b/spec/unit/indirector/envelope_spec.rb
index 61a951bce..29c6253dd 100755
--- a/spec/unit/indirector/envelope_spec.rb
+++ b/spec/unit/indirector/envelope_spec.rb
@@ -1,33 +1,33 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/envelope'
describe Puppet::Indirector::Envelope do
before do
@instance = Object.new
@instance.extend(Puppet::Indirector::Envelope)
end
describe "when testing if it is expired" do
it "should return false if there is no expiration set" do
- @instance.should_not be_expired
+ expect(@instance).not_to be_expired
end
it "should return true if the current date is after the expiration date" do
@instance.expiration = Time.now - 10
- @instance.should be_expired
+ expect(@instance).to be_expired
end
it "should return false if the current date is prior to the expiration date" do
@instance.expiration = Time.now + 10
- @instance.should_not be_expired
+ expect(@instance).not_to be_expired
end
it "should return false if the current date is equal to the expiration date" do
now = Time.now
Time.stubs(:now).returns(now)
@instance.expiration = now
- @instance.should_not be_expired
+ expect(@instance).not_to be_expired
end
end
end
diff --git a/spec/unit/indirector/exec_spec.rb b/spec/unit/indirector/exec_spec.rb
index c5203eda9..88cb4109d 100755
--- a/spec/unit/indirector/exec_spec.rb
+++ b/spec/unit/indirector/exec_spec.rb
@@ -1,58 +1,58 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/exec'
describe Puppet::Indirector::Exec do
before :all do
@indirection = stub 'indirection', :name => :testing
Puppet::Indirector::Indirection.expects(:instance).with(:testing).returns(@indirection)
module Testing; end
@exec_class = class Testing::MyTesting < Puppet::Indirector::Exec
attr_accessor :command
self
end
end
let(:path) { File.expand_path('/echo') }
let(:arguments) { {:failonfail => true, :combine => false } }
before :each do
@searcher = @exec_class.new
@searcher.command = [path]
@request = stub 'request', :key => "foo"
end
it "should throw an exception if the command is not an array" do
@searcher.command = path
- proc { @searcher.find(@request) }.should raise_error(Puppet::DevError)
+ expect { @searcher.find(@request) }.to raise_error(Puppet::DevError)
end
it "should throw an exception if the command is not fully qualified" do
@searcher.command = ["mycommand"]
- proc { @searcher.find(@request) }.should raise_error(ArgumentError)
+ expect { @searcher.find(@request) }.to raise_error(ArgumentError)
end
it "should execute the command with the object name as the only argument" do
@searcher.expects(:execute).with([path, 'foo'], arguments)
@searcher.find(@request)
end
it "should return the output of the script" do
@searcher.expects(:execute).with([path, 'foo'], arguments).returns("whatever")
- @searcher.find(@request).should == "whatever"
+ expect(@searcher.find(@request)).to eq("whatever")
end
it "should return nil when the command produces no output" do
@searcher.expects(:execute).with([path, 'foo'], arguments).returns(nil)
- @searcher.find(@request).should be_nil
+ expect(@searcher.find(@request)).to be_nil
end
it "should raise an exception if there's an execution failure" do
@searcher.expects(:execute).with([path, 'foo'], arguments).raises(Puppet::ExecutionFailure.new("message"))
expect {
@searcher.find(@request)
}.to raise_exception(Puppet::Error, 'Failed to find foo via exec: message')
end
end
diff --git a/spec/unit/indirector/face_spec.rb b/spec/unit/indirector/face_spec.rb
index 575a5cc99..688a50b39 100755
--- a/spec/unit/indirector/face_spec.rb
+++ b/spec/unit/indirector/face_spec.rb
@@ -1,75 +1,75 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/face'
describe Puppet::Indirector::Face do
subject do
instance = Puppet::Indirector::Face.new(:test, '0.0.1')
indirection = stub('indirection',
:name => :stub_indirection,
:reset_terminus_class => nil)
instance.stubs(:indirection).returns indirection
instance
end
- it { should be_option :extra }
+ it { is_expected.to be_option :extra }
it "should be able to return a list of indirections" do
- Puppet::Indirector::Face.indirections.should be_include("catalog")
+ expect(Puppet::Indirector::Face.indirections).to be_include("catalog")
end
it "should return the sorted to_s list of terminus classes" do
Puppet::Indirector::Terminus.expects(:terminus_classes).returns([
:yaml,
:compiler,
:rest
])
- Puppet::Indirector::Face.terminus_classes(:catalog).should == [
+ expect(Puppet::Indirector::Face.terminus_classes(:catalog)).to eq([
'compiler',
'rest',
'yaml'
- ]
+ ])
end
describe "as an instance" do
it "should be able to determine its indirection" do
# Loading actions here can get, um, complicated
Puppet::Face.stubs(:load_actions)
- Puppet::Indirector::Face.new(:catalog, '0.0.1').indirection.should equal(Puppet::Resource::Catalog.indirection)
+ expect(Puppet::Indirector::Face.new(:catalog, '0.0.1').indirection).to equal(Puppet::Resource::Catalog.indirection)
end
end
[:find, :search, :save, :destroy].each do |method|
it "should define a '#{method}' action" do
- Puppet::Indirector::Face.should be_action(method)
+ expect(Puppet::Indirector::Face).to be_action(method)
end
it "should call the indirection method with options when the '#{method}' action is invoked" do
subject.indirection.expects(method).with(:test, {})
subject.send(method, :test)
end
it "should forward passed options" do
subject.indirection.expects(method).with(:test, {'one'=>'1'})
subject.send(method, :test, :extra => {'one'=>'1'})
end
end
it "should default key to certname for find action" do
subject.indirection.expects(:find).with(Puppet[:certname], {'one'=>'1'})
subject.send(:find, :extra => {'one'=>'1'})
end
it "should be able to override its indirection name" do
subject.set_indirection_name :foo
- subject.indirection_name.should == :foo
+ expect(subject.indirection_name).to eq(:foo)
end
it "should be able to set its terminus class" do
subject.indirection.expects(:terminus_class=).with(:myterm)
subject.set_terminus(:myterm)
end
it "should define a class-level 'info' action" do
- Puppet::Indirector::Face.should be_action(:info)
+ expect(Puppet::Indirector::Face).to be_action(:info)
end
end
diff --git a/spec/unit/indirector/facts/facter_spec.rb b/spec/unit/indirector/facts/facter_spec.rb
index b71dafff4..22a4820e2 100755
--- a/spec/unit/indirector/facts/facter_spec.rb
+++ b/spec/unit/indirector/facts/facter_spec.rb
@@ -1,160 +1,160 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/facts/facter'
module NodeFactsFacterSpec
describe Puppet::Node::Facts::Facter do
FS = Puppet::FileSystem
it "should be a subclass of the Code terminus" do
- Puppet::Node::Facts::Facter.superclass.should equal(Puppet::Indirector::Code)
+ expect(Puppet::Node::Facts::Facter.superclass).to equal(Puppet::Indirector::Code)
end
it "should have documentation" do
- Puppet::Node::Facts::Facter.doc.should_not be_nil
+ 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)
- Puppet::Node::Facts::Facter.indirection.should equal(indirection)
+ expect(Puppet::Node::Facts::Facter.indirection).to equal(indirection)
end
it "should have its name set to :facter" do
- Puppet::Node::Facts::Facter.name.should == :facter
+ expect(Puppet::Node::Facts::Facter.name).to eq(:facter)
end
before :each do
Puppet::Node::Facts::Facter.stubs(:reload_facter)
@facter = Puppet::Node::Facts::Facter.new
Facter.stubs(:to_hash).returns({})
@name = "me"
@request = stub 'request', :key => @name
@environment = stub 'environment'
@request.stubs(:environment).returns(@environment)
@request.environment.stubs(:modules).returns([])
@request.environment.stubs(:modulepath).returns([])
end
describe 'when finding facts' do
it 'should reset facts' do
reset = sequence 'reset'
Facter.expects(:reset).in_sequence(reset)
Puppet::Node::Facts::Facter.expects(:setup_search_paths).in_sequence(reset)
@facter.find(@request)
end
it 'should include external facts when feature is present' do
reset = sequence 'reset'
Puppet.features.stubs(:external_facts?).returns true
Facter.expects(:reset).in_sequence(reset)
Puppet::Node::Facts::Facter.expects(:setup_external_search_paths).in_sequence(reset)
Puppet::Node::Facts::Facter.expects(:setup_search_paths).in_sequence(reset)
@facter.find(@request)
end
it 'should not include external facts when feature is not present' do
reset = sequence 'reset'
Puppet.features.stubs(:external_facts?).returns false
Facter.expects(:reset).in_sequence(reset)
Puppet::Node::Facts::Facter.expects(:setup_search_paths).in_sequence(reset)
@facter.find(@request)
end
it "should return a Facts instance" do
- @facter.find(@request).should be_instance_of(Puppet::Node::Facts)
+ 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
- @facter.find(@request).name.should == @name
+ expect(@facter.find(@request).name).to eq(@name)
end
it "should return the Facter facts as the values in the Facts instance" do
Facter.expects(:to_hash).returns("one" => "two")
facts = @facter.find(@request)
- facts.values["one"].should == "two"
+ expect(facts.values["one"]).to eq("two")
end
it "should add local facts" do
facts = Puppet::Node::Facts.new("foo")
Puppet::Node::Facts.expects(:new).returns facts
facts.expects(:add_local_facts)
@facter.find(@request)
end
it "should sanitize facts" do
facts = Puppet::Node::Facts.new("foo")
Puppet::Node::Facts.expects(:new).returns facts
facts.expects(:sanitize)
@facter.find(@request)
end
end
it 'should fail when saving facts' do
- proc { @facter.save(@facts) }.should raise_error(Puppet::DevError)
+ expect { @facter.save(@facts) }.to raise_error(Puppet::DevError)
end
it 'should fail when destroying facts' do
- proc { @facter.destroy(@facts) }.should raise_error(Puppet::DevError)
+ 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
FileTest.expects(:directory?).with(factpath1).returns true
FileTest.expects(:directory?).with(factpath2).returns true
@request.environment.stubs(:modulepath).returns [modulepath]
Dir.expects(:glob).with("#{modulepath}/*/lib/facter").returns [modulelibfacter]
Dir.expects(:glob).with("#{modulepath}/*/plugins/facter").returns [modulepluginsfacter]
Puppet[:factpath] = factpath
end
it 'should skip files' do
FileTest.expects(:directory?).with(modulelibfacter).returns false
FileTest.expects(:directory?).with(modulepluginsfacter).returns false
Facter.expects(:search).with(factpath1, factpath2)
Puppet::Node::Facts::Facter.setup_search_paths @request
end
it 'should add directories' do
FileTest.expects(:directory?).with(modulelibfacter).returns true
FileTest.expects(:directory?).with(modulepluginsfacter).returns true
Facter.expects(:search).with(modulelibfacter, modulepluginsfacter, factpath1, factpath2)
Puppet::Node::Facts::Facter.setup_search_paths @request
end
end
describe 'when setting up external search paths', :if => Puppet.features.external_facts? 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
FileTest.expects(:directory?).with(pluginfactdest).returns true
mod = Puppet::Module.new('foo', modulepath, @request.environment)
@request.environment.stubs(:modules).returns [mod]
Puppet[:pluginfactdest] = pluginfactdest
end
it 'should skip files' do
File.expects(:directory?).with(modulefactsd).returns false
Facter.expects(:search_external).with [pluginfactdest]
Puppet::Node::Facts::Facter.setup_external_search_paths @request
end
it 'should add directories' do
File.expects(:directory?).with(modulefactsd).returns true
Facter.expects(:search_external).with [modulefactsd, pluginfactdest]
Puppet::Node::Facts::Facter.setup_external_search_paths @request
end
end
end
end
diff --git a/spec/unit/indirector/facts/network_device_spec.rb b/spec/unit/indirector/facts/network_device_spec.rb
index 151ecc762..a32da5cf7 100755
--- a/spec/unit/indirector/facts/network_device_spec.rb
+++ b/spec/unit/indirector/facts/network_device_spec.rb
@@ -1,78 +1,78 @@
#! /usr/bin/env ruby
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
- Puppet::Node::Facts::NetworkDevice.superclass.should equal(Puppet::Indirector::Code)
+ expect(Puppet::Node::Facts::NetworkDevice.superclass).to equal(Puppet::Indirector::Code)
end
it "should have documentation" do
- Puppet::Node::Facts::NetworkDevice.doc.should_not be_nil
+ 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)
- Puppet::Node::Facts::NetworkDevice.indirection.should equal(indirection)
+ expect(Puppet::Node::Facts::NetworkDevice.indirection).to equal(indirection)
end
it "should have its name set to :facter" do
- Puppet::Node::Facts::NetworkDevice.name.should == :network_device
+ expect(Puppet::Node::Facts::NetworkDevice.name).to eq(:network_device)
end
end
describe Puppet::Node::Facts::NetworkDevice do
before :each do
@remote_device = stub 'remote_device', :facts => {}
Puppet::Util::NetworkDevice.stubs(:current).returns(@remote_device)
@device = Puppet::Node::Facts::NetworkDevice.new
@name = "me"
@request = stub 'request', :key => @name
end
describe Puppet::Node::Facts::NetworkDevice, " when finding facts" do
it "should return a Facts instance" do
- @device.find(@request).should be_instance_of(Puppet::Node::Facts)
+ 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
- @device.find(@request).name.should == @name
+ expect(@device.find(@request).name).to eq(@name)
end
it "should return the device facts as the values in the Facts instance" do
@remote_device.expects(:facts).returns("one" => "two")
facts = @device.find(@request)
- facts.values["one"].should == "two"
+ expect(facts.values["one"]).to eq("two")
end
it "should add local facts" do
facts = Puppet::Node::Facts.new("foo")
Puppet::Node::Facts.expects(:new).returns facts
facts.expects(:add_local_facts)
@device.find(@request)
end
it "should sanitize facts" do
facts = Puppet::Node::Facts.new("foo")
Puppet::Node::Facts.expects(:new).returns facts
facts.expects(:sanitize)
@device.find(@request)
end
end
describe Puppet::Node::Facts::NetworkDevice, " when saving facts" do
it "should fail" do
- proc { @device.save(@facts) }.should raise_error(Puppet::DevError)
+ expect { @device.save(@facts) }.to raise_error(Puppet::DevError)
end
end
describe Puppet::Node::Facts::NetworkDevice, " when destroying facts" do
it "should fail" do
- proc { @device.destroy(@facts) }.should raise_error(Puppet::DevError)
+ expect { @device.destroy(@facts) }.to raise_error(Puppet::DevError)
end
end
end
diff --git a/spec/unit/indirector/facts/yaml_spec.rb b/spec/unit/indirector/facts/yaml_spec.rb
index 45cee893d..e3ca713e6 100755
--- a/spec/unit/indirector/facts/yaml_spec.rb
+++ b/spec/unit/indirector/facts/yaml_spec.rb
@@ -1,239 +1,239 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/node/facts'
require 'puppet/indirector/facts/yaml'
describe Puppet::Node::Facts::Yaml do
it "should be a subclass of the Yaml terminus" do
- Puppet::Node::Facts::Yaml.superclass.should equal(Puppet::Indirector::Yaml)
+ expect(Puppet::Node::Facts::Yaml.superclass).to equal(Puppet::Indirector::Yaml)
end
it "should have documentation" do
- Puppet::Node::Facts::Yaml.doc.should_not be_nil
- Puppet::Node::Facts::Yaml.doc.should_not be_empty
+ 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)
- Puppet::Node::Facts::Yaml.indirection.should equal(indirection)
+ expect(Puppet::Node::Facts::Yaml.indirection).to equal(indirection)
end
it "should have its name set to :yaml" do
- Puppet::Node::Facts::Yaml.name.should == :yaml
+ expect(Puppet::Node::Facts::Yaml.name).to eq(:yaml)
end
describe "#search" do
def assert_search_matches(matching, nonmatching, query)
request = Puppet::Indirector::Request.new(:inventory, :search, nil, nil, query)
Dir.stubs(:glob).returns(matching.keys + nonmatching.keys)
[matching, nonmatching].each do |examples|
examples.each do |key, value|
YAML.stubs(:load_file).with(key).returns value
end
end
- Puppet::Node::Facts::Yaml.new.search(request).should =~ matching.values.map {|facts| facts.name}
+ expect(Puppet::Node::Facts::Yaml.new.search(request)).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({
'/path/to/matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '4'),
'/path/to/matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "i386", 'processor_count' => '4', 'randomfact' => 'foo')
},
{
"/path/to/nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '4'),
"/path/to/nonmatching1.yaml" => Puppet::Node::Facts.new("nonmatchingnode1", "architecture" => "powerpc", 'processor_count' => '5'),
"/path/to/nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5'),
"/path/to/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({}, {
"/path/to/nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '10'),
"/path/to/nonmatching1.yaml" => Puppet::Node::Facts.new("nonmatchingnode1", "architecture" => "powerpc", 'processor_count' => '5'),
"/path/to/nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5'),
"/path/to/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({
'/path/to/matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'),
'/path/to/matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '10', 'randomfact' => 'foo')
},
{
"/path/to/nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '4'),
"/path/to/nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '3'),
"/path/to/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({
'/path/to/matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'),
'/path/to/matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '30', 'randomfact' => 'foo')
},
{
"/path/to/nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '50' ),
"/path/to/nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '100'),
"/path/to/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({
'/path/to/matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'),
'/path/to/matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '50', 'randomfact' => 'foo')
},
{
"/path/to/nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '100' ),
"/path/to/nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5000'),
"/path/to/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({
'/path/to/matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '100'),
'/path/to/matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '50', 'randomfact' => 'foo')
},
{
"/path/to/nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '40'),
"/path/to/nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '9' ),
"/path/to/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({
'/path/to/matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => 'arm' ),
'/path/to/matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => 'powerpc', 'randomfact' => 'foo')
},
{
"/path/to/nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "i386" ),
"/path/to/nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '9' ),
"/path/to/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({
'/path/to/2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")),
'/path/to/2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")),
},
{
'/path/to/2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")),
'/path/to/2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")),
'/path/to/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({
'/path/to/2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")),
'/path/to/2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")),
'/path/to/2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")),
},
{
'/path/to/2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")),
'/path/to/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({
'/path/to/2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")),
'/path/to/2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")),
},
{
'/path/to/2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")),
'/path/to/2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")),
'/path/to/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({
'/path/to/2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")),
'/path/to/2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")),
'/path/to/2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")),
},
{
'/path/to/2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")),
'/path/to/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({
'/path/to/2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")),
},
{
'/path/to/2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")),
'/path/to/2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")),
'/path/to/2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")),
'/path/to/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({
'/path/to/2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")),
},
{
'/path/to/2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")),
'/path/to/2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")),
'/path/to/2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")),
'/path/to/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({
'/path/to/2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")),
'/path/to/2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")),
'/path/to/2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")),
'/path/to/2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")),
},
{
'/path/to/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
diff --git a/spec/unit/indirector/file_bucket_file/file_spec.rb b/spec/unit/indirector/file_bucket_file/file_spec.rb
index 56dacb7d7..6520a8e8e 100755
--- a/spec/unit/indirector/file_bucket_file/file_spec.rb
+++ b/spec/unit/indirector/file_bucket_file/file_spec.rb
@@ -1,286 +1,286 @@
#! /usr/bin/env ruby
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, "md5/c13d88cb4cb02003daedb8a84e5d272a")
- result.contents.should be_empty
+ expect(result.contents).to be_empty
end
it "deals with multiple processes saving at the same time", :unless => Puppet::Util::Platform.windows? 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]}/9/8/b/f/7/d/8/c/98bf7d8c15784f0a3d63204441e1e2aa/paths").lines.to_a
- paths.length.should == 1
- Puppet::FileBucket::File.indirection.head("#{bucket_file.checksum_type}/#{bucket_file.checksum_data}/testing").should be_true
+ 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
# This is the shortest known MD5 collision. See http://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("I" * 16)
collision_contents = [0x6165300e,0x87a79a55,0xf7c60bd0,0x34febd0b,
0x6503cf04,0x854f749e,0xfb0fc034,0x874c9c65,
0x2f94cc40,0x15a12deb,0xdc15f4a3,0x490786bb,
0x6d658673,0xa4341f7d,0x8fd75920,0xefd18d5a].pack("I" * 16)
save_bucket_file(first_contents, "/foo/bar")
expect do
save_bucket_file(collision_contents, "/foo/bar")
end.to raise_error(Puppet::FileBucket::BucketError, /Got passed new contents/)
end
describe "when supplying a path" do
with_digest_algorithms do
it "should store the path if not already stored" do
checksum = save_bucket_file(plaintext, "/foo/bar")
dir_path = "#{Puppet[:bucketdir]}/#{bucket_dir}"
contents_file = "#{dir_path}/contents"
paths_file = "#{dir_path}/paths"
- Puppet::FileSystem.binread(contents_file).should == plaintext
- Puppet::FileSystem.read(paths_file).should == "foo/bar\n"
+ expect(Puppet::FileSystem.binread(contents_file)).to eq(plaintext)
+ expect(Puppet::FileSystem.read(paths_file)).to eq("foo/bar\n")
end
it "should leave the paths file alone if the path is already stored" do
checksum = save_bucket_file(plaintext, "/foo/bar")
checksum = save_bucket_file(plaintext, "/foo/bar")
dir_path = "#{Puppet[:bucketdir]}/#{bucket_dir}"
- Puppet::FileSystem.binread("#{dir_path}/contents").should == plaintext
- File.read("#{dir_path}/paths").should == "foo/bar\n"
+ expect(Puppet::FileSystem.binread("#{dir_path}/contents")).to eq(plaintext)
+ expect(File.read("#{dir_path}/paths")).to eq("foo/bar\n")
end
it "should store an additional path if the new path differs from those already stored" do
checksum = save_bucket_file(plaintext, "/foo/bar")
checksum = save_bucket_file(plaintext, "/foo/baz")
dir_path = "#{Puppet[:bucketdir]}/#{bucket_dir}"
- Puppet::FileSystem.binread("#{dir_path}/contents").should == plaintext
- File.read("#{dir_path}/paths").should == "foo/bar\nfoo/baz\n"
+ 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
describe "when not supplying a path" do
with_digest_algorithms do
it "should save the file and create an empty paths file" do
checksum = save_bucket_file(plaintext, "")
dir_path = "#{Puppet[:bucketdir]}/#{bucket_dir}"
- Puppet::FileSystem.binread("#{dir_path}/contents").should == plaintext
- File.read("#{dir_path}/paths").should == ""
+ expect(Puppet::FileSystem.binread("#{dir_path}/contents")).to eq(plaintext)
+ expect(File.read("#{dir_path}/paths")).to eq("")
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 supplying a path" do
it "should return false/nil if the file isn't bucketed" do
- Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{not_bucketed_checksum}/foo/bar").should == false
- Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{not_bucketed_checksum}/foo/bar").should == nil
+ 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
checksum = save_bucket_file("I'm the contents of a file", '/foo/bar')
- Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{checksum}/foo/baz").should == false
- Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum}/foo/baz").should == nil
+ 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
it "should return true/file if the file is already bucketed with the given path" do
contents = "I'm the contents of a file"
checksum = save_bucket_file(contents, '/foo/bar')
- Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{checksum}/foo/bar").should == true
+ 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")
- find_result.checksum.should == "{#{digest_algorithm}}#{checksum}"
- find_result.to_s.should == contents
+ expect(find_result.checksum).to eq("{#{digest_algorithm}}#{checksum}")
+ expect(find_result.to_s).to eq(contents)
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
- Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{not_bucketed_checksum}#{trailing_string}").should == false
- Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{not_bucketed_checksum}#{trailing_string}").should == nil
+ 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
contents = "I'm the contents of a file"
checksum = save_bucket_file(contents, '/foo/bar')
- Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{checksum}#{trailing_string}").should == true
+ 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}")
- find_result.checksum.should == "{#{digest_algorithm}}#{checksum}"
- find_result.to_s.should == contents
+ expect(find_result.checksum).to eq("{#{digest_algorithm}}#{checksum}")
+ expect(find_result.to_s).to eq(contents)
end
end
end
end
end
end
describe "when diffing files", :unless => Puppet.features.microsoft_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
checksum = save_bucket_file("I'm the contents of a file")
- Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum}", :diff_with => checksum).should == ''
+ expect(Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum}", :diff_with => checksum)).to eq('')
end
it "should generate a proper diff if there is a diff" do
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)
- diff.should == "2c2\n< bar\n---\n> biz\n"
+ expect(diff).to eq("2c2\n< bar\n---\n> biz\n")
end
it "should raise an exception if the hash to diff against isn't found" do
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
it "should return nil if the hash to diff from isn't found" do
checksum = save_bucket_file("whatever")
- Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{not_bucketed_checksum}", :diff_with => checksum).should == nil
+ expect(Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{not_bucketed_checksum}", :diff_with => checksum)).to eq(nil)
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
Puppet.settings.stubs(: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
- @store.find(@request).should == nil
- @store.head(@request).should == false # because path didn't match
+ expect(@store.find(@request)).to eq(nil)
+ expect(@store.head(@request)).to eq(false) # because path didn't match
else
bucketfile = @store.find(@request)
- bucketfile.should be_a(Puppet::FileBucket::File)
- bucketfile.contents.should == plaintext
- @store.head(@request).should == true
+ 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
- @store.find(@request).should be_nil
- @store.head(@request).should == false
+ 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
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)
- Puppet::FileSystem.binread("#{@dir}/contents").should == plaintext
+ expect(Puppet::FileSystem.binread("#{@dir}/contents")).to eq(plaintext)
end
end
end
end
end
end
end
end
diff --git a/spec/unit/indirector/file_bucket_file/rest_spec.rb b/spec/unit/indirector/file_bucket_file/rest_spec.rb
index baba30a3d..67887873d 100755
--- a/spec/unit/indirector/file_bucket_file/rest_spec.rb
+++ b/spec/unit/indirector/file_bucket_file/rest_spec.rb
@@ -1,10 +1,10 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/file_bucket_file/rest'
describe Puppet::FileBucketFile::Rest do
it "should be a sublcass of Puppet::Indirector::REST" do
- Puppet::FileBucketFile::Rest.superclass.should equal(Puppet::Indirector::REST)
+ expect(Puppet::FileBucketFile::Rest.superclass).to equal(Puppet::Indirector::REST)
end
end
diff --git a/spec/unit/indirector/file_content/file_server_spec.rb b/spec/unit/indirector/file_content/file_server_spec.rb
index b4a82fcdc..a94c0aee6 100755
--- a/spec/unit/indirector/file_content/file_server_spec.rb
+++ b/spec/unit/indirector/file_content/file_server_spec.rb
@@ -1,14 +1,14 @@
#! /usr/bin/env ruby
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
- Puppet::Indirector::Terminus.terminus_class(:file_content, :file_server).should equal(Puppet::Indirector::FileContent::FileServer)
+ 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
- Puppet::Indirector::FileContent::FileServer.superclass.should equal(Puppet::Indirector::FileServer)
+ expect(Puppet::Indirector::FileContent::FileServer.superclass).to equal(Puppet::Indirector::FileServer)
end
end
diff --git a/spec/unit/indirector/file_content/file_spec.rb b/spec/unit/indirector/file_content/file_spec.rb
index e5638af5d..86de28b63 100755
--- a/spec/unit/indirector/file_content/file_spec.rb
+++ b/spec/unit/indirector/file_content/file_spec.rb
@@ -1,14 +1,14 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/file_content/file'
describe Puppet::Indirector::FileContent::File do
it "should be registered with the file_content indirection" do
- Puppet::Indirector::Terminus.terminus_class(:file_content, :file).should equal(Puppet::Indirector::FileContent::File)
+ expect(Puppet::Indirector::Terminus.terminus_class(:file_content, :file)).to equal(Puppet::Indirector::FileContent::File)
end
it "should be a subclass of the DirectFileServer terminus" do
- Puppet::Indirector::FileContent::File.superclass.should equal(Puppet::Indirector::DirectFileServer)
+ expect(Puppet::Indirector::FileContent::File.superclass).to equal(Puppet::Indirector::DirectFileServer)
end
end
diff --git a/spec/unit/indirector/file_content/rest_spec.rb b/spec/unit/indirector/file_content/rest_spec.rb
index fcc441992..f5169c742 100755
--- a/spec/unit/indirector/file_content/rest_spec.rb
+++ b/spec/unit/indirector/file_content/rest_spec.rb
@@ -1,14 +1,14 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/file_content/rest'
describe Puppet::Indirector::FileContent::Rest do
it "should add the node's cert name to the arguments"
it "should set the content type to text/plain"
it "should use the :fileserver SRV service" do
- Puppet::Indirector::FileContent::Rest.srv_service.should == :fileserver
+ expect(Puppet::Indirector::FileContent::Rest.srv_service).to eq(:fileserver)
end
end
diff --git a/spec/unit/indirector/file_metadata/file_server_spec.rb b/spec/unit/indirector/file_metadata/file_server_spec.rb
index 07c12bb77..a57851709 100755
--- a/spec/unit/indirector/file_metadata/file_server_spec.rb
+++ b/spec/unit/indirector/file_metadata/file_server_spec.rb
@@ -1,14 +1,14 @@
#! /usr/bin/env ruby
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
- Puppet::Indirector::Terminus.terminus_class(:file_metadata, :file_server).should equal(Puppet::Indirector::FileMetadata::FileServer)
+ 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
- Puppet::Indirector::FileMetadata::FileServer.superclass.should equal(Puppet::Indirector::FileServer)
+ expect(Puppet::Indirector::FileMetadata::FileServer.superclass).to equal(Puppet::Indirector::FileServer)
end
end
diff --git a/spec/unit/indirector/file_metadata/file_spec.rb b/spec/unit/indirector/file_metadata/file_spec.rb
index fd6ef8ce5..85b4cf3ea 100755
--- a/spec/unit/indirector/file_metadata/file_spec.rb
+++ b/spec/unit/indirector/file_metadata/file_spec.rb
@@ -1,50 +1,50 @@
#! /usr/bin/env ruby
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
- Puppet::Indirector::Terminus.terminus_class(:file_metadata, :file).should equal(Puppet::Indirector::FileMetadata::File)
+ 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
- Puppet::Indirector::FileMetadata::File.superclass.should equal(Puppet::Indirector::DirectFileServer)
+ 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 = mock 'metadata'
@data.stubs(:collect)
Puppet::FileSystem.expects(:exist?).with(@path).returns true
@request = Puppet::Indirector::Request.new(:file_metadata, :find, @uri, nil)
end
it "should collect its attributes when a file is found" do
@data.expects(:collect)
Puppet::FileServing::Metadata.expects(:new).returns(@data)
- @metadata.find(@request).should == @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
Puppet::FileSystem.expects(:exist?).with(@path).returns true
@metadata.expects(:path2instances).returns( [mock("one", :collect => nil), mock("two", :collect => nil)] )
@metadata.search(@request)
end
end
end
diff --git a/spec/unit/indirector/file_metadata/rest_spec.rb b/spec/unit/indirector/file_metadata/rest_spec.rb
index ddc4d9d7e..a7e213df2 100755
--- a/spec/unit/indirector/file_metadata/rest_spec.rb
+++ b/spec/unit/indirector/file_metadata/rest_spec.rb
@@ -1,13 +1,13 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/file_metadata'
require 'puppet/indirector/file_metadata/rest'
describe "Puppet::Indirector::Metadata::Rest" do
it "should add the node's cert name to the arguments"
it "should use the :fileserver SRV service" do
- Puppet::Indirector::FileMetadata::Rest.srv_service.should == :fileserver
+ expect(Puppet::Indirector::FileMetadata::Rest.srv_service).to eq(:fileserver)
end
end
diff --git a/spec/unit/indirector/file_server_spec.rb b/spec/unit/indirector/file_server_spec.rb
index 9e354556d..8cbccdc37 100755
--- a/spec/unit/indirector/file_server_spec.rb
+++ b/spec/unit/indirector/file_server_spec.rb
@@ -1,263 +1,263 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/file_server'
require 'puppet/file_serving/configuration'
describe Puppet::Indirector::FileServer do
before :all do
Puppet::Indirector::Terminus.stubs(:register_terminus_class)
@model = mock 'model'
@indirection = stub 'indirection', :name => :mystuff, :register_terminus_type => nil, :model => @model
Puppet::Indirector::Indirection.stubs(:instance).returns(@indirection)
module Testing; end
@file_server_class = class Testing::MyFileServer < Puppet::Indirector::FileServer
self
end
end
before :each do
@file_server = @file_server_class.new
@uri = "puppet://host/my/local/file"
@configuration = mock 'configuration'
Puppet::FileServing::Configuration.stubs(:configuration).returns(@configuration)
@request = Puppet::Indirector::Request.new(:myind, :mymethod, @uri, :environment => "myenv")
end
describe "when finding files" do
before do
@mount = stub 'mount', :find => nil
@instance = stub('instance', :links= => nil, :collect => nil)
end
it "should use the configuration to find the mount and relative path" do
@configuration.expects(:split_path).with(@request)
@file_server.find(@request)
end
it "should return nil if it cannot find the mount" do
@configuration.expects(:split_path).with(@request).returns(nil, nil)
- @file_server.find(@request).should be_nil
+ expect(@file_server.find(@request)).to be_nil
end
it "should use the mount to find the full path" do
@configuration.expects(:split_path).with(@request).returns([@mount, "rel/path"])
@mount.expects(:find).with { |key, request| key == "rel/path" }
@file_server.find(@request)
end
it "should pass the request when finding a file" do
@configuration.expects(:split_path).with(@request).returns([@mount, "rel/path"])
@mount.expects(:find).with { |key, request| request == @request }
@file_server.find(@request)
end
it "should return nil if it cannot find a full path" do
@configuration.expects(:split_path).with(@request).returns([@mount, "rel/path"])
@mount.expects(:find).with { |key, request| key == "rel/path" }.returns nil
- @file_server.find(@request).should be_nil
+ expect(@file_server.find(@request)).to be_nil
end
it "should create an instance with the found path" do
@configuration.expects(:split_path).with(@request).returns([@mount, "rel/path"])
@mount.expects(:find).with { |key, request| key == "rel/path" }.returns "/my/file"
@model.expects(:new).with("/my/file").returns @instance
- @file_server.find(@request).should equal(@instance)
+ expect(@file_server.find(@request)).to equal(@instance)
end
it "should set 'links' on the instance if it is set in the request options" do
@request.options[:links] = true
@configuration.expects(:split_path).with(@request).returns([@mount, "rel/path"])
@mount.expects(:find).with { |key, request| key == "rel/path" }.returns "/my/file"
@model.expects(:new).with("/my/file").returns @instance
@instance.expects(:links=).with(true)
- @file_server.find(@request).should equal(@instance)
+ expect(@file_server.find(@request)).to equal(@instance)
end
it "should collect the instance" do
@request.options[:links] = true
@configuration.expects(:split_path).with(@request).returns([@mount, "rel/path"])
@mount.expects(:find).with { |key, request| key == "rel/path" }.returns "/my/file"
@model.expects(:new).with("/my/file").returns @instance
@instance.expects(:collect)
- @file_server.find(@request).should equal(@instance)
+ expect(@file_server.find(@request)).to equal(@instance)
end
end
describe "when searching for instances" do
before do
@mount = stub 'mount', :search => nil
@instance = stub('instance', :links= => nil, :collect => nil)
end
it "should use the configuration to search the mount and relative path" do
@configuration.expects(:split_path).with(@request)
@file_server.search(@request)
end
it "should return nil if it cannot search the mount" do
@configuration.expects(:split_path).with(@request).returns(nil, nil)
- @file_server.search(@request).should be_nil
+ expect(@file_server.search(@request)).to be_nil
end
it "should use the mount to search for the full paths" do
@configuration.expects(:split_path).with(@request).returns([@mount, "rel/path"])
@mount.expects(:search).with { |key, request| key == "rel/path" }
@file_server.search(@request)
end
it "should pass the request" do
@configuration.stubs(:split_path).returns([@mount, "rel/path"])
@mount.expects(:search).with { |key, request| request == @request }
@file_server.search(@request)
end
it "should return nil if searching does not find any full paths" do
@configuration.expects(:split_path).with(@request).returns([@mount, "rel/path"])
@mount.expects(:search).with { |key, request| key == "rel/path" }.returns nil
- @file_server.search(@request).should be_nil
+ expect(@file_server.search(@request)).to be_nil
end
it "should create a fileset with each returned path and merge them" do
@configuration.expects(:split_path).with(@request).returns([@mount, "rel/path"])
@mount.expects(:search).with { |key, request| key == "rel/path" }.returns %w{/one /two}
Puppet::FileSystem.stubs(:exist?).returns true
one = mock 'fileset_one'
Puppet::FileServing::Fileset.expects(:new).with("/one", @request).returns(one)
two = mock 'fileset_two'
Puppet::FileServing::Fileset.expects(:new).with("/two", @request).returns(two)
Puppet::FileServing::Fileset.expects(:merge).with(one, two).returns []
@file_server.search(@request)
end
it "should create an instance with each path resulting from the merger of the filesets" do
@configuration.expects(:split_path).with(@request).returns([@mount, "rel/path"])
@mount.expects(:search).with { |key, request| key == "rel/path" }.returns []
Puppet::FileSystem.stubs(:exist?).returns true
Puppet::FileServing::Fileset.expects(:merge).returns("one" => "/one", "two" => "/two")
one = stub 'one', :collect => nil
@model.expects(:new).with("/one", :relative_path => "one").returns one
two = stub 'two', :collect => nil
@model.expects(:new).with("/two", :relative_path => "two").returns two
# order can't be guaranteed
result = @file_server.search(@request)
- result.should be_include(one)
- result.should be_include(two)
- result.length.should == 2
+ expect(result).to be_include(one)
+ expect(result).to be_include(two)
+ expect(result.length).to eq(2)
end
it "should set 'links' on the instances if it is set in the request options" do
@configuration.expects(:split_path).with(@request).returns([@mount, "rel/path"])
@mount.expects(:search).with { |key, request| key == "rel/path" }.returns []
Puppet::FileSystem.stubs(:exist?).returns true
Puppet::FileServing::Fileset.expects(:merge).returns("one" => "/one")
one = stub 'one', :collect => nil
@model.expects(:new).with("/one", :relative_path => "one").returns one
one.expects(:links=).with true
@request.options[:links] = true
@file_server.search(@request)
end
it "should collect the instances" do
@configuration.expects(:split_path).with(@request).returns([@mount, "rel/path"])
@mount.expects(:search).with { |key, options| key == "rel/path" }.returns []
Puppet::FileSystem.stubs(:exist?).returns true
Puppet::FileServing::Fileset.expects(:merge).returns("one" => "/one")
one = mock 'one'
@model.expects(:new).with("/one", :relative_path => "one").returns one
one.expects(:collect)
@file_server.search(@request)
end
end
describe "when checking authorization" do
before do
@request.method = :find
@mount = stub 'mount'
@configuration.stubs(:split_path).with(@request).returns([@mount, "rel/path"])
@request.stubs(:node).returns("mynode")
@request.stubs(:ip).returns("myip")
@mount.stubs(:allowed?).with("mynode", "myip").returns "something"
end
it "should return false when destroying" do
@request.method = :destroy
- @file_server.should_not be_authorized(@request)
+ expect(@file_server).not_to be_authorized(@request)
end
it "should return false when saving" do
@request.method = :save
- @file_server.should_not be_authorized(@request)
+ expect(@file_server).not_to be_authorized(@request)
end
it "should use the configuration to find the mount and relative path" do
@configuration.expects(:split_path).with(@request)
@file_server.authorized?(@request)
end
it "should return false if it cannot find the mount" do
@configuration.expects(:split_path).with(@request).returns(nil, nil)
- @file_server.should_not be_authorized(@request)
+ expect(@file_server).not_to be_authorized(@request)
end
it "should return the results of asking the mount whether the node and IP are authorized" do
- @file_server.authorized?(@request).should == "something"
+ expect(@file_server.authorized?(@request)).to eq("something")
end
end
end
diff --git a/spec/unit/indirector/indirection_spec.rb b/spec/unit/indirector/indirection_spec.rb
index 43d709acf..10be91109 100755
--- a/spec/unit/indirector/indirection_spec.rb
+++ b/spec/unit/indirector/indirection_spec.rb
@@ -1,875 +1,875 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/indirection'
shared_examples_for "Indirection Delegator" do
it "should create a request object with the appropriate method name and all of the passed arguments" do
request = Puppet::Indirector::Request.new(:indirection, :find, "me", nil)
@indirection.expects(:request).with(@method, "mystuff", nil, :one => :two).returns request
@terminus.stubs(@method)
@indirection.send(@method, "mystuff", :one => :two)
end
it "should let the :select_terminus method choose the terminus using the created request if the :select_terminus method is available" do
# Define the method, so our respond_to? hook matches.
class << @indirection
def select_terminus(request)
end
end
request = Puppet::Indirector::Request.new(:indirection, :find, "me", nil)
@indirection.stubs(:request).returns request
@indirection.expects(:select_terminus).with(request).returns :test_terminus
@indirection.stubs(:check_authorization)
@terminus.expects(@method)
@indirection.send(@method, "me")
end
it "should fail if the :select_terminus hook does not return a terminus name" do
# Define the method, so our respond_to? hook matches.
class << @indirection
def select_terminus(request)
end
end
request = Puppet::Indirector::Request.new(:indirection, :find, "me", nil)
@indirection.stubs(:request).returns request
@indirection.expects(:select_terminus).with(request).returns nil
- lambda { @indirection.send(@method, "me") }.should raise_error(ArgumentError)
+ expect { @indirection.send(@method, "me") }.to raise_error(ArgumentError)
end
it "should choose the terminus returned by the :terminus_class method if no :select_terminus method is available" do
@indirection.expects(:terminus_class).returns :test_terminus
@terminus.expects(@method)
@indirection.send(@method, "me")
end
it "should let the appropriate terminus perform the lookup" do
@terminus.expects(@method).with { |r| r.is_a?(Puppet::Indirector::Request) }
@indirection.send(@method, "me")
end
end
shared_examples_for "Delegation Authorizer" do
before do
# So the :respond_to? turns out correctly.
class << @terminus
def authorized?
end
end
end
it "should not check authorization if a node name is not provided" do
@terminus.expects(:authorized?).never
@terminus.stubs(@method)
# The quotes are necessary here, else it looks like a block.
@request.stubs(:options).returns({})
@indirection.send(@method, "/my/key")
end
it "should pass the request to the terminus's authorization method" do
@terminus.expects(:authorized?).with { |r| r.is_a?(Puppet::Indirector::Request) }.returns(true)
@terminus.stubs(@method)
@indirection.send(@method, "/my/key", :node => "mynode")
end
it "should fail if authorization returns false" do
@terminus.expects(:authorized?).returns(false)
@terminus.stubs(@method)
- proc { @indirection.send(@method, "/my/key", :node => "mynode") }.should raise_error(ArgumentError)
+ expect { @indirection.send(@method, "/my/key", :node => "mynode") }.to raise_error(ArgumentError)
end
it "should continue if authorization returns true" do
@terminus.expects(:authorized?).returns(true)
@terminus.stubs(@method)
@indirection.send(@method, "/my/key", :node => "mynode")
end
end
shared_examples_for "Request validator" do
it "asks the terminus to validate the request" do
@terminus.expects(:validate).raises(Puppet::Indirector::ValidationError, "Invalid")
@terminus.expects(@method).never
expect {
@indirection.send(@method, "key")
}.to raise_error Puppet::Indirector::ValidationError
end
end
describe Puppet::Indirector::Indirection do
describe "when initializing" do
# (LAK) I've no idea how to test this, really.
it "should store a reference to itself before it consumes its options" do
- proc { @indirection = Puppet::Indirector::Indirection.new(Object.new, :testingness, :not_valid_option) }.should raise_error
- Puppet::Indirector::Indirection.instance(:testingness).should be_instance_of(Puppet::Indirector::Indirection)
+ expect { @indirection = Puppet::Indirector::Indirection.new(Object.new, :testingness, :not_valid_option) }.to raise_error
+ expect(Puppet::Indirector::Indirection.instance(:testingness)).to be_instance_of(Puppet::Indirector::Indirection)
Puppet::Indirector::Indirection.instance(:testingness).delete
end
it "should keep a reference to the indirecting model" do
model = mock 'model'
@indirection = Puppet::Indirector::Indirection.new(model, :myind)
- @indirection.model.should equal(model)
+ expect(@indirection.model).to equal(model)
end
it "should set the name" do
@indirection = Puppet::Indirector::Indirection.new(mock('model'), :myind)
- @indirection.name.should == :myind
+ expect(@indirection.name).to eq(:myind)
end
it "should require indirections to have unique names" do
@indirection = Puppet::Indirector::Indirection.new(mock('model'), :test)
- proc { Puppet::Indirector::Indirection.new(:test) }.should raise_error(ArgumentError)
+ expect { Puppet::Indirector::Indirection.new(:test) }.to raise_error(ArgumentError)
end
it "should extend itself with any specified module" do
mod = Module.new
@indirection = Puppet::Indirector::Indirection.new(mock('model'), :test, :extend => mod)
- @indirection.singleton_class.included_modules.should include(mod)
+ expect(@indirection.singleton_class.included_modules).to include(mod)
end
after do
@indirection.delete if defined?(@indirection)
end
end
describe "when an instance" do
before :each do
@terminus_class = mock 'terminus_class'
@terminus = mock 'terminus'
@terminus.stubs(:validate)
@terminus_class.stubs(:new).returns(@terminus)
@cache = stub 'cache', :name => "mycache"
@cache_class = mock 'cache_class'
Puppet::Indirector::Terminus.stubs(:terminus_class).with(:test, :cache_terminus).returns(@cache_class)
Puppet::Indirector::Terminus.stubs(:terminus_class).with(:test, :test_terminus).returns(@terminus_class)
@indirection = Puppet::Indirector::Indirection.new(mock('model'), :test)
@indirection.terminus_class = :test_terminus
@instance = stub 'instance', :expiration => nil, :expiration= => nil, :name => "whatever"
@name = :mything
#@request = stub 'instance', :key => "/my/key", :instance => @instance, :options => {}
@request = mock 'instance'
end
it "should allow setting the ttl" do
@indirection.ttl = 300
- @indirection.ttl.should == 300
+ expect(@indirection.ttl).to eq(300)
end
it "should default to the :runinterval setting, converted to an integer, for its ttl" do
Puppet[:runinterval] = 1800
- @indirection.ttl.should == 1800
+ expect(@indirection.ttl).to eq(1800)
end
it "should calculate the current expiration by adding the TTL to the current time" do
@indirection.stubs(:ttl).returns(100)
now = Time.now
Time.stubs(:now).returns now
- @indirection.expiration.should == (Time.now + 100)
+ expect(@indirection.expiration).to eq(Time.now + 100)
end
it "should have a method for creating an indirection request instance" do
- @indirection.should respond_to(:request)
+ expect(@indirection).to respond_to(:request)
end
describe "creates a request" do
it "should create it with its name as the request's indirection name" do
Puppet::Indirector::Request.expects(:new).with { |name, *other| @indirection.name == name }
@indirection.request(:funtest, "yayness")
end
it "should require a method and key" do
Puppet::Indirector::Request.expects(:new).with { |name, method, key, *other| method == :funtest and key == "yayness" }
@indirection.request(:funtest, "yayness")
end
it "should support optional arguments" do
Puppet::Indirector::Request.expects(:new).with { |name, method, key, other| other == {:one => :two} }
@indirection.request(:funtest, "yayness", :one => :two)
end
it "should not pass options if none are supplied" do
Puppet::Indirector::Request.expects(:new).with { |*args| args.length < 4 }
@indirection.request(:funtest, "yayness")
end
it "should return the request" do
request = mock 'request'
Puppet::Indirector::Request.expects(:new).returns request
- @indirection.request(:funtest, "yayness").should equal(request)
+ expect(@indirection.request(:funtest, "yayness")).to equal(request)
end
end
describe "and looking for a model instance" do
before { @method = :find }
it_should_behave_like "Indirection Delegator"
it_should_behave_like "Delegation Authorizer"
it_should_behave_like "Request validator"
it "should return the results of the delegation" do
@terminus.expects(:find).returns(@instance)
- @indirection.find("me").should equal(@instance)
+ expect(@indirection.find("me")).to equal(@instance)
end
it "should return false if the instance is false" do
@terminus.expects(:find).returns(false)
- @indirection.find("me").should equal(false)
+ expect(@indirection.find("me")).to equal(false)
end
it "should set the expiration date on any instances without one set" do
@terminus.stubs(:find).returns(@instance)
@indirection.expects(:expiration).returns :yay
@instance.expects(:expiration).returns(nil)
@instance.expects(:expiration=).with(:yay)
@indirection.find("/my/key")
end
it "should not override an already-set expiration date on returned instances" do
@terminus.stubs(:find).returns(@instance)
@indirection.expects(:expiration).never
@instance.expects(:expiration).returns(:yay)
@instance.expects(:expiration=).never
@indirection.find("/my/key")
end
it "should filter the result instance if the terminus supports it" do
@terminus.stubs(:find).returns(@instance)
@terminus.stubs(:respond_to?).with(:filter).returns(true)
@terminus.expects(:filter).with(@instance)
@indirection.find("/my/key")
end
describe "when caching is enabled" do
before do
@indirection.cache_class = :cache_terminus
@cache_class.stubs(:new).returns(@cache)
@instance.stubs(:expired?).returns false
end
it "should first look in the cache for an instance" do
@terminus.stubs(:find).never
@cache.expects(:find).returns @instance
@indirection.find("/my/key")
end
it "should not look in the cache if the request specifies not to use the cache" do
@terminus.expects(:find).returns @instance
@cache.expects(:find).never
@cache.stubs(:save)
@indirection.find("/my/key", :ignore_cache => true)
end
it "should still save to the cache even if the cache is being ignored during readin" do
@terminus.expects(:find).returns @instance
@cache.expects(:save)
@indirection.find("/my/key", :ignore_cache => true)
end
it "should only look in the cache if the request specifies not to use the terminus" do
@terminus.expects(:find).never
@cache.expects(:find)
@indirection.find("/my/key", :ignore_terminus => true)
end
it "should use a request to look in the cache for cached objects" do
@cache.expects(:find).with { |r| r.method == :find and r.key == "/my/key" }.returns @instance
@cache.stubs(:save)
@indirection.find("/my/key")
end
it "should return the cached object if it is not expired" do
@instance.stubs(:expired?).returns false
@cache.stubs(:find).returns @instance
- @indirection.find("/my/key").should equal(@instance)
+ expect(@indirection.find("/my/key")).to equal(@instance)
end
it "should not fail if the cache fails" do
@terminus.stubs(:find).returns @instance
@cache.expects(:find).raises ArgumentError
@cache.stubs(:save)
- lambda { @indirection.find("/my/key") }.should_not raise_error
+ expect { @indirection.find("/my/key") }.not_to raise_error
end
it "should look in the main terminus if the cache fails" do
@terminus.expects(:find).returns @instance
@cache.expects(:find).raises ArgumentError
@cache.stubs(:save)
- @indirection.find("/my/key").should equal(@instance)
+ expect(@indirection.find("/my/key")).to equal(@instance)
end
it "should send a debug log if it is using the cached object" do
Puppet.expects(:debug)
@cache.stubs(:find).returns @instance
@indirection.find("/my/key")
end
it "should not return the cached object if it is expired" do
@instance.stubs(:expired?).returns true
@cache.stubs(:find).returns @instance
@terminus.stubs(:find).returns nil
- @indirection.find("/my/key").should be_nil
+ expect(@indirection.find("/my/key")).to be_nil
end
it "should send an info log if it is using the cached object" do
Puppet.expects(:info)
@instance.stubs(:expired?).returns true
@cache.stubs(:find).returns @instance
@terminus.stubs(:find).returns nil
@indirection.find("/my/key")
end
it "should cache any objects not retrieved from the cache" do
@cache.expects(:find).returns nil
@terminus.expects(:find).returns(@instance)
@cache.expects(:save)
@indirection.find("/my/key")
end
it "should use a request to look in the cache for cached objects" do
@cache.expects(:find).with { |r| r.method == :find and r.key == "/my/key" }.returns nil
@terminus.stubs(:find).returns(@instance)
@cache.stubs(:save)
@indirection.find("/my/key")
end
it "should cache the instance using a request with the instance set to the cached object" do
@cache.stubs(:find).returns nil
@terminus.stubs(:find).returns(@instance)
@cache.expects(:save).with { |r| r.method == :save and r.instance == @instance }
@indirection.find("/my/key")
end
it "should send an info log that the object is being cached" do
@cache.stubs(:find).returns nil
@terminus.stubs(:find).returns(@instance)
@cache.stubs(:save)
Puppet.expects(:info)
@indirection.find("/my/key")
end
end
end
describe "and doing a head operation" do
before { @method = :head }
it_should_behave_like "Indirection Delegator"
it_should_behave_like "Delegation Authorizer"
it_should_behave_like "Request validator"
it "should return true if the head method returned true" do
@terminus.expects(:head).returns(true)
- @indirection.head("me").should == true
+ expect(@indirection.head("me")).to eq(true)
end
it "should return false if the head method returned false" do
@terminus.expects(:head).returns(false)
- @indirection.head("me").should == false
+ expect(@indirection.head("me")).to eq(false)
end
describe "when caching is enabled" do
before do
@indirection.cache_class = :cache_terminus
@cache_class.stubs(:new).returns(@cache)
@instance.stubs(:expired?).returns false
end
it "should first look in the cache for an instance" do
@terminus.stubs(:find).never
@terminus.stubs(:head).never
@cache.expects(:find).returns @instance
- @indirection.head("/my/key").should == true
+ expect(@indirection.head("/my/key")).to eq(true)
end
it "should not save to the cache" do
@cache.expects(:find).returns nil
@cache.expects(:save).never
@terminus.expects(:head).returns true
- @indirection.head("/my/key").should == true
+ expect(@indirection.head("/my/key")).to eq(true)
end
it "should not fail if the cache fails" do
@terminus.stubs(:head).returns true
@cache.expects(:find).raises ArgumentError
- lambda { @indirection.head("/my/key") }.should_not raise_error
+ expect { @indirection.head("/my/key") }.not_to raise_error
end
it "should look in the main terminus if the cache fails" do
@terminus.expects(:head).returns true
@cache.expects(:find).raises ArgumentError
- @indirection.head("/my/key").should == true
+ expect(@indirection.head("/my/key")).to eq(true)
end
it "should send a debug log if it is using the cached object" do
Puppet.expects(:debug)
@cache.stubs(:find).returns @instance
@indirection.head("/my/key")
end
it "should not accept the cached object if it is expired" do
@instance.stubs(:expired?).returns true
@cache.stubs(:find).returns @instance
@terminus.stubs(:head).returns false
- @indirection.head("/my/key").should == false
+ expect(@indirection.head("/my/key")).to eq(false)
end
end
end
describe "and storing a model instance" do
before { @method = :save }
it "should return the result of the save" do
@terminus.stubs(:save).returns "foo"
- @indirection.save(@instance).should == "foo"
+ expect(@indirection.save(@instance)).to eq("foo")
end
describe "when caching is enabled" do
before do
@indirection.cache_class = :cache_terminus
@cache_class.stubs(:new).returns(@cache)
@instance.stubs(:expired?).returns false
end
it "should return the result of saving to the terminus" do
request = stub 'request', :instance => @instance, :node => nil
@indirection.expects(:request).returns request
@cache.stubs(:save)
@terminus.stubs(:save).returns @instance
- @indirection.save(@instance).should equal(@instance)
+ expect(@indirection.save(@instance)).to equal(@instance)
end
it "should use a request to save the object to the cache" do
request = stub 'request', :instance => @instance, :node => nil
@indirection.expects(:request).returns request
@cache.expects(:save).with(request)
@terminus.stubs(:save)
@indirection.save(@instance)
end
it "should not save to the cache if the normal save fails" do
request = stub 'request', :instance => @instance, :node => nil
@indirection.expects(:request).returns request
@cache.expects(:save).never
@terminus.expects(:save).raises "eh"
- lambda { @indirection.save(@instance) }.should raise_error
+ expect { @indirection.save(@instance) }.to raise_error
end
end
end
describe "and removing a model instance" do
before { @method = :destroy }
it_should_behave_like "Indirection Delegator"
it_should_behave_like "Delegation Authorizer"
it_should_behave_like "Request validator"
it "should return the result of removing the instance" do
@terminus.stubs(:destroy).returns "yayness"
- @indirection.destroy("/my/key").should == "yayness"
+ expect(@indirection.destroy("/my/key")).to eq("yayness")
end
describe "when caching is enabled" do
before do
@indirection.cache_class = :cache_terminus
@cache_class.expects(:new).returns(@cache)
@instance.stubs(:expired?).returns false
end
it "should use a request instance to search in and remove objects from the cache" do
destroy = stub 'destroy_request', :key => "/my/key", :node => nil
find = stub 'destroy_request', :key => "/my/key", :node => nil
@indirection.expects(:request).with(:destroy, "/my/key", nil, optionally(instance_of(Hash))).returns destroy
@indirection.expects(:request).with(:find, "/my/key", nil, optionally(instance_of(Hash))).returns find
cached = mock 'cache'
@cache.expects(:find).with(find).returns cached
@cache.expects(:destroy).with(destroy)
@terminus.stubs(:destroy)
@indirection.destroy("/my/key")
end
end
end
describe "and searching for multiple model instances" do
before { @method = :search }
it_should_behave_like "Indirection Delegator"
it_should_behave_like "Delegation Authorizer"
it_should_behave_like "Request validator"
it "should set the expiration date on any instances without one set" do
@terminus.stubs(:search).returns([@instance])
@indirection.expects(:expiration).returns :yay
@instance.expects(:expiration).returns(nil)
@instance.expects(:expiration=).with(:yay)
@indirection.search("/my/key")
end
it "should not override an already-set expiration date on returned instances" do
@terminus.stubs(:search).returns([@instance])
@indirection.expects(:expiration).never
@instance.expects(:expiration).returns(:yay)
@instance.expects(:expiration=).never
@indirection.search("/my/key")
end
it "should return the results of searching in the terminus" do
@terminus.expects(:search).returns([@instance])
- @indirection.search("/my/key").should == [@instance]
+ expect(@indirection.search("/my/key")).to eq([@instance])
end
end
describe "and expiring a model instance" do
describe "when caching is not enabled" do
it "should do nothing" do
@cache_class.expects(:new).never
@indirection.expire("/my/key")
end
end
describe "when caching is enabled" do
before do
@indirection.cache_class = :cache_terminus
@cache_class.expects(:new).returns(@cache)
@instance.stubs(:expired?).returns false
@cached = stub 'cached', :expiration= => nil, :name => "/my/key"
end
it "should use a request to find within the cache" do
@cache.expects(:find).with { |r| r.is_a?(Puppet::Indirector::Request) and r.method == :find }
@indirection.expire("/my/key")
end
it "should do nothing if no such instance is cached" do
@cache.expects(:find).returns nil
@indirection.expire("/my/key")
end
it "should log when expiring a found instance" do
@cache.expects(:find).returns @cached
@cache.stubs(:save)
Puppet.expects(:info)
@indirection.expire("/my/key")
end
it "should set the cached instance's expiration to a time in the past" do
@cache.expects(:find).returns @cached
@cache.stubs(:save)
@cached.expects(:expiration=).with { |t| t < Time.now }
@indirection.expire("/my/key")
end
it "should save the now expired instance back into the cache" do
@cache.expects(:find).returns @cached
@cached.expects(:expiration=).with { |t| t < Time.now }
@cache.expects(:save)
@indirection.expire("/my/key")
end
it "should use a request to save the expired resource to the cache" do
@cache.expects(:find).returns @cached
@cached.expects(:expiration=).with { |t| t < Time.now }
@cache.expects(:save).with { |r| r.is_a?(Puppet::Indirector::Request) and r.instance == @cached and r.method == :save }.returns(@cached)
@indirection.expire("/my/key")
end
end
end
after :each do
@indirection.delete
end
end
describe "when managing indirection instances" do
it "should allow an indirection to be retrieved by name" do
@indirection = Puppet::Indirector::Indirection.new(mock('model'), :test)
- Puppet::Indirector::Indirection.instance(:test).should equal(@indirection)
+ expect(Puppet::Indirector::Indirection.instance(:test)).to equal(@indirection)
end
it "should return nil when the named indirection has not been created" do
- Puppet::Indirector::Indirection.instance(:test).should be_nil
+ expect(Puppet::Indirector::Indirection.instance(:test)).to be_nil
end
it "should allow an indirection's model to be retrieved by name" do
mock_model = mock('model')
@indirection = Puppet::Indirector::Indirection.new(mock_model, :test)
- Puppet::Indirector::Indirection.model(:test).should equal(mock_model)
+ expect(Puppet::Indirector::Indirection.model(:test)).to equal(mock_model)
end
it "should return nil when no model matches the requested name" do
- Puppet::Indirector::Indirection.model(:test).should be_nil
+ expect(Puppet::Indirector::Indirection.model(:test)).to be_nil
end
after do
@indirection.delete if defined?(@indirection)
end
end
describe "when routing to the correct the terminus class" do
before do
@indirection = Puppet::Indirector::Indirection.new(mock('model'), :test)
@terminus = mock 'terminus'
@terminus_class = stub 'terminus class', :new => @terminus
Puppet::Indirector::Terminus.stubs(:terminus_class).with(:test, :default).returns(@terminus_class)
end
it "should fail if no terminus class can be picked" do
- proc { @indirection.terminus_class }.should raise_error(Puppet::DevError)
+ expect { @indirection.terminus_class }.to raise_error(Puppet::DevError)
end
it "should choose the default terminus class if one is specified" do
@indirection.terminus_class = :default
- @indirection.terminus_class.should equal(:default)
+ expect(@indirection.terminus_class).to equal(:default)
end
it "should use the provided Puppet setting if told to do so" do
Puppet::Indirector::Terminus.stubs(:terminus_class).with(:test, :my_terminus).returns(mock("terminus_class2"))
Puppet[:node_terminus] = :my_terminus
@indirection.terminus_setting = :node_terminus
- @indirection.terminus_class.should equal(:my_terminus)
+ expect(@indirection.terminus_class).to equal(:my_terminus)
end
it "should fail if the provided terminus class is not valid" do
Puppet::Indirector::Terminus.stubs(:terminus_class).with(:test, :nosuchclass).returns(nil)
- proc { @indirection.terminus_class = :nosuchclass }.should raise_error(ArgumentError)
+ expect { @indirection.terminus_class = :nosuchclass }.to raise_error(ArgumentError)
end
after do
@indirection.delete if defined?(@indirection)
end
end
describe "when specifying the terminus class to use" do
before do
@indirection = Puppet::Indirector::Indirection.new(mock('model'), :test)
@terminus = mock 'terminus'
@terminus.stubs(:validate)
@terminus_class = stub 'terminus class', :new => @terminus
end
it "should allow specification of a terminus type" do
- @indirection.should respond_to(:terminus_class=)
+ expect(@indirection).to respond_to(:terminus_class=)
end
it "should fail to redirect if no terminus type has been specified" do
- proc { @indirection.find("blah") }.should raise_error(Puppet::DevError)
+ expect { @indirection.find("blah") }.to raise_error(Puppet::DevError)
end
it "should fail when the terminus class name is an empty string" do
- proc { @indirection.terminus_class = "" }.should raise_error(ArgumentError)
+ expect { @indirection.terminus_class = "" }.to raise_error(ArgumentError)
end
it "should fail when the terminus class name is nil" do
- proc { @indirection.terminus_class = nil }.should raise_error(ArgumentError)
+ expect { @indirection.terminus_class = nil }.to raise_error(ArgumentError)
end
it "should fail when the specified terminus class cannot be found" do
Puppet::Indirector::Terminus.expects(:terminus_class).with(:test, :foo).returns(nil)
- proc { @indirection.terminus_class = :foo }.should raise_error(ArgumentError)
+ expect { @indirection.terminus_class = :foo }.to raise_error(ArgumentError)
end
it "should select the specified terminus class if a terminus class name is provided" do
Puppet::Indirector::Terminus.expects(:terminus_class).with(:test, :foo).returns(@terminus_class)
- @indirection.terminus(:foo).should equal(@terminus)
+ expect(@indirection.terminus(:foo)).to equal(@terminus)
end
it "should use the configured terminus class if no terminus name is specified" do
Puppet::Indirector::Terminus.stubs(:terminus_class).with(:test, :foo).returns(@terminus_class)
@indirection.terminus_class = :foo
- @indirection.terminus.should equal(@terminus)
+ expect(@indirection.terminus).to equal(@terminus)
end
after do
@indirection.delete if defined?(@indirection)
end
end
describe "when managing terminus instances" do
before do
@indirection = Puppet::Indirector::Indirection.new(mock('model'), :test)
@terminus = mock 'terminus'
@terminus_class = mock 'terminus class'
Puppet::Indirector::Terminus.stubs(:terminus_class).with(:test, :foo).returns(@terminus_class)
end
it "should create an instance of the chosen terminus class" do
@terminus_class.stubs(:new).returns(@terminus)
- @indirection.terminus(:foo).should equal(@terminus)
+ expect(@indirection.terminus(:foo)).to equal(@terminus)
end
# Make sure it caches the terminus.
it "should return the same terminus instance each time for a given name" do
@terminus_class.stubs(:new).returns(@terminus)
- @indirection.terminus(:foo).should equal(@terminus)
- @indirection.terminus(:foo).should equal(@terminus)
+ expect(@indirection.terminus(:foo)).to equal(@terminus)
+ expect(@indirection.terminus(:foo)).to equal(@terminus)
end
it "should not create a terminus instance until one is actually needed" do
Puppet::Indirector.expects(:terminus).never
indirection = Puppet::Indirector::Indirection.new(mock('model'), :lazytest)
end
after do
@indirection.delete
end
end
describe "when deciding whether to cache" do
before do
@indirection = Puppet::Indirector::Indirection.new(mock('model'), :test)
@terminus = mock 'terminus'
@terminus_class = mock 'terminus class'
@terminus_class.stubs(:new).returns(@terminus)
Puppet::Indirector::Terminus.stubs(:terminus_class).with(:test, :foo).returns(@terminus_class)
@indirection.terminus_class = :foo
end
it "should provide a method for setting the cache terminus class" do
- @indirection.should respond_to(:cache_class=)
+ expect(@indirection).to respond_to(:cache_class=)
end
it "should fail to cache if no cache type has been specified" do
- proc { @indirection.cache }.should raise_error(Puppet::DevError)
+ expect { @indirection.cache }.to raise_error(Puppet::DevError)
end
it "should fail to set the cache class when the cache class name is an empty string" do
- proc { @indirection.cache_class = "" }.should raise_error(ArgumentError)
+ expect { @indirection.cache_class = "" }.to raise_error(ArgumentError)
end
it "should allow resetting the cache_class to nil" do
@indirection.cache_class = nil
- @indirection.cache_class.should be_nil
+ expect(@indirection.cache_class).to be_nil
end
it "should fail to set the cache class when the specified cache class cannot be found" do
Puppet::Indirector::Terminus.expects(:terminus_class).with(:test, :foo).returns(nil)
- proc { @indirection.cache_class = :foo }.should raise_error(ArgumentError)
+ expect { @indirection.cache_class = :foo }.to raise_error(ArgumentError)
end
after do
@indirection.delete
end
end
describe "when using a cache" do
before :each do
@terminus_class = mock 'terminus_class'
@terminus = mock 'terminus'
@terminus_class.stubs(:new).returns(@terminus)
@cache = mock 'cache'
@cache_class = mock 'cache_class'
Puppet::Indirector::Terminus.stubs(:terminus_class).with(:test, :cache_terminus).returns(@cache_class)
Puppet::Indirector::Terminus.stubs(:terminus_class).with(:test, :test_terminus).returns(@terminus_class)
@indirection = Puppet::Indirector::Indirection.new(mock('model'), :test)
@indirection.terminus_class = :test_terminus
end
describe "and managing the cache terminus" do
it "should not create a cache terminus at initialization" do
# This is weird, because all of the code is in the setup. If we got
# new called on the cache class, we'd get an exception here.
end
it "should reuse the cache terminus" do
@cache_class.expects(:new).returns(@cache)
@indirection.cache_class = :cache_terminus
- @indirection.cache.should equal(@cache)
- @indirection.cache.should equal(@cache)
+ expect(@indirection.cache).to equal(@cache)
+ expect(@indirection.cache).to equal(@cache)
end
end
describe "and saving" do
end
describe "and finding" do
end
after :each do
@indirection.delete
end
end
end
diff --git a/spec/unit/indirector/json_spec.rb b/spec/unit/indirector/json_spec.rb
index 656d156c0..3225c0375 100755
--- a/spec/unit/indirector/json_spec.rb
+++ b/spec/unit/indirector/json_spec.rb
@@ -1,192 +1,192 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/indirector/indirector_testing/json'
describe Puppet::Indirector::JSON do
include PuppetSpec::Files
subject { Puppet::IndirectorTesting::JSON.new }
let :model do Puppet::IndirectorTesting end
let :indirection do model.indirection end
context "#path" do
before :each do
Puppet[:server_datadir] = '/sample/datadir/master'
Puppet[:client_datadir] = '/sample/datadir/client'
end
it "uses the :server_datadir setting if this is the master" do
Puppet.run_mode.stubs(:master?).returns(true)
expected = File.join(Puppet[:server_datadir], 'indirector_testing', 'testing.json')
- subject.path('testing').should == expected
+ expect(subject.path('testing')).to eq(expected)
end
it "uses the :client_datadir setting if this is not the master" do
Puppet.run_mode.stubs(:master?).returns(false)
expected = File.join(Puppet[:client_datadir], 'indirector_testing', 'testing.json')
- subject.path('testing').should == expected
+ expect(subject.path('testing')).to eq(expected)
end
it "overrides the default extension with a supplied value" do
Puppet.run_mode.stubs(:master?).returns(true)
expected = File.join(Puppet[:server_datadir], 'indirector_testing', 'testing.not-json')
- subject.path('testing', '.not-json').should == expected
+ expect(subject.path('testing', '.not-json')).to eq(expected)
end
['../foo', '..\\foo', './../foo', '.\\..\\foo',
'/foo', '//foo', '\\foo', '\\\\goo',
"test\0/../bar", "test\0\\..\\bar",
"..\\/bar", "/tmp/bar", "/tmp\\bar", "tmp\\bar",
" / bar", " /../ bar", " \\..\\ bar",
"c:\\foo", "c:/foo", "\\\\?\\UNC\\bar", "\\\\foo\\bar",
"\\\\?\\c:\\foo", "//?/UNC/bar", "//foo/bar",
"//?/c:/foo",
].each do |input|
it "should resist directory traversal attacks (#{input.inspect})" do
expect { subject.path(input) }.to raise_error ArgumentError, 'invalid key'
end
end
end
context "handling requests" do
before :each do
Puppet.run_mode.stubs(:master?).returns(true)
Puppet[:server_datadir] = tmpdir('jsondir')
FileUtils.mkdir_p(File.join(Puppet[:server_datadir], 'indirector_testing'))
end
let :file do subject.path(request.key) end
def with_content(text)
FileUtils.mkdir_p(File.dirname(file))
File.open(file, 'w') {|f| f.puts text }
yield if block_given?
end
it "data saves and then loads again correctly" do
subject.save(indirection.request(:save, 'example', model.new('banana')))
- subject.find(indirection.request(:find, 'example', nil)).value.should == 'banana'
+ expect(subject.find(indirection.request(:find, 'example', nil)).value).to eq('banana')
end
context "#find" do
let :request do indirection.request(:find, 'example', nil) end
it "returns nil if the file doesn't exist" do
- subject.find(request).should be_nil
+ expect(subject.find(request)).to be_nil
end
it "raises a descriptive error when the file can't be read" do
with_content(model.new('foo').to_pson) do
# I don't like this, but there isn't a credible alternative that
# also works on Windows, so a stub it is. At least the expectation
# will fail if the implementation changes. Sorry to the next dev.
File.expects(:read).with(file).raises(Errno::EPERM)
expect { subject.find(request) }.
to raise_error Puppet::Error, /Could not read JSON/
end
end
it "raises a descriptive error when the file content is invalid" do
with_content("this is totally invalid JSON") do
expect { subject.find(request) }.
to raise_error Puppet::Error, /Could not parse JSON data/
end
end
it "should return an instance of the indirected object when valid" do
with_content(model.new(1).to_pson) do
instance = subject.find(request)
- instance.should be_an_instance_of model
- instance.value.should == 1
+ expect(instance).to be_an_instance_of model
+ expect(instance.value).to eq(1)
end
end
end
context "#save" do
let :instance do model.new(4) end
let :request do indirection.request(:find, 'example', instance) end
it "should save the instance of the request as JSON to disk" do
subject.save(request)
content = File.read(file)
- content.should =~ /"value"\s*:\s*4/
+ expect(content).to match(/"value"\s*:\s*4/)
end
it "should create the indirection directory if required" do
target = File.join(Puppet[:server_datadir], 'indirector_testing')
Dir.rmdir(target)
subject.save(request)
- File.should be_directory(target)
+ expect(File).to be_directory(target)
end
end
context "#destroy" do
let :request do indirection.request(:find, 'example', nil) end
it "removes an existing file" do
with_content('hello') do
subject.destroy(request)
end
- Puppet::FileSystem.exist?(file).should be_false
+ expect(Puppet::FileSystem.exist?(file)).to be_falsey
end
it "silently succeeds when files don't exist" do
Puppet::FileSystem.unlink(file) rescue nil
- subject.destroy(request).should be_true
+ expect(subject.destroy(request)).to be_truthy
end
it "raises an informative error for other failures" do
Puppet::FileSystem.stubs(:unlink).with(file).raises(Errno::EPERM, 'fake permission problem')
with_content('hello') do
expect { subject.destroy(request) }.to raise_error(Puppet::Error)
end
Puppet::FileSystem.unstub(:unlink) # thanks, mocha
end
end
end
context "#search" do
before :each do
Puppet.run_mode.stubs(:master?).returns(true)
Puppet[:server_datadir] = tmpdir('jsondir')
FileUtils.mkdir_p(File.join(Puppet[:server_datadir], 'indirector_testing'))
end
def request(glob)
indirection.request(:search, glob, nil)
end
def create_file(name, value = 12)
File.open(subject.path(name, ''), 'w') do |f|
f.puts Puppet::IndirectorTesting.new(value).to_pson
end
end
it "returns an empty array when nothing matches the key as a glob" do
- subject.search(request('*')).should == []
+ expect(subject.search(request('*'))).to eq([])
end
it "returns an array with one item if one item matches" do
create_file('foo.json', 'foo')
create_file('bar.json', 'bar')
- subject.search(request('f*')).map(&:value).should == ['foo']
+ expect(subject.search(request('f*')).map(&:value)).to eq(['foo'])
end
it "returns an array of items when more than one item matches" do
create_file('foo.json', 'foo')
create_file('bar.json', 'bar')
create_file('baz.json', 'baz')
- subject.search(request('b*')).map(&:value).should =~ ['bar', 'baz']
+ expect(subject.search(request('b*')).map(&:value)).to match_array(['bar', 'baz'])
end
it "only items with the .json extension" do
create_file('foo.json', 'foo-json')
create_file('foo.pson', 'foo-pson')
create_file('foo.json~', 'foo-backup')
- subject.search(request('f*')).map(&:value).should == ['foo-json']
+ expect(subject.search(request('f*')).map(&:value)).to eq(['foo-json'])
end
end
end
diff --git a/spec/unit/indirector/key/ca_spec.rb b/spec/unit/indirector/key/ca_spec.rb
index 949bf7c80..73fbc1821 100755
--- a/spec/unit/indirector/key/ca_spec.rb
+++ b/spec/unit/indirector/key/ca_spec.rb
@@ -1,23 +1,23 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/key/ca'
describe Puppet::SSL::Key::Ca do
it "should have documentation" do
- Puppet::SSL::Key::Ca.doc.should be_instance_of(String)
+ expect(Puppet::SSL::Key::Ca.doc).to be_instance_of(String)
end
it "should use the :privatekeydir as the collection directory" do
Puppet[:privatekeydir] = "/key/dir"
- Puppet::SSL::Key::Ca.collection_directory.should == Puppet[:privatekeydir]
+ expect(Puppet::SSL::Key::Ca.collection_directory).to eq(Puppet[:privatekeydir])
end
it "should store the ca key at the :cakey location" do
Puppet.settings.stubs(:use)
Puppet[:cakey] = "/ca/key"
file = Puppet::SSL::Key::Ca.new
file.stubs(:ca?).returns true
- file.path("whatever").should == Puppet[:cakey]
+ expect(file.path("whatever")).to eq(Puppet[:cakey])
end
end
diff --git a/spec/unit/indirector/key/file_spec.rb b/spec/unit/indirector/key/file_spec.rb
index 44b658cc2..47a6b1ee9 100755
--- a/spec/unit/indirector/key/file_spec.rb
+++ b/spec/unit/indirector/key/file_spec.rb
@@ -1,97 +1,97 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/key/file'
describe Puppet::SSL::Key::File do
it "should have documentation" do
- Puppet::SSL::Key::File.doc.should be_instance_of(String)
+ expect(Puppet::SSL::Key::File.doc).to be_instance_of(String)
end
it "should use the :privatekeydir as the collection directory" do
Puppet[:privatekeydir] = File.expand_path("/key/dir")
- Puppet::SSL::Key::File.collection_directory.should == Puppet[:privatekeydir]
+ expect(Puppet::SSL::Key::File.collection_directory).to eq(Puppet[:privatekeydir])
end
it "should store the ca key at the :cakey location" do
Puppet.settings.stubs(:use)
Puppet[:cakey] = File.expand_path("/ca/key")
file = Puppet::SSL::Key::File.new
file.stubs(:ca?).returns true
- file.path("whatever").should == Puppet[:cakey]
+ expect(file.path("whatever")).to eq(Puppet[:cakey])
end
describe "when choosing the path for the public key" do
it "should use the :capub setting location if the key is for the certificate authority" do
Puppet[:capub] = File.expand_path("/ca/pubkey")
Puppet.settings.stubs(:use)
@searcher = Puppet::SSL::Key::File.new
@searcher.stubs(:ca?).returns true
- @searcher.public_key_path("whatever").should == Puppet[:capub]
+ expect(@searcher.public_key_path("whatever")).to eq(Puppet[:capub])
end
it "should use the host name plus '.pem' in :publickeydir for normal hosts" do
Puppet[:privatekeydir] = File.expand_path("/private/key/dir")
Puppet[:publickeydir] = File.expand_path("/public/key/dir")
Puppet.settings.stubs(:use)
@searcher = Puppet::SSL::Key::File.new
@searcher.stubs(:ca?).returns false
- @searcher.public_key_path("whatever").should == File.expand_path("/public/key/dir/whatever.pem")
+ expect(@searcher.public_key_path("whatever")).to eq(File.expand_path("/public/key/dir/whatever.pem"))
end
end
describe "when managing private keys" do
before do
@searcher = Puppet::SSL::Key::File.new
@private_key_path = File.join("/fake/key/path")
@public_key_path = File.join("/other/fake/key/path")
@searcher.stubs(:public_key_path).returns @public_key_path
@searcher.stubs(:path).returns @private_key_path
FileTest.stubs(:directory?).returns true
FileTest.stubs(:writable?).returns true
@public_key = stub 'public_key'
@real_key = stub 'sslkey', :public_key => @public_key
@key = stub 'key', :name => "myname", :content => @real_key
@request = stub 'request', :key => "myname", :instance => @key
end
it "should save the public key when saving the private key" do
fh = StringIO.new
Puppet.settings.setting(:publickeydir).expects(:open_file).with(@public_key_path, 'w').yields fh
Puppet.settings.setting(:privatekeydir).stubs(:open_file)
@public_key.expects(:to_pem).returns "my pem"
@searcher.save(@request)
expect(fh.string).to eq("my pem")
end
it "should destroy the public key when destroying the private key" do
Puppet::FileSystem.expects(:unlink).with(Puppet::FileSystem.pathname(@private_key_path))
Puppet::FileSystem.expects(:exist?).with(Puppet::FileSystem.pathname(@private_key_path)).returns true
Puppet::FileSystem.expects(:exist?).with(Puppet::FileSystem.pathname(@public_key_path)).returns true
Puppet::FileSystem.expects(:unlink).with(Puppet::FileSystem.pathname(@public_key_path))
@searcher.destroy(@request)
end
it "should not fail if the public key does not exist when deleting the private key" do
Puppet::FileSystem.stubs(:unlink).with(Puppet::FileSystem.pathname(@private_key_path))
Puppet::FileSystem.stubs(:exist?).with(Puppet::FileSystem.pathname(@private_key_path)).returns true
Puppet::FileSystem.expects(:exist?).with(Puppet::FileSystem.pathname(@public_key_path)).returns false
Puppet::FileSystem.expects(:unlink).with(Puppet::FileSystem.pathname(@public_key_path)).never
@searcher.destroy(@request)
end
end
end
diff --git a/spec/unit/indirector/ldap_spec.rb b/spec/unit/indirector/ldap_spec.rb
index eb8be0f04..0bf79db93 100755
--- a/spec/unit/indirector/ldap_spec.rb
+++ b/spec/unit/indirector/ldap_spec.rb
@@ -1,137 +1,137 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/ldap'
describe Puppet::Indirector::Ldap do
before do
@indirection = stub 'indirection', :name => :testing
Puppet::Indirector::Indirection.stubs(:instance).returns(@indirection)
module Testing; end
@ldap_class = class Testing::MyLdap < Puppet::Indirector::Ldap
self
end
@connection = mock 'ldap'
@searcher = @ldap_class.new
end
describe "when searching ldap" do
before do
# Stub everything, and we can selectively replace with an expect as
# we need to for testing.
@searcher.stubs(:connection).returns(@connection)
@searcher.stubs(:search_filter).returns(:filter)
@searcher.stubs(:search_base).returns(:base)
@searcher.stubs(:process)
@request = stub 'request', :key => "yay"
end
it "should call the ldapsearch method with the search filter" do
@searcher.expects(:search_filter).with("yay").returns("yay's filter")
@searcher.expects(:ldapsearch).with("yay's filter")
@searcher.find @request
end
it "should fail if no block is passed to the ldapsearch method" do
- proc { @searcher.ldapsearch("blah") }.should raise_error(ArgumentError)
+ expect { @searcher.ldapsearch("blah") }.to raise_error(ArgumentError)
end
it "should use the results of the ldapbase method as the ldap search base" do
@searcher.stubs(:search_base).returns("mybase")
@connection.expects(:search).with do |*args|
- args[0].should == "mybase"
+ expect(args[0]).to eq("mybase")
true
end
@searcher.find @request
end
it "should default to the value of the :search_base setting as the result of the ldapbase method" do
Puppet[:ldapbase] = "myldapbase"
searcher = @ldap_class.new
- searcher.search_base.should == "myldapbase"
+ expect(searcher.search_base).to eq("myldapbase")
end
it "should use the results of the :search_attributes method as the list of attributes to return" do
@searcher.stubs(:search_attributes).returns(:myattrs)
@connection.expects(:search).with do |*args|
- args[3].should == :myattrs
+ expect(args[3]).to eq(:myattrs)
true
end
@searcher.find @request
end
it "should use depth 2 when searching" do
@connection.expects(:search).with do |*args|
- args[1].should == 2
+ expect(args[1]).to eq(2)
true
end
@searcher.find @request
end
it "should call process() on the first found entry" do
@connection.expects(:search).yields("myresult")
@searcher.expects(:process).with("myresult")
@searcher.find @request
end
it "should reconnect and retry the search if there is a failure" do
run = false
@connection.stubs(:search).with do |*args|
if run
true
else
run = true
raise "failed"
end
end.yields("myresult")
@searcher.expects(:process).with("myresult")
@searcher.find @request
end
it "should not reconnect on failure more than once" do
count = 0
@connection.stubs(:search).with do |*args|
count += 1
raise ArgumentError, "yay"
end
- proc { @searcher.find(@request) }.should raise_error(Puppet::Error)
- count.should == 2
+ expect { @searcher.find(@request) }.to raise_error(Puppet::Error)
+ expect(count).to eq(2)
end
it "should return true if an entry is found" do
@connection.expects(:search).yields("result")
- @searcher.ldapsearch("whatever") { |r| }.should be_true
+ expect(@searcher.ldapsearch("whatever") { |r| }).to be_truthy
end
end
describe "when connecting to ldap", :if => Puppet.features.ldap? do
it "should create and start a Util::Ldap::Connection instance" do
- conn = mock 'connection', :connection => "myconn", :start => nil
+ conn = double 'connection', :connection => "myconn", :start => nil
Puppet::Util::Ldap::Connection.expects(:instance).returns conn
- @searcher.connection.should == "myconn"
+ expect(@searcher.connection).to eq("myconn")
end
it "should only create the ldap connection when asked for it the first time" do
- conn = mock 'connection', :connection => "myconn", :start => nil
+ conn = double 'connection', :connection => "myconn", :start => nil
Puppet::Util::Ldap::Connection.expects(:instance).returns conn
@searcher.connection
end
it "should cache the connection" do
- conn = mock 'connection', :connection => "myconn", :start => nil
+ conn = double 'connection', :connection => "myconn", :start => nil
Puppet::Util::Ldap::Connection.expects(:instance).returns conn
- @searcher.connection.should equal(@searcher.connection)
+ expect(@searcher.connection).to equal(@searcher.connection)
end
end
describe "when reconnecting to ldap", :if => (Puppet.features.root? and Facter.value("hostname") == "culain") do
it "should reconnect to ldap when connections are lost"
end
end
diff --git a/spec/unit/indirector/msgpack_spec.rb b/spec/unit/indirector/msgpack_spec.rb
index 9391f94b0..cb289e084 100755
--- a/spec/unit/indirector/msgpack_spec.rb
+++ b/spec/unit/indirector/msgpack_spec.rb
@@ -1,191 +1,191 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/indirector/indirector_testing/msgpack'
describe Puppet::Indirector::Msgpack, :if => Puppet.features.msgpack? do
include PuppetSpec::Files
subject { Puppet::IndirectorTesting::Msgpack.new }
let :model do Puppet::IndirectorTesting end
let :indirection do model.indirection end
context "#path" do
before :each do
Puppet[:server_datadir] = '/sample/datadir/master'
Puppet[:client_datadir] = '/sample/datadir/client'
end
it "uses the :server_datadir setting if this is the master" do
Puppet.run_mode.stubs(:master?).returns(true)
expected = File.join(Puppet[:server_datadir], 'indirector_testing', 'testing.msgpack')
- subject.path('testing').should == expected
+ expect(subject.path('testing')).to eq(expected)
end
it "uses the :client_datadir setting if this is not the master" do
Puppet.run_mode.stubs(:master?).returns(false)
expected = File.join(Puppet[:client_datadir], 'indirector_testing', 'testing.msgpack')
- subject.path('testing').should == expected
+ expect(subject.path('testing')).to eq(expected)
end
it "overrides the default extension with a supplied value" do
Puppet.run_mode.stubs(:master?).returns(true)
expected = File.join(Puppet[:server_datadir], 'indirector_testing', 'testing.not-msgpack')
- subject.path('testing', '.not-msgpack').should == expected
+ expect(subject.path('testing', '.not-msgpack')).to eq(expected)
end
['../foo', '..\\foo', './../foo', '.\\..\\foo',
'/foo', '//foo', '\\foo', '\\\\goo',
"test\0/../bar", "test\0\\..\\bar",
"..\\/bar", "/tmp/bar", "/tmp\\bar", "tmp\\bar",
" / bar", " /../ bar", " \\..\\ bar",
"c:\\foo", "c:/foo", "\\\\?\\UNC\\bar", "\\\\foo\\bar",
"\\\\?\\c:\\foo", "//?/UNC/bar", "//foo/bar",
"//?/c:/foo",
].each do |input|
it "should resist directory traversal attacks (#{input.inspect})" do
expect { subject.path(input) }.to raise_error ArgumentError, 'invalid key'
end
end
end
context "handling requests" do
before :each do
Puppet.run_mode.stubs(:master?).returns(true)
Puppet[:server_datadir] = tmpdir('msgpackdir')
FileUtils.mkdir_p(File.join(Puppet[:server_datadir], 'indirector_testing'))
end
let :file do subject.path(request.key) end
def with_content(text)
FileUtils.mkdir_p(File.dirname(file))
File.open(file, 'w') {|f| f.write text }
yield if block_given?
end
it "data saves and then loads again correctly" do
subject.save(indirection.request(:save, 'example', model.new('banana')))
- subject.find(indirection.request(:find, 'example', nil)).value.should == 'banana'
+ expect(subject.find(indirection.request(:find, 'example', nil)).value).to eq('banana')
end
context "#find" do
let :request do indirection.request(:find, 'example', nil) end
it "returns nil if the file doesn't exist" do
- subject.find(request).should be_nil
+ expect(subject.find(request)).to be_nil
end
it "raises a descriptive error when the file can't be read" do
with_content(model.new('foo').to_msgpack) do
# I don't like this, but there isn't a credible alternative that
# also works on Windows, so a stub it is. At least the expectation
# will fail if the implementation changes. Sorry to the next dev.
File.expects(:read).with(file).raises(Errno::EPERM)
expect { subject.find(request) }.
to raise_error Puppet::Error, /Could not read MessagePack/
end
end
it "raises a descriptive error when the file content is invalid" do
with_content("this is totally invalid MessagePack") do
expect { subject.find(request) }.
to raise_error Puppet::Error, /Could not parse MessagePack data/
end
end
it "should return an instance of the indirected object when valid" do
with_content(model.new(1).to_msgpack) do
instance = subject.find(request)
- instance.should be_an_instance_of model
- instance.value.should == 1
+ expect(instance).to be_an_instance_of model
+ expect(instance.value).to eq(1)
end
end
end
context "#save" do
let :instance do model.new(4) end
let :request do indirection.request(:find, 'example', instance) end
it "should save the instance of the request as MessagePack to disk" do
subject.save(request)
content = File.read(file)
- MessagePack.unpack(content)['value'].should == 4
+ expect(MessagePack.unpack(content)['value']).to eq(4)
end
it "should create the indirection directory if required" do
target = File.join(Puppet[:server_datadir], 'indirector_testing')
Dir.rmdir(target)
subject.save(request)
- File.should be_directory(target)
+ expect(File).to be_directory(target)
end
end
context "#destroy" do
let :request do indirection.request(:find, 'example', nil) end
it "removes an existing file" do
with_content('hello') do
subject.destroy(request)
end
- Puppet::FileSystem.exist?(file).should be_false
+ expect(Puppet::FileSystem.exist?(file)).to be_falsey
end
it "silently succeeds when files don't exist" do
Puppet::FileSystem.unlink(file) rescue nil
- subject.destroy(request).should be_true
+ expect(subject.destroy(request)).to be_truthy
end
it "raises an informative error for other failures" do
Puppet::FileSystem.stubs(:unlink).with(file).raises(Errno::EPERM, 'fake permission problem')
with_content('hello') do
expect { subject.destroy(request) }.to raise_error(Puppet::Error)
end
Puppet::FileSystem.unstub(:unlink) # thanks, mocha
end
end
end
context "#search" do
before :each do
Puppet.run_mode.stubs(:master?).returns(true)
Puppet[:server_datadir] = tmpdir('msgpackdir')
FileUtils.mkdir_p(File.join(Puppet[:server_datadir], 'indirector_testing'))
end
def request(glob)
indirection.request(:search, glob, nil)
end
def create_file(name, value = 12)
File.open(subject.path(name, ''), 'w') do |f|
f.write Puppet::IndirectorTesting.new(value).to_msgpack
end
end
it "returns an empty array when nothing matches the key as a glob" do
- subject.search(request('*')).should == []
+ expect(subject.search(request('*'))).to eq([])
end
it "returns an array with one item if one item matches" do
create_file('foo.msgpack', 'foo')
create_file('bar.msgpack', 'bar')
- subject.search(request('f*')).map(&:value).should == ['foo']
+ expect(subject.search(request('f*')).map(&:value)).to eq(['foo'])
end
it "returns an array of items when more than one item matches" do
create_file('foo.msgpack', 'foo')
create_file('bar.msgpack', 'bar')
create_file('baz.msgpack', 'baz')
- subject.search(request('b*')).map(&:value).should =~ ['bar', 'baz']
+ expect(subject.search(request('b*')).map(&:value)).to match_array(['bar', 'baz'])
end
it "only items with the .msgpack extension" do
create_file('foo.msgpack', 'foo-msgpack')
create_file('foo.msgpack~', 'foo-backup')
- subject.search(request('f*')).map(&:value).should == ['foo-msgpack']
+ expect(subject.search(request('f*')).map(&:value)).to eq(['foo-msgpack'])
end
end
end
diff --git a/spec/unit/indirector/node/exec_spec.rb b/spec/unit/indirector/node/exec_spec.rb
index b39483f92..452c89397 100755
--- a/spec/unit/indirector/node/exec_spec.rb
+++ b/spec/unit/indirector/node/exec_spec.rb
@@ -1,87 +1,87 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/node/exec'
require 'puppet/indirector/request'
describe Puppet::Node::Exec do
before do
@indirection = mock 'indirection'
Puppet.settings[:external_nodes] = File.expand_path("/echo")
@searcher = Puppet::Node::Exec.new
end
describe "when constructing the command to run" do
it "should use the external_node script as the command" do
Puppet[:external_nodes] = "/bin/echo"
- @searcher.command.should == %w{/bin/echo}
+ expect(@searcher.command).to eq(%w{/bin/echo})
end
it "should throw an exception if no external node command is set" do
Puppet[:external_nodes] = "none"
- proc { @searcher.find(stub('request', :key => "foo")) }.should raise_error(ArgumentError)
+ expect { @searcher.find(stub('request', :key => "foo")) }.to raise_error(ArgumentError)
end
end
describe "when handling the results of the command" do
let(:testing_env) { Puppet::Node::Environment.create(:testing, []) }
let(:other_env) { Puppet::Node::Environment.create(:other, []) }
before do
@name = "yay"
@node = Puppet::Node.new(@name)
@node.stubs(:fact_merge)
Puppet::Node.expects(:new).with(@name).returns(@node)
@result = {}
# Use a local variable so the reference is usable in the execute definition.
result = @result
@searcher.meta_def(:execute) do |command, arguments|
return YAML.dump(result)
end
@request = Puppet::Indirector::Request.new(:node, :find, @name, nil)
end
around do |example|
envs = Puppet::Environments::Static.new(testing_env, other_env)
Puppet.override(:environments => envs) do
example.run
end
end
it "should translate the YAML into a Node instance" do
# Use an empty hash
- @searcher.find(@request).should equal(@node)
+ expect(@searcher.find(@request)).to equal(@node)
end
it "should set the resulting parameters as the node parameters" do
@result[:parameters] = {"a" => "b", "c" => "d"}
@searcher.find(@request)
- @node.parameters.should == {"a" => "b", "c" => "d"}
+ expect(@node.parameters).to eq({"a" => "b", "c" => "d"})
end
it "should set the resulting classes as the node classes" do
@result[:classes] = %w{one two}
@searcher.find(@request)
- @node.classes.should == [ 'one', 'two' ]
+ expect(@node.classes).to eq([ 'one', 'two' ])
end
it "should merge the node's facts with its parameters" do
@node.expects(:fact_merge)
@searcher.find(@request)
end
it "should set the node's environment if one is provided" do
@result[:environment] = "testing"
@searcher.find(@request)
expect(@node.environment.name).to eq(:testing)
end
it "should set the node's environment based on the request if not otherwise provided" do
@request.environment = "other"
@searcher.find(@request)
expect(@node.environment.name).to eq(:other)
end
end
end
diff --git a/spec/unit/indirector/node/ldap_spec.rb b/spec/unit/indirector/node/ldap_spec.rb
index 76860e15d..ca0cc4e23 100755
--- a/spec/unit/indirector/node/ldap_spec.rb
+++ b/spec/unit/indirector/node/ldap_spec.rb
@@ -1,441 +1,441 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/node/ldap'
describe Puppet::Node::Ldap do
let(:nodename) { "mynode.domain.com" }
let(:node_indirection) { Puppet::Node::Ldap.new }
let(:environment) { Puppet::Node::Environment.create(:myenv, []) }
let(:fact_values) { {:afact => "a value", "one" => "boo"} }
let(:facts) { Puppet::Node::Facts.new(nodename, fact_values) }
before do
Puppet::Node::Facts.indirection.stubs(:find).with(nodename, :environment => environment).returns(facts)
end
describe "when searching for a single node" do
let(:request) { Puppet::Indirector::Request.new(:node, :find, nodename, nil, :environment => environment) }
it "should convert the hostname into a search filter" do
entry = stub 'entry', :dn => 'cn=mynode.domain.com,ou=hosts,dc=madstop,dc=com', :vals => %w{}, :to_hash => {}
node_indirection.expects(:ldapsearch).with("(&(objectclass=puppetClient)(cn=#{nodename}))").yields entry
node_indirection.name2hash(nodename)
end
it "should convert any found entry into a hash" do
entry = stub 'entry', :dn => 'cn=mynode.domain.com,ou=hosts,dc=madstop,dc=com', :vals => %w{}, :to_hash => {}
node_indirection.expects(:ldapsearch).with("(&(objectclass=puppetClient)(cn=#{nodename}))").yields entry
myhash = {"myhash" => true}
node_indirection.expects(:entry2hash).with(entry).returns myhash
- node_indirection.name2hash(nodename).should == myhash
+ expect(node_indirection.name2hash(nodename)).to eq(myhash)
end
# This heavily tests our entry2hash method, so we don't have to stub out the stupid entry information any more.
describe "when an ldap entry is found" do
before do
@entry = stub 'entry', :dn => 'cn=mynode,ou=hosts,dc=madstop,dc=com', :vals => %w{}, :to_hash => {}
node_indirection.stubs(:ldapsearch).yields @entry
end
it "should convert the entry to a hash" do
- node_indirection.entry2hash(@entry).should be_instance_of(Hash)
+ expect(node_indirection.entry2hash(@entry)).to be_instance_of(Hash)
end
it "should add the entry's common name to the hash if fqdn if false" do
- node_indirection.entry2hash(@entry,fqdn = false)[:name].should == "mynode"
+ expect(node_indirection.entry2hash(@entry,fqdn = false)[:name]).to eq("mynode")
end
it "should add the entry's fqdn name to the hash if fqdn if true" do
- node_indirection.entry2hash(@entry,fqdn = true)[:name].should == "mynode.madstop.com"
+ expect(node_indirection.entry2hash(@entry,fqdn = true)[:name]).to eq("mynode.madstop.com")
end
it "should add all of the entry's classes to the hash" do
@entry.stubs(:vals).with("puppetclass").returns %w{one two}
- node_indirection.entry2hash(@entry)[:classes].should == %w{one two}
+ expect(node_indirection.entry2hash(@entry)[:classes]).to eq(%w{one two})
end
it "should deduplicate class values" do
@entry.stubs(:to_hash).returns({})
node_indirection.stubs(:class_attributes).returns(%w{one two})
@entry.stubs(:vals).with("one").returns(%w{a b})
@entry.stubs(:vals).with("two").returns(%w{b c})
- node_indirection.entry2hash(@entry)[:classes].should == %w{a b c}
+ expect(node_indirection.entry2hash(@entry)[:classes]).to eq(%w{a b c})
end
it "should add the entry's environment to the hash" do
@entry.stubs(:to_hash).returns("environment" => %w{production})
- node_indirection.entry2hash(@entry)[:environment].should == "production"
+ expect(node_indirection.entry2hash(@entry)[:environment]).to eq("production")
end
it "should add all stacked parameters as parameters in the hash" do
@entry.stubs(:vals).with("puppetvar").returns(%w{one=two three=four})
result = node_indirection.entry2hash(@entry)
- result[:parameters]["one"].should == "two"
- result[:parameters]["three"].should == "four"
+ expect(result[:parameters]["one"]).to eq("two")
+ expect(result[:parameters]["three"]).to eq("four")
end
it "should not add the stacked parameter as a normal parameter" do
@entry.stubs(:vals).with("puppetvar").returns(%w{one=two three=four})
@entry.stubs(:to_hash).returns("puppetvar" => %w{one=two three=four})
- node_indirection.entry2hash(@entry)[:parameters]["puppetvar"].should be_nil
+ expect(node_indirection.entry2hash(@entry)[:parameters]["puppetvar"]).to be_nil
end
it "should add all other attributes as parameters in the hash" do
@entry.stubs(:to_hash).returns("foo" => %w{one two})
- node_indirection.entry2hash(@entry)[:parameters]["foo"].should == %w{one two}
+ expect(node_indirection.entry2hash(@entry)[:parameters]["foo"]).to eq(%w{one two})
end
it "should return single-value parameters as strings, not arrays" do
@entry.stubs(:to_hash).returns("foo" => %w{one})
- node_indirection.entry2hash(@entry)[:parameters]["foo"].should == "one"
+ expect(node_indirection.entry2hash(@entry)[:parameters]["foo"]).to eq("one")
end
it "should convert 'true' values to the boolean 'true'" do
@entry.stubs(:to_hash).returns({"one" => ["true"]})
- node_indirection.entry2hash(@entry)[:parameters]["one"].should == true
+ expect(node_indirection.entry2hash(@entry)[:parameters]["one"]).to eq(true)
end
it "should convert 'false' values to the boolean 'false'" do
@entry.stubs(:to_hash).returns({"one" => ["false"]})
- node_indirection.entry2hash(@entry)[:parameters]["one"].should == false
+ expect(node_indirection.entry2hash(@entry)[:parameters]["one"]).to eq(false)
end
it "should convert 'true' values to the boolean 'true' inside an array" do
@entry.stubs(:to_hash).returns({"one" => ["true", "other"]})
- node_indirection.entry2hash(@entry)[:parameters]["one"].should == [true, "other"]
+ expect(node_indirection.entry2hash(@entry)[:parameters]["one"]).to eq([true, "other"])
end
it "should convert 'false' values to the boolean 'false' inside an array" do
@entry.stubs(:to_hash).returns({"one" => ["false", "other"]})
- node_indirection.entry2hash(@entry)[:parameters]["one"].should == [false, "other"]
+ expect(node_indirection.entry2hash(@entry)[:parameters]["one"]).to eq([false, "other"])
end
it "should add the parent's name if present" do
@entry.stubs(:vals).with("parentnode").returns(%w{foo})
- node_indirection.entry2hash(@entry)[:parent].should == "foo"
+ expect(node_indirection.entry2hash(@entry)[:parent]).to eq("foo")
end
it "should fail if more than one parent is specified" do
@entry.stubs(:vals).with("parentnode").returns(%w{foo})
- node_indirection.entry2hash(@entry)[:parent].should == "foo"
+ expect(node_indirection.entry2hash(@entry)[:parent]).to eq("foo")
end
end
it "should search first for the provided key" do
node_indirection.expects(:name2hash).with("mynode.domain.com").returns({})
node_indirection.find(request)
end
it "should search for the short version of the provided key if the key looks like a hostname and no results are found for the key itself" do
node_indirection.expects(:name2hash).with("mynode.domain.com").returns(nil)
node_indirection.expects(:name2hash).with("mynode").returns({})
node_indirection.find(request)
end
it "should search for default information if no information can be found for the key" do
node_indirection.expects(:name2hash).with("mynode.domain.com").returns(nil)
node_indirection.expects(:name2hash).with("mynode").returns(nil)
node_indirection.expects(:name2hash).with("default").returns({})
node_indirection.find(request)
end
it "should return nil if no results are found in ldap" do
node_indirection.stubs(:name2hash).returns nil
- node_indirection.find(request).should be_nil
+ expect(node_indirection.find(request)).to be_nil
end
it "should return a node object if results are found in ldap" do
node_indirection.stubs(:name2hash).returns({})
- node_indirection.find(request).should be
+ expect(node_indirection.find(request)).to be
end
describe "and node information is found in LDAP" do
before do
@result = {}
node_indirection.stubs(:name2hash).returns @result
end
it "should create the node with the correct name, even if it was found by a different name" do
node_indirection.expects(:name2hash).with(nodename).returns nil
node_indirection.expects(:name2hash).with("mynode").returns @result
- node_indirection.find(request).name.should == nodename
+ expect(node_indirection.find(request).name).to eq(nodename)
end
it "should add any classes from ldap" do
classes = %w{a b c d}
@result[:classes] = classes
- node_indirection.find(request).classes.should == classes
+ expect(node_indirection.find(request).classes).to eq(classes)
end
it "should add all entry attributes as node parameters" do
params = {"one" => "two", "three" => "four"}
@result[:parameters] = params
- node_indirection.find(request).parameters.should include(params)
+ expect(node_indirection.find(request).parameters).to include(params)
end
it "should set the node's environment to the environment of the results" do
result_env = Puppet::Node::Environment.create(:local_test, [])
Puppet::Node::Facts.indirection.stubs(:find).with(nodename, :environment => result_env).returns(facts)
@result[:environment] = "local_test"
Puppet.override(:environments => Puppet::Environments::Static.new(result_env)) do
- node_indirection.find(request).environment.should == result_env
+ expect(node_indirection.find(request).environment).to eq(result_env)
end
end
it "should retain false parameter values" do
@result[:parameters] = {}
@result[:parameters]["one"] = false
- node_indirection.find(request).parameters.should include({"one" => false})
+ expect(node_indirection.find(request).parameters).to include({"one" => false})
end
it "should merge the node's facts after the parameters from ldap are assigned" do
# Make sure we've got data to start with, so the parameters are actually set.
params = {"one" => "yay", "two" => "hooray"}
@result[:parameters] = params
# Node implements its own merge so that an existing param takes
# precedence over facts. We get the same result here by merging params
# into facts
- node_indirection.find(request).parameters.should == facts.values.merge(params)
+ expect(node_indirection.find(request).parameters).to eq(facts.values.merge(params))
end
describe "and a parent node is specified" do
before do
@entry = {:classes => [], :parameters => {}}
@parent = {:classes => [], :parameters => {}}
@parent_parent = {:classes => [], :parameters => {}}
node_indirection.stubs(:name2hash).with(nodename).returns(@entry)
node_indirection.stubs(:name2hash).with('parent').returns(@parent)
node_indirection.stubs(:name2hash).with('parent_parent').returns(@parent_parent)
node_indirection.stubs(:parent_attribute).returns(:parent)
end
it "should search for the parent node" do
@entry[:parent] = "parent"
node_indirection.expects(:name2hash).with(nodename).returns @entry
node_indirection.expects(:name2hash).with('parent').returns @parent
node_indirection.find(request)
end
it "should fail if the parent cannot be found" do
@entry[:parent] = "parent"
node_indirection.expects(:name2hash).with('parent').returns nil
- proc { node_indirection.find(request) }.should raise_error(Puppet::Error, /Could not find parent node/)
+ expect { node_indirection.find(request) }.to raise_error(Puppet::Error, /Could not find parent node/)
end
it "should add any parent classes to the node's classes" do
@entry[:parent] = "parent"
@entry[:classes] = %w{a b}
@parent[:classes] = %w{c d}
- node_indirection.find(request).classes.should == %w{a b c d}
+ expect(node_indirection.find(request).classes).to eq(%w{a b c d})
end
it "should add any parent parameters to the node's parameters" do
@entry[:parent] = "parent"
@entry[:parameters]["one"] = "two"
@parent[:parameters]["three"] = "four"
- node_indirection.find(request).parameters.should include({"one" => "two", "three" => "four"})
+ expect(node_indirection.find(request).parameters).to include({"one" => "two", "three" => "four"})
end
it "should prefer node parameters over parent parameters" do
@entry[:parent] = "parent"
@entry[:parameters]["one"] = "two"
@parent[:parameters]["one"] = "three"
- node_indirection.find(request).parameters.should include({"one" => "two"})
+ expect(node_indirection.find(request).parameters).to include({"one" => "two"})
end
it "should use the parent's environment if the node has none" do
env = Puppet::Node::Environment.create(:parent, [])
@entry[:parent] = "parent"
@parent[:environment] = "parent"
Puppet::Node::Facts.indirection.stubs(:find).with(nodename, :environment => env).returns(facts)
Puppet.override(:environments => Puppet::Environments::Static.new(env)) do
- node_indirection.find(request).environment.should == env
+ expect(node_indirection.find(request).environment).to eq(env)
end
end
it "should prefer the node's environment to the parent's" do
child_env = Puppet::Node::Environment.create(:child, [])
@entry[:parent] = "parent"
@entry[:environment] = "child"
@parent[:environment] = "parent"
Puppet::Node::Facts.indirection.stubs(:find).with(nodename, :environment => child_env).returns(facts)
Puppet.override(:environments => Puppet::Environments::Static.new(child_env)) do
- node_indirection.find(request).environment.should == child_env
+ expect(node_indirection.find(request).environment).to eq(child_env)
end
end
it "should recursively look up parent information" do
@entry[:parent] = "parent"
@entry[:parameters]["one"] = "two"
@parent[:parent] = "parent_parent"
@parent[:parameters]["three"] = "four"
@parent_parent[:parameters]["five"] = "six"
- node_indirection.find(request).parameters.should include("one" => "two", "three" => "four", "five" => "six")
+ expect(node_indirection.find(request).parameters).to include("one" => "two", "three" => "four", "five" => "six")
end
it "should not allow loops in parent declarations" do
@entry[:parent] = "parent"
@parent[:parent] = nodename
- proc { node_indirection.find(request) }.should raise_error(ArgumentError)
+ expect { node_indirection.find(request) }.to raise_error(ArgumentError)
end
end
end
end
describe "when searching for multiple nodes" do
let(:options) { {:environment => environment} }
let(:request) { Puppet::Indirector::Request.new(:node, :find, nodename, nil, options) }
before :each do
Puppet::Node::Facts.indirection.stubs(:terminus_class).returns :yaml
end
it "should find all nodes if no arguments are provided" do
node_indirection.expects(:ldapsearch).with("(objectclass=puppetClient)")
# LAK:NOTE The search method requires an essentially bogus key. It's
# an API problem that I don't really know how to fix.
node_indirection.search request
end
describe "and a class is specified" do
it "should find all nodes that are members of that class" do
node_indirection.expects(:ldapsearch).with("(&(objectclass=puppetClient)(puppetclass=one))")
options[:class] = "one"
node_indirection.search request
end
end
describe "multiple classes are specified" do
it "should find all nodes that are members of all classes" do
node_indirection.expects(:ldapsearch).with("(&(objectclass=puppetClient)(puppetclass=one)(puppetclass=two))")
options[:class] = %w{one two}
node_indirection.search request
end
end
it "should process each found entry" do
# .yields can't be used to yield multiple values :/
node_indirection.expects(:ldapsearch).yields("one")
node_indirection.expects(:entry2hash).with("one",nil).returns(:name => nodename)
node_indirection.search request
end
it "should return a node for each processed entry with the name from the entry" do
node_indirection.expects(:ldapsearch).yields("whatever")
node_indirection.expects(:entry2hash).with("whatever",nil).returns(:name => nodename)
result = node_indirection.search(request)
- result[0].should be_instance_of(Puppet::Node)
- result[0].name.should == nodename
+ expect(result[0]).to be_instance_of(Puppet::Node)
+ expect(result[0].name).to eq(nodename)
end
it "should merge each node's facts" do
node_indirection.stubs(:ldapsearch).yields("one")
node_indirection.stubs(:entry2hash).with("one",nil).returns(:name => nodename)
- node_indirection.search(request)[0].parameters.should include(fact_values)
+ expect(node_indirection.search(request)[0].parameters).to include(fact_values)
end
it "should pass the request's fqdn option to entry2hash" do
options[:fqdn] = :hello
node_indirection.stubs(:ldapsearch).yields("one")
node_indirection.expects(:entry2hash).with("one",:hello).returns(:name => nodename)
node_indirection.search(request)
end
end
describe Puppet::Node::Ldap, " when developing the search query" do
it "should return the value of the :ldapclassattrs split on commas as the class attributes" do
Puppet[:ldapclassattrs] = "one,two"
- node_indirection.class_attributes.should == %w{one two}
+ expect(node_indirection.class_attributes).to eq(%w{one two})
end
it "should return nil as the parent attribute if the :ldapparentattr is set to an empty string" do
Puppet[:ldapparentattr] = ""
- node_indirection.parent_attribute.should be_nil
+ expect(node_indirection.parent_attribute).to be_nil
end
it "should return the value of the :ldapparentattr as the parent attribute" do
Puppet[:ldapparentattr] = "pere"
- node_indirection.parent_attribute.should == "pere"
+ expect(node_indirection.parent_attribute).to eq("pere")
end
it "should use the value of the :ldapstring as the search filter" do
Puppet[:ldapstring] = "mystring"
- node_indirection.search_filter("testing").should == "mystring"
+ expect(node_indirection.search_filter("testing")).to eq("mystring")
end
it "should replace '%s' with the node name in the search filter if it is present" do
Puppet[:ldapstring] = "my%sstring"
- node_indirection.search_filter("testing").should == "mytestingstring"
+ expect(node_indirection.search_filter("testing")).to eq("mytestingstring")
end
it "should not modify the global :ldapstring when replacing '%s' in the search filter" do
filter = mock 'filter'
filter.expects(:include?).with("%s").returns(true)
filter.expects(:gsub).with("%s", "testing").returns("mynewstring")
Puppet[:ldapstring] = filter
- node_indirection.search_filter("testing").should == "mynewstring"
+ expect(node_indirection.search_filter("testing")).to eq("mynewstring")
end
end
describe Puppet::Node::Ldap, " when deciding attributes to search for" do
it "should use 'nil' if the :ldapattrs setting is 'all'" do
Puppet[:ldapattrs] = "all"
- node_indirection.search_attributes.should be_nil
+ expect(node_indirection.search_attributes).to be_nil
end
it "should split the value of :ldapattrs on commas and use the result as the attribute list" do
Puppet[:ldapattrs] = "one,two"
node_indirection.stubs(:class_attributes).returns([])
node_indirection.stubs(:parent_attribute).returns(nil)
- node_indirection.search_attributes.should == %w{one two}
+ expect(node_indirection.search_attributes).to eq(%w{one two})
end
it "should add the class attributes to the search attributes if not returning all attributes" do
Puppet[:ldapattrs] = "one,two"
node_indirection.stubs(:class_attributes).returns(%w{three four})
node_indirection.stubs(:parent_attribute).returns(nil)
# Sort them so i don't have to care about return order
- node_indirection.search_attributes.sort.should == %w{one two three four}.sort
+ expect(node_indirection.search_attributes.sort).to eq(%w{one two three four}.sort)
end
it "should add the parent attribute to the search attributes if not returning all attributes" do
Puppet[:ldapattrs] = "one,two"
node_indirection.stubs(:class_attributes).returns([])
node_indirection.stubs(:parent_attribute).returns("parent")
- node_indirection.search_attributes.sort.should == %w{one two parent}.sort
+ expect(node_indirection.search_attributes.sort).to eq(%w{one two parent}.sort)
end
it "should not add nil parent attributes to the search attributes" do
Puppet[:ldapattrs] = "one,two"
node_indirection.stubs(:class_attributes).returns([])
node_indirection.stubs(:parent_attribute).returns(nil)
- node_indirection.search_attributes.should == %w{one two}
+ expect(node_indirection.search_attributes).to eq(%w{one two})
end
end
end
diff --git a/spec/unit/indirector/node/msgpack_spec.rb b/spec/unit/indirector/node/msgpack_spec.rb
index 18ba50f97..d8751a178 100755
--- a/spec/unit/indirector/node/msgpack_spec.rb
+++ b/spec/unit/indirector/node/msgpack_spec.rb
@@ -1,24 +1,24 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/node'
require 'puppet/indirector/node/msgpack'
describe Puppet::Node::Msgpack, :if => Puppet.features.msgpack? do
it "should be a subclass of the Msgpack terminus" do
- Puppet::Node::Msgpack.superclass.should equal(Puppet::Indirector::Msgpack)
+ expect(Puppet::Node::Msgpack.superclass).to equal(Puppet::Indirector::Msgpack)
end
it "should have documentation" do
- Puppet::Node::Msgpack.doc.should_not be_nil
+ expect(Puppet::Node::Msgpack.doc).not_to be_nil
end
it "should be registered with the configuration store indirection" do
indirection = Puppet::Indirector::Indirection.instance(:node)
- Puppet::Node::Msgpack.indirection.should equal(indirection)
+ expect(Puppet::Node::Msgpack.indirection).to equal(indirection)
end
it "should have its name set to :msgpack" do
- Puppet::Node::Msgpack.name.should == :msgpack
+ expect(Puppet::Node::Msgpack.name).to eq(:msgpack)
end
end
diff --git a/spec/unit/indirector/node/plain_spec.rb b/spec/unit/indirector/node/plain_spec.rb
index 607fdefdf..b9e111abe 100755
--- a/spec/unit/indirector/node/plain_spec.rb
+++ b/spec/unit/indirector/node/plain_spec.rb
@@ -1,26 +1,26 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/node/plain'
describe Puppet::Node::Plain do
let(:nodename) { "mynode" }
let(:fact_values) { {:afact => "a value"} }
let(:facts) { Puppet::Node::Facts.new(nodename, fact_values) }
let(:environment) { Puppet::Node::Environment.create(:myenv, []) }
let(:request) { Puppet::Indirector::Request.new(:node, :find, nodename, nil, :environment => environment) }
let(:node_indirection) { Puppet::Node::Plain.new }
before do
Puppet::Node::Facts.indirection.expects(:find).with(nodename, :environment => environment).returns(facts)
end
it "merges facts into the node" do
- node_indirection.find(request).parameters.should include(fact_values)
+ expect(node_indirection.find(request).parameters).to include(fact_values)
end
it "should set the node environment from the request" do
- node_indirection.find(request).environment.should == environment
+ expect(node_indirection.find(request).environment).to eq(environment)
end
end
diff --git a/spec/unit/indirector/node/yaml_spec.rb b/spec/unit/indirector/node/yaml_spec.rb
index 0b08dbabf..b6b412603 100755
--- a/spec/unit/indirector/node/yaml_spec.rb
+++ b/spec/unit/indirector/node/yaml_spec.rb
@@ -1,24 +1,24 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/node'
require 'puppet/indirector/node/yaml'
describe Puppet::Node::Yaml do
it "should be a subclass of the Yaml terminus" do
- Puppet::Node::Yaml.superclass.should equal(Puppet::Indirector::Yaml)
+ expect(Puppet::Node::Yaml.superclass).to equal(Puppet::Indirector::Yaml)
end
it "should have documentation" do
- Puppet::Node::Yaml.doc.should_not be_nil
+ expect(Puppet::Node::Yaml.doc).not_to be_nil
end
it "should be registered with the configuration store indirection" do
indirection = Puppet::Indirector::Indirection.instance(:node)
- Puppet::Node::Yaml.indirection.should equal(indirection)
+ expect(Puppet::Node::Yaml.indirection).to equal(indirection)
end
it "should have its name set to :node" do
- Puppet::Node::Yaml.name.should == :yaml
+ expect(Puppet::Node::Yaml.name).to eq(:yaml)
end
end
diff --git a/spec/unit/indirector/none_spec.rb b/spec/unit/indirector/none_spec.rb
index ae621c3e2..99383850b 100644
--- a/spec/unit/indirector/none_spec.rb
+++ b/spec/unit/indirector/none_spec.rb
@@ -1,33 +1,33 @@
require 'spec_helper'
require 'puppet/indirector/none'
describe Puppet::Indirector::None do
before do
Puppet::Indirector::Terminus.stubs(:register_terminus_class)
Puppet::Indirector::Indirection.stubs(:instance).returns(indirection)
module Testing; end
@none_class = class Testing::None < Puppet::Indirector::None
self
end
@data_binder = @none_class.new
end
let(:model) { mock('model') }
let(:request) { stub('request', :key => "port") }
let(:indirection) do
stub('indirection', :name => :none, :register_terminus_type => nil,
:model => model)
end
it "should not be the default data_binding_terminus" do
- Puppet.settings[:data_binding_terminus].should_not == 'none'
+ expect(Puppet.settings[:data_binding_terminus]).not_to eq('none')
end
describe "the behavior of the find method" do
it "should just return nil" do
- @data_binder.find(request).should be_nil
+ expect(@data_binder.find(request)).to be_nil
end
end
end
diff --git a/spec/unit/indirector/plain_spec.rb b/spec/unit/indirector/plain_spec.rb
index 554c64841..a7f8fdd2c 100755
--- a/spec/unit/indirector/plain_spec.rb
+++ b/spec/unit/indirector/plain_spec.rb
@@ -1,27 +1,27 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/plain'
describe Puppet::Indirector::Plain do
before do
Puppet::Indirector::Terminus.stubs(:register_terminus_class)
@model = mock 'model'
@indirection = stub 'indirection', :name => :mystuff, :register_terminus_type => nil, :model => @model
Puppet::Indirector::Indirection.stubs(:instance).returns(@indirection)
module Testing; end
@plain_class = class Testing::MyPlain < Puppet::Indirector::Plain
self
end
@searcher = @plain_class.new
@request = stub 'request', :key => "yay"
end
it "should return return an instance of the indirected model" do
object = mock 'object'
@model.expects(:new).with(@request.key).returns object
- @searcher.find(@request).should equal(object)
+ expect(@searcher.find(@request)).to equal(object)
end
end
diff --git a/spec/unit/indirector/report/msgpack_spec.rb b/spec/unit/indirector/report/msgpack_spec.rb
index 20bc225af..f28787c7c 100755
--- a/spec/unit/indirector/report/msgpack_spec.rb
+++ b/spec/unit/indirector/report/msgpack_spec.rb
@@ -1,28 +1,28 @@
#! /usr/bin/env ruby
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
- Puppet::Transaction::Report::Msgpack.superclass.should equal(Puppet::Indirector::Msgpack)
+ expect(Puppet::Transaction::Report::Msgpack.superclass).to equal(Puppet::Indirector::Msgpack)
end
it "should have documentation" do
- Puppet::Transaction::Report::Msgpack.doc.should_not be_nil
+ 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)
- Puppet::Transaction::Report::Msgpack.indirection.should equal(indirection)
+ expect(Puppet::Transaction::Report::Msgpack.indirection).to equal(indirection)
end
it "should have its name set to :msgpack" do
- Puppet::Transaction::Report::Msgpack.name.should == :msgpack
+ expect(Puppet::Transaction::Report::Msgpack.name).to eq(:msgpack)
end
it "should unconditionally save/load from the --lastrunreport setting" do
- subject.path(:me).should == Puppet[:lastrunreport]
+ expect(subject.path(:me)).to eq(Puppet[:lastrunreport])
end
end
diff --git a/spec/unit/indirector/report/processor_spec.rb b/spec/unit/indirector/report/processor_spec.rb
index 32e63e38c..9d7ace27a 100755
--- a/spec/unit/indirector/report/processor_spec.rb
+++ b/spec/unit/indirector/report/processor_spec.rb
@@ -1,100 +1,100 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/report/processor'
describe Puppet::Transaction::Report::Processor do
before do
Puppet.settings.stubs(:use).returns(true)
end
it "should provide a method for saving reports" do
- Puppet::Transaction::Report::Processor.new.should respond_to(:save)
+ expect(Puppet::Transaction::Report::Processor.new).to respond_to(:save)
end
it "should provide a method for cleaning reports" do
- Puppet::Transaction::Report::Processor.new.should respond_to(:destroy)
+ expect(Puppet::Transaction::Report::Processor.new).to respond_to(:destroy)
end
end
describe Puppet::Transaction::Report::Processor, " when processing a report" do
before do
Puppet.settings.stubs(:use)
@reporter = Puppet::Transaction::Report::Processor.new
@request = stub 'request', :instance => stub("report", :host => 'hostname'), :key => 'node'
end
it "should not save the report if reports are set to 'none'" do
Puppet::Reports.expects(:report).never
Puppet[:reports] = 'none'
request = Puppet::Indirector::Request.new(:indirection_name, :head, "key", nil)
report = Puppet::Transaction::Report.new('apply')
request.instance = report
@reporter.save(request)
end
it "should save the report with each configured report type" do
Puppet[:reports] = "one,two"
- @reporter.send(:reports).should == %w{one two}
+ expect(@reporter.send(:reports)).to eq(%w{one two})
Puppet::Reports.expects(:report).with('one')
Puppet::Reports.expects(: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 = mock()
store_report = mock()
store_report.expects(:destroy).with(@request.key)
Puppet::Reports.expects(:report).with('http').returns(http_report)
Puppet::Reports.expects(:report).with('store').returns(store_report)
@reporter.destroy(@request)
end
end
describe Puppet::Transaction::Report::Processor, " when processing a report" do
before do
Puppet[:reports] = "one"
Puppet.settings.stubs(:use)
@reporter = Puppet::Transaction::Report::Processor.new
@report_type = mock 'one'
@dup_report = mock 'dupe report'
@dup_report.stubs(:process)
@report = Puppet::Transaction::Report.new('apply')
@report.expects(:dup).returns(@dup_report)
@request = stub 'request', :instance => @report
Puppet::Reports.expects(:report).with("one").returns(@report_type)
@dup_report.expects(: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
@dup_report.expects(:process)
@reporter.save(@request)
end
it "should not raise exceptions" do
Puppet[:trace] = false
@dup_report.expects(:process).raises(ArgumentError)
- proc { @reporter.save(@request) }.should_not raise_error
+ expect { @reporter.save(@request) }.not_to raise_error
end
end
diff --git a/spec/unit/indirector/report/rest_spec.rb b/spec/unit/indirector/report/rest_spec.rb
index 352799343..8356c4cc4 100755
--- a/spec/unit/indirector/report/rest_spec.rb
+++ b/spec/unit/indirector/report/rest_spec.rb
@@ -1,67 +1,67 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/report/rest'
describe Puppet::Transaction::Report::Rest do
it "should be a subclass of Puppet::Indirector::REST" do
- Puppet::Transaction::Report::Rest.superclass.should equal(Puppet::Indirector::REST)
+ expect(Puppet::Transaction::Report::Rest.superclass).to equal(Puppet::Indirector::REST)
end
it "should use the :report_server setting in preference to :server" do
Puppet.settings[:server] = "server"
Puppet.settings[:report_server] = "report_server"
- Puppet::Transaction::Report::Rest.server.should == "report_server"
+ expect(Puppet::Transaction::Report::Rest.server).to eq("report_server")
end
it "should have a value for report_server and report_port" do
- Puppet::Transaction::Report::Rest.server.should_not be_nil
- Puppet::Transaction::Report::Rest.port.should_not be_nil
+ expect(Puppet::Transaction::Report::Rest.server).not_to be_nil
+ expect(Puppet::Transaction::Report::Rest.port).not_to be_nil
end
it "should use the :report SRV service" do
- Puppet::Transaction::Report::Rest.srv_service.should == :report
+ expect(Puppet::Transaction::Report::Rest.srv_service).to eq(:report)
end
let(:model) { Puppet::Transaction::Report }
let(:terminus_class) { Puppet::Transaction::Report::Rest }
let(:terminus) { model.indirection.terminus(:rest) }
let(:indirection) { model.indirection }
before(:each) do
Puppet::Transaction::Report.indirection.terminus_class = :rest
end
def mock_response(code, body, content_type='text/plain', encoding=nil)
obj = stub('http 200 ok', :code => code.to_s, :body => body)
obj.stubs(:[]).with('content-type').returns(content_type)
obj.stubs(:[]).with('content-encoding').returns(encoding)
obj.stubs(:[]).with(Puppet::Network::HTTP::HEADER_PUPPET_VERSION).returns(Puppet.version)
obj
end
def save_request(key, instance, options={})
Puppet::Indirector::Request.new(:report, :find, key, instance, options)
end
describe "#save" do
let(:http_method) { :put }
let(:response) { mock_response(200, 'body') }
let(:connection) { stub('mock http connection', :put => response, :verify_callback= => nil) }
let(:instance) { model.new('the thing', 'some contents') }
let(:request) { save_request(instance.name, instance) }
before :each do
terminus.stubs(:network).returns(connection)
end
it "deserializes the response as an array of report processor names" do
processors = ["store", "http"]
body = processors.to_pson()
response = mock_response('200', body, 'text/pson')
connection.expects(:put).returns response
- terminus.save(request).should == ["store", "http"]
+ expect(terminus.save(request)).to eq(["store", "http"])
end
end
end
diff --git a/spec/unit/indirector/report/yaml_spec.rb b/spec/unit/indirector/report/yaml_spec.rb
index a5daab268..cf073fbda 100755
--- a/spec/unit/indirector/report/yaml_spec.rb
+++ b/spec/unit/indirector/report/yaml_spec.rb
@@ -1,28 +1,28 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/transaction/report'
require 'puppet/indirector/report/yaml'
describe Puppet::Transaction::Report::Yaml do
it "should be a subclass of the Yaml terminus" do
- Puppet::Transaction::Report::Yaml.superclass.should equal(Puppet::Indirector::Yaml)
+ expect(Puppet::Transaction::Report::Yaml.superclass).to equal(Puppet::Indirector::Yaml)
end
it "should have documentation" do
- Puppet::Transaction::Report::Yaml.doc.should_not be_nil
+ expect(Puppet::Transaction::Report::Yaml.doc).not_to be_nil
end
it "should be registered with the report indirection" do
indirection = Puppet::Indirector::Indirection.instance(:report)
- Puppet::Transaction::Report::Yaml.indirection.should equal(indirection)
+ expect(Puppet::Transaction::Report::Yaml.indirection).to equal(indirection)
end
it "should have its name set to :yaml" do
- Puppet::Transaction::Report::Yaml.name.should == :yaml
+ expect(Puppet::Transaction::Report::Yaml.name).to eq(:yaml)
end
it "should unconditionally save/load from the --lastrunreport setting" do
- subject.path(:me).should == Puppet[:lastrunreport]
+ expect(subject.path(:me)).to eq(Puppet[:lastrunreport])
end
end
diff --git a/spec/unit/indirector/request_spec.rb b/spec/unit/indirector/request_spec.rb
index f198dd7fd..5393782e0 100755
--- a/spec/unit/indirector/request_spec.rb
+++ b/spec/unit/indirector/request_spec.rb
@@ -1,500 +1,500 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'matchers/json'
require 'puppet/indirector/request'
describe Puppet::Indirector::Request do
include JSONMatchers
describe "when initializing" do
it "should always convert the indirection name to a symbol" do
- Puppet::Indirector::Request.new("ind", :method, "mykey", nil).indirection_name.should == :ind
+ expect(Puppet::Indirector::Request.new("ind", :method, "mykey", nil).indirection_name).to eq(:ind)
end
it "should use provided value as the key if it is a string" do
- Puppet::Indirector::Request.new(:ind, :method, "mykey", nil).key.should == "mykey"
+ expect(Puppet::Indirector::Request.new(:ind, :method, "mykey", nil).key).to eq("mykey")
end
it "should use provided value as the key if it is a symbol" do
- Puppet::Indirector::Request.new(:ind, :method, :mykey, nil).key.should == :mykey
+ expect(Puppet::Indirector::Request.new(:ind, :method, :mykey, nil).key).to eq(:mykey)
end
it "should use the name of the provided instance as its key if an instance is provided as the key instead of a string" do
instance = mock 'instance', :name => "mykey"
request = Puppet::Indirector::Request.new(:ind, :method, nil, instance)
- request.key.should == "mykey"
- request.instance.should equal(instance)
+ expect(request.key).to eq("mykey")
+ expect(request.instance).to equal(instance)
end
it "should support options specified as a hash" do
expect { Puppet::Indirector::Request.new(:ind, :method, :key, nil, :one => :two) }.to_not raise_error
end
it "should support nil options" do
expect { Puppet::Indirector::Request.new(:ind, :method, :key, nil, nil) }.to_not raise_error
end
it "should support unspecified options" do
expect { Puppet::Indirector::Request.new(:ind, :method, :key, nil) }.to_not raise_error
end
it "should use an empty options hash if nil was provided" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil, nil).options.should == {}
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, nil).options).to eq({})
end
it "should default to a nil node" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil).node.should be_nil
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil).node).to be_nil
end
it "should set its node attribute if provided in the options" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil, :node => "foo.com").node.should == "foo.com"
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :node => "foo.com").node).to eq("foo.com")
end
it "should default to a nil ip" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil).ip.should be_nil
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil).ip).to be_nil
end
it "should set its ip attribute if provided in the options" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil, :ip => "192.168.0.1").ip.should == "192.168.0.1"
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :ip => "192.168.0.1").ip).to eq("192.168.0.1")
end
it "should default to being unauthenticated" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil).should_not be_authenticated
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil)).not_to be_authenticated
end
it "should set be marked authenticated if configured in the options" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil, :authenticated => "eh").should be_authenticated
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :authenticated => "eh")).to be_authenticated
end
it "should keep its options as a hash even if a node is specified" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil, :node => "eh").options.should be_instance_of(Hash)
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :node => "eh").options).to be_instance_of(Hash)
end
it "should keep its options as a hash even if another option is specified" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil, :foo => "bar").options.should be_instance_of(Hash)
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :foo => "bar").options).to be_instance_of(Hash)
end
it "should treat options other than :ip, :node, and :authenticated as options rather than attributes" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil, :server => "bar").options[:server].should == "bar"
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :server => "bar").options[:server]).to eq("bar")
end
it "should normalize options to use symbols as keys" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil, "foo" => "bar").options[:foo].should == "bar"
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, "foo" => "bar").options[:foo]).to eq("bar")
end
describe "and the request key is a URI" do
let(:file) { File.expand_path("/my/file with spaces") }
let(:an_environment) { Puppet::Node::Environment.create(:an_environment, []) }
let(:env_loaders) { Puppet::Environments::Static.new(an_environment) }
around(:each) do |example|
Puppet.override({ :environments => env_loaders }, "Static environment loader for specs") do
example.run
end
end
describe "and the URI is a 'file' URI" do
before do
@request = Puppet::Indirector::Request.new(:ind, :method, "#{URI.unescape(Puppet::Util.path_to_uri(file).to_s)}", nil)
end
it "should set the request key to the unescaped full file path" do
- @request.key.should == file
+ expect(@request.key).to eq(file)
end
it "should not set the protocol" do
- @request.protocol.should be_nil
+ expect(@request.protocol).to be_nil
end
it "should not set the port" do
- @request.port.should be_nil
+ expect(@request.port).to be_nil
end
it "should not set the server" do
- @request.server.should be_nil
+ expect(@request.server).to be_nil
end
end
it "should set the protocol to the URI scheme" do
- Puppet::Indirector::Request.new(:ind, :method, "http://host/an_environment", nil).protocol.should == "http"
+ expect(Puppet::Indirector::Request.new(:ind, :method, "http://host/an_environment", nil).protocol).to eq("http")
end
it "should set the server if a server is provided" do
- Puppet::Indirector::Request.new(:ind, :method, "http://host/an_environment", nil).server.should == "host"
+ expect(Puppet::Indirector::Request.new(:ind, :method, "http://host/an_environment", nil).server).to eq("host")
end
it "should set the server and port if both are provided" do
- Puppet::Indirector::Request.new(:ind, :method, "http://host:543/an_environment", nil).port.should == 543
+ expect(Puppet::Indirector::Request.new(:ind, :method, "http://host:543/an_environment", nil).port).to eq(543)
end
it "should default to the masterport if the URI scheme is 'puppet'" do
Puppet[:masterport] = "321"
- Puppet::Indirector::Request.new(:ind, :method, "puppet://host/an_environment", nil).port.should == 321
+ expect(Puppet::Indirector::Request.new(:ind, :method, "puppet://host/an_environment", nil).port).to eq(321)
end
it "should use the provided port if the URI scheme is not 'puppet'" do
- Puppet::Indirector::Request.new(:ind, :method, "http://host/an_environment", nil).port.should == 80
+ expect(Puppet::Indirector::Request.new(:ind, :method, "http://host/an_environment", nil).port).to eq(80)
end
it "should set the request key to the unescaped key part path from the URI" do
- Puppet::Indirector::Request.new(:ind, :method, "http://host/an_environment/terminus/stuff with spaces", nil).key.should == "stuff with spaces"
+ expect(Puppet::Indirector::Request.new(:ind, :method, "http://host/an_environment/terminus/stuff with spaces", nil).key).to eq("stuff with spaces")
end
it "should set the :uri attribute to the full URI" do
- Puppet::Indirector::Request.new(:ind, :method, "http:///an_environment/stu ff", nil).uri.should == 'http:///an_environment/stu ff'
+ expect(Puppet::Indirector::Request.new(:ind, :method, "http:///an_environment/stu ff", nil).uri).to eq('http:///an_environment/stu ff')
end
it "should not parse relative URI" do
- Puppet::Indirector::Request.new(:ind, :method, "foo/bar", nil).uri.should be_nil
+ expect(Puppet::Indirector::Request.new(:ind, :method, "foo/bar", nil).uri).to be_nil
end
it "should not parse opaque URI" do
- Puppet::Indirector::Request.new(:ind, :method, "mailto:joe", nil).uri.should be_nil
+ expect(Puppet::Indirector::Request.new(:ind, :method, "mailto:joe", nil).uri).to be_nil
end
end
it "should allow indication that it should not read a cached instance" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil, :ignore_cache => true).should be_ignore_cache
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :ignore_cache => true)).to be_ignore_cache
end
it "should default to not ignoring the cache" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil).should_not be_ignore_cache
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil)).not_to be_ignore_cache
end
it "should allow indication that it should not not read an instance from the terminus" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil, :ignore_terminus => true).should be_ignore_terminus
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :ignore_terminus => true)).to be_ignore_terminus
end
it "should default to not ignoring the terminus" do
- Puppet::Indirector::Request.new(:ind, :method, :key, nil).should_not be_ignore_terminus
+ expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil)).not_to be_ignore_terminus
end
end
it "should look use the Indirection class to return the appropriate indirection" do
ind = mock 'indirection'
Puppet::Indirector::Indirection.expects(:instance).with(:myind).returns ind
request = Puppet::Indirector::Request.new(:myind, :method, :key, nil)
- request.indirection.should equal(ind)
+ expect(request.indirection).to equal(ind)
end
it "should use its indirection to look up the appropriate model" do
ind = mock 'indirection'
Puppet::Indirector::Indirection.expects(:instance).with(:myind).returns ind
request = Puppet::Indirector::Request.new(:myind, :method, :key, nil)
ind.expects(:model).returns "mymodel"
- request.model.should == "mymodel"
+ expect(request.model).to eq("mymodel")
end
it "should fail intelligently when asked to find a model but the indirection cannot be found" do
Puppet::Indirector::Indirection.expects(:instance).with(:myind).returns nil
request = Puppet::Indirector::Request.new(:myind, :method, :key, nil)
expect { request.model }.to raise_error(ArgumentError)
end
it "should have a method for determining if the request is plural or singular" do
- Puppet::Indirector::Request.new(:myind, :method, :key, nil).should respond_to(:plural?)
+ expect(Puppet::Indirector::Request.new(:myind, :method, :key, nil)).to respond_to(:plural?)
end
it "should be considered plural if the method is 'search'" do
- Puppet::Indirector::Request.new(:myind, :search, :key, nil).should be_plural
+ expect(Puppet::Indirector::Request.new(:myind, :search, :key, nil)).to be_plural
end
it "should not be considered plural if the method is not 'search'" do
- Puppet::Indirector::Request.new(:myind, :find, :key, nil).should_not be_plural
+ expect(Puppet::Indirector::Request.new(:myind, :find, :key, nil)).not_to be_plural
end
it "should use its uri, if it has one, as its description" do
Puppet.override({
:environments => Puppet::Environments::Static.new(
Puppet::Node::Environment.create(:baz, [])
)},
"Static loader for spec") do
- Puppet::Indirector::Request.new(:myind, :find, "foo://bar/baz", nil).description.should == "foo://bar/baz"
+ expect(Puppet::Indirector::Request.new(:myind, :find, "foo://bar/baz", nil).description).to eq("foo://bar/baz")
end
end
it "should use its indirection name and key, if it has no uri, as its description" do
- Puppet::Indirector::Request.new(:myind, :find, "key", nil).description.should == "/myind/key"
+ expect(Puppet::Indirector::Request.new(:myind, :find, "key", nil).description).to eq("/myind/key")
end
it "should be able to return the URI-escaped key" do
- Puppet::Indirector::Request.new(:myind, :find, "my key", nil).escaped_key.should == URI.escape("my key")
+ expect(Puppet::Indirector::Request.new(:myind, :find, "my key", nil).escaped_key).to eq(URI.escape("my key"))
end
it "should set its environment to an environment instance when a string is specified as its environment" do
env = Puppet::Node::Environment.create(:foo, [])
Puppet.override(:environments => Puppet::Environments::Static.new(env)) do
- Puppet::Indirector::Request.new(:myind, :find, "my key", nil, :environment => "foo").environment.should == env
+ expect(Puppet::Indirector::Request.new(:myind, :find, "my key", nil, :environment => "foo").environment).to eq(env)
end
end
it "should use any passed in environment instances as its environment" do
env = Puppet::Node::Environment.create(:foo, [])
- Puppet::Indirector::Request.new(:myind, :find, "my key", nil, :environment => env).environment.should equal(env)
+ expect(Puppet::Indirector::Request.new(:myind, :find, "my key", nil, :environment => env).environment).to equal(env)
end
it "should use the current environment when none is provided" do
configured = Puppet::Node::Environment.create(:foo, [])
Puppet[:environment] = "foo"
expect(Puppet::Indirector::Request.new(:myind, :find, "my key", nil).environment).to eq(Puppet.lookup(:current_environment))
end
it "should support converting its options to a hash" do
- Puppet::Indirector::Request.new(:myind, :find, "my key", nil ).should respond_to(:to_hash)
+ expect(Puppet::Indirector::Request.new(:myind, :find, "my key", nil )).to respond_to(:to_hash)
end
it "should include all of its attributes when its options are converted to a hash" do
- Puppet::Indirector::Request.new(:myind, :find, "my key", nil, :node => 'foo').to_hash[:node].should == 'foo'
+ expect(Puppet::Indirector::Request.new(:myind, :find, "my key", nil, :node => 'foo').to_hash[:node]).to eq('foo')
end
describe "when building a query string from its options" do
def a_request_with_options(options)
Puppet::Indirector::Request.new(:myind, :find, "my key", nil, options)
end
def the_parsed_query_string_from(request)
CGI.parse(request.query_string.sub(/^\?/, ''))
end
it "should return an empty query string if there are no options" do
request = a_request_with_options(nil)
- request.query_string.should == ""
+ expect(request.query_string).to eq("")
end
it "should return an empty query string if the options are empty" do
request = a_request_with_options({})
- request.query_string.should == ""
+ expect(request.query_string).to eq("")
end
it "should include all options in the query string, separated by '&'" do
request = a_request_with_options(:one => "two", :three => "four")
- the_parsed_query_string_from(request).should == {
+ expect(the_parsed_query_string_from(request)).to eq({
"one" => ["two"],
"three" => ["four"]
- }
+ })
end
it "should ignore nil options" do
request = a_request_with_options(:one => "two", :three => nil)
- the_parsed_query_string_from(request).should == {
+ expect(the_parsed_query_string_from(request)).to eq({
"one" => ["two"]
- }
+ })
end
it "should convert 'true' option values into strings" do
request = a_request_with_options(:one => true)
- the_parsed_query_string_from(request).should == {
+ expect(the_parsed_query_string_from(request)).to eq({
"one" => ["true"]
- }
+ })
end
it "should convert 'false' option values into strings" do
request = a_request_with_options(:one => false)
- the_parsed_query_string_from(request).should == {
+ expect(the_parsed_query_string_from(request)).to eq({
"one" => ["false"]
- }
+ })
end
it "should convert to a string all option values that are integers" do
request = a_request_with_options(:one => 50)
- the_parsed_query_string_from(request).should == {
+ expect(the_parsed_query_string_from(request)).to eq({
"one" => ["50"]
- }
+ })
end
it "should convert to a string all option values that are floating point numbers" do
request = a_request_with_options(:one => 1.2)
- the_parsed_query_string_from(request).should == {
+ expect(the_parsed_query_string_from(request)).to eq({
"one" => ["1.2"]
- }
+ })
end
it "should CGI-escape all option values that are strings" do
request = a_request_with_options(:one => "one two")
- the_parsed_query_string_from(request).should == {
+ expect(the_parsed_query_string_from(request)).to eq({
"one" => ["one two"]
- }
+ })
end
it "should convert an array of values into multiple entries for the same key" do
request = a_request_with_options(:one => %w{one two})
- the_parsed_query_string_from(request).should == {
+ expect(the_parsed_query_string_from(request)).to eq({
"one" => ["one", "two"]
- }
+ })
end
it "should stringify simple data types inside an array" do
request = a_request_with_options(:one => ['one', nil])
- the_parsed_query_string_from(request).should == {
+ expect(the_parsed_query_string_from(request)).to eq({
"one" => ["one"]
- }
+ })
end
it "should error if an array contains another array" do
request = a_request_with_options(:one => ['one', ["not allowed"]])
expect { request.query_string }.to raise_error(ArgumentError)
end
it "should error if an array contains illegal data" do
request = a_request_with_options(:one => ['one', { :not => "allowed" }])
expect { request.query_string }.to raise_error(ArgumentError)
end
it "should convert to a string and CGI-escape all option values that are symbols" do
request = a_request_with_options(:one => :"sym bol")
- the_parsed_query_string_from(request).should == {
+ expect(the_parsed_query_string_from(request)).to eq({
"one" => ["sym bol"]
- }
+ })
end
it "should fail if options other than booleans or strings are provided" do
request = a_request_with_options(:one => { :one => :two })
expect { request.query_string }.to raise_error(ArgumentError)
end
end
context '#do_request' do
before :each do
@request = Puppet::Indirector::Request.new(:myind, :find, "my key", nil)
end
context 'when not using SRV records' do
before :each do
Puppet.settings[:use_srv_records] = false
end
it "yields the request with the default server and port when no server or port were specified on the original request" do
count = 0
rval = @request.do_request(:puppet, 'puppet.example.com', '90210') do |got|
count += 1
- got.server.should == 'puppet.example.com'
- got.port.should == '90210'
+ expect(got.server).to eq('puppet.example.com')
+ expect(got.port).to eq('90210')
'Block return value'
end
- count.should == 1
+ expect(count).to eq(1)
- rval.should == 'Block return value'
+ expect(rval).to eq('Block return value')
end
end
context 'when using SRV records' do
before :each do
Puppet.settings[:use_srv_records] = true
Puppet.settings[:srv_domain] = 'example.com'
end
it "yields the request with the original server and port unmodified" do
@request.server = 'puppet.example.com'
@request.port = '90210'
count = 0
rval = @request.do_request do |got|
count += 1
- got.server.should == 'puppet.example.com'
- got.port.should == '90210'
+ expect(got.server).to eq('puppet.example.com')
+ expect(got.port).to eq('90210')
'Block return value'
end
- count.should == 1
+ expect(count).to eq(1)
- rval.should == 'Block return value'
+ expect(rval).to eq('Block return value')
end
context "when SRV returns servers" do
before :each do
@dns_mock = mock('dns')
Resolv::DNS.expects(:new).returns(@dns_mock)
@port = 7205
@host = '_x-puppet._tcp.example.com'
@srv_records = [Resolv::DNS::Resource::IN::SRV.new(0, 0, @port, @host)]
@dns_mock.expects(:getresources).
with("_x-puppet._tcp.#{Puppet.settings[:srv_domain]}", Resolv::DNS::Resource::IN::SRV).
returns(@srv_records)
end
it "yields a request using the server and port from the SRV record" do
count = 0
rval = @request.do_request do |got|
count += 1
- got.server.should == '_x-puppet._tcp.example.com'
- got.port.should == 7205
+ expect(got.server).to eq('_x-puppet._tcp.example.com')
+ expect(got.port).to eq(7205)
@block_return
end
- count.should == 1
+ expect(count).to eq(1)
- rval.should == @block_return
+ expect(rval).to eq(@block_return)
end
it "should fall back to the default server when the block raises a SystemCallError" do
count = 0
second_pass = nil
rval = @request.do_request(:puppet, 'puppet', 8140) do |got|
count += 1
if got.server == '_x-puppet._tcp.example.com' then
raise SystemCallError, "example failure"
else
second_pass = got
end
@block_return
end
- second_pass.server.should == 'puppet'
- second_pass.port.should == 8140
- count.should == 2
+ expect(second_pass.server).to eq('puppet')
+ expect(second_pass.port).to eq(8140)
+ expect(count).to eq(2)
- rval.should == @block_return
+ expect(rval).to eq(@block_return)
end
end
end
end
describe "#remote?" do
def request(options = {})
Puppet::Indirector::Request.new('node', 'find', 'localhost', nil, options)
end
it "should not be unless node or ip is set" do
- request.should_not be_remote
+ expect(request).not_to be_remote
end
it "should be remote if node is set" do
- request(:node => 'example.com').should be_remote
+ expect(request(:node => 'example.com')).to be_remote
end
it "should be remote if ip is set" do
- request(:ip => '127.0.0.1').should be_remote
+ expect(request(:ip => '127.0.0.1')).to be_remote
end
it "should be remote if node and ip are set" do
- request(:node => 'example.com', :ip => '127.0.0.1').should be_remote
+ expect(request(:node => 'example.com', :ip => '127.0.0.1')).to be_remote
end
end
end
diff --git a/spec/unit/indirector/resource/ral_spec.rb b/spec/unit/indirector/resource/ral_spec.rb
index b05575694..3ade45596 100755
--- a/spec/unit/indirector/resource/ral_spec.rb
+++ b/spec/unit/indirector/resource/ral_spec.rb
@@ -1,131 +1,131 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "Puppet::Resource::Ral" do
it "disallows remote requests" do
expect(Puppet::Resource::Ral.new.allow_remote_requests?).to eq(false)
end
describe "find" do
before do
@request = stub 'request', :key => "user/root"
end
it "should find an existing instance" do
my_resource = stub "my user resource"
wrong_instance = stub "wrong user", :name => "bob"
my_instance = stub "my user", :name => "root", :to_resource => my_resource
require 'puppet/type/user'
Puppet::Type::User.expects(:instances).returns([ wrong_instance, my_instance, wrong_instance ])
- Puppet::Resource::Ral.new.find(@request).should == my_resource
+ expect(Puppet::Resource::Ral.new.find(@request)).to eq(my_resource)
end
it "should produce Puppet::Error instead of ArgumentError" do
@bad_request = stub 'thiswillcauseanerror', :key => "thiswill/causeanerror"
expect{Puppet::Resource::Ral.new.find(@bad_request)}.to raise_error(Puppet::Error)
end
it "if there is no instance, it should create one" do
wrong_instance = stub "wrong user", :name => "bob"
root = mock "Root User"
root_resource = mock "Root Resource"
require 'puppet/type/user'
Puppet::Type::User.expects(:instances).returns([ wrong_instance, wrong_instance ])
Puppet::Type::User.expects(:new).with(has_entry(:name => "root")).returns(root)
root.expects(:to_resource).returns(root_resource)
result = Puppet::Resource::Ral.new.find(@request)
- result.should == root_resource
+ expect(result).to eq(root_resource)
end
end
describe "search" do
before do
@request = stub 'request', :key => "user/", :options => {}
end
it "should convert ral resources into regular resources" do
my_resource = stub "my user resource"
my_instance = stub "my user", :name => "root", :to_resource => my_resource
require 'puppet/type/user'
Puppet::Type::User.expects(:instances).returns([ my_instance ])
- Puppet::Resource::Ral.new.search(@request).should == [my_resource]
+ expect(Puppet::Resource::Ral.new.search(@request)).to eq([my_resource])
end
it "should filter results by name if there's a name in the key" do
my_resource = stub "my user resource"
my_resource.stubs(:to_resource).returns(my_resource)
my_resource.stubs(:[]).with(:name).returns("root")
wrong_resource = stub "wrong resource"
wrong_resource.stubs(:to_resource).returns(wrong_resource)
wrong_resource.stubs(:[]).with(:name).returns("bad")
my_instance = stub "my user", :to_resource => my_resource
wrong_instance = stub "wrong user", :to_resource => wrong_resource
@request = stub 'request', :key => "user/root", :options => {}
require 'puppet/type/user'
Puppet::Type::User.expects(:instances).returns([ my_instance, wrong_instance ])
- Puppet::Resource::Ral.new.search(@request).should == [my_resource]
+ expect(Puppet::Resource::Ral.new.search(@request)).to eq([my_resource])
end
it "should filter results by query parameters" do
wrong_resource = stub "my user resource"
wrong_resource.stubs(:to_resource).returns(wrong_resource)
wrong_resource.stubs(:[]).with(:name).returns("root")
my_resource = stub "wrong resource"
my_resource.stubs(:to_resource).returns(my_resource)
my_resource.stubs(:[]).with(:name).returns("bob")
my_instance = stub "my user", :to_resource => my_resource
wrong_instance = stub "wrong user", :to_resource => wrong_resource
@request = stub 'request', :key => "user/", :options => {:name => "bob"}
require 'puppet/type/user'
Puppet::Type::User.expects(:instances).returns([ my_instance, wrong_instance ])
- Puppet::Resource::Ral.new.search(@request).should == [my_resource]
+ expect(Puppet::Resource::Ral.new.search(@request)).to eq([my_resource])
end
it "should return sorted results" do
a_resource = stub "alice resource"
a_resource.stubs(:to_resource).returns(a_resource)
a_resource.stubs(:title).returns("alice")
b_resource = stub "bob resource"
b_resource.stubs(:to_resource).returns(b_resource)
b_resource.stubs(:title).returns("bob")
a_instance = stub "alice user", :to_resource => a_resource
b_instance = stub "bob user", :to_resource => b_resource
@request = stub 'request', :key => "user/", :options => {}
require 'puppet/type/user'
Puppet::Type::User.expects(:instances).returns([ b_instance, a_instance ])
- Puppet::Resource::Ral.new.search(@request).should == [a_resource, b_resource]
+ expect(Puppet::Resource::Ral.new.search(@request)).to eq([a_resource, b_resource])
end
end
describe "save" do
it "returns a report covering the application of the given resource to the system" do
resource = Puppet::Resource.new(:notify, "the title")
ral = Puppet::Resource::Ral.new
applied_resource, report = ral.save(Puppet::Indirector::Request.new(:ral, :save, 'testing', resource, :environment => Puppet::Node::Environment.remote(:testing)))
expect(applied_resource.title).to eq("the title")
expect(report.environment).to eq("testing")
expect(report.resource_statuses["Notify[the title]"].changed).to eq(true)
end
end
end
diff --git a/spec/unit/indirector/resource_type/parser_spec.rb b/spec/unit/indirector/resource_type/parser_spec.rb
index fdbab84e7..bf01fb1b7 100755
--- a/spec/unit/indirector/resource_type/parser_spec.rb
+++ b/spec/unit/indirector/resource_type/parser_spec.rb
@@ -1,254 +1,254 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/resource_type/parser'
require 'puppet_spec/files'
describe Puppet::Indirector::ResourceType::Parser do
include PuppetSpec::Files
let(:environmentpath) { tmpdir("envs") }
let(:modulepath) { "#{environmentpath}/test/modules" }
let(:environment) { Puppet::Node::Environment.create(:test, [modulepath]) }
before do
@terminus = Puppet::Indirector::ResourceType::Parser.new
@request = Puppet::Indirector::Request.new(:resource_type, :find, "foo", nil)
@request.environment = environment
@krt = @request.environment.known_resource_types
end
it "should be registered with the resource_type indirection" do
- Puppet::Indirector::Terminus.terminus_class(:resource_type, :parser).should equal(Puppet::Indirector::ResourceType::Parser)
+ expect(Puppet::Indirector::Terminus.terminus_class(:resource_type, :parser)).to equal(Puppet::Indirector::ResourceType::Parser)
end
describe "when finding" do
it "should return any found type from the request's environment" do
type = Puppet::Resource::Type.new(:hostclass, "foo")
@request.environment.known_resource_types.add(type)
- @terminus.find(@request).should == type
+ expect(@terminus.find(@request)).to eq(type)
end
it "should attempt to load the type if none is found in memory" do
FileUtils.mkdir_p(modulepath)
# Make a new request, since we've reset the env
request = Puppet::Indirector::Request.new(:resource_type, :find, "foo::bar", nil)
request.environment = environment
manifest_path = File.join(modulepath, "foo", "manifests")
FileUtils.mkdir_p(manifest_path)
File.open(File.join(manifest_path, "bar.pp"), "w") { |f| f.puts "class foo::bar {}" }
result = @terminus.find(request)
- result.should be_instance_of(Puppet::Resource::Type)
- result.name.should == "foo::bar"
+ expect(result).to be_instance_of(Puppet::Resource::Type)
+ expect(result.name).to eq("foo::bar")
end
it "should return nil if no type can be found" do
- @terminus.find(@request).should be_nil
+ expect(@terminus.find(@request)).to be_nil
end
it "should prefer definitions to nodes" do
type = @krt.add(Puppet::Resource::Type.new(:hostclass, "foo"))
node = @krt.add(Puppet::Resource::Type.new(:node, "foo"))
- @terminus.find(@request).should == type
+ expect(@terminus.find(@request)).to eq(type)
end
end
describe "when searching" do
describe "when the search key is a wildcard" do
before do
@request.key = "*"
end
it "should use the request's environment's list of known resource types" do
@request.environment.known_resource_types.expects(:hostclasses).returns({})
@terminus.search(@request)
end
it "should return all results if '*' is provided as the search string" do
type = @krt.add(Puppet::Resource::Type.new(:hostclass, "foo"))
node = @krt.add(Puppet::Resource::Type.new(:node, "bar"))
define = @krt.add(Puppet::Resource::Type.new(:definition, "baz"))
result = @terminus.search(@request)
- result.should be_include(type)
- result.should be_include(node)
- result.should be_include(define)
+ expect(result).to be_include(type)
+ expect(result).to be_include(node)
+ expect(result).to be_include(define)
end
it "should return all known types" do
type = @krt.add(Puppet::Resource::Type.new(:hostclass, "foo"))
node = @krt.add(Puppet::Resource::Type.new(:node, "bar"))
define = @krt.add(Puppet::Resource::Type.new(:definition, "baz"))
result = @terminus.search(@request)
- result.should be_include(type)
- result.should be_include(node)
- result.should be_include(define)
+ expect(result).to be_include(type)
+ expect(result).to be_include(node)
+ expect(result).to be_include(define)
end
it "should not return the 'main' class" do
main = @krt.add(Puppet::Resource::Type.new(:hostclass, ""))
# So there is a return value
foo = @krt.add(Puppet::Resource::Type.new(:hostclass, "foo"))
- @terminus.search(@request).should_not be_include(main)
+ expect(@terminus.search(@request)).not_to be_include(main)
end
it "should return nil if no types can be found" do
- @terminus.search(@request).should be_nil
+ expect(@terminus.search(@request)).to be_nil
end
it "should load all resource types from all search paths" do
dir = tmpdir("searching_in_all")
first = File.join(dir, "first")
second = File.join(dir, "second")
FileUtils.mkdir_p(first)
FileUtils.mkdir_p(second)
environment = Puppet::Node::Environment.create(:test, [first, second])
# Make a new request, since we've reset the env
request = Puppet::Indirector::Request.new(:resource_type, :search, "*", nil)
request.environment = environment
onepath = File.join(first, "one", "manifests")
FileUtils.mkdir_p(onepath)
twopath = File.join(first, "two", "manifests")
FileUtils.mkdir_p(twopath)
File.open(File.join(onepath, "oneklass.pp"), "w") { |f| f.puts "class one::oneklass {}" }
File.open(File.join(twopath, "twoklass.pp"), "w") { |f| f.puts "class two::twoklass {}" }
result = @terminus.search(request)
- result.find { |t| t.name == "one::oneklass" }.should be_instance_of(Puppet::Resource::Type)
- result.find { |t| t.name == "two::twoklass" }.should be_instance_of(Puppet::Resource::Type)
+ expect(result.find { |t| t.name == "one::oneklass" }).to be_instance_of(Puppet::Resource::Type)
+ expect(result.find { |t| t.name == "two::twoklass" }).to be_instance_of(Puppet::Resource::Type)
end
context "when specifying a 'kind' parameter" do
before :each do
@klass = @krt.add(Puppet::Resource::Type.new(:hostclass, "foo"))
@node = @krt.add(Puppet::Resource::Type.new(:node, "bar"))
@define = @krt.add(Puppet::Resource::Type.new(:definition, "baz"))
end
it "should raise an error if you pass an invalid kind filter" do
@request.options[:kind] = "i bet you don't have a kind called this"
expect {
@terminus.search(@request)
}.to raise_error(ArgumentError, /Unrecognized kind filter/)
end
it "should support filtering for only hostclass results" do
@request.options[:kind] = "class"
result = @terminus.search(@request)
- result.should be_include(@klass)
- result.should_not be_include(@node)
- result.should_not be_include(@define)
+ expect(result).to be_include(@klass)
+ expect(result).not_to be_include(@node)
+ expect(result).not_to be_include(@define)
end
it "should support filtering for only node results" do
@request.options[:kind] = "node"
result = @terminus.search(@request)
- result.should_not be_include(@klass)
- result.should be_include(@node)
- result.should_not be_include(@define)
+ expect(result).not_to be_include(@klass)
+ expect(result).to be_include(@node)
+ expect(result).not_to be_include(@define)
end
it "should support filtering for only definition results" do
@request.options[:kind] = "defined_type"
result = @terminus.search(@request)
- result.should_not be_include(@klass)
- result.should_not be_include(@node)
- result.should be_include(@define)
+ expect(result).not_to be_include(@klass)
+ expect(result).not_to be_include(@node)
+ expect(result).to be_include(@define)
end
end
end
context "when the search string is not a wildcard" do
it "should treat any search string as a regex" do
@request.key = "a"
foo = @krt.add(Puppet::Resource::Type.new(:hostclass, "foo"))
bar = @krt.add(Puppet::Resource::Type.new(:hostclass, "bar"))
baz = @krt.add(Puppet::Resource::Type.new(:hostclass, "baz"))
result = @terminus.search(@request)
- result.should be_include(bar)
- result.should be_include(baz)
- result.should_not be_include(foo)
+ expect(result).to be_include(bar)
+ expect(result).to be_include(baz)
+ expect(result).not_to be_include(foo)
end
it "should support kind filtering with a regex" do
@request.key = "foo"
@request.options[:kind] = "class"
foobar = @krt.add(Puppet::Resource::Type.new(:hostclass, "foobar"))
foobaz = @krt.add(Puppet::Resource::Type.new(:hostclass, "foobaz"))
foobam = @krt.add(Puppet::Resource::Type.new(:definition, "foobam"))
fooball = @krt.add(Puppet::Resource::Type.new(:node, "fooball"))
result = @terminus.search(@request)
- result.should be_include(foobar)
- result.should be_include(foobaz)
- result.should_not be_include(foobam)
- result.should_not be_include(fooball)
+ expect(result).to be_include(foobar)
+ expect(result).to be_include(foobaz)
+ expect(result).not_to be_include(foobam)
+ expect(result).not_to be_include(fooball)
end
it "should fail if a provided search string is not a valid regex" do
@request.key = "*foo*"
# Add one instance so we don't just get an empty array"
@krt.add(Puppet::Resource::Type.new(:hostclass, "foo"))
- lambda { @terminus.search(@request) }.should raise_error(ArgumentError)
+ expect { @terminus.search(@request) }.to raise_error(ArgumentError)
end
end
it "should not return the 'main' class" do
main = @krt.add(Puppet::Resource::Type.new(:hostclass, ""))
# So there is a return value
foo = @krt.add(Puppet::Resource::Type.new(:hostclass, "foo"))
- @terminus.search(@request).should_not be_include(main)
+ expect(@terminus.search(@request)).not_to be_include(main)
end
it "should return nil if no types can be found" do
- @terminus.search(@request).should be_nil
+ expect(@terminus.search(@request)).to be_nil
end
it "should load all resource types from all search paths" do
dir = tmpdir("searching_in_all")
first = File.join(dir, "first")
second = File.join(dir, "second")
FileUtils.mkdir_p(first)
FileUtils.mkdir_p(second)
environment = Puppet::Node::Environment.create(:test, [first,second])
# Make a new request, since we've reset the env
request = Puppet::Indirector::Request.new(:resource_type, :search, "*", nil)
request.environment = environment
onepath = File.join(first, "one", "manifests")
FileUtils.mkdir_p(onepath)
twopath = File.join(first, "two", "manifests")
FileUtils.mkdir_p(twopath)
File.open(File.join(onepath, "oneklass.pp"), "w") { |f| f.puts "class one::oneklass {}" }
File.open(File.join(twopath, "twoklass.pp"), "w") { |f| f.puts "class two::twoklass {}" }
result = @terminus.search(request)
- result.find { |t| t.name == "one::oneklass" }.should be_instance_of(Puppet::Resource::Type)
- result.find { |t| t.name == "two::twoklass" }.should be_instance_of(Puppet::Resource::Type)
+ expect(result.find { |t| t.name == "one::oneklass" }).to be_instance_of(Puppet::Resource::Type)
+ expect(result.find { |t| t.name == "two::twoklass" }).to be_instance_of(Puppet::Resource::Type)
end
end
end
diff --git a/spec/unit/indirector/resource_type/rest_spec.rb b/spec/unit/indirector/resource_type/rest_spec.rb
index e3239c98b..bd68aedf8 100755
--- a/spec/unit/indirector/resource_type/rest_spec.rb
+++ b/spec/unit/indirector/resource_type/rest_spec.rb
@@ -1,14 +1,14 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/resource_type/rest'
describe Puppet::Indirector::ResourceType::Rest do
it "should be registered with the resource_type indirection" do
- Puppet::Indirector::Terminus.terminus_class(:resource_type, :rest).should equal(Puppet::Indirector::ResourceType::Rest)
+ expect(Puppet::Indirector::Terminus.terminus_class(:resource_type, :rest)).to equal(Puppet::Indirector::ResourceType::Rest)
end
it "should be a subclass of Puppet::Indirector::Rest" do
- Puppet::Indirector::ResourceType::Rest.superclass.should == Puppet::Indirector::REST
+ expect(Puppet::Indirector::ResourceType::Rest.superclass).to eq(Puppet::Indirector::REST)
end
end
diff --git a/spec/unit/indirector/rest_spec.rb b/spec/unit/indirector/rest_spec.rb
index 18266d632..76043b975 100755
--- a/spec/unit/indirector/rest_spec.rb
+++ b/spec/unit/indirector/rest_spec.rb
@@ -1,574 +1,574 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector'
require 'puppet/indirector/errors'
require 'puppet/indirector/rest'
require 'puppet/util/psych_support'
HTTP_ERROR_CODES = [300, 400, 500]
# Just one from each category since the code makes no real distinctions
shared_examples_for "a REST terminus method" do |terminus_method|
HTTP_ERROR_CODES.each do |code|
describe "when the response code is #{code}" do
let(:response) { mock_response(code, 'error messaged!!!') }
it "raises an http error with the body of the response" do
expect {
terminus.send(terminus_method, request)
}.to raise_error(Net::HTTPError, "Error #{code} on SERVER: #{response.body}")
end
it "does not attempt to deserialize the response" do
model.expects(:convert_from).never
expect {
terminus.send(terminus_method, request)
}.to raise_error(Net::HTTPError)
end
# I'm not sure what this means or if it's used
it "if the body is empty raises an http error with the response header" do
response.stubs(:body).returns ""
response.stubs(:message).returns "fhqwhgads"
expect {
terminus.send(terminus_method, request)
}.to raise_error(Net::HTTPError, "Error #{code} on SERVER: #{response.message}")
end
describe "and the body is compressed" do
it "raises an http error with the decompressed body of the response" do
uncompressed_body = "why"
compressed_body = Zlib::Deflate.deflate(uncompressed_body)
response = mock_response(code, compressed_body, 'text/plain', 'deflate')
connection.expects(http_method).returns(response)
expect {
terminus.send(terminus_method, request)
}.to raise_error(Net::HTTPError, "Error #{code} on SERVER: #{uncompressed_body}")
end
end
end
end
end
shared_examples_for "a deserializing terminus method" do |terminus_method|
describe "when the response has no content-type" do
let(:response) { mock_response(200, "body", nil, nil) }
it "raises an error" do
expect {
terminus.send(terminus_method, request)
}.to raise_error(RuntimeError, "No content type in http response; cannot parse")
end
end
it "doesn't catch errors in deserialization" do
model.expects(:convert_from).raises(Puppet::Error, "Whoa there")
expect { terminus.send(terminus_method, request) }.to raise_error(Puppet::Error, "Whoa there")
end
end
describe Puppet::Indirector::REST do
before :all do
class Puppet::TestModel
include Puppet::Util::PsychSupport
extend Puppet::Indirector
indirects :test_model
attr_accessor :name, :data
def initialize(name = "name", data = '')
@name = name
@data = data
end
def self.convert_from(format, string)
new('', string)
end
def self.convert_from_multiple(format, string)
string.split(',').collect { |s| convert_from(format, s) }
end
def to_data_hash
{ 'name' => @name, 'data' => @data }
end
def ==(other)
other.is_a? Puppet::TestModel and other.name == name and other.data == data
end
end
# The subclass must not be all caps even though the superclass is
class Puppet::TestModel::Rest < Puppet::Indirector::REST
end
Puppet::TestModel.indirection.terminus_class = :rest
end
after :all do
Puppet::TestModel.indirection.delete
# Remove the class, unlinking it from the rest of the system.
Puppet.send(:remove_const, :TestModel)
end
let(:terminus_class) { Puppet::TestModel::Rest }
let(:terminus) { Puppet::TestModel.indirection.terminus(:rest) }
let(:indirection) { Puppet::TestModel.indirection }
let(:model) { Puppet::TestModel }
let(:url_prefix) { "#{Puppet::Network::HTTP::MASTER_URL_PREFIX}/v3"}
around(:each) do |example|
Puppet.override(:current_environment => Puppet::Node::Environment.create(:production, [])) do
example.run
end
end
def mock_response(code, body, content_type='text/plain', encoding=nil)
obj = stub('http 200 ok', :code => code.to_s, :body => body)
obj.stubs(:[]).with('content-type').returns(content_type)
obj.stubs(:[]).with('content-encoding').returns(encoding)
obj.stubs(:[]).with(Puppet::Network::HTTP::HEADER_PUPPET_VERSION).returns(Puppet.version)
obj
end
def find_request(key, options={})
Puppet::Indirector::Request.new(:test_model, :find, key, nil, options)
end
def head_request(key, options={})
Puppet::Indirector::Request.new(:test_model, :head, key, nil, options)
end
def search_request(key, options={})
Puppet::Indirector::Request.new(:test_model, :search, key, nil, options)
end
def delete_request(key, options={})
Puppet::Indirector::Request.new(:test_model, :destroy, key, nil, options)
end
def save_request(key, instance, options={})
Puppet::Indirector::Request.new(:test_model, :save, key, instance, options)
end
it "should have a method for specifying what setting a subclass should use to retrieve its server" do
- terminus_class.should respond_to(:use_server_setting)
+ expect(terminus_class).to respond_to(:use_server_setting)
end
it "should use any specified setting to pick the server" do
terminus_class.expects(:server_setting).returns :ca_server
Puppet[:ca_server] = "myserver"
- terminus_class.server.should == "myserver"
+ expect(terminus_class.server).to eq("myserver")
end
it "should default to :server for the server setting" do
terminus_class.expects(:server_setting).returns nil
Puppet[:server] = "myserver"
- terminus_class.server.should == "myserver"
+ expect(terminus_class.server).to eq("myserver")
end
it "should have a method for specifying what setting a subclass should use to retrieve its port" do
- terminus_class.should respond_to(:use_port_setting)
+ expect(terminus_class).to respond_to(:use_port_setting)
end
it "should use any specified setting to pick the port" do
terminus_class.expects(:port_setting).returns :ca_port
Puppet[:ca_port] = "321"
- terminus_class.port.should == 321
+ expect(terminus_class.port).to eq(321)
end
it "should default to :port for the port setting" do
terminus_class.expects(:port_setting).returns nil
Puppet[:masterport] = "543"
- terminus_class.port.should == 543
+ expect(terminus_class.port).to eq(543)
end
it 'should default to :puppet for the srv_service' do
- Puppet::Indirector::REST.srv_service.should == :puppet
+ expect(Puppet::Indirector::REST.srv_service).to eq(:puppet)
end
describe "when creating an HTTP client" do
it "should use the class's server and port if the indirection request provides neither" do
@request = stub 'request', :key => "foo", :server => nil, :port => nil
terminus.class.expects(:port).returns 321
terminus.class.expects(:server).returns "myserver"
Puppet::Network::HttpPool.expects(:http_instance).with("myserver", 321).returns "myconn"
- terminus.network(@request).should == "myconn"
+ expect(terminus.network(@request)).to eq("myconn")
end
it "should use the server from the indirection request if one is present" do
@request = stub 'request', :key => "foo", :server => "myserver", :port => nil
terminus.class.stubs(:port).returns 321
Puppet::Network::HttpPool.expects(:http_instance).with("myserver", 321).returns "myconn"
- terminus.network(@request).should == "myconn"
+ expect(terminus.network(@request)).to eq("myconn")
end
it "should use the port from the indirection request if one is present" do
@request = stub 'request', :key => "foo", :server => nil, :port => 321
terminus.class.stubs(:server).returns "myserver"
Puppet::Network::HttpPool.expects(:http_instance).with("myserver", 321).returns "myconn"
- terminus.network(@request).should == "myconn"
+ expect(terminus.network(@request)).to eq("myconn")
end
end
describe "#find" do
let(:http_method) { :get }
let(:response) { mock_response(200, 'body') }
let(:connection) { stub('mock http connection', :get => response, :verify_callback= => nil) }
let(:request) { find_request('foo') }
before :each do
terminus.stubs(:network).returns(connection)
end
it_behaves_like 'a REST terminus method', :find
it_behaves_like 'a deserializing terminus method', :find
describe "with a long set of parameters" do
it "calls post on the connection with the query params in the body" do
params = {}
'aa'.upto('zz') do |s|
params[s] = 'foo'
end
# The request special-cases this parameter, and it
# won't be passed on to the server, so we remove it here
# to avoid a failure.
params.delete('ip')
params["environment"] = "production"
request = find_request('whoa', params)
connection.expects(:post).with do |uri, body|
body.split("&").sort == params.map {|key,value| "#{key}=#{value}"}.sort
end.returns(mock_response(200, 'body'))
terminus.find(request)
end
end
describe "with no parameters" do
it "calls get on the connection" do
request = find_request('foo bar')
connection.expects(:get).with("#{url_prefix}/test_model/foo%20bar?environment=production&", anything).returns(mock_response('200', 'response body'))
- terminus.find(request).should == model.new('foo bar', 'response body')
+ expect(terminus.find(request)).to eq(model.new('foo bar', 'response body'))
end
end
it "returns nil on 404" do
response = mock_response('404', nil)
connection.expects(:get).returns(response)
- terminus.find(request).should == nil
+ expect(terminus.find(request)).to eq(nil)
end
it 'raises no warning for a 404 (when not asked to do so)' do
response = mock_response('404', 'this is the notfound you are looking for')
connection.expects(:get).returns(response)
expect{terminus.find(request)}.to_not raise_error()
end
context 'when fail_on_404 is used in request' do
it 'raises an error for a 404 when asked to do so' do
request = find_request('foo', :fail_on_404 => true)
response = mock_response('404', 'this is the notfound you are looking for')
connection.expects(:get).returns(response)
expect do
terminus.find(request)
end.to raise_error(
Puppet::Error,
"Find #{url_prefix}/test_model/foo?environment=production&fail_on_404=true resulted in 404 with the message: this is the notfound you are looking for")
end
it 'truncates the URI when it is very long' do
request = find_request('foo', :fail_on_404 => true, :long_param => ('A' * 100) + 'B')
response = mock_response('404', 'this is the notfound you are looking for')
connection.expects(:get).returns(response)
expect do
terminus.find(request)
end.to raise_error(
Puppet::Error,
/\/test_model\/foo.*\?environment=production&.*long_param=A+\.\.\..*resulted in 404 with the message/)
end
it 'does not truncate the URI when logging debug information' do
Puppet.debug = true
request = find_request('foo', :fail_on_404 => true, :long_param => ('A' * 100) + 'B')
response = mock_response('404', 'this is the notfound you are looking for')
connection.expects(:get).returns(response)
expect do
terminus.find(request)
end.to raise_error(
Puppet::Error,
/\/test_model\/foo.*\?environment=production&.*long_param=A+B.*resulted in 404 with the message/)
end
end
it "asks the model to deserialize the response body and sets the name on the resulting object to the find key" do
connection.expects(:get).returns response
model.expects(:convert_from).with(response['content-type'], response.body).returns(
model.new('overwritten', 'decoded body')
)
- terminus.find(request).should == model.new('foo', 'decoded body')
+ expect(terminus.find(request)).to eq(model.new('foo', 'decoded body'))
end
it "doesn't require the model to support name=" do
connection.expects(:get).returns response
instance = model.new('name', 'decoded body')
model.expects(:convert_from).with(response['content-type'], response.body).returns(instance)
instance.expects(:respond_to?).with(:name=).returns(false)
instance.expects(:name=).never
- terminus.find(request).should == model.new('name', 'decoded body')
+ expect(terminus.find(request)).to eq(model.new('name', 'decoded body'))
end
it "provides an Accept header containing the list of supported formats joined with commas" do
connection.expects(:get).with(anything, has_entry("Accept" => "supported, formats")).returns(response)
terminus.model.expects(:supported_formats).returns %w{supported formats}
terminus.find(request)
end
it "adds an Accept-Encoding header" do
terminus.expects(:add_accept_encoding).returns({"accept-encoding" => "gzip"})
connection.expects(:get).with(anything, has_entry("accept-encoding" => "gzip")).returns(response)
terminus.find(request)
end
it "uses only the mime-type from the content-type header when asking the model to deserialize" do
response = mock_response('200', 'mydata', "text/plain; charset=utf-8")
connection.expects(:get).returns(response)
model.expects(:convert_from).with("text/plain", "mydata").returns "myobject"
- terminus.find(request).should == "myobject"
+ expect(terminus.find(request)).to eq("myobject")
end
it "decompresses the body before passing it to the model for deserialization" do
uncompressed_body = "Why hello there"
compressed_body = Zlib::Deflate.deflate(uncompressed_body)
response = mock_response('200', compressed_body, 'text/plain', 'deflate')
connection.expects(:get).returns(response)
model.expects(:convert_from).with("text/plain", uncompressed_body).returns "myobject"
- terminus.find(request).should == "myobject"
+ expect(terminus.find(request)).to eq("myobject")
end
end
describe "#head" do
let(:http_method) { :head }
let(:response) { mock_response(200, nil) }
let(:connection) { stub('mock http connection', :head => response, :verify_callback= => nil) }
let(:request) { head_request('foo') }
before :each do
terminus.stubs(:network).returns(connection)
end
it_behaves_like 'a REST terminus method', :head
it "returns true if there was a successful http response" do
connection.expects(:head).returns mock_response('200', nil)
- terminus.head(request).should == true
+ expect(terminus.head(request)).to eq(true)
end
it "returns false on a 404 response" do
connection.expects(:head).returns mock_response('404', nil)
- terminus.head(request).should == false
+ expect(terminus.head(request)).to eq(false)
end
end
describe "#search" do
let(:http_method) { :get }
let(:response) { mock_response(200, 'data1,data2,data3') }
let(:connection) { stub('mock http connection', :get => response, :verify_callback= => nil) }
let(:request) { search_request('foo') }
before :each do
terminus.stubs(:network).returns(connection)
end
it_behaves_like 'a REST terminus method', :search
it_behaves_like 'a deserializing terminus method', :search
it "should call the GET http method on a network connection" do
connection.expects(:get).with("#{url_prefix}/test_models/foo?environment=production&", has_key('Accept')).returns mock_response(200, 'data3, data4')
terminus.search(request)
end
it "returns an empty list on 404" do
response = mock_response('404', nil)
connection.expects(:get).returns(response)
- terminus.search(request).should == []
+ expect(terminus.search(request)).to eq([])
end
it "asks the model to deserialize the response body into multiple instances" do
- terminus.search(request).should == [model.new('', 'data1'), model.new('', 'data2'), model.new('', 'data3')]
+ expect(terminus.search(request)).to eq([model.new('', 'data1'), model.new('', 'data2'), model.new('', 'data3')])
end
it "should provide an Accept header containing the list of supported formats joined with commas" do
connection.expects(:get).with(anything, has_entry("Accept" => "supported, formats")).returns(mock_response(200, ''))
terminus.model.expects(:supported_formats).returns %w{supported formats}
terminus.search(request)
end
it "should return an empty array if serialization returns nil" do
model.stubs(:convert_from_multiple).returns nil
- terminus.search(request).should == []
+ expect(terminus.search(request)).to eq([])
end
end
describe "#destroy" do
let(:http_method) { :delete }
let(:response) { mock_response(200, 'body') }
let(:connection) { stub('mock http connection', :delete => response, :verify_callback= => nil) }
let(:request) { delete_request('foo') }
before :each do
terminus.stubs(:network).returns(connection)
end
it_behaves_like 'a REST terminus method', :destroy
it_behaves_like 'a deserializing terminus method', :destroy
it "should call the DELETE http method on a network connection" do
connection.expects(:delete).with("#{url_prefix}/test_model/foo?environment=production&", has_key('Accept')).returns(response)
terminus.destroy(request)
end
it "should fail if any options are provided, since DELETE apparently does not support query options" do
request = delete_request('foo', :one => "two", :three => "four")
expect { terminus.destroy(request) }.to raise_error(ArgumentError)
end
it "should deserialize and return the http response" do
connection.expects(:delete).returns response
- terminus.destroy(request).should == model.new('', 'body')
+ expect(terminus.destroy(request)).to eq(model.new('', 'body'))
end
it "returns nil on 404" do
response = mock_response('404', nil)
connection.expects(:delete).returns(response)
- terminus.destroy(request).should == nil
+ expect(terminus.destroy(request)).to eq(nil)
end
it "should provide an Accept header containing the list of supported formats joined with commas" do
connection.expects(:delete).with(anything, has_entry("Accept" => "supported, formats")).returns(response)
terminus.model.expects(:supported_formats).returns %w{supported formats}
terminus.destroy(request)
end
end
describe "#save" do
let(:http_method) { :put }
let(:response) { mock_response(200, 'body') }
let(:connection) { stub('mock http connection', :put => response, :verify_callback= => nil) }
let(:instance) { model.new('the thing', 'some contents') }
let(:request) { save_request(instance.name, instance) }
before :each do
terminus.stubs(:network).returns(connection)
end
it_behaves_like 'a REST terminus method', :save
it "should call the PUT http method on a network connection" do
connection.expects(:put).with("#{url_prefix}/test_model/the%20thing?environment=production&", anything, has_key("Content-Type")).returns response
terminus.save(request)
end
it "should fail if any options are provided, since PUT apparently does not support query options" do
request = save_request(instance.name, instance, :one => "two", :three => "four")
expect { terminus.save(request) }.to raise_error(ArgumentError)
end
it "should serialize the instance using the default format and pass the result as the body of the request" do
instance.expects(:render).returns "serial_instance"
connection.expects(:put).with(anything, "serial_instance", anything).returns response
terminus.save(request)
end
it "returns nil on 404" do
response = mock_response('404', nil)
connection.expects(:put).returns(response)
- terminus.save(request).should == nil
+ expect(terminus.save(request)).to eq(nil)
end
it "returns nil" do
connection.expects(:put).returns response
- terminus.save(request).should be_nil
+ expect(terminus.save(request)).to be_nil
end
it "should provide an Accept header containing the list of supported formats joined with commas" do
connection.expects(:put).with(anything, anything, has_entry("Accept" => "supported, formats")).returns(response)
instance.expects(:render).returns('')
model.expects(:supported_formats).returns %w{supported formats}
instance.expects(:mime).returns "supported"
terminus.save(request)
end
it "should provide a Content-Type header containing the mime-type of the sent object" do
instance.expects(:mime).returns "mime"
connection.expects(:put).with(anything, anything, has_entry('Content-Type' => "mime")).returns(response)
terminus.save(request)
end
end
context 'dealing with SRV settings' do
[
:destroy,
:find,
:head,
:save,
:search
].each do |method|
it "##{method} passes the SRV service, and fall-back server & port to the request's do_request method" do
request = Puppet::Indirector::Request.new(:indirection, method, 'key', nil)
stub_response = mock_response('200', 'body')
request.expects(:do_request).with(terminus.class.srv_service, terminus.class.server, terminus.class.port).returns(stub_response)
terminus.send(method, request)
end
end
end
end
diff --git a/spec/unit/indirector/ssl_file_spec.rb b/spec/unit/indirector/ssl_file_spec.rb
index 8d13bdc94..04fe85271 100755
--- a/spec/unit/indirector/ssl_file_spec.rb
+++ b/spec/unit/indirector/ssl_file_spec.rb
@@ -1,328 +1,328 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/ssl_file'
describe Puppet::Indirector::SslFile do
include PuppetSpec::Files
before :all do
@indirection = stub 'indirection', :name => :testing, :model => @model
Puppet::Indirector::Indirection.expects(:instance).with(:testing).returns(@indirection)
module Testing; end
@file_class = class Testing::MyType < Puppet::Indirector::SslFile
self
end
end
before :each do
@model = mock 'model'
@setting = :certdir
@file_class.store_in @setting
@file_class.store_at nil
@file_class.store_ca_at nil
@path = make_absolute("/thisdoesntexist/my_directory")
Puppet[:noop] = false
Puppet[@setting] = @path
Puppet[:trace] = false
end
after :each do
@file_class.store_in nil
@file_class.store_at nil
@file_class.store_ca_at nil
end
it "should use :main and :ssl upon initialization" do
Puppet.settings.expects(:use).with(:main, :ssl)
@file_class.new
end
it "should return a nil collection directory if no directory setting has been provided" do
@file_class.store_in nil
- @file_class.collection_directory.should be_nil
+ expect(@file_class.collection_directory).to be_nil
end
it "should return a nil file location if no location has been provided" do
@file_class.store_at nil
- @file_class.file_location.should be_nil
+ expect(@file_class.file_location).to be_nil
end
it "should fail if no store directory or file location has been set" do
Puppet.settings.expects(:use).with(:main, :ssl)
@file_class.store_in nil
@file_class.store_at nil
expect {
@file_class.new
}.to raise_error(Puppet::DevError, /No file or directory setting provided/)
end
describe "when managing ssl files" do
before do
Puppet.settings.stubs(:use)
@searcher = @file_class.new
@cert = stub 'certificate', :name => "myname"
@certpath = File.join(@path, "myname.pem")
@request = stub 'request', :key => @cert.name, :instance => @cert
end
it "should consider the file a ca file if the name is equal to what the SSL::Host class says is the CA name" do
Puppet::SSL::Host.expects(:ca_name).returns "amaca"
- @searcher.should be_ca("amaca")
+ expect(@searcher).to be_ca("amaca")
end
describe "when choosing the location for certificates" do
it "should set them at the ca setting's path if a ca setting is available and the name resolves to the CA name" do
@file_class.store_in nil
@file_class.store_at :mysetting
@file_class.store_ca_at :cakey
Puppet[:cakey] = File.expand_path("/ca/file")
@searcher.expects(:ca?).with(@cert.name).returns true
- @searcher.path(@cert.name).should == Puppet[:cakey]
+ expect(@searcher.path(@cert.name)).to eq(Puppet[:cakey])
end
it "should set them at the file location if a file setting is available" do
@file_class.store_in nil
@file_class.store_at :cacrl
Puppet[:cacrl] = File.expand_path("/some/file")
- @searcher.path(@cert.name).should == Puppet[:cacrl]
+ expect(@searcher.path(@cert.name)).to eq(Puppet[:cacrl])
end
it "should set them in the setting directory, with the certificate name plus '.pem', if a directory setting is available" do
- @searcher.path(@cert.name).should == @certpath
+ expect(@searcher.path(@cert.name)).to eq(@certpath)
end
['../foo', '..\\foo', './../foo', '.\\..\\foo',
'/foo', '//foo', '\\foo', '\\\\goo',
"test\0/../bar", "test\0\\..\\bar",
"..\\/bar", "/tmp/bar", "/tmp\\bar", "tmp\\bar",
" / bar", " /../ bar", " \\..\\ bar",
"c:\\foo", "c:/foo", "\\\\?\\UNC\\bar", "\\\\foo\\bar",
"\\\\?\\c:\\foo", "//?/UNC/bar", "//foo/bar",
"//?/c:/foo",
].each do |input|
it "should resist directory traversal attacks (#{input.inspect})" do
expect { @searcher.path(input) }.to raise_error
end
end
# REVISIT: Should probably test MS-DOS reserved names here, too, since
# they would represent a vulnerability on a Win32 system, should we ever
# support that path. Don't forget that 'CON.foo' == 'CON'
# --daniel 2011-09-24
end
describe "when finding certificates on disk" do
describe "and no certificate is present" do
it "should return nil" do
Puppet::FileSystem.expects(:exist?).with(@path).returns(true)
Dir.expects(:entries).with(@path).returns([])
Puppet::FileSystem.expects(:exist?).with(@certpath).returns(false)
- @searcher.find(@request).should be_nil
+ expect(@searcher.find(@request)).to be_nil
end
end
describe "and a certificate is present" do
let(:cert) { mock 'cert' }
let(:model) { mock 'model' }
before(:each) do
@file_class.stubs(:model).returns model
end
context "is readable" do
it "should return an instance of the model, which it should use to read the certificate" do
Puppet::FileSystem.expects(:exist?).with(@certpath).returns true
model.expects(:new).with("myname").returns cert
cert.expects(:read).with(@certpath)
- @searcher.find(@request).should equal(cert)
+ expect(@searcher.find(@request)).to equal(cert)
end
end
context "is unreadable" do
it "should raise an exception" do
Puppet::FileSystem.expects(:exist?).with(@certpath).returns(true)
model.expects(:new).with("myname").returns cert
cert.expects(:read).with(@certpath).raises(Errno::EACCES)
expect {
@searcher.find(@request)
}.to raise_error(Errno::EACCES)
end
end
end
describe "and a certificate is present but has uppercase letters" do
before do
@request = stub 'request', :key => "myhost"
end
# This is kind of more an integration test; it's for #1382, until
# the support for upper-case certs can be removed around mid-2009.
it "should rename the existing file to the lower-case path" do
@path = @searcher.path("myhost")
Puppet::FileSystem.expects(:exist?).with(@path).returns(false)
dir, file = File.split(@path)
Puppet::FileSystem.expects(:exist?).with(dir).returns true
Dir.expects(:entries).with(dir).returns [".", "..", "something.pem", file.upcase]
File.expects(:rename).with(File.join(dir, file.upcase), @path)
cert = mock 'cert'
model = mock 'model'
@searcher.stubs(:model).returns model
@searcher.model.expects(:new).with("myhost").returns cert
cert.expects(:read).with(@path)
@searcher.find(@request)
end
end
end
describe "when saving certificates to disk" do
before do
FileTest.stubs(:directory?).returns true
FileTest.stubs(:writable?).returns true
end
it "should fail if the directory is absent" do
FileTest.expects(:directory?).with(File.dirname(@certpath)).returns false
- lambda { @searcher.save(@request) }.should raise_error(Puppet::Error)
+ expect { @searcher.save(@request) }.to raise_error(Puppet::Error)
end
it "should fail if the directory is not writeable" do
FileTest.stubs(:directory?).returns true
FileTest.expects(:writable?).with(File.dirname(@certpath)).returns false
- lambda { @searcher.save(@request) }.should raise_error(Puppet::Error)
+ expect { @searcher.save(@request) }.to raise_error(Puppet::Error)
end
it "should save to the path the output of converting the certificate to a string" do
fh = mock 'filehandle'
fh.expects(:print).with("mycert")
@searcher.stubs(:write).yields fh
@cert.expects(:to_s).returns "mycert"
@searcher.save(@request)
end
describe "and a directory setting is set" do
it "should use the Settings class to write the file" do
@searcher.class.store_in @setting
fh = mock 'filehandle'
fh.stubs :print
Puppet.settings.setting(@setting).expects(:open_file).with(@certpath, 'w').yields fh
@searcher.save(@request)
end
end
describe "and a file location is set" do
it "should use the filehandle provided by the Settings" do
@searcher.class.store_at @setting
fh = mock 'filehandle'
fh.stubs :print
Puppet.settings.setting(@setting).expects(:open).with('w').yields fh
@searcher.save(@request)
end
end
describe "and the name is the CA name and a ca setting is set" do
it "should use the filehandle provided by the Settings" do
@searcher.class.store_at @setting
@searcher.class.store_ca_at :cakey
Puppet[:cakey] = "castuff stub"
fh = mock 'filehandle'
fh.stubs :print
Puppet.settings.setting(:cakey).expects(:open).with('w').yields fh
@searcher.stubs(:ca?).returns true
@searcher.save(@request)
end
end
end
describe "when destroying certificates" do
describe "that do not exist" do
before do
Puppet::FileSystem.expects(:exist?).with(Puppet::FileSystem.pathname(@certpath)).returns false
end
it "should return false" do
- @searcher.destroy(@request).should be_false
+ expect(@searcher.destroy(@request)).to be_falsey
end
end
describe "that exist" do
it "should unlink the certificate file" do
path = Puppet::FileSystem.pathname(@certpath)
Puppet::FileSystem.expects(:exist?).with(path).returns true
Puppet::FileSystem.expects(:unlink).with(path)
@searcher.destroy(@request)
end
it "should log that is removing the file" do
Puppet::FileSystem.stubs(:exist?).returns true
Puppet::FileSystem.stubs(:unlink)
Puppet.expects(:notice)
@searcher.destroy(@request)
end
end
end
describe "when searching for certificates" do
let(:one) { stub 'one' }
let(:two) { stub 'two' }
let(:one_path) { File.join(@path, 'one.pem') }
let(:two_path) { File.join(@path, 'two.pem') }
let(:model) { mock 'model' }
before :each do
@file_class.stubs(:model).returns model
end
it "should return a certificate instance for all files that exist" do
Dir.expects(:entries).with(@path).returns(%w{. .. one.pem two.pem})
model.expects(:new).with("one").returns one
one.expects(:read).with(one_path)
model.expects(:new).with("two").returns two
two.expects(:read).with(two_path)
- @searcher.search(@request).should == [one, two]
+ expect(@searcher.search(@request)).to eq([one, two])
end
it "should raise an exception if any file is unreadable" do
Dir.expects(:entries).with(@path).returns(%w{. .. one.pem two.pem})
model.expects(:new).with("one").returns(one)
one.expects(:read).with(one_path)
model.expects(:new).with("two").returns(two)
two.expects(:read).raises(Errno::EACCES)
expect {
@searcher.search(@request)
}.to raise_error(Errno::EACCES)
end
it "should skip any files that do not match /\.pem$/" do
Dir.expects(:entries).with(@path).returns(%w{. .. one two.notpem})
model.expects(:new).never
- @searcher.search(@request).should == []
+ expect(@searcher.search(@request)).to eq([])
end
end
end
end
diff --git a/spec/unit/indirector/status/rest_spec.rb b/spec/unit/indirector/status/rest_spec.rb
index 24361e24c..b863a2f9d 100755
--- a/spec/unit/indirector/status/rest_spec.rb
+++ b/spec/unit/indirector/status/rest_spec.rb
@@ -1,10 +1,10 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/status/rest'
describe Puppet::Indirector::Status::Rest do
it "should be a subclass of Puppet::Indirector::REST" do
- Puppet::Indirector::Status::Rest.superclass.should equal(Puppet::Indirector::REST)
+ expect(Puppet::Indirector::Status::Rest.superclass).to equal(Puppet::Indirector::REST)
end
end
diff --git a/spec/unit/indirector/terminus_spec.rb b/spec/unit/indirector/terminus_spec.rb
index 56888e9b3..0a0c0c743 100755
--- a/spec/unit/indirector/terminus_spec.rb
+++ b/spec/unit/indirector/terminus_spec.rb
@@ -1,264 +1,264 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/defaults'
require 'puppet/indirector'
require 'puppet/indirector/memory'
describe Puppet::Indirector::Terminus do
before :all do
class Puppet::AbstractConcept
extend Puppet::Indirector
indirects :abstract_concept
attr_accessor :name
def initialize(name = "name")
@name = name
end
end
class Puppet::AbstractConcept::Freedom < Puppet::Indirector::Code
end
end
after :all do
# Remove the class, unlinking it from the rest of the system.
Puppet.send(:remove_const, :AbstractConcept)
end
let :terminus_class do Puppet::AbstractConcept::Freedom end
let :terminus do terminus_class.new end
let :indirection do Puppet::AbstractConcept.indirection end
let :model do Puppet::AbstractConcept end
it "should provide a method for setting terminus class documentation" do
- terminus_class.should respond_to(:desc)
+ expect(terminus_class).to respond_to(:desc)
end
it "should support a class-level name attribute" do
- terminus_class.should respond_to(:name)
+ expect(terminus_class).to respond_to(:name)
end
it "should support a class-level indirection attribute" do
- terminus_class.should respond_to(:indirection)
+ expect(terminus_class).to respond_to(:indirection)
end
it "should support a class-level terminus-type attribute" do
- terminus_class.should respond_to(:terminus_type)
+ expect(terminus_class).to respond_to(:terminus_type)
end
it "should support a class-level model attribute" do
- terminus_class.should respond_to(:model)
+ expect(terminus_class).to respond_to(:model)
end
it "should accept indirection instances as its indirection" do
# The test is that this shouldn't raise, and should preserve the object
# instance exactly, hence "equal", not just "==".
terminus_class.indirection = indirection
- terminus_class.indirection.should equal indirection
+ expect(terminus_class.indirection).to equal indirection
end
it "should look up indirection instances when only a name has been provided" do
terminus_class.indirection = :abstract_concept
- terminus_class.indirection.should equal indirection
+ expect(terminus_class.indirection).to equal indirection
end
it "should fail when provided a name that does not resolve to an indirection" do
expect {
terminus_class.indirection = :exploding_whales
}.to raise_error(ArgumentError, /Could not find indirection instance/)
# We should still have the default indirection.
- terminus_class.indirection.should equal indirection
+ expect(terminus_class.indirection).to equal indirection
end
describe "when a terminus instance" do
it "should return the class's name as its name" do
- terminus.name.should == :freedom
+ expect(terminus.name).to eq(:freedom)
end
it "should return the class's indirection as its indirection" do
- terminus.indirection.should equal indirection
+ expect(terminus.indirection).to equal indirection
end
it "should set the instances's type to the abstract terminus type's name" do
- terminus.terminus_type.should == :code
+ expect(terminus.terminus_type).to eq(:code)
end
it "should set the instances's model to the indirection's model" do
- terminus.model.should equal indirection.model
+ expect(terminus.model).to equal indirection.model
end
end
describe "when managing terminus classes" do
it "should provide a method for registering terminus classes" do
- Puppet::Indirector::Terminus.should respond_to(:register_terminus_class)
+ expect(Puppet::Indirector::Terminus).to respond_to(:register_terminus_class)
end
it "should provide a method for returning terminus classes by name and type" do
terminus = stub 'terminus_type', :name => :abstract, :indirection_name => :whatever
Puppet::Indirector::Terminus.register_terminus_class(terminus)
- Puppet::Indirector::Terminus.terminus_class(:whatever, :abstract).should equal(terminus)
+ expect(Puppet::Indirector::Terminus.terminus_class(:whatever, :abstract)).to equal(terminus)
end
it "should set up autoloading for any terminus class types requested" do
Puppet::Indirector::Terminus.expects(:instance_load).with(:test2, "puppet/indirector/test2")
Puppet::Indirector::Terminus.terminus_class(:test2, :whatever)
end
it "should load terminus classes that are not found" do
# Set up instance loading; it would normally happen automatically
Puppet::Indirector::Terminus.instance_load :test1, "puppet/indirector/test1"
Puppet::Indirector::Terminus.instance_loader(:test1).expects(:load).with(:yay)
Puppet::Indirector::Terminus.terminus_class(:test1, :yay)
end
it "should fail when no indirection can be found" do
Puppet::Indirector::Indirection.expects(:instance).with(:abstract_concept).returns(nil)
expect {
class Puppet::AbstractConcept::Physics < Puppet::Indirector::Code
end
}.to raise_error(ArgumentError, /Could not find indirection instance/)
end
it "should register the terminus class with the terminus base class" do
Puppet::Indirector::Terminus.expects(:register_terminus_class).with do |type|
type.indirection_name == :abstract_concept and type.name == :intellect
end
begin
class Puppet::AbstractConcept::Intellect < Puppet::Indirector::Code
end
ensure
Puppet::AbstractConcept.send(:remove_const, :Intellect) rescue nil
end
end
end
describe "when parsing class constants for indirection and terminus names" do
before :each do
Puppet::Indirector::Terminus.stubs(:register_terminus_class)
end
let :subclass do
subclass = mock 'subclass'
subclass.stubs(:to_s).returns("TestInd::OneTwo")
subclass.stubs(:mark_as_abstract_terminus)
subclass
end
it "should fail when anonymous classes are used" do
expect {
Puppet::Indirector::Terminus.inherited(Class.new)
}.to raise_error(Puppet::DevError, /Terminus subclasses must have associated constants/)
end
it "should use the last term in the constant for the terminus class name" do
subclass.expects(:name=).with(:one_two)
subclass.stubs(:indirection=)
Puppet::Indirector::Terminus.inherited(subclass)
end
it "should convert the terminus name to a downcased symbol" do
subclass.expects(:name=).with(:one_two)
subclass.stubs(:indirection=)
Puppet::Indirector::Terminus.inherited(subclass)
end
it "should use the second to last term in the constant for the indirection name" do
subclass.expects(:indirection=).with(:test_ind)
subclass.stubs(:name=)
subclass.stubs(:terminus_type=)
Puppet::Indirector::Memory.inherited(subclass)
end
it "should convert the indirection name to a downcased symbol" do
subclass.expects(:indirection=).with(:test_ind)
subclass.stubs(:name=)
subclass.stubs(:terminus_type=)
Puppet::Indirector::Memory.inherited(subclass)
end
it "should convert camel case to lower case with underscores as word separators" do
subclass.expects(:name=).with(:one_two)
subclass.stubs(:indirection=)
Puppet::Indirector::Terminus.inherited(subclass)
end
end
describe "when creating terminus class types" do
before :all do
Puppet::Indirector::Terminus.stubs(:register_terminus_class)
class Puppet::Indirector::Terminus::TestTerminusType < Puppet::Indirector::Terminus
end
end
after :all do
Puppet::Indirector::Terminus.send(:remove_const, :TestTerminusType)
end
let :subclass do
Puppet::Indirector::Terminus::TestTerminusType
end
it "should set the name of the abstract subclass to be its class constant" do
- subclass.name.should == :test_terminus_type
+ expect(subclass.name).to eq(:test_terminus_type)
end
it "should mark abstract terminus types as such" do
- subclass.should be_abstract_terminus
+ expect(subclass).to be_abstract_terminus
end
it "should not allow instances of abstract subclasses to be created" do
expect { subclass.new }.to raise_error(Puppet::DevError)
end
end
describe "when listing terminus classes" do
it "should list the terminus files available to load" do
Puppet::Util::Autoload.any_instance.stubs(:files_to_load).returns ["/foo/bar/baz", "/max/runs/marathon"]
- Puppet::Indirector::Terminus.terminus_classes('my_stuff').should == [:baz, :marathon]
+ expect(Puppet::Indirector::Terminus.terminus_classes('my_stuff')).to eq([:baz, :marathon])
end
end
describe "when validating a request" do
let :request do
Puppet::Indirector::Request.new(indirection.name, :find, "the_key", instance)
end
describe "`instance.name` does not match the key in the request" do
let(:instance) { model.new("wrong_key") }
it "raises an error " do
expect {
terminus.validate(request)
}.to raise_error(
Puppet::Indirector::ValidationError,
/Instance name .* does not match requested key/
)
end
end
describe "`instance` is not an instance of the model class" do
let(:instance) { mock "instance" }
it "raises an error" do
expect {
terminus.validate(request)
}.to raise_error(
Puppet::Indirector::ValidationError,
/Invalid instance type/
)
end
end
describe "the instance key and class match the request key and model class" do
let(:instance) { model.new("the_key") }
it "passes" do
terminus.validate(request)
end
end
end
end
diff --git a/spec/unit/indirector/yaml_spec.rb b/spec/unit/indirector/yaml_spec.rb
index 6fae8831c..703fdf214 100755
--- a/spec/unit/indirector/yaml_spec.rb
+++ b/spec/unit/indirector/yaml_spec.rb
@@ -1,166 +1,166 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/yaml'
describe Puppet::Indirector::Yaml do
include PuppetSpec::Files
class TestSubject
attr_accessor :name
end
before :all do
@indirection = stub 'indirection', :name => :my_yaml, :register_terminus_type => nil
Puppet::Indirector::Indirection.expects(:instance).with(:my_yaml).returns(@indirection)
module MyYaml; end
@store_class = class MyYaml::MyType < Puppet::Indirector::Yaml
self
end
end
before :each do
@store = @store_class.new
@subject = TestSubject.new
@subject.name = :me
@dir = tmpdir("yaml_indirector")
Puppet[:clientyamldir] = @dir
Puppet.run_mode.stubs(:master?).returns false
@request = stub 'request', :key => :me, :instance => @subject
end
let(:serverdir) { File.expand_path("/server/yaml/dir") }
let(:clientdir) { File.expand_path("/client/yaml/dir") }
describe "when choosing file location" do
it "should use the server_datadir if the run_mode is master" do
Puppet.run_mode.stubs(:master?).returns true
Puppet[:yamldir] = serverdir
- @store.path(:me).should =~ /^#{serverdir}/
+ expect(@store.path(:me)).to match(/^#{serverdir}/)
end
it "should use the client yamldir if the run_mode is not master" do
Puppet.run_mode.stubs(:master?).returns false
Puppet[:clientyamldir] = clientdir
- @store.path(:me).should =~ /^#{clientdir}/
+ expect(@store.path(:me)).to match(/^#{clientdir}/)
end
it "should use the extension if one is specified" do
Puppet.run_mode.stubs(:master?).returns true
Puppet[:yamldir] = serverdir
- @store.path(:me,'.farfignewton').should =~ %r{\.farfignewton$}
+ expect(@store.path(:me,'.farfignewton')).to match(%r{\.farfignewton$})
end
it "should assume an extension of .yaml if none is specified" do
Puppet.run_mode.stubs(:master?).returns true
Puppet[:yamldir] = serverdir
- @store.path(:me).should =~ %r{\.yaml$}
+ expect(@store.path(:me)).to match(%r{\.yaml$})
end
it "should store all files in a single file root set in the Puppet defaults" do
- @store.path(:me).should =~ %r{^#{@dir}}
+ expect(@store.path(:me)).to match(%r{^#{@dir}})
end
it "should use the terminus name for choosing the subdirectory" do
- @store.path(:me).should =~ %r{^#{@dir}/my_yaml}
+ expect(@store.path(:me)).to match(%r{^#{@dir}/my_yaml})
end
it "should use the object's name to determine the file name" do
- @store.path(:me).should =~ %r{me.yaml$}
+ expect(@store.path(:me)).to match(%r{me.yaml$})
end
['../foo', '..\\foo', './../foo', '.\\..\\foo',
'/foo', '//foo', '\\foo', '\\\\goo',
"test\0/../bar", "test\0\\..\\bar",
"..\\/bar", "/tmp/bar", "/tmp\\bar", "tmp\\bar",
" / bar", " /../ bar", " \\..\\ bar",
"c:\\foo", "c:/foo", "\\\\?\\UNC\\bar", "\\\\foo\\bar",
"\\\\?\\c:\\foo", "//?/UNC/bar", "//foo/bar",
"//?/c:/foo",
].each do |input|
it "should resist directory traversal attacks (#{input.inspect})" do
expect { @store.path(input) }.to raise_error
end
end
end
describe "when storing objects as YAML" do
it "should only store objects that respond to :name" do
@request.stubs(:instance).returns Object.new
- proc { @store.save(@request) }.should raise_error(ArgumentError)
+ expect { @store.save(@request) }.to raise_error(ArgumentError)
end
end
describe "when retrieving YAML" do
it "should read YAML in from disk and convert it to Ruby objects" do
@store.save(Puppet::Indirector::Request.new(:my_yaml, :save, "testing", @subject))
- @store.find(Puppet::Indirector::Request.new(:my_yaml, :find, "testing", nil)).name.should == :me
+ expect(@store.find(Puppet::Indirector::Request.new(:my_yaml, :find, "testing", nil)).name).to eq(:me)
end
it "should fail coherently when the stored YAML is invalid" do
saved_structure = Struct.new(:name).new("testing")
@store.save(Puppet::Indirector::Request.new(:my_yaml, :save, "testing", saved_structure))
File.open(@store.path(saved_structure.name), "w") do |file|
file.puts "{ invalid"
end
expect {
@store.find(Puppet::Indirector::Request.new(:my_yaml, :find, "testing", nil))
}.to raise_error(Puppet::Error, /Could not parse YAML data/)
end
end
describe "when searching" do
it "should return an array of fact instances with one instance for each file when globbing *" do
@request = stub 'request', :key => "*", :instance => @subject
@one = mock 'one'
@two = mock 'two'
@store.expects(:path).with(@request.key,'').returns :glob
Dir.expects(:glob).with(:glob).returns(%w{one.yaml two.yaml})
YAML.expects(:load_file).with("one.yaml").returns @one;
YAML.expects(:load_file).with("two.yaml").returns @two;
- @store.search(@request).should == [@one, @two]
+ expect(@store.search(@request)).to eq([@one, @two])
end
it "should return an array containing a single instance of fact when globbing 'one*'" do
@request = stub 'request', :key => "one*", :instance => @subject
@one = mock 'one'
@store.expects(:path).with(@request.key,'').returns :glob
Dir.expects(:glob).with(:glob).returns(%w{one.yaml})
YAML.expects(:load_file).with("one.yaml").returns @one;
- @store.search(@request).should == [@one]
+ expect(@store.search(@request)).to eq([@one])
end
it "should return an empty array when the glob doesn't match anything" do
@request = stub 'request', :key => "f*ilglobcanfail*", :instance => @subject
@store.expects(:path).with(@request.key,'').returns :glob
Dir.expects(:glob).with(:glob).returns []
- @store.search(@request).should == []
+ expect(@store.search(@request)).to eq([])
end
describe "when destroying" do
let(:path) do
File.join(@dir, @store.class.indirection_name.to_s, @request.key.to_s + ".yaml")
end
it "should unlink the right yaml file if it exists" do
Puppet::FileSystem.expects(:exist?).with(path).returns true
Puppet::FileSystem.expects(:unlink).with(path)
@store.destroy(@request)
end
it "should not unlink the yaml file if it does not exists" do
Puppet::FileSystem.expects(:exist?).with(path).returns false
Puppet::FileSystem.expects(:unlink).with(path).never
@store.destroy(@request)
end
end
end
end
diff --git a/spec/unit/indirector_spec.rb b/spec/unit/indirector_spec.rb
index 913c0fe87..6734fb4de 100755
--- a/spec/unit/indirector_spec.rb
+++ b/spec/unit/indirector_spec.rb
@@ -1,150 +1,150 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/defaults'
require 'puppet/indirector'
describe Puppet::Indirector, "when configuring routes" do
before :each do
Puppet::Node.indirection.reset_terminus_class
Puppet::Node.indirection.cache_class = nil
end
after :each do
Puppet::Node.indirection.reset_terminus_class
Puppet::Node.indirection.cache_class = nil
end
it "should configure routes as requested" do
routes = {
"node" => {
"terminus" => "exec",
"cache" => "plain"
}
}
Puppet::Indirector.configure_routes(routes)
- Puppet::Node.indirection.terminus_class.should == "exec"
- Puppet::Node.indirection.cache_class.should == "plain"
+ expect(Puppet::Node.indirection.terminus_class).to eq("exec")
+ expect(Puppet::Node.indirection.cache_class).to eq("plain")
end
it "should fail when given an invalid indirection" do
routes = {
"fake_indirection" => {
"terminus" => "exec",
"cache" => "plain"
}
}
expect { Puppet::Indirector.configure_routes(routes) }.to raise_error(/fake_indirection does not exist/)
end
it "should fail when given an invalid terminus" do
routes = {
"node" => {
"terminus" => "fake_terminus",
"cache" => "plain"
}
}
expect { Puppet::Indirector.configure_routes(routes) }.to raise_error(/Could not find terminus fake_terminus/)
end
it "should fail when given an invalid cache" do
routes = {
"node" => {
"terminus" => "exec",
"cache" => "fake_cache"
}
}
expect { Puppet::Indirector.configure_routes(routes) }.to raise_error(/Could not find terminus fake_cache/)
end
end
describe Puppet::Indirector, " when available to a model" do
before do
@thingie = Class.new do
extend Puppet::Indirector
end
end
it "should provide a way for the model to register an indirection under a name" do
- @thingie.should respond_to(:indirects)
+ expect(@thingie).to respond_to(:indirects)
end
end
describe Puppet::Indirector, "when registering an indirection" do
before do
@thingie = Class.new do
extend Puppet::Indirector
# override Class#name, since we're not naming this ephemeral class
def self.name
'Thingie'
end
attr_reader :name
def initialize(name)
@name = name
end
end
end
it "should require a name when registering a model" do
expect {@thingie.send(:indirects) }.to raise_error(ArgumentError)
end
it "should create an indirection instance to manage each indirecting model" do
@indirection = @thingie.indirects(:test)
- @indirection.should be_instance_of(Puppet::Indirector::Indirection)
+ expect(@indirection).to be_instance_of(Puppet::Indirector::Indirection)
end
it "should not allow a model to register under multiple names" do
# Keep track of the indirection instance so we can delete it on cleanup
@indirection = @thingie.indirects :first
expect { @thingie.indirects :second }.to raise_error(ArgumentError)
end
it "should make the indirection available via an accessor" do
@indirection = @thingie.indirects :first
- @thingie.indirection.should equal(@indirection)
+ expect(@thingie.indirection).to equal(@indirection)
end
it "should pass any provided options to the indirection during initialization" do
klass = mock 'terminus class'
Puppet::Indirector::Indirection.expects(:new).with(@thingie, :first, {:some => :options, :indirected_class => 'Thingie'})
@indirection = @thingie.indirects :first, :some => :options
end
it "should extend the class to handle serialization" do
@indirection = @thingie.indirects :first
- @thingie.should respond_to(:convert_from)
+ expect(@thingie).to respond_to(:convert_from)
end
after do
@indirection.delete if @indirection
end
end
describe Puppet::Indirector, "when redirecting a model" do
before do
@thingie = Class.new do
extend Puppet::Indirector
attr_reader :name
def initialize(name)
@name = name
end
end
@indirection = @thingie.send(:indirects, :test)
end
it "should include the Envelope module in the model" do
- @thingie.ancestors.should be_include(Puppet::Indirector::Envelope)
+ expect(@thingie.ancestors).to be_include(Puppet::Indirector::Envelope)
end
after do
@indirection.delete
end
end
diff --git a/spec/unit/interface/action_builder_spec.rb b/spec/unit/interface/action_builder_spec.rb
index 0fb64641a..e6c5a7fce 100755
--- a/spec/unit/interface/action_builder_spec.rb
+++ b/spec/unit/interface/action_builder_spec.rb
@@ -1,217 +1,217 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/interface'
require 'puppet/network/format_handler'
describe Puppet::Interface::ActionBuilder do
let :face do Puppet::Interface.new(:puppet_interface_actionbuilder, '0.0.1') end
it "should build an action" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
end
- action.should be_a(Puppet::Interface::Action)
- action.name.should == :foo
+ expect(action).to be_a(Puppet::Interface::Action)
+ expect(action.name).to eq(:foo)
end
it "should define a method on the face which invokes the action" do
face = Puppet::Interface.new(:action_builder_test_interface, '0.0.1') do
action(:foo) { when_invoked { |options| "invoked the method" } }
end
- face.foo.should == "invoked the method"
+ expect(face.foo).to eq("invoked the method")
end
it "should require a block" do
expect {
Puppet::Interface::ActionBuilder.build(nil, :foo)
}.to raise_error("Action :foo must specify a block")
end
it "should require an invocation block" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) {}
}.to raise_error(/actions need to know what to do when_invoked; please add the block/)
end
describe "when handling options" do
it "should have a #option DSL function" do
method = nil
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
method = self.method(:option)
end
- method.should be_an_instance_of Method
+ expect(method).to be_an_instance_of Method
end
it "should define an option without a block" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
option "--bar"
end
- action.should be_option :bar
+ expect(action).to be_option :bar
end
it "should accept an empty block" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
option "--bar" do
# This space left deliberately blank.
end
end
- action.should be_option :bar
+ expect(action).to be_option :bar
end
end
context "inline documentation" do
it "should set the summary" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
summary "this is some text"
end
- action.summary.should == "this is some text"
+ expect(action.summary).to eq("this is some text")
end
end
context "action defaulting" do
it "should set the default to true" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
default
end
- action.default.should be_true
+ expect(action.default).to be_truthy
end
it "should not be default by, er, default. *cough*" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
end
- action.default.should be_false
+ expect(action.default).to be_falsey
end
end
context "#when_rendering" do
it "should fail if no rendering format is given" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering do true end
end
}.to raise_error ArgumentError, /must give a rendering format to when_rendering/
end
it "should fail if no block is given" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json
end
}.to raise_error ArgumentError, /must give a block to when_rendering/
end
it "should fail if the block takes no arguments" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json do true end
end
}.to raise_error ArgumentError,
/the puppet_interface_actionbuilder face foo action takes .* not/
end
it "should fail if the when_rendering block takes a different number of arguments than when_invoked" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json do |a, b, c| true end
end
}.to raise_error ArgumentError,
/the puppet_interface_actionbuilder face foo action takes .* not 3/
end
it "should fail if the block takes a variable number of arguments" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json do |*args| true end
end
}.to raise_error ArgumentError,
/the puppet_interface_actionbuilder face foo action takes .* not/
end
it "should stash a rendering block" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json do |a| true end
end
- action.when_rendering(:json).should be_an_instance_of Method
+ expect(action.when_rendering(:json)).to be_an_instance_of Method
end
it "should fail if you try to set the same rendering twice" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json do |a| true end
when_rendering :json do |a| true end
end
}.to raise_error ArgumentError, /You can't define a rendering method for json twice/
end
it "should work if you set two different renderings" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json do |a| true end
when_rendering :yaml do |a| true end
end
- action.when_rendering(:json).should be_an_instance_of Method
- action.when_rendering(:yaml).should be_an_instance_of Method
+ expect(action.when_rendering(:json)).to be_an_instance_of Method
+ expect(action.when_rendering(:yaml)).to be_an_instance_of Method
end
it "should be bound to the face when called" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json do |a| self end
end
- action.when_rendering(:json).call(true).should == face
+ expect(action.when_rendering(:json).call(true)).to eq(face)
end
end
context "#render_as" do
it "should default to nil (eg: based on context)" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
end
- action.render_as.should be_nil
+ expect(action.render_as).to be_nil
end
it "should fail if not rendering format is given" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
render_as
end
}.to raise_error ArgumentError, /must give a rendering format to render_as/
end
Puppet::Network::FormatHandler.formats.each do |name|
it "should accept #{name.inspect} format" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
render_as name
end
- action.render_as.should == name
+ expect(action.render_as).to eq(name)
end
end
[:if_you_define_this_format_you_frighten_me, "json", 12].each do |input|
it "should fail if given #{input.inspect}" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
render_as input
end
}.to raise_error ArgumentError, /#{input.inspect} is not a valid rendering format/
end
end
end
end
diff --git a/spec/unit/interface/action_manager_spec.rb b/spec/unit/interface/action_manager_spec.rb
index 9b310473b..9c7bd5fa0 100755
--- a/spec/unit/interface/action_manager_spec.rb
+++ b/spec/unit/interface/action_manager_spec.rb
@@ -1,255 +1,255 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/interface'
class ActionManagerTester
include Puppet::Interface::ActionManager
end
describe Puppet::Interface::ActionManager do
subject { ActionManagerTester.new }
describe "when included in a class" do
it "should be able to define an action" do
subject.action(:foo) do
when_invoked { |options| "something "}
end
end
it "should be able to list defined actions" do
subject.action(:foo) do
when_invoked { |options| "something" }
end
subject.action(:bar) do
when_invoked { |options| "something" }
end
- subject.actions.should =~ [:foo, :bar]
+ expect(subject.actions).to match_array([:foo, :bar])
end
it "should be able to indicate when an action is defined" do
subject.action(:foo) do
when_invoked { |options| "something" }
end
- subject.should be_action(:foo)
+ expect(subject).to be_action(:foo)
end
it "should correctly treat action names specified as strings" do
subject.action(:foo) do
when_invoked { |options| "something" }
end
- subject.should be_action("foo")
+ expect(subject).to be_action("foo")
end
end
describe "when used to extend a class" do
subject { Class.new.extend(Puppet::Interface::ActionManager) }
it "should be able to define an action" do
subject.action(:foo) do
when_invoked { |options| "something "}
end
end
it "should be able to list defined actions" do
subject.action(:foo) do
when_invoked { |options| "something" }
end
subject.action(:bar) do
when_invoked { |options| "something" }
end
- subject.actions.should include(:bar)
- subject.actions.should include(:foo)
+ expect(subject.actions).to include(:bar)
+ expect(subject.actions).to include(:foo)
end
it "should be able to indicate when an action is defined" do
subject.action(:foo) { when_invoked do |options| true end }
- subject.should be_action(:foo)
+ expect(subject).to be_action(:foo)
end
end
describe "when used both at the class and instance level" do
before do
@klass = Class.new do
include Puppet::Interface::ActionManager
extend Puppet::Interface::ActionManager
def __invoke_decorations(*args) true end
def options() [] end
end
@instance = @klass.new
end
it "should be able to define an action at the class level" do
@klass.action(:foo) do
when_invoked { |options| "something "}
end
end
it "should create an instance method when an action is defined at the class level" do
@klass.action(:foo) do
when_invoked { |options| "something" }
end
- @instance.foo.should == "something"
+ expect(@instance.foo).to eq("something")
end
it "should be able to define an action at the instance level" do
@instance.action(:foo) do
when_invoked { |options| "something "}
end
end
it "should create an instance method when an action is defined at the instance level" do
@instance.action(:foo) do
when_invoked { |options| "something" }
end
- @instance.foo.should == "something"
+ expect(@instance.foo).to eq("something")
end
it "should be able to list actions defined at the class level" do
@klass.action(:foo) do
when_invoked { |options| "something" }
end
@klass.action(:bar) do
when_invoked { |options| "something" }
end
- @klass.actions.should include(:bar)
- @klass.actions.should include(:foo)
+ expect(@klass.actions).to include(:bar)
+ expect(@klass.actions).to include(:foo)
end
it "should be able to list actions defined at the instance level" do
@instance.action(:foo) do
when_invoked { |options| "something" }
end
@instance.action(:bar) do
when_invoked { |options| "something" }
end
- @instance.actions.should include(:bar)
- @instance.actions.should include(:foo)
+ expect(@instance.actions).to include(:bar)
+ expect(@instance.actions).to include(:foo)
end
it "should be able to list actions defined at both instance and class level" do
@klass.action(:foo) do
when_invoked { |options| "something" }
end
@instance.action(:bar) do
when_invoked { |options| "something" }
end
- @instance.actions.should include(:bar)
- @instance.actions.should include(:foo)
+ expect(@instance.actions).to include(:bar)
+ expect(@instance.actions).to include(:foo)
end
it "should be able to indicate when an action is defined at the class level" do
@klass.action(:foo) do
when_invoked { |options| "something" }
end
- @instance.should be_action(:foo)
+ expect(@instance).to be_action(:foo)
end
it "should be able to indicate when an action is defined at the instance level" do
@klass.action(:foo) do
when_invoked { |options| "something" }
end
- @instance.should be_action(:foo)
+ expect(@instance).to be_action(:foo)
end
context "with actions defined in superclass" do
before :each do
@subclass = Class.new(@klass)
@instance = @subclass.new
@klass.action(:parent) do
when_invoked { |options| "a" }
end
@subclass.action(:sub) do
when_invoked { |options| "a" }
end
@instance.action(:instance) do
when_invoked { |options| "a" }
end
end
it "should list actions defined in superclasses" do
- @instance.should be_action(:parent)
- @instance.should be_action(:sub)
- @instance.should be_action(:instance)
+ expect(@instance).to be_action(:parent)
+ expect(@instance).to be_action(:sub)
+ expect(@instance).to be_action(:instance)
end
it "should list inherited actions" do
- @instance.actions.should =~ [:instance, :parent, :sub]
+ expect(@instance.actions).to match_array([:instance, :parent, :sub])
end
it "should not duplicate instance actions after fetching them (#7699)" do
- @instance.actions.should =~ [:instance, :parent, :sub]
+ expect(@instance.actions).to match_array([:instance, :parent, :sub])
@instance.get_action(:instance)
- @instance.actions.should =~ [:instance, :parent, :sub]
+ expect(@instance.actions).to match_array([:instance, :parent, :sub])
end
it "should not duplicate subclass actions after fetching them (#7699)" do
- @instance.actions.should =~ [:instance, :parent, :sub]
+ expect(@instance.actions).to match_array([:instance, :parent, :sub])
@instance.get_action(:sub)
- @instance.actions.should =~ [:instance, :parent, :sub]
+ expect(@instance.actions).to match_array([:instance, :parent, :sub])
end
it "should not duplicate superclass actions after fetching them (#7699)" do
- @instance.actions.should =~ [:instance, :parent, :sub]
+ expect(@instance.actions).to match_array([:instance, :parent, :sub])
@instance.get_action(:parent)
- @instance.actions.should =~ [:instance, :parent, :sub]
+ expect(@instance.actions).to match_array([:instance, :parent, :sub])
end
end
it "should create an instance method when an action is defined in a superclass" do
@subclass = Class.new(@klass)
@instance = @subclass.new
@klass.action(:foo) do
when_invoked { |options| "something" }
end
- @instance.foo.should == "something"
+ expect(@instance.foo).to eq("something")
end
end
describe "#action" do
it 'should add an action' do
subject.action(:foo) { when_invoked do |options| true end }
- subject.get_action(:foo).should be_a Puppet::Interface::Action
+ expect(subject.get_action(:foo)).to be_a Puppet::Interface::Action
end
it 'should support default actions' do
subject.action(:foo) { when_invoked do |options| true end; default }
- subject.get_default_action.should == subject.get_action(:foo)
+ expect(subject.get_default_action).to eq(subject.get_action(:foo))
end
it 'should not support more than one default action' do
subject.action(:foo) { when_invoked do |options| true end; default }
expect { subject.action(:bar) {
when_invoked do |options| true end
default
}
}.to raise_error /cannot both be default/
end
end
describe "#get_action" do
let :parent_class do
parent_class = Class.new(Puppet::Interface)
parent_class.action(:foo) { when_invoked do |options| true end }
parent_class
end
it "should check that we can find inherited actions when we are a class" do
- Class.new(parent_class).get_action(:foo).name.should == :foo
+ expect(Class.new(parent_class).get_action(:foo).name).to eq(:foo)
end
it "should check that we can find inherited actions when we are an instance" do
instance = parent_class.new(:foo, '0.0.0')
- instance.get_action(:foo).name.should == :foo
+ expect(instance.get_action(:foo).name).to eq(:foo)
end
end
end
diff --git a/spec/unit/interface/action_spec.rb b/spec/unit/interface/action_spec.rb
index 8ef7379f5..b8c7f31a2 100755
--- a/spec/unit/interface/action_spec.rb
+++ b/spec/unit/interface/action_spec.rb
@@ -1,647 +1,647 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/interface'
describe Puppet::Interface::Action do
describe "when validating the action name" do
[nil, '', 'foo bar', '-foobar'].each do |input|
it "should treat #{input.inspect} as an invalid name" do
expect {
Puppet::Interface::Action.new(nil, input)
}.to raise_error(/is an invalid action name/)
end
end
end
describe "#when_invoked=" do
it "should fail if the block has arity 0" do
expect {
Puppet::Interface.new(:action_when_invoked, '1.0.0') do
action :foo do
when_invoked { }
end
end
}.to raise_error ArgumentError, /foo/
end
it "should work with arity 1 blocks" do
face = Puppet::Interface.new(:action_when_invoked, '1.0.0') do
action :foo do
when_invoked {|one| }
end
end
# -1, because we use option defaulting. :(
- face.method(:foo).arity.should == -1
+ expect(face.method(:foo).arity).to eq(-1)
end
it "should work with arity 2 blocks" do
face = Puppet::Interface.new(:action_when_invoked, '1.0.0') do
action :foo do
when_invoked {|one, two| }
end
end
# -2, because we use option defaulting. :(
- face.method(:foo).arity.should == -2
+ expect(face.method(:foo).arity).to eq(-2)
end
it "should work with arity 1 blocks that collect arguments" do
face = Puppet::Interface.new(:action_when_invoked, '1.0.0') do
action :foo do
when_invoked {|*one| }
end
end
# -1, because we use only varargs
- face.method(:foo).arity.should == -1
+ expect(face.method(:foo).arity).to eq(-1)
end
it "should work with arity 2 blocks that collect arguments" do
face = Puppet::Interface.new(:action_when_invoked, '1.0.0') do
action :foo do
when_invoked {|one, *two| }
end
end
# -2, because we take one mandatory argument, and one varargs
- face.method(:foo).arity.should == -2
+ expect(face.method(:foo).arity).to eq(-2)
end
end
describe "when invoking" do
it "should be able to call other actions on the same object" do
face = Puppet::Interface.new(:my_face, '0.0.1') do
action(:foo) do
when_invoked { |options| 25 }
end
action(:bar) do
when_invoked { |options| "the value of foo is '#{foo}'" }
end
end
- face.foo.should == 25
- face.bar.should == "the value of foo is '25'"
+ expect(face.foo).to eq(25)
+ expect(face.bar).to eq("the value of foo is '25'")
end
# bar is a class action calling a class action
# quux is a class action calling an instance action
# baz is an instance action calling a class action
# qux is an instance action calling an instance action
it "should be able to call other actions on the same object when defined on a class" do
class Puppet::Interface::MyInterfaceBaseClass < Puppet::Interface
action(:foo) do
when_invoked { |options| 25 }
end
action(:bar) do
when_invoked { |options| "the value of foo is '#{foo}'" }
end
action(:quux) do
when_invoked { |options| "qux told me #{qux}" }
end
end
face = Puppet::Interface::MyInterfaceBaseClass.new(:my_inherited_face, '0.0.1') do
action(:baz) do
when_invoked { |options| "the value of foo in baz is '#{foo}'" }
end
action(:qux) do
when_invoked { |options| baz }
end
end
- face.foo.should == 25
- face.bar.should == "the value of foo is '25'"
- face.quux.should == "qux told me the value of foo in baz is '25'"
- face.baz.should == "the value of foo in baz is '25'"
- face.qux.should == "the value of foo in baz is '25'"
+ expect(face.foo).to eq(25)
+ expect(face.bar).to eq("the value of foo is '25'")
+ expect(face.quux).to eq("qux told me the value of foo in baz is '25'")
+ expect(face.baz).to eq("the value of foo in baz is '25'")
+ expect(face.qux).to eq("the value of foo in baz is '25'")
end
context "when calling the Ruby API" do
let :face do
Puppet::Interface.new(:ruby_api, '1.0.0') do
action :bar do
option "--bar"
when_invoked do |*args|
args.last
end
end
end
end
it "should work when no options are supplied" do
options = face.bar
- options.should == {}
+ expect(options).to eq({})
end
it "should work when options are supplied" do
options = face.bar(:bar => "beer")
- options.should == { :bar => "beer" }
+ expect(options).to eq({ :bar => "beer" })
end
it "should call #validate_and_clean on the action when invoked" do
face.get_action(:bar).expects(:validate_and_clean).with({}).returns({})
face.bar 1, :two, 'three'
end
end
end
describe "with action-level options" do
it "should support options with an empty block" do
face = Puppet::Interface.new(:action_level_options, '0.0.1') do
action :foo do
when_invoked do |options| true end
option "--bar" do
# this line left deliberately blank
end
end
end
- face.should_not be_option :bar
- face.get_action(:foo).should be_option :bar
+ expect(face).not_to be_option :bar
+ expect(face.get_action(:foo)).to be_option :bar
end
it "should return only action level options when there are no face options" do
face = Puppet::Interface.new(:action_level_options, '0.0.1') do
action :foo do
when_invoked do |options| true end
option "--bar"
end
end
- face.get_action(:foo).options.should =~ [:bar]
+ expect(face.get_action(:foo).options).to match_array([:bar])
end
describe "option aliases" do
let :option do action.get_option :bar end
let :action do face.get_action :foo end
let :face do
Puppet::Interface.new(:action_level_options, '0.0.1') do
action :foo do
when_invoked do |options| options end
option "--bar", "--foo", "-b"
end
end
end
it "should only list options and not aliases" do
- action.options.should =~ [:bar]
+ expect(action.options).to match_array([:bar])
end
it "should use the canonical option name when passed aliases" do
name = option.name
option.aliases.each do |input|
- face.foo(input => 1).should == { name => 1 }
+ expect(face.foo(input => 1)).to eq({ name => 1 })
end
end
end
describe "with both face and action options" do
let :face do
Puppet::Interface.new(:action_level_options, '0.0.1') do
action :foo do when_invoked do |options| true end ; option "--bar" end
action :baz do when_invoked do |options| true end ; option "--bim" end
option "--quux"
end
end
it "should return combined face and action options" do
- face.get_action(:foo).options.should =~ [:bar, :quux]
+ expect(face.get_action(:foo).options).to match_array([:bar, :quux])
end
it "should fetch options that the face inherited" do
parent = Class.new(Puppet::Interface)
parent.option "--foo"
child = parent.new(:inherited_options, '0.0.1') do
option "--bar"
action :action do
when_invoked do |options| true end
option "--baz"
end
end
action = child.get_action(:action)
- action.should be
+ expect(action).to be
[:baz, :bar, :foo].each do |name|
- action.get_option(name).should be_an_instance_of Puppet::Interface::Option
+ expect(action.get_option(name)).to be_an_instance_of Puppet::Interface::Option
end
end
it "should get an action option when asked" do
- face.get_action(:foo).get_option(:bar).
- should be_an_instance_of Puppet::Interface::Option
+ expect(face.get_action(:foo).get_option(:bar)).
+ to be_an_instance_of Puppet::Interface::Option
end
it "should get a face option when asked" do
- face.get_action(:foo).get_option(:quux).
- should be_an_instance_of Puppet::Interface::Option
+ expect(face.get_action(:foo).get_option(:quux)).
+ to be_an_instance_of Puppet::Interface::Option
end
it "should return options only for this action" do
- face.get_action(:baz).options.should =~ [:bim, :quux]
+ expect(face.get_action(:baz).options).to match_array([:bim, :quux])
end
end
it_should_behave_like "things that declare options" do
def add_options_to(&block)
face = Puppet::Interface.new(:with_options, '0.0.1') do
action(:foo) do
when_invoked do |options| true end
self.instance_eval &block
end
end
face.get_action(:foo)
end
end
it "should fail when a face option duplicates an action option" do
expect {
Puppet::Interface.new(:action_level_options, '0.0.1') do
option "--foo"
action :bar do option "--foo" end
end
}.to raise_error ArgumentError, /Option foo conflicts with existing option foo/i
end
it "should fail when a required action option is not provided" do
face = Puppet::Interface.new(:required_action_option, '0.0.1') do
action(:bar) do
option('--foo') { required }
when_invoked {|options| }
end
end
expect { face.bar }.to raise_error ArgumentError, /The following options are required: foo/
end
it "should fail when a required face option is not provided" do
face = Puppet::Interface.new(:required_face_option, '0.0.1') do
option('--foo') { required }
action(:bar) { when_invoked {|options| } }
end
expect { face.bar }.to raise_error ArgumentError, /The following options are required: foo/
end
end
context "with decorators" do
context "declared locally" do
let :face do
Puppet::Interface.new(:action_decorators, '0.0.1') do
action :bar do when_invoked do |options| true end end
def reported; @reported; end
def report(arg)
(@reported ||= []) << arg
end
end
end
it "should execute before advice on action options in declaration order" do
face.action(:boo) do
option("--foo") { before_action { |_,_,_| report :foo } }
option("--bar", '-b') { before_action { |_,_,_| report :bar } }
option("-q", "--quux") { before_action { |_,_,_| report :quux } }
option("-f") { before_action { |_,_,_| report :f } }
option("--baz") { before_action { |_,_,_| report :baz } }
when_invoked {|options| }
end
face.boo :foo => 1, :bar => 1, :quux => 1, :f => 1, :baz => 1
- face.reported.should == [ :foo, :bar, :quux, :f, :baz ]
+ expect(face.reported).to eq([ :foo, :bar, :quux, :f, :baz ])
end
it "should execute after advice on action options in declaration order" do
face.action(:boo) do
option("--foo") { after_action { |_,_,_| report :foo } }
option("--bar", '-b') { after_action { |_,_,_| report :bar } }
option("-q", "--quux") { after_action { |_,_,_| report :quux } }
option("-f") { after_action { |_,_,_| report :f } }
option("--baz") { after_action { |_,_,_| report :baz } }
when_invoked {|options| }
end
face.boo :foo => 1, :bar => 1, :quux => 1, :f => 1, :baz => 1
- face.reported.should == [ :foo, :bar, :quux, :f, :baz ].reverse
+ expect(face.reported).to eq([ :foo, :bar, :quux, :f, :baz ].reverse)
end
it "should execute before advice on face options in declaration order" do
face.instance_eval do
option("--foo") { before_action { |_,_,_| report :foo } }
option("--bar", '-b') { before_action { |_,_,_| report :bar } }
option("-q", "--quux") { before_action { |_,_,_| report :quux } }
option("-f") { before_action { |_,_,_| report :f } }
option("--baz") { before_action { |_,_,_| report :baz } }
end
face.action(:boo) { when_invoked { |options| } }
face.boo :foo => 1, :bar => 1, :quux => 1, :f => 1, :baz => 1
- face.reported.should == [ :foo, :bar, :quux, :f, :baz ]
+ expect(face.reported).to eq([ :foo, :bar, :quux, :f, :baz ])
end
it "should execute after advice on face options in declaration order" do
face.instance_eval do
option("--foo") { after_action { |_,_,_| report :foo } }
option("--bar", '-b') { after_action { |_,_,_| report :bar } }
option("-q", "--quux") { after_action { |_,_,_| report :quux } }
option("-f") { after_action { |_,_,_| report :f } }
option("--baz") { after_action { |_,_,_| report :baz } }
end
face.action(:boo) { when_invoked { |options| } }
face.boo :foo => 1, :bar => 1, :quux => 1, :f => 1, :baz => 1
- face.reported.should == [ :foo, :bar, :quux, :f, :baz ].reverse
+ expect(face.reported).to eq([ :foo, :bar, :quux, :f, :baz ].reverse)
end
it "should execute before advice on face options before action options" do
face.instance_eval do
option("--face-foo") { before_action { |_,_,_| report :face_foo } }
option("--face-bar", '-r') { before_action { |_,_,_| report :face_bar } }
action(:boo) do
option("--action-foo") { before_action { |_,_,_| report :action_foo } }
option("--action-bar", '-b') { before_action { |_,_,_| report :action_bar } }
option("-q", "--action-quux") { before_action { |_,_,_| report :action_quux } }
option("-a") { before_action { |_,_,_| report :a } }
option("--action-baz") { before_action { |_,_,_| report :action_baz } }
when_invoked {|options| }
end
option("-u", "--face-quux") { before_action { |_,_,_| report :face_quux } }
option("-f") { before_action { |_,_,_| report :f } }
option("--face-baz") { before_action { |_,_,_| report :face_baz } }
end
expected_calls = [ :face_foo, :face_bar, :face_quux, :f, :face_baz,
:action_foo, :action_bar, :action_quux, :a, :action_baz ]
face.boo Hash[ *expected_calls.zip([]).flatten ]
- face.reported.should == expected_calls
+ expect(face.reported).to eq(expected_calls)
end
it "should execute after advice on face options in declaration order" do
face.instance_eval do
option("--face-foo") { after_action { |_,_,_| report :face_foo } }
option("--face-bar", '-r') { after_action { |_,_,_| report :face_bar } }
action(:boo) do
option("--action-foo") { after_action { |_,_,_| report :action_foo } }
option("--action-bar", '-b') { after_action { |_,_,_| report :action_bar } }
option("-q", "--action-quux") { after_action { |_,_,_| report :action_quux } }
option("-a") { after_action { |_,_,_| report :a } }
option("--action-baz") { after_action { |_,_,_| report :action_baz } }
when_invoked {|options| }
end
option("-u", "--face-quux") { after_action { |_,_,_| report :face_quux } }
option("-f") { after_action { |_,_,_| report :f } }
option("--face-baz") { after_action { |_,_,_| report :face_baz } }
end
expected_calls = [ :face_foo, :face_bar, :face_quux, :f, :face_baz,
:action_foo, :action_bar, :action_quux, :a, :action_baz ]
face.boo Hash[ *expected_calls.zip([]).flatten ]
- face.reported.should == expected_calls.reverse
+ expect(face.reported).to eq(expected_calls.reverse)
end
it "should not invoke a decorator if the options are empty" do
face.option("--foo FOO") { before_action { |_,_,_| report :before_action } }
face.expects(:report).never
face.bar
end
context "passing a subset of the options" do
before :each do
face.option("--foo") { before_action { |_,_,_| report :foo } }
face.option("--bar") { before_action { |_,_,_| report :bar } }
end
it "should invoke only foo's advice when passed only 'foo'" do
face.bar(:foo => true)
- face.reported.should == [ :foo ]
+ expect(face.reported).to eq([ :foo ])
end
it "should invoke only bar's advice when passed only 'bar'" do
face.bar(:bar => true)
- face.reported.should == [ :bar ]
+ expect(face.reported).to eq([ :bar ])
end
it "should invoke advice for all passed options" do
face.bar(:foo => true, :bar => true)
- face.reported.should == [ :foo, :bar ]
+ expect(face.reported).to eq([ :foo, :bar ])
end
end
end
context "and inheritance" do
let :parent do
Class.new(Puppet::Interface) do
action(:on_parent) { when_invoked { |options| :on_parent } }
def reported; @reported; end
def report(arg)
(@reported ||= []) << arg
end
end
end
let :child do
parent.new(:inherited_decorators, '0.0.1') do
action(:on_child) { when_invoked { |options| :on_child } }
end
end
context "locally declared face options" do
subject do
child.option("--foo=") { before_action { |_,_,_| report :child_before } }
child
end
it "should be invoked when calling a child action" do
- subject.on_child(:foo => true).should == :on_child
- subject.reported.should == [ :child_before ]
+ expect(subject.on_child(:foo => true)).to eq(:on_child)
+ expect(subject.reported).to eq([ :child_before ])
end
it "should be invoked when calling a parent action" do
- subject.on_parent(:foo => true).should == :on_parent
- subject.reported.should == [ :child_before ]
+ expect(subject.on_parent(:foo => true)).to eq(:on_parent)
+ expect(subject.reported).to eq([ :child_before ])
end
end
context "inherited face option decorators" do
subject do
parent.option("--foo=") { before_action { |_,_,_| report :parent_before } }
child
end
it "should be invoked when calling a child action" do
- subject.on_child(:foo => true).should == :on_child
- subject.reported.should == [ :parent_before ]
+ expect(subject.on_child(:foo => true)).to eq(:on_child)
+ expect(subject.reported).to eq([ :parent_before ])
end
it "should be invoked when calling a parent action" do
- subject.on_parent(:foo => true).should == :on_parent
- subject.reported.should == [ :parent_before ]
+ expect(subject.on_parent(:foo => true)).to eq(:on_parent)
+ expect(subject.reported).to eq([ :parent_before ])
end
end
context "with both inherited and local face options" do
# Decorations should be invoked in declaration order, according to
# inheritance (e.g. parent class options should be handled before
# subclass options).
subject do
child.option "-c" do
before_action { |action, args, options| report :c_before }
after_action { |action, args, options| report :c_after }
end
parent.option "-a" do
before_action { |action, args, options| report :a_before }
after_action { |action, args, options| report :a_after }
end
child.option "-d" do
before_action { |action, args, options| report :d_before }
after_action { |action, args, options| report :d_after }
end
parent.option "-b" do
before_action { |action, args, options| report :b_before }
after_action { |action, args, options| report :b_after }
end
child.action(:decorations) { when_invoked { |options| report :invoked } }
child
end
it "should invoke all decorations when calling a child action" do
subject.decorations(:a => 1, :b => 1, :c => 1, :d => 1)
- subject.reported.should == [
+ expect(subject.reported).to eq([
:a_before, :b_before, :c_before, :d_before,
:invoked,
:d_after, :c_after, :b_after, :a_after
- ]
+ ])
end
it "should invoke all decorations when calling a parent action" do
subject.decorations(:a => 1, :b => 1, :c => 1, :d => 1)
- subject.reported.should == [
+ expect(subject.reported).to eq([
:a_before, :b_before, :c_before, :d_before,
:invoked,
:d_after, :c_after, :b_after, :a_after
- ]
+ ])
end
end
end
end
it_should_behave_like "documentation on faces" do
subject do
face = Puppet::Interface.new(:action_documentation, '0.0.1') do
action :documentation do
when_invoked do |options| true end
end
end
face.get_action(:documentation)
end
end
context "#when_rendering" do
it "should fail if no type is given when_rendering"
it "should accept a when_rendering block"
it "should accept multiple when_rendering blocks"
it "should fail if when_rendering gets a non-symbol identifier"
it "should fail if a second block is given for the same type"
it "should return the block if asked"
end
context "#validate_and_clean" do
subject do
Puppet::Interface.new(:validate_args, '1.0.0') do
action(:test) { when_invoked { |options| options } }
end
end
it "should fail if a required option is not passed" do
subject.option "--foo" do required end
expect { subject.test }.to raise_error ArgumentError, /options are required/
end
it "should fail if two aliases to one option are passed" do
subject.option "--foo", "-f"
expect { subject.test :foo => true, :f => true }.
to raise_error ArgumentError, /Multiple aliases for the same option/
end
it "should fail if an unknown option is passed" do
expect { subject.test :unknown => true }.
to raise_error ArgumentError, /Unknown options passed: unknown/
end
it "should report all the unknown options passed" do
expect { subject.test :unknown => true, :unseen => false }.
to raise_error ArgumentError, /Unknown options passed: unknown, unseen/
end
it "should accept 'global' options from settings" do
expect {
- subject.test(:certname => "true").should == { :certname => "true" }
+ expect(subject.test(:certname => "true")).to eq({ :certname => "true" })
}.not_to raise_error
end
end
context "default option values" do
subject do
Puppet::Interface.new(:default_option_values, '1.0.0') do
action :foo do
option "--foo" do end
option "--bar" do end
when_invoked do |options| options end
end
end
end
let :action do subject.get_action :foo end
let :option do action.get_option :foo end
it "should not add options without defaults" do
- subject.foo.should == {}
+ expect(subject.foo).to eq({})
end
it "should not add options without defaults, if options are given" do
- subject.foo(:bar => 1).should == { :bar => 1 }
+ expect(subject.foo(:bar => 1)).to eq({ :bar => 1 })
end
it "should add the option default value when set" do
option.default = proc { 12 }
- subject.foo.should == { :foo => 12 }
+ expect(subject.foo).to eq({ :foo => 12 })
end
it "should add the option default value when set, if other options are given" do
option.default = proc { 12 }
- subject.foo(:bar => 1).should == { :foo => 12, :bar => 1 }
+ expect(subject.foo(:bar => 1)).to eq({ :foo => 12, :bar => 1 })
end
it "should invoke the same default proc every time called" do
option.default = proc { @foo ||= {} }
- subject.foo[:foo].object_id.should == subject.foo[:foo].object_id
+ expect(subject.foo[:foo].object_id).to eq(subject.foo[:foo].object_id)
end
[nil, 0, 1, true, false, {}, []].each do |input|
it "should not override a passed option (#{input.inspect})" do
option.default = proc { :fail }
- subject.foo(:foo => input).should == { :foo => input }
+ expect(subject.foo(:foo => input)).to eq({ :foo => input })
end
end
end
context "runtime manipulations" do
subject do
Puppet::Interface.new(:runtime_manipulations, '1.0.0') do
action :foo do
when_invoked do |options| options end
end
end
end
let :action do subject.get_action :foo end
it "should be the face default action if default is set true" do
- subject.get_default_action.should be_nil
+ expect(subject.get_default_action).to be_nil
action.default = true
- subject.get_default_action.should == action
+ expect(subject.get_default_action).to eq(action)
end
end
end
diff --git a/spec/unit/interface/documentation_spec.rb b/spec/unit/interface/documentation_spec.rb
index 27ade8574..cb2bfb64d 100755
--- a/spec/unit/interface/documentation_spec.rb
+++ b/spec/unit/interface/documentation_spec.rb
@@ -1,33 +1,33 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/interface'
class Puppet::Interface::TinyDocs::Test
include Puppet::Interface::TinyDocs
attr_accessor :name, :options, :display_global_options
def initialize
self.name = "tinydoc-test"
self.options = []
self.display_global_options = []
end
def get_option(name)
Puppet::Interface::Option.new(nil, "--#{name}")
end
end
describe Puppet::Interface::TinyDocs do
subject { Puppet::Interface::TinyDocs::Test.new }
context "#build_synopsis" do
before :each do
subject.options = [:foo, :bar]
end
- it { should respond_to :build_synopsis }
+ it { is_expected.to respond_to :build_synopsis }
it "should put a space between options (#7828)" do
- subject.build_synopsis('baz').should =~ /#{Regexp.quote('[--foo] [--bar]')}/
+ expect(subject.build_synopsis('baz')).to match(/#{Regexp.quote('[--foo] [--bar]')}/)
end
end
end
diff --git a/spec/unit/interface/face_collection_spec.rb b/spec/unit/interface/face_collection_spec.rb
index 89928b70a..c3003831b 100755
--- a/spec/unit/interface/face_collection_spec.rb
+++ b/spec/unit/interface/face_collection_spec.rb
@@ -1,212 +1,212 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'tmpdir'
require 'puppet/interface'
describe Puppet::Interface::FaceCollection do
# To prevent conflicts with other specs that use faces, we must save and restore global state.
# Because there are specs that do 'describe Puppet::Face[...]', we must restore the same objects otherwise
# the 'subject' of the specs will differ.
before :all do
# Save FaceCollection's global state
faces = described_class.instance_variable_get(:@faces)
@faces = faces.dup
faces.each do |k, v|
@faces[k] = v.dup
end
@faces_loaded = described_class.instance_variable_get(:@loaded)
# Save the already required face files
@required = []
$".each do |path|
@required << path if path =~ /face\/.*\.rb$/
end
# Save Autoload's global state
@loaded = Puppet::Util::Autoload.instance_variable_get(:@loaded).dup
end
after :all do
# Restore global state
- subject.instance_variable_set :@faces, @faces
- subject.instance_variable_set :@loaded, @faces_loaded
+ described_class.instance_variable_set :@faces, @faces
+ described_class.instance_variable_set :@loaded, @faces_loaded
$".delete_if { |path| path =~ /face\/.*\.rb$/ }
@required.each { |path| $".push path unless $".include? path }
Puppet::Util::Autoload.instance_variable_set(:@loaded, @loaded)
end
before :each do
# Before each test, clear the faces
subject.instance_variable_get(:@faces).clear
subject.instance_variable_set(:@loaded, false)
Puppet::Util::Autoload.instance_variable_get(:@loaded).clear
$".delete_if { |path| path =~ /face\/.*\.rb$/ }
end
describe "::[]" do
before :each do
subject.instance_variable_get("@faces")[:foo][SemVer.new('0.0.1')] = 10
end
it "should return the face with the given name" do
- subject["foo", '0.0.1'].should == 10
+ expect(subject["foo", '0.0.1']).to eq(10)
end
it "should attempt to load the face if it isn't found" do
subject.expects(:require).once.with('puppet/face/bar')
subject.expects(:require).once.with('puppet/face/0.0.1/bar')
subject["bar", '0.0.1']
end
it "should attempt to load the default face for the specified version :current" do
subject.expects(:require).with('puppet/face/fozzie')
subject['fozzie', :current]
end
it "should return true if the face specified is registered" do
subject.instance_variable_get("@faces")[:foo][SemVer.new('0.0.1')] = 10
- subject["foo", '0.0.1'].should == 10
+ expect(subject["foo", '0.0.1']).to eq(10)
end
it "should attempt to require the face if it is not registered" do
subject.expects(:require).with do |file|
subject.instance_variable_get("@faces")[:bar][SemVer.new('0.0.1')] = true
file == 'puppet/face/bar'
end
- subject["bar", '0.0.1'].should be_true
+ expect(subject["bar", '0.0.1']).to be_truthy
end
it "should return false if the face is not registered" do
subject.stubs(:require).returns(true)
- subject["bar", '0.0.1'].should be_false
+ expect(subject["bar", '0.0.1']).to be_falsey
end
it "should return false if the face file itself is missing" do
subject.stubs(:require).
raises(LoadError, 'no such file to load -- puppet/face/bar').then.
raises(LoadError, 'no such file to load -- puppet/face/0.0.1/bar')
- subject["bar", '0.0.1'].should be_false
+ expect(subject["bar", '0.0.1']).to be_falsey
end
it "should register the version loaded by `:current` as `:current`" do
subject.expects(:require).with do |file|
subject.instance_variable_get("@faces")[:huzzah]['2.0.1'] = :huzzah_face
file == 'puppet/face/huzzah'
end
subject["huzzah", :current]
- subject.instance_variable_get("@faces")[:huzzah][:current].should == :huzzah_face
+ expect(subject.instance_variable_get("@faces")[:huzzah][:current]).to eq(:huzzah_face)
end
context "with something on disk" do
it "should register the version loaded from `puppet/face/{name}` as `:current`" do
- subject["huzzah", '2.0.1'].should be
- subject["huzzah", :current].should be
- Puppet::Face[:huzzah, '2.0.1'].should == Puppet::Face[:huzzah, :current]
+ expect(subject["huzzah", '2.0.1']).to be
+ expect(subject["huzzah", :current]).to be
+ expect(Puppet::Face[:huzzah, '2.0.1']).to eq(Puppet::Face[:huzzah, :current])
end
it "should index :current when the code was pre-required" do
- subject.instance_variable_get("@faces")[:huzzah].should_not be_key :current
+ expect(subject.instance_variable_get("@faces")[:huzzah]).not_to be_key :current
require 'puppet/face/huzzah'
- subject[:huzzah, :current].should be_true
+ expect(subject[:huzzah, :current]).to be_truthy
end
end
it "should not cause an invalid face to be enumerated later" do
- subject[:there_is_no_face, :current].should be_false
- subject.faces.should_not include :there_is_no_face
+ expect(subject[:there_is_no_face, :current]).to be_falsey
+ expect(subject.faces).not_to include :there_is_no_face
end
end
describe "::get_action_for_face" do
it "should return an action on the current face" do
- Puppet::Face::FaceCollection.get_action_for_face(:huzzah, :bar, :current).
- should be_an_instance_of Puppet::Interface::Action
+ expect(Puppet::Face::FaceCollection.get_action_for_face(:huzzah, :bar, :current)).
+ to be_an_instance_of Puppet::Interface::Action
end
it "should return an action on an older version of a face" do
action = Puppet::Face::FaceCollection.
get_action_for_face(:huzzah, :obsolete, :current)
- action.should be_an_instance_of Puppet::Interface::Action
- action.face.version.should == SemVer.new('1.0.0')
+ expect(action).to be_an_instance_of Puppet::Interface::Action
+ expect(action.face.version).to eq(SemVer.new('1.0.0'))
end
it "should load the full older version of a face" do
action = Puppet::Face::FaceCollection.
get_action_for_face(:huzzah, :obsolete, :current)
- action.face.version.should == SemVer.new('1.0.0')
- action.face.should be_action :obsolete_in_core
+ expect(action.face.version).to eq(SemVer.new('1.0.0'))
+ expect(action.face).to be_action :obsolete_in_core
end
it "should not add obsolete actions to the current version" do
action = Puppet::Face::FaceCollection.
get_action_for_face(:huzzah, :obsolete, :current)
- action.face.version.should == SemVer.new('1.0.0')
- action.face.should be_action :obsolete_in_core
+ expect(action.face.version).to eq(SemVer.new('1.0.0'))
+ expect(action.face).to be_action :obsolete_in_core
current = Puppet::Face[:huzzah, :current]
- current.version.should == SemVer.new('2.0.1')
- current.should_not be_action :obsolete_in_core
- current.should_not be_action :obsolete
+ expect(current.version).to eq(SemVer.new('2.0.1'))
+ expect(current).not_to be_action :obsolete_in_core
+ expect(current).not_to be_action :obsolete
end
end
describe "::register" do
it "should store the face by name" do
face = Puppet::Face.new(:my_face, '0.0.1')
subject.register(face)
- subject.instance_variable_get("@faces").should == {
+ expect(subject.instance_variable_get("@faces")).to eq({
:my_face => { face.version => face }
- }
+ })
end
end
describe "::underscorize" do
faulty = [1, "23foo", "#foo", "$bar", "sturm und drang", :"sturm und drang"]
valid = {
"Foo" => :foo,
:Foo => :foo,
"foo_bar" => :foo_bar,
:foo_bar => :foo_bar,
"foo-bar" => :foo_bar,
:"foo-bar" => :foo_bar,
"foo_bar23" => :foo_bar23,
:foo_bar23 => :foo_bar23,
}
valid.each do |input, expect|
it "should map #{input.inspect} to #{expect.inspect}" do
result = subject.underscorize(input)
- result.should == expect
+ expect(result).to eq(expect)
end
end
faulty.each do |input|
it "should fail when presented with #{input.inspect} (#{input.class})" do
expect { subject.underscorize(input) }.
to raise_error ArgumentError, /not a valid face name/
end
end
end
context "faulty faces" do
before :each do
$:.unshift "#{PuppetSpec::FIXTURE_DIR}/faulty_face"
end
after :each do
$:.delete_if {|x| x == "#{PuppetSpec::FIXTURE_DIR}/faulty_face"}
end
it "should not die if a face has a syntax error" do
- subject.faces.should be_include :help
- subject.faces.should_not be_include :syntax
- @logs.should_not be_empty
- @logs.first.message.should =~ /syntax error/
+ expect(subject.faces).to be_include :help
+ expect(subject.faces).not_to be_include :syntax
+ expect(@logs).not_to be_empty
+ expect(@logs.first.message).to match(/syntax error/)
end
end
end
diff --git a/spec/unit/interface/option_builder_spec.rb b/spec/unit/interface/option_builder_spec.rb
index cc4eba2f6..010818bb5 100755
--- a/spec/unit/interface/option_builder_spec.rb
+++ b/spec/unit/interface/option_builder_spec.rb
@@ -1,86 +1,86 @@
require 'spec_helper'
require 'puppet/interface'
describe Puppet::Interface::OptionBuilder do
let :face do Puppet::Interface.new(:option_builder_testing, '0.0.1') end
it "should be able to construct an option without a block" do
- Puppet::Interface::OptionBuilder.build(face, "--foo").
- should be_an_instance_of Puppet::Interface::Option
+ expect(Puppet::Interface::OptionBuilder.build(face, "--foo")).
+ to be_an_instance_of Puppet::Interface::Option
end
Puppet.settings.each do |name, value|
it "should fail when option #{name.inspect} already exists in puppet core" do
expect do
Puppet::Interface::OptionBuilder.build(face, "--#{name}")
end.to raise_error ArgumentError, /already defined/
end
end
it "should work with an empty block" do
option = Puppet::Interface::OptionBuilder.build(face, "--foo") do
# This block deliberately left blank.
end
- option.should be_an_instance_of Puppet::Interface::Option
+ expect(option).to be_an_instance_of Puppet::Interface::Option
end
[:description, :summary].each do |doc|
it "should support #{doc} declarations" do
text = "this is the #{doc}"
option = Puppet::Interface::OptionBuilder.build(face, "--foo") do
self.send doc, text
end
- option.should be_an_instance_of Puppet::Interface::Option
- option.send(doc).should == text
+ expect(option).to be_an_instance_of Puppet::Interface::Option
+ expect(option.send(doc)).to eq(text)
end
end
context "before_action hook" do
it "should support a before_action hook" do
option = Puppet::Interface::OptionBuilder.build(face, "--foo") do
before_action do |a,b,c| :whatever end
end
- option.before_action.should be_an_instance_of UnboundMethod
+ expect(option.before_action).to be_an_instance_of UnboundMethod
end
it "should fail if the hook block takes too few arguments" do
expect do
Puppet::Interface::OptionBuilder.build(face, "--foo") do
before_action do |one, two| true end
end
end.to raise_error ArgumentError, /takes three arguments/
end
it "should fail if the hook block takes too many arguments" do
expect do
Puppet::Interface::OptionBuilder.build(face, "--foo") do
before_action do |one, two, three, four| true end
end
end.to raise_error ArgumentError, /takes three arguments/
end
it "should fail if the hook block takes a variable number of arguments" do
expect do
Puppet::Interface::OptionBuilder.build(face, "--foo") do
before_action do |*blah| true end
end
end.to raise_error ArgumentError, /takes three arguments/
end
it "should support simple required declarations" do
opt = Puppet::Interface::OptionBuilder.build(face, "--foo") do
required
end
- opt.should be_required
+ expect(opt).to be_required
end
it "should support arguments to the required property" do
opt = Puppet::Interface::OptionBuilder.build(face, "--foo") do
required(false)
end
- opt.should_not be_required
+ expect(opt).not_to be_required
end
end
end
diff --git a/spec/unit/interface/option_spec.rb b/spec/unit/interface/option_spec.rb
index 2299e70d0..c7fba7378 100755
--- a/spec/unit/interface/option_spec.rb
+++ b/spec/unit/interface/option_spec.rb
@@ -1,156 +1,156 @@
require 'spec_helper'
require 'puppet/interface'
describe Puppet::Interface::Option do
let :face do Puppet::Interface.new(:option_testing, '0.0.1') end
describe "#optparse_to_name" do
["", "=BAR", " BAR", "=bar", " bar"].each do |postfix|
{ "--foo" => :foo, "-f" => :f }.each do |base, expect|
input = base + postfix
it "should map #{input.inspect} to #{expect.inspect}" do
option = Puppet::Interface::Option.new(face, input)
- option.name.should == expect
+ expect(option.name).to eq(expect)
end
end
end
[:foo, 12, nil, {}, []].each do |input|
it "should fail sensible when given #{input.inspect}" do
expect {
Puppet::Interface::Option.new(face, input)
}.to raise_error ArgumentError, /is not valid for an option argument/
end
end
["-foo", "-foo=BAR", "-foo BAR"].each do |input|
it "should fail with a single dash for long option #{input.inspect}" do
expect {
Puppet::Interface::Option.new(face, input)
}.to raise_error ArgumentError, /long options need two dashes \(--\)/
end
end
end
it "requires a face when created" do
expect {
Puppet::Interface::Option.new
}.to raise_error ArgumentError, /wrong number of arguments/
end
it "also requires some declaration arguments when created" do
expect {
Puppet::Interface::Option.new(face)
}.to raise_error ArgumentError, /No option declarations found/
end
it "should infer the name from an optparse string" do
option = Puppet::Interface::Option.new(face, "--foo")
- option.name.should == :foo
+ expect(option.name).to eq(:foo)
end
it "should infer the name when multiple optparse string are given" do
option = Puppet::Interface::Option.new(face, "--foo", "-f")
- option.name.should == :foo
+ expect(option.name).to eq(:foo)
end
it "should prefer the first long option name over a short option name" do
option = Puppet::Interface::Option.new(face, "-f", "--foo")
- option.name.should == :foo
+ expect(option.name).to eq(:foo)
end
it "should create an instance when given a face and name" do
- Puppet::Interface::Option.new(face, "--foo").
- should be_instance_of Puppet::Interface::Option
+ expect(Puppet::Interface::Option.new(face, "--foo")).
+ to be_instance_of Puppet::Interface::Option
end
Puppet.settings.each do |name, value|
it "should fail when option #{name.inspect} already exists in puppet core" do
expect do
Puppet::Interface::Option.new(face, "--#{name}")
end.to raise_error ArgumentError, /already defined/
end
end
describe "#to_s" do
it "should transform a symbol into a string" do
option = Puppet::Interface::Option.new(face, "--foo")
- option.name.should == :foo
- option.to_s.should == "foo"
+ expect(option.name).to eq(:foo)
+ expect(option.to_s).to eq("foo")
end
it "should use - rather than _ to separate words in strings but not symbols" do
option = Puppet::Interface::Option.new(face, "--foo-bar")
- option.name.should == :foo_bar
- option.to_s.should == "foo-bar"
+ expect(option.name).to eq(:foo_bar)
+ expect(option.to_s).to eq("foo-bar")
end
end
%w{before after}.each do |side|
describe "#{side} hooks" do
subject { Puppet::Interface::Option.new(face, "--foo") }
let :proc do Proc.new do :from_proc end end
- it { should respond_to "#{side}_action" }
- it { should respond_to "#{side}_action=" }
+ it { is_expected.to respond_to "#{side}_action" }
+ it { is_expected.to respond_to "#{side}_action=" }
it "should set the #{side}_action hook" do
- subject.send("#{side}_action").should be_nil
+ expect(subject.send("#{side}_action")).to be_nil
subject.send("#{side}_action=", proc)
- subject.send("#{side}_action").should be_an_instance_of UnboundMethod
+ expect(subject.send("#{side}_action")).to be_an_instance_of UnboundMethod
end
data = [1, "foo", :foo, Object.new, method(:hash), method(:hash).unbind]
data.each do |input|
it "should fail if a #{input.class} is added to the #{side} hooks" do
expect { subject.send("#{side}_action=", input) }.
to raise_error ArgumentError, /not a proc/
end
end
end
end
context "defaults" do
subject { Puppet::Interface::Option.new(face, "--foo") }
it "should work sanely if member variables are used for state" do
subject.default = proc { @foo ||= 0; @foo += 1 }
- subject.default.should == 1
- subject.default.should == 2
- subject.default.should == 3
+ expect(subject.default).to eq(1)
+ expect(subject.default).to eq(2)
+ expect(subject.default).to eq(3)
end
context "with no default" do
- it { should_not be_has_default }
+ it { is_expected.not_to be_has_default }
its :default do should be_nil end
it "should set a proc as default" do
expect { subject.default = proc { 12 } }.to_not raise_error
end
[1, {}, [], Object.new, "foo"].each do |input|
it "should reject anything but a proc (#{input.class})" do
expect { subject.default = input }.to raise_error ArgumentError, /not a proc/
end
end
end
context "with a default" do
before :each do subject.default = proc { [:foo] } end
- it { should be_has_default }
+ it { is_expected.to be_has_default }
its :default do should == [:foo] end
it "should invoke the block every time" do
- subject.default.object_id.should_not == subject.default.object_id
- subject.default.should == subject.default
+ expect(subject.default.object_id).not_to eq(subject.default.object_id)
+ expect(subject.default).to eq(subject.default)
end
it "should allow replacing the default proc" do
- subject.default.should == [:foo]
+ expect(subject.default).to eq([:foo])
subject.default = proc { :bar }
- subject.default.should == :bar
+ expect(subject.default).to eq(:bar)
end
end
end
end
diff --git a/spec/unit/interface_spec.rb b/spec/unit/interface_spec.rb
index 50f902de0..e533ac4a0 100755
--- a/spec/unit/interface_spec.rb
+++ b/spec/unit/interface_spec.rb
@@ -1,266 +1,266 @@
require 'spec_helper'
require 'puppet/face'
require 'puppet/interface'
describe Puppet::Interface do
subject { Puppet::Interface }
before :each do
@faces = Puppet::Interface::FaceCollection.
instance_variable_get("@faces").dup
@dq = $".dup
$".delete_if do |path| path =~ %r{/face/.*\.rb$} end
Puppet::Interface::FaceCollection.instance_variable_get("@faces").clear
end
after :each do
Puppet::Interface::FaceCollection.instance_variable_set("@faces", @faces)
$".clear ; @dq.each do |item| $" << item end
end
describe "#[]" do
it "should fail when no version is requested" do
expect { subject[:huzzah] }.to raise_error ArgumentError
end
it "should raise an exception when the requested version is unavailable" do
expect { subject[:huzzah, '17.0.0'] }.to raise_error(Puppet::Error, /Could not find version/)
end
it "should raise an exception when the requested face doesn't exist" do
expect { subject[:burrble_toot, :current] }.to raise_error(Puppet::Error, /Could not find Puppet Face/)
end
describe "version matching" do
{ '1' => '1.1.1',
'1.0' => '1.0.1',
'1.0.1' => '1.0.1',
'1.1' => '1.1.1',
'1.1.1' => '1.1.1'
}.each do |input, expect|
it "should match #{input.inspect} to #{expect.inspect}" do
face = subject[:version_matching, input]
- face.should be
- face.version.should == expect
+ expect(face).to be
+ expect(face.version).to eq(expect)
end
end
%w{1.0.2 1.2}.each do |input|
it "should not match #{input.inspect} to any version" do
expect { subject[:version_matching, input] }.
to raise_error Puppet::Error, /Could not find version/
end
end
end
end
describe "#define" do
it "should register the face" do
face = subject.define(:face_test_register, '0.0.1')
- face.should == subject[:face_test_register, '0.0.1']
+ expect(face).to eq(subject[:face_test_register, '0.0.1'])
end
it "should load actions" do
subject.any_instance.expects(:load_actions)
subject.define(:face_test_load_actions, '0.0.1')
end
it "should require a version number" do
expect { subject.define(:no_version) }.to raise_error ArgumentError
end
it "should support summary builder and accessor methods" do
- subject.new(:foo, '1.0.0').should respond_to(:summary).with(0).arguments
- subject.new(:foo, '1.0.0').should respond_to(:summary=).with(1).arguments
+ expect(subject.new(:foo, '1.0.0')).to respond_to(:summary).with(0).arguments
+ expect(subject.new(:foo, '1.0.0')).to respond_to(:summary=).with(1).arguments
end
# Required documentation methods...
{ :summary => "summary",
:description => "This is the description of the stuff\n\nWhee",
:examples => "This is my example",
:short_description => "This is my custom short description",
:notes => "These are my notes...",
:author => "This is my authorship data",
}.each do |attr, value|
it "should support #{attr} in the builder" do
face = subject.new(:builder, '1.0.0') do
self.send(attr, value)
end
- face.send(attr).should == value
+ expect(face.send(attr)).to eq(value)
end
end
end
describe "#initialize" do
it "should require a version number" do
expect { subject.new(:no_version) }.to raise_error ArgumentError
end
it "should require a valid version number" do
expect { subject.new(:bad_version, 'Rasins') }.
to raise_error ArgumentError
end
it "should instance-eval any provided block" do
face = subject.new(:face_test_block, '0.0.1') do
action(:something) do
when_invoked {|_| "foo" }
end
end
- face.something.should == "foo"
+ expect(face.something).to eq("foo")
end
end
it "should have a name" do
- subject.new(:me, '0.0.1').name.should == :me
+ expect(subject.new(:me, '0.0.1').name).to eq(:me)
end
it "should stringify with its own name" do
- subject.new(:me, '0.0.1').to_s.should =~ /\bme\b/
+ expect(subject.new(:me, '0.0.1').to_s).to match(/\bme\b/)
end
it "should try to require faces that are not known" do
subject::FaceCollection.expects(:load_face).with(:foo, :current)
subject::FaceCollection.expects(:load_face).with(:foo, '0.0.1')
expect { subject[:foo, '0.0.1'] }.to raise_error Puppet::Error
end
it_should_behave_like "things that declare options" do
def add_options_to(&block)
subject.new(:with_options, '0.0.1', &block)
end
end
describe "with face-level display_global_options" do
it "should not return any action level display_global_options" do
face = subject.new(:with_display_global_options, '0.0.1') do
display_global_options "environment"
action :baz do
when_invoked {|_| true }
display_global_options "modulepath"
end
end
face.display_global_options =~ ["environment"]
end
it "should not fail when a face d_g_o duplicates an action d_g_o" do
expect {
subject.new(:action_level_display_global_options, '0.0.1') do
action :bar do
when_invoked {|_| true }
display_global_options "environment"
end
display_global_options "environment"
end
}.to_not raise_error
end
it "should work when two actions have the same d_g_o" do
face = subject.new(:with_display_global_options, '0.0.1') do
action :foo do when_invoked {|_| true} ; display_global_options "environment" end
action :bar do when_invoked {|_| true} ; display_global_options "environment" end
end
face.get_action(:foo).display_global_options =~ ["environment"]
face.get_action(:bar).display_global_options =~ ["environment"]
end
end
describe "with inherited display_global_options" do
end
describe "with face-level options" do
it "should not return any action-level options" do
face = subject.new(:with_options, '0.0.1') do
option "--foo"
option "--bar"
action :baz do
when_invoked {|_| true }
option "--quux"
end
end
- face.options.should =~ [:foo, :bar]
+ expect(face.options).to match_array([:foo, :bar])
end
it "should fail when a face option duplicates an action option" do
expect {
subject.new(:action_level_options, '0.0.1') do
action :bar do
when_invoked {|_| true }
option "--foo"
end
option "--foo"
end
}.to raise_error ArgumentError, /Option foo conflicts with existing option foo on/i
end
it "should work when two actions have the same option" do
face = subject.new(:with_options, '0.0.1') do
action :foo do when_invoked {|_| true } ; option "--quux" end
action :bar do when_invoked {|_| true } ; option "--quux" end
end
- face.get_action(:foo).options.should =~ [:quux]
- face.get_action(:bar).options.should =~ [:quux]
+ expect(face.get_action(:foo).options).to match_array([:quux])
+ expect(face.get_action(:bar).options).to match_array([:quux])
end
it "should only list options and not aliases" do
face = subject.new(:face_options, '0.0.1') do
option "--bar", "-b", "--foo-bar"
end
- face.options.should =~ [:bar]
+ expect(face.options).to match_array([:bar])
end
end
describe "with inherited options" do
let :parent do
parent = Class.new(subject)
parent.option("--inherited")
parent.action(:parent_action) do when_invoked {|_| true } end
parent
end
let :face do
face = parent.new(:example, '0.2.1')
face.option("--local")
face.action(:face_action) do when_invoked {|_| true } end
face
end
describe "#options" do
it "should list inherited options" do
- face.options.should =~ [:inherited, :local]
+ expect(face.options).to match_array([:inherited, :local])
end
it "should see all options on face actions" do
- face.get_action(:face_action).options.should =~ [:inherited, :local]
+ expect(face.get_action(:face_action).options).to match_array([:inherited, :local])
end
it "should see all options on inherited actions accessed on the subclass" do
- face.get_action(:parent_action).options.should =~ [:inherited, :local]
+ expect(face.get_action(:parent_action).options).to match_array([:inherited, :local])
end
it "should not see subclass actions on the parent class" do
- parent.options.should =~ [:inherited]
+ expect(parent.options).to match_array([:inherited])
end
it "should not see subclass actions on actions accessed on the parent class" do
- parent.get_action(:parent_action).options.should =~ [:inherited]
+ expect(parent.get_action(:parent_action).options).to match_array([:inherited])
end
end
describe "#get_option" do
it "should return an inherited option object" do
- face.get_option(:inherited).should be_an_instance_of subject::Option
+ expect(face.get_option(:inherited)).to be_an_instance_of subject::Option
end
end
end
it_should_behave_like "documentation on faces" do
subject do
Puppet::Interface.new(:face_documentation, '0.0.1')
end
end
end
diff --git a/spec/unit/module_spec.rb b/spec/unit/module_spec.rb
index ce9d7b55e..0574f5bb2 100755
--- a/spec/unit/module_spec.rb
+++ b/spec/unit/module_spec.rb
@@ -1,718 +1,718 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_spec/modules'
require 'puppet/module_tool/checksums'
describe Puppet::Module do
include PuppetSpec::Files
let(:env) { mock("environment") }
let(:path) { "/path" }
let(:name) { "mymod" }
let(:mod) { Puppet::Module.new(name, path, env) }
before do
# This is necessary because of the extra checks we have for the deprecated
# 'plugins' directory
Puppet::FileSystem.stubs(:exist?).returns false
end
it "should have a class method that returns a named module from a given environment" do
env = Puppet::Node::Environment.create(:myenv, [])
env.expects(:module).with(name).returns "yep"
Puppet.override(:environments => Puppet::Environments::Static.new(env)) do
- Puppet::Module.find(name, "myenv").should == "yep"
+ expect(Puppet::Module.find(name, "myenv")).to eq("yep")
end
end
it "should return nil if asked for a named module that doesn't exist" do
env = Puppet::Node::Environment.create(:myenv, [])
env.expects(:module).with(name).returns nil
Puppet.override(:environments => Puppet::Environments::Static.new(env)) do
- Puppet::Module.find(name, "myenv").should be_nil
+ expect(Puppet::Module.find(name, "myenv")).to be_nil
end
end
describe "attributes" do
it "should support a 'version' attribute" do
mod.version = 1.09
- mod.version.should == 1.09
+ expect(mod.version).to eq(1.09)
end
it "should support a 'source' attribute" do
mod.source = "http://foo/bar"
- mod.source.should == "http://foo/bar"
+ expect(mod.source).to eq("http://foo/bar")
end
it "should support a 'project_page' attribute" do
mod.project_page = "http://foo/bar"
- mod.project_page.should == "http://foo/bar"
+ expect(mod.project_page).to eq("http://foo/bar")
end
it "should support an 'author' attribute" do
mod.author = "Luke Kanies <luke@madstop.com>"
- mod.author.should == "Luke Kanies <luke@madstop.com>"
+ expect(mod.author).to eq("Luke Kanies <luke@madstop.com>")
end
it "should support a 'license' attribute" do
mod.license = "GPL2"
- mod.license.should == "GPL2"
+ expect(mod.license).to eq("GPL2")
end
it "should support a 'summary' attribute" do
mod.summary = "GPL2"
- mod.summary.should == "GPL2"
+ expect(mod.summary).to eq("GPL2")
end
it "should support a 'description' attribute" do
mod.description = "GPL2"
- mod.description.should == "GPL2"
+ expect(mod.description).to eq("GPL2")
end
it "should support specifying a compatible puppet version" do
mod.puppetversion = "0.25"
- mod.puppetversion.should == "0.25"
+ expect(mod.puppetversion).to eq("0.25")
end
end
it "should validate that the puppet version is compatible" do
mod.puppetversion = "0.25"
Puppet.expects(:version).returns "0.25"
mod.validate_puppet_version
end
it "should fail if the specified puppet version is not compatible" do
mod.puppetversion = "0.25"
Puppet.stubs(:version).returns "0.24"
- lambda { mod.validate_puppet_version }.should raise_error(Puppet::Module::IncompatibleModule)
+ expect { mod.validate_puppet_version }.to raise_error(Puppet::Module::IncompatibleModule)
end
describe "when finding unmet dependencies" do
before do
Puppet::FileSystem.unstub(:exist?)
@modpath = tmpdir('modpath')
Puppet.settings[:modulepath] = @modpath
end
it "should list modules that are missing" do
metadata_file = "#{@modpath}/needy/metadata.json"
Puppet::FileSystem.expects(:exist?).with(metadata_file).returns true
mod = PuppetSpec::Modules.create(
'needy',
@modpath,
:metadata => {
:dependencies => [{
"version_requirement" => ">= 2.2.0",
"name" => "baz/foobar"
}]
}
)
- mod.unmet_dependencies.should == [{
+ expect(mod.unmet_dependencies).to eq([{
:reason => :missing,
:name => "baz/foobar",
:version_constraint => ">= 2.2.0",
:parent => { :name => 'puppetlabs/needy', :version => 'v9.9.9' },
:mod_details => { :installed_version => nil }
- }]
+ }])
end
it "should list modules that are missing and have invalid names" do
metadata_file = "#{@modpath}/needy/metadata.json"
Puppet::FileSystem.expects(:exist?).with(metadata_file).returns true
mod = PuppetSpec::Modules.create(
'needy',
@modpath,
:metadata => {
:dependencies => [{
"version_requirement" => ">= 2.2.0",
"name" => "baz/foobar=bar"
}]
}
)
- mod.unmet_dependencies.should == [{
+ expect(mod.unmet_dependencies).to eq([{
:reason => :missing,
:name => "baz/foobar=bar",
:version_constraint => ">= 2.2.0",
:parent => { :name => 'puppetlabs/needy', :version => 'v9.9.9' },
:mod_details => { :installed_version => nil }
- }]
+ }])
end
it "should list modules with unmet version requirement" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
['test_gte_req', 'test_specific_req', 'foobar'].each do |mod_name|
metadata_file = "#{@modpath}/#{mod_name}/metadata.json"
Puppet::FileSystem.stubs(:exist?).with(metadata_file).returns true
end
mod = PuppetSpec::Modules.create(
'test_gte_req',
@modpath,
:metadata => {
:dependencies => [{
"version_requirement" => ">= 2.2.0",
"name" => "baz/foobar"
}]
},
:environment => env
)
mod2 = PuppetSpec::Modules.create(
'test_specific_req',
@modpath,
:metadata => {
:dependencies => [{
"version_requirement" => "1.0.0",
"name" => "baz/foobar"
}]
},
:environment => env
)
PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => { :version => '2.0.0', :author => 'baz' },
:environment => env
)
- mod.unmet_dependencies.should == [{
+ expect(mod.unmet_dependencies).to eq([{
:reason => :version_mismatch,
:name => "baz/foobar",
:version_constraint => ">= 2.2.0",
:parent => { :version => "v9.9.9", :name => "puppetlabs/test_gte_req" },
:mod_details => { :installed_version => "2.0.0" }
- }]
+ }])
- mod2.unmet_dependencies.should == [{
+ expect(mod2.unmet_dependencies).to eq([{
:reason => :version_mismatch,
:name => "baz/foobar",
:version_constraint => "v1.0.0",
:parent => { :version => "v9.9.9", :name => "puppetlabs/test_specific_req" },
:mod_details => { :installed_version => "2.0.0" }
- }]
+ }])
end
it "should consider a dependency without a version requirement to be satisfied" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
mod = PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:dependencies => [{
"name" => "baz/foobar"
}]
},
:environment => env
)
PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:version => '2.0.0',
:author => 'baz'
},
:environment => env
)
- mod.unmet_dependencies.should be_empty
+ expect(mod.unmet_dependencies).to be_empty
end
it "should consider a dependency without a semantic version to be unmet" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
metadata_file = "#{@modpath}/foobar/metadata.json"
Puppet::FileSystem.expects(:exist?).with(metadata_file).times(3).returns true
mod = PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:dependencies => [{
"name" => "baz/foobar"
}]
},
:environment => env
)
PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:version => '5.1',
:author => 'baz'
},
:environment => env
)
- mod.unmet_dependencies.should == [{
+ expect(mod.unmet_dependencies).to eq([{
:reason => :non_semantic_version,
:parent => { :version => "v9.9.9", :name => "puppetlabs/foobar" },
:mod_details => { :installed_version => "5.1" },
:name => "baz/foobar",
:version_constraint => ">= 0.0.0"
- }]
+ }])
end
it "should have valid dependencies when no dependencies have been specified" do
mod = PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:dependencies => []
}
)
- mod.unmet_dependencies.should == []
+ expect(mod.unmet_dependencies).to eq([])
end
it "should only list unmet dependencies" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
[name, 'satisfied'].each do |mod_name|
metadata_file = "#{@modpath}/#{mod_name}/metadata.json"
Puppet::FileSystem.expects(:exist?).with(metadata_file).twice.returns true
end
mod = PuppetSpec::Modules.create(
name,
@modpath,
:metadata => {
:dependencies => [
{
"version_requirement" => ">= 2.2.0",
"name" => "baz/satisfied"
},
{
"version_requirement" => ">= 2.2.0",
"name" => "baz/notsatisfied"
}
]
},
:environment => env
)
PuppetSpec::Modules.create(
'satisfied',
@modpath,
:metadata => {
:version => '3.3.0',
:author => 'baz'
},
:environment => env
)
- mod.unmet_dependencies.should == [{
+ expect(mod.unmet_dependencies).to eq([{
:reason => :missing,
:mod_details => { :installed_version => nil },
:parent => { :version => "v9.9.9", :name => "puppetlabs/#{name}" },
:name => "baz/notsatisfied",
:version_constraint => ">= 2.2.0"
- }]
+ }])
end
it "should be empty when all dependencies are met" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
mod = PuppetSpec::Modules.create(
'mymod2',
@modpath,
:metadata => {
:dependencies => [
{
"version_requirement" => ">= 2.2.0",
"name" => "baz/satisfied"
},
{
"version_requirement" => "< 2.2.0",
"name" => "baz/alsosatisfied"
}
]
},
:environment => env
)
PuppetSpec::Modules.create(
'satisfied',
@modpath,
:metadata => {
:version => '3.3.0',
:author => 'baz'
},
:environment => env
)
PuppetSpec::Modules.create(
'alsosatisfied',
@modpath,
:metadata => {
:version => '2.1.0',
:author => 'baz'
},
:environment => env
)
- mod.unmet_dependencies.should be_empty
+ expect(mod.unmet_dependencies).to be_empty
end
end
describe "when managing supported platforms" do
it "should support specifying a supported platform" do
mod.supports "solaris"
end
it "should support specifying a supported platform and version" do
mod.supports "solaris", 1.0
end
end
it "should return nil if asked for a module whose name is 'nil'" do
- Puppet::Module.find(nil, "myenv").should be_nil
+ expect(Puppet::Module.find(nil, "myenv")).to be_nil
end
it "should provide support for logging" do
- Puppet::Module.ancestors.should be_include(Puppet::Util::Logging)
+ expect(Puppet::Module.ancestors).to be_include(Puppet::Util::Logging)
end
it "should be able to be converted to a string" do
- mod.to_s.should == "Module #{name}(#{path})"
+ expect(mod.to_s).to eq("Module #{name}(#{path})")
end
it "should fail if its name is not alphanumeric" do
- lambda { Puppet::Module.new(".something", "/path", env) }.should raise_error(Puppet::Module::InvalidName)
+ expect { Puppet::Module.new(".something", "/path", env) }.to raise_error(Puppet::Module::InvalidName)
end
it "should require a name at initialization" do
- lambda { Puppet::Module.new }.should raise_error(ArgumentError)
+ expect { Puppet::Module.new }.to raise_error(ArgumentError)
end
it "should accept an environment at initialization" do
- Puppet::Module.new("foo", "/path", env).environment.should == env
+ expect(Puppet::Module.new("foo", "/path", env).environment).to eq(env)
end
describe '#modulepath' do
it "should return the directory the module is installed in, if a path exists" do
mod = Puppet::Module.new("foo", "/a/foo", env)
- mod.modulepath.should == '/a'
+ expect(mod.modulepath).to eq('/a')
end
end
[:plugins, :pluginfacts, :templates, :files, :manifests].each do |filetype|
case filetype
when :plugins
dirname = "lib"
when :pluginfacts
dirname = "facts.d"
else
dirname = filetype.to_s
end
it "should be able to return individual #{filetype}" do
module_file = File.join(path, dirname, "my/file")
Puppet::FileSystem.expects(:exist?).with(module_file).returns true
- mod.send(filetype.to_s.sub(/s$/, ''), "my/file").should == module_file
+ expect(mod.send(filetype.to_s.sub(/s$/, ''), "my/file")).to eq(module_file)
end
it "should consider #{filetype} to be present if their base directory exists" do
module_file = File.join(path, dirname)
Puppet::FileSystem.expects(:exist?).with(module_file).returns true
- mod.send(filetype.to_s + "?").should be_true
+ expect(mod.send(filetype.to_s + "?")).to be_truthy
end
it "should consider #{filetype} to be absent if their base directory does not exist" do
module_file = File.join(path, dirname)
Puppet::FileSystem.expects(:exist?).with(module_file).returns false
- mod.send(filetype.to_s + "?").should be_false
+ expect(mod.send(filetype.to_s + "?")).to be_falsey
end
it "should return nil if asked to return individual #{filetype} that don't exist" do
module_file = File.join(path, dirname, "my/file")
Puppet::FileSystem.expects(:exist?).with(module_file).returns false
- mod.send(filetype.to_s.sub(/s$/, ''), "my/file").should be_nil
+ expect(mod.send(filetype.to_s.sub(/s$/, ''), "my/file")).to be_nil
end
it "should return the base directory if asked for a nil path" do
base = File.join(path, dirname)
Puppet::FileSystem.expects(:exist?).with(base).returns true
- mod.send(filetype.to_s.sub(/s$/, ''), nil).should == base
+ expect(mod.send(filetype.to_s.sub(/s$/, ''), nil)).to eq(base)
end
end
it "should return the path to the plugin directory" do
- mod.plugin_directory.should == File.join(path, "lib")
+ expect(mod.plugin_directory).to eq(File.join(path, "lib"))
end
end
describe Puppet::Module, "when finding matching manifests" do
before do
@mod = Puppet::Module.new("mymod", "/a", mock("environment"))
@pq_glob_with_extension = "yay/*.xx"
@fq_glob_with_extension = "/a/manifests/#{@pq_glob_with_extension}"
end
it "should return all manifests matching the glob pattern" do
Dir.expects(:glob).with(@fq_glob_with_extension).returns(%w{foo bar})
FileTest.stubs(:directory?).returns false
- @mod.match_manifests(@pq_glob_with_extension).should == %w{foo bar}
+ expect(@mod.match_manifests(@pq_glob_with_extension)).to eq(%w{foo bar})
end
it "should not return directories" do
Dir.expects(:glob).with(@fq_glob_with_extension).returns(%w{foo bar})
FileTest.expects(:directory?).with("foo").returns false
FileTest.expects(:directory?).with("bar").returns true
- @mod.match_manifests(@pq_glob_with_extension).should == %w{foo}
+ expect(@mod.match_manifests(@pq_glob_with_extension)).to eq(%w{foo})
end
it "should default to the 'init' file if no glob pattern is specified" do
Puppet::FileSystem.expects(:exist?).with("/a/manifests/init.pp").returns(true)
- @mod.match_manifests(nil).should == %w{/a/manifests/init.pp}
+ expect(@mod.match_manifests(nil)).to eq(%w{/a/manifests/init.pp})
end
it "should return all manifests matching the glob pattern in all existing paths" do
Dir.expects(:glob).with(@fq_glob_with_extension).returns(%w{a b})
- @mod.match_manifests(@pq_glob_with_extension).should == %w{a b}
+ expect(@mod.match_manifests(@pq_glob_with_extension)).to eq(%w{a b})
end
it "should match the glob pattern plus '.pp' if no extension is specified" do
Dir.expects(:glob).with("/a/manifests/yay/foo.pp").returns(%w{yay})
- @mod.match_manifests("yay/foo").should == %w{yay}
+ expect(@mod.match_manifests("yay/foo")).to eq(%w{yay})
end
it "should return an empty array if no manifests matched" do
Dir.expects(:glob).with(@fq_glob_with_extension).returns([])
- @mod.match_manifests(@pq_glob_with_extension).should == []
+ expect(@mod.match_manifests(@pq_glob_with_extension)).to eq([])
end
it "should raise an error if the pattern tries to leave the manifest directory" do
expect do
@mod.match_manifests("something/../../*")
end.to raise_error(Puppet::Module::InvalidFilePattern, 'The pattern "something/../../*" to find manifests in the module "mymod" is invalid and potentially unsafe.')
end
end
describe Puppet::Module do
include PuppetSpec::Files
before do
@modpath = tmpdir('modpath')
@module = PuppetSpec::Modules.create('mymod', @modpath)
end
it "should use 'License' in its current path as its metadata file" do
- @module.license_file.should == "#{@modpath}/mymod/License"
+ expect(@module.license_file).to eq("#{@modpath}/mymod/License")
end
it "should cache the license file" do
@module.expects(:path).once.returns nil
@module.license_file
@module.license_file
end
it "should use 'metadata.json' in its current path as its metadata file" do
- @module.metadata_file.should == "#{@modpath}/mymod/metadata.json"
+ expect(@module.metadata_file).to eq("#{@modpath}/mymod/metadata.json")
end
it "should have metadata if it has a metadata file and its data is not empty" do
Puppet::FileSystem.expects(:exist?).with(@module.metadata_file).returns true
File.stubs(:read).with(@module.metadata_file).returns "{\"foo\" : \"bar\"}"
- @module.should be_has_metadata
+ expect(@module).to be_has_metadata
end
it "should have metadata if it has a metadata file and its data is not empty" do
Puppet::FileSystem.expects(:exist?).with(@module.metadata_file).returns true
File.stubs(:read).with(@module.metadata_file).returns "{\"foo\" : \"bar\"}"
- @module.should be_has_metadata
+ expect(@module).to be_has_metadata
end
it "should not have metadata if has a metadata file and its data is empty" do
Puppet::FileSystem.expects(:exist?).with(@module.metadata_file).returns true
File.stubs(:read).with(@module.metadata_file).returns "/*
+-----------------------------------------------------------------------+
| |
| ==> DO NOT EDIT THIS FILE! <== |
| |
| You should edit the `Modulefile` and run `puppet-module build` |
| to generate the `metadata.json` file for your releases. |
| |
+-----------------------------------------------------------------------+
*/
{}"
- @module.should_not be_has_metadata
+ expect(@module).not_to be_has_metadata
end
it "should know if it is missing a metadata file" do
Puppet::FileSystem.expects(:exist?).with(@module.metadata_file).returns false
- @module.should_not be_has_metadata
+ expect(@module).not_to be_has_metadata
end
it "should be able to parse its metadata file" do
- @module.should respond_to(:load_metadata)
+ expect(@module).to respond_to(:load_metadata)
end
it "should parse its metadata file on initialization if it is present" do
Puppet::Module.any_instance.expects(:has_metadata?).returns true
Puppet::Module.any_instance.expects(:load_metadata)
Puppet::Module.new("yay", "/path", mock("env"))
end
it "should tolerate failure to parse" do
Puppet::FileSystem.expects(:exist?).with(@module.metadata_file).returns true
File.stubs(:read).with(@module.metadata_file).returns(my_fixture('trailing-comma.json'))
- @module.has_metadata?.should be_false
+ expect(@module.has_metadata?).to be_falsey
end
def a_module_with_metadata(data)
text = data.to_pson
mod = Puppet::Module.new("foo", "/path", mock("env"))
mod.stubs(:metadata_file).returns "/my/file"
File.stubs(:read).with("/my/file").returns text
mod
end
describe "when loading the metadata file" do
before do
@data = {
:license => "GPL2",
:author => "luke",
:version => "1.0",
:source => "http://foo/",
:puppetversion => "0.25",
:dependencies => []
}
@module = a_module_with_metadata(@data)
end
%w{source author version license}.each do |attr|
it "should set #{attr} if present in the metadata file" do
@module.load_metadata
- @module.send(attr).should == @data[attr.to_sym]
+ expect(@module.send(attr)).to eq(@data[attr.to_sym])
end
it "should fail if #{attr} is not present in the metadata file" do
@data.delete(attr.to_sym)
@text = @data.to_pson
File.stubs(:read).with("/my/file").returns @text
- lambda { @module.load_metadata }.should raise_error(
+ expect { @module.load_metadata }.to raise_error(
Puppet::Module::MissingMetadata,
"No #{attr} module metadata provided for foo"
)
end
end
it "should set puppetversion if present in the metadata file" do
@module.load_metadata
- @module.puppetversion.should == @data[:puppetversion]
+ expect(@module.puppetversion).to eq(@data[:puppetversion])
end
context "when versionRequirement is used for dependency version info" do
before do
@data = {
:license => "GPL2",
:author => "luke",
:version => "1.0",
:source => "http://foo/",
:puppetversion => "0.25",
:dependencies => [
{
"versionRequirement" => "0.0.1",
"name" => "pmtacceptance/stdlib"
},
{
"versionRequirement" => "0.1.0",
"name" => "pmtacceptance/apache"
}
]
}
@module = a_module_with_metadata(@data)
end
it "should set the dependency version_requirement key" do
@module.load_metadata
- @module.dependencies[0]['version_requirement'].should == "0.0.1"
+ expect(@module.dependencies[0]['version_requirement']).to eq("0.0.1")
end
it "should set the version_requirement key for all dependencies" do
@module.load_metadata
- @module.dependencies[0]['version_requirement'].should == "0.0.1"
- @module.dependencies[1]['version_requirement'].should == "0.1.0"
+ expect(@module.dependencies[0]['version_requirement']).to eq("0.0.1")
+ expect(@module.dependencies[1]['version_requirement']).to eq("0.1.0")
end
end
end
it "should be able to tell if there are local changes" do
modpath = tmpdir('modpath')
foo_checksum = 'acbd18db4cc2f85cedef654fccc4a4d8'
checksummed_module = PuppetSpec::Modules.create(
'changed',
modpath,
:metadata => {
:checksums => {
"foo" => foo_checksum,
}
}
)
foo_path = Pathname.new(File.join(checksummed_module.path, 'foo'))
IO.binwrite(foo_path, 'notfoo')
- Puppet::ModuleTool::Checksums.new(foo_path).checksum(foo_path).should_not == foo_checksum
+ expect(Puppet::ModuleTool::Checksums.new(foo_path).checksum(foo_path)).not_to eq(foo_checksum)
IO.binwrite(foo_path, 'foo')
- Puppet::ModuleTool::Checksums.new(foo_path).checksum(foo_path).should == foo_checksum
+ expect(Puppet::ModuleTool::Checksums.new(foo_path).checksum(foo_path)).to eq(foo_checksum)
end
it "should know what other modules require it" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
dependable = PuppetSpec::Modules.create(
'dependable',
@modpath,
:metadata => {:author => 'puppetlabs'},
:environment => env
)
PuppetSpec::Modules.create(
'needy',
@modpath,
:metadata => {
:author => 'beggar',
:dependencies => [{
"version_requirement" => ">= 2.2.0",
"name" => "puppetlabs/dependable"
}]
},
:environment => env
)
PuppetSpec::Modules.create(
'wantit',
@modpath,
:metadata => {
:author => 'spoiled',
:dependencies => [{
"version_requirement" => "< 5.0.0",
"name" => "puppetlabs/dependable"
}]
},
:environment => env
)
- dependable.required_by.should =~ [
+ expect(dependable.required_by).to match_array([
{
"name" => "beggar/needy",
"version" => "9.9.9",
"version_requirement" => ">= 2.2.0"
},
{
"name" => "spoiled/wantit",
"version" => "9.9.9",
"version_requirement" => "< 5.0.0"
}
- ]
+ ])
end
end
diff --git a/spec/unit/module_tool/applications/installer_spec.rb b/spec/unit/module_tool/applications/installer_spec.rb
index 088e67abf..80f87162c 100644
--- a/spec/unit/module_tool/applications/installer_spec.rb
+++ b/spec/unit/module_tool/applications/installer_spec.rb
@@ -1,363 +1,363 @@
require 'spec_helper'
require 'puppet/module_tool/applications'
require 'puppet_spec/module_tool/shared_functions'
require 'puppet_spec/module_tool/stub_source'
require 'semver'
describe Puppet::ModuleTool::Applications::Installer do
include PuppetSpec::ModuleTool::SharedFunctions
include PuppetSpec::Files
include PuppetSpec::Fixtures
before do
FileUtils.mkdir_p(primary_dir)
FileUtils.mkdir_p(secondary_dir)
end
let(:vardir) { tmpdir('installer') }
let(:primary_dir) { File.join(vardir, "primary") }
let(:secondary_dir) { File.join(vardir, "secondary") }
let(:remote_source) { PuppetSpec::ModuleTool::StubSource.new }
let(:install_dir) do
mock("Puppet::ModuleTool::InstallDirectory").tap do |dir|
dir.stubs(:prepare)
dir.stubs(:target).returns(primary_dir)
end
end
before do
Semantic::Dependency.clear_sources
installer = Puppet::ModuleTool::Applications::Installer.any_instance
installer.stubs(:module_repository).returns(remote_source)
end
def installer(modname, target_dir, options)
Puppet::ModuleTool.set_option_defaults(options)
Puppet::ModuleTool::Applications::Installer.new(modname, target_dir, options)
end
let(:environment) do
Puppet.lookup(:current_environment).override_with(
:vardir => vardir,
:modulepath => [ primary_dir, secondary_dir ]
)
end
context '#run' do
let(:module) { 'pmtacceptance-stdlib' }
def options
{ :environment => environment }
end
let(:application) { installer(self.module, install_dir, options) }
subject { application.run }
it 'installs the specified module' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', nil => v('4.1.0')
end
context 'with a tarball file' do
let(:module) { fixtures('stdlib.tgz') }
it 'installs the specified tarball' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'puppetlabs-stdlib', nil => v('3.2.0')
end
context 'with --ignore-dependencies' do
def options
super.merge(:ignore_dependencies => true)
end
it 'installs the specified tarball' do
remote_source.expects(:fetch).never
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'puppetlabs-stdlib', nil => v('3.2.0')
end
end
context 'with dependencies' do
let(:module) { fixtures('java.tgz') }
it 'installs the specified tarball' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'puppetlabs-java', nil => v('1.0.0')
graph_should_include 'puppetlabs-stdlib', nil => v('4.1.0')
end
context 'with --ignore-dependencies' do
def options
super.merge(:ignore_dependencies => true)
end
it 'installs the specified tarball without dependencies' do
remote_source.expects(:fetch).never
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'puppetlabs-java', nil => v('1.0.0')
graph_should_include 'puppetlabs-stdlib', nil
end
end
end
end
context 'with dependencies' do
let(:module) { 'pmtacceptance-apache' }
it 'installs the specified module and its dependencies' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', nil => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', nil => v('4.1.0')
end
context 'and using --ignore_dependencies' do
def options
super.merge(:ignore_dependencies => true)
end
it 'installs only the specified module' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', nil => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', nil
end
end
context 'that are already installed' do
context 'and satisfied' do
before { preinstall('pmtacceptance-stdlib', '4.1.0') }
it 'installs only the specified module' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', nil => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', :path => primary_dir
end
context '(outdated but suitable version)' do
before { preinstall('pmtacceptance-stdlib', '2.4.0') }
it 'installs only the specified module' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', nil => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', v('2.4.0') => v('2.4.0'), :path => primary_dir
end
end
context '(outdated and unsuitable version)' do
before { preinstall('pmtacceptance-stdlib', '1.0.0') }
it 'installs a version that is compatible with the installed dependencies' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', nil => v('0.0.4')
graph_should_include 'pmtacceptance-stdlib', nil
end
end
end
context 'but not satisfied' do
let(:module) { 'pmtacceptance-keystone' }
def options
super.merge(:version => '2.0.0')
end
before { preinstall('pmtacceptance-mysql', '2.1.0') }
it 'installs only the specified module' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-keystone', nil => v('2.0.0')
graph_should_include 'pmtacceptance-mysql', v('2.1.0') => v('2.1.0')
graph_should_include 'pmtacceptance-stdlib', nil
end
end
end
context 'that are already installed in other modulepath directories' do
before { preinstall('pmtacceptance-stdlib', '1.0.0', :into => secondary_dir) }
let(:module) { 'pmtacceptance-apache' }
context 'without dependency updates' do
it 'installs the module only' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', nil => v('0.0.4')
graph_should_include 'pmtacceptance-stdlib', nil
end
end
context 'with dependency updates' do
before { preinstall('pmtacceptance-stdlib', '2.0.0', :into => secondary_dir) }
it 'installs the module and upgrades dependencies in-place' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', nil => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', v('2.0.0') => v('2.6.0'), :path => secondary_dir
end
end
end
end
context 'with a specified' do
context 'version' do
def options
super.merge(:version => '3.0.0')
end
it 'installs the specified release (or a prerelease thereof)' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', nil => v('3.0.0')
end
end
context 'version range' do
def options
super.merge(:version => '3.x')
end
it 'installs the greatest available version matching that range' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', nil => v('3.2.0')
end
end
end
context 'when depended upon' do
before { preinstall('pmtacceptance-keystone', '2.1.0') }
let(:module) { 'pmtacceptance-mysql' }
it 'installs the greatest available version meeting the dependency constraints' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-mysql', nil => v('0.9.0')
end
context 'with a --version that can satisfy' do
def options
super.merge(:version => '0.8.0')
end
it 'installs the greatest available version satisfying both constraints' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-mysql', nil => v('0.8.0')
end
end
context 'with a --version that cannot satisfy' do
def options
super.merge(:version => '> 1.0.0')
end
it 'fails to install, since there is no version that can satisfy both constraints' do
- subject.should include :result => :failure
+ expect(subject).to include :result => :failure
end
context 'with --ignore-dependencies' do
def options
super.merge(:ignore_dependencies => true)
end
it 'fails to install, since ignore_dependencies should still respect dependencies from installed modules' do
- subject.should include :result => :failure
+ expect(subject).to include :result => :failure
end
end
context 'with --force' do
def options
super.merge(:force => true)
end
it 'installs the greatest available version, ignoring dependencies' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-mysql', nil => v('2.1.0')
end
end
end
end
context 'when already installed' do
before { preinstall('pmtacceptance-stdlib', '1.0.0') }
context 'but matching the requested version' do
it 'does nothing, since the installed version satisfies' do
- subject.should include :result => :noop
+ expect(subject).to include :result => :noop
end
context 'with --force' do
def options
super.merge(:force => true)
end
it 'does reinstall the module' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('4.1.0')
end
end
context 'with local changes' do
before do
release = application.send(:installed_modules)['pmtacceptance-stdlib']
mark_changed(release.mod.path)
end
it 'does nothing, since local changes do not affect that' do
- subject.should include :result => :noop
+ expect(subject).to include :result => :noop
end
context 'with --force' do
def options
super.merge(:force => true)
end
it 'does reinstall the module, since --force ignores local changes' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('4.1.0')
end
end
end
end
context 'but not matching the requested version' do
def options
super.merge(:version => '2.x')
end
it 'fails to install the module, since it is already installed' do
- subject.should include :result => :failure
- subject[:error].should include :oneline => "'pmtacceptance-stdlib' (v2.x) requested; 'pmtacceptance-stdlib' (v1.0.0) already installed"
+ expect(subject).to include :result => :failure
+ expect(subject[:error]).to include :oneline => "'pmtacceptance-stdlib' (v2.x) requested; 'pmtacceptance-stdlib' (v1.0.0) already installed"
end
context 'with --force' do
def options
super.merge(:force => true)
end
it 'installs the greatest version matching the new version range' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('2.6.0')
end
end
end
end
context 'when a module with the same name is already installed' do
let(:module) { 'pmtacceptance-stdlib' }
before { preinstall('puppetlabs-stdlib', '4.1.0') }
it 'fails to install, since two modules with the same name cannot be installed simultaneously' do
- subject.should include :result => :failure
+ expect(subject).to include :result => :failure
end
context 'using --force' do
def options
super.merge(:force => true)
end
it 'overwrites the existing module with the greatest version of the requested module' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', nil => v('4.1.0')
end
end
end
end
end
diff --git a/spec/unit/module_tool/applications/searcher_spec.rb b/spec/unit/module_tool/applications/searcher_spec.rb
index b53848585..c3d284a8a 100644
--- a/spec/unit/module_tool/applications/searcher_spec.rb
+++ b/spec/unit/module_tool/applications/searcher_spec.rb
@@ -1,38 +1,38 @@
require 'spec_helper'
require 'puppet/module_tool/applications'
require 'puppet_spec/modules'
describe Puppet::ModuleTool::Applications::Searcher do
include PuppetSpec::Files
describe "when searching" do
let(:forge) { mock 'forge', :host => 'http://nowhe.re' }
let(:searcher) do
described_class.new('search_term', forge)
end
it "should return results from a forge query when successful" do
results = 'mock results'
forge.expects(:search).with('search_term').returns(results)
search_result = searcher.run
- search_result.should == {
+ expect(search_result).to eq({
:result => :success,
:answers => results,
- }
+ })
end
it "should return an error when the forge query throws an exception" do
forge.expects(:search).with('search_term').raises Puppet::Forge::Errors::ForgeError.new("something went wrong")
search_result = searcher.run
- search_result.should == {
+ expect(search_result).to eq({
:result => :failure,
:error => {
:oneline => 'something went wrong',
:multiline => 'something went wrong',
},
- }
+ })
end
end
end
diff --git a/spec/unit/module_tool/applications/uninstaller_spec.rb b/spec/unit/module_tool/applications/uninstaller_spec.rb
index 66e71b638..684b2ede5 100644
--- a/spec/unit/module_tool/applications/uninstaller_spec.rb
+++ b/spec/unit/module_tool/applications/uninstaller_spec.rb
@@ -1,165 +1,165 @@
require 'spec_helper'
require 'puppet/module_tool'
require 'tmpdir'
require 'puppet_spec/module_tool/shared_functions'
require 'puppet_spec/module_tool/stub_source'
describe Puppet::ModuleTool::Applications::Uninstaller do
include PuppetSpec::ModuleTool::SharedFunctions
include PuppetSpec::Files
before do
FileUtils.mkdir_p(primary_dir)
FileUtils.mkdir_p(secondary_dir)
end
let(:environment) do
Puppet.lookup(:current_environment).override_with(
:vardir => vardir,
:modulepath => [ primary_dir, secondary_dir ]
)
end
let(:vardir) { tmpdir('uninstaller') }
let(:primary_dir) { File.join(vardir, "primary") }
let(:secondary_dir) { File.join(vardir, "secondary") }
let(:remote_source) { PuppetSpec::ModuleTool::StubSource.new }
let(:module) { 'module-not_installed' }
let(:application) do
opts = options
Puppet::ModuleTool.set_option_defaults(opts)
Puppet::ModuleTool::Applications::Uninstaller.new(self.module, opts)
end
def options
{ :environment => environment }
end
subject { application.run }
context "when the module is not installed" do
it "should fail" do
- subject.should include :result => :failure
+ expect(subject).to include :result => :failure
end
end
context "when the module is installed" do
let(:module) { 'pmtacceptance-stdlib' }
before { preinstall('pmtacceptance-stdlib', '1.0.0') }
before { preinstall('pmtacceptance-apache', '0.0.4') }
it "should uninstall the module" do
- subject[:affected_modules].first.forge_name.should == "pmtacceptance/stdlib"
+ expect(subject[:affected_modules].first.forge_name).to eq("pmtacceptance/stdlib")
end
it "should only uninstall the requested module" do
subject[:affected_modules].length == 1
end
context 'in two modulepaths' do
before { preinstall('pmtacceptance-stdlib', '2.0.0', :into => secondary_dir) }
it "should fail if a module exists twice in the modpath" do
- subject.should include :result => :failure
+ expect(subject).to include :result => :failure
end
end
context "when options[:version] is specified" do
def options
super.merge(:version => '1.0.0')
end
it "should uninstall the module if the version matches" do
- subject[:affected_modules].length.should == 1
- subject[:affected_modules].first.version.should == "1.0.0"
+ expect(subject[:affected_modules].length).to eq(1)
+ expect(subject[:affected_modules].first.version).to eq("1.0.0")
end
context 'but not matched' do
def options
super.merge(:version => '2.0.0')
end
it "should not uninstall the module if the version does not match" do
- subject.should include :result => :failure
+ expect(subject).to include :result => :failure
end
end
end
context "when the module metadata is missing" do
before { File.unlink(File.join(primary_dir, 'stdlib', 'metadata.json')) }
it "should not uninstall the module" do
- application.run[:result].should == :failure
+ expect(application.run[:result]).to eq(:failure)
end
end
context "when the module has local changes" do
before do
mark_changed(File.join(primary_dir, 'stdlib'))
end
it "should not uninstall the module" do
- subject.should include :result => :failure
+ expect(subject).to include :result => :failure
end
end
context "when uninstalling the module will cause broken dependencies" do
before { preinstall('pmtacceptance-apache', '0.10.0') }
it "should not uninstall the module" do
- subject.should include :result => :failure
+ expect(subject).to include :result => :failure
end
end
context 'with --ignore-changes' do
def options
super.merge(:ignore_changes => true)
end
context 'with local changes' do
before do
mark_changed(File.join(primary_dir, 'stdlib'))
end
it 'overwrites the installed module with the greatest version matching that range' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
end
end
context 'without local changes' do
it 'overwrites the installed module with the greatest version matching that range' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
end
end
end
context "when using the --force flag" do
def options
super.merge(:force => true)
end
context "with local changes" do
before do
mark_changed(File.join(primary_dir, 'stdlib'))
end
it "should ignore local changes" do
- subject[:affected_modules].length.should == 1
- subject[:affected_modules].first.forge_name.should == "pmtacceptance/stdlib"
+ expect(subject[:affected_modules].length).to eq(1)
+ expect(subject[:affected_modules].first.forge_name).to eq("pmtacceptance/stdlib")
end
end
context "while depended upon" do
before { preinstall('pmtacceptance-apache', '0.10.0') }
it "should ignore broken dependencies" do
- subject[:affected_modules].length.should == 1
- subject[:affected_modules].first.forge_name.should == "pmtacceptance/stdlib"
+ expect(subject[:affected_modules].length).to eq(1)
+ expect(subject[:affected_modules].first.forge_name).to eq("pmtacceptance/stdlib")
end
end
end
end
end
diff --git a/spec/unit/module_tool/applications/unpacker_spec.rb b/spec/unit/module_tool/applications/unpacker_spec.rb
index 81557df99..32d1cc3f7 100644
--- a/spec/unit/module_tool/applications/unpacker_spec.rb
+++ b/spec/unit/module_tool/applications/unpacker_spec.rb
@@ -1,74 +1,74 @@
require 'spec_helper'
require 'json'
require 'puppet/module_tool/applications'
require 'puppet/file_system'
require 'puppet_spec/modules'
describe Puppet::ModuleTool::Applications::Unpacker do
include PuppetSpec::Files
let(:target) { tmpdir("unpacker") }
let(:module_name) { 'myusername-mytarball' }
let(:filename) { tmpdir("module") + "/module.tar.gz" }
let(:working_dir) { tmpdir("working_dir") }
before :each do
Puppet.settings[:module_working_dir] = working_dir
end
it "should attempt to untar file to temporary location" do
untar = mock('Tar')
untar.expects(:unpack).with(filename, anything()) do |src, dest, _|
FileUtils.mkdir(File.join(dest, 'extractedmodule'))
File.open(File.join(dest, 'extractedmodule', 'metadata.json'), 'w+') do |file|
file.puts JSON.generate('name' => module_name, 'version' => '1.0.0')
end
true
end
Puppet::ModuleTool::Tar.expects(:instance).returns(untar)
Puppet::ModuleTool::Applications::Unpacker.run(filename, :target_dir => target)
- File.should be_directory(File.join(target, 'mytarball'))
+ expect(File).to be_directory(File.join(target, 'mytarball'))
end
it "should warn about symlinks", :if => Puppet.features.manages_symlinks? do
untar = mock('Tar')
untar.expects(:unpack).with(filename, anything()) do |src, dest, _|
FileUtils.mkdir(File.join(dest, 'extractedmodule'))
File.open(File.join(dest, 'extractedmodule', 'metadata.json'), 'w+') do |file|
file.puts JSON.generate('name' => module_name, 'version' => '1.0.0')
end
FileUtils.touch(File.join(dest, 'extractedmodule/tempfile'))
Puppet::FileSystem.symlink(File.join(dest, 'extractedmodule/tempfile'), File.join(dest, 'extractedmodule/tempfile2'))
true
end
Puppet::ModuleTool::Tar.expects(:instance).returns(untar)
Puppet.expects(:warning).with(regexp_matches(/symlinks/i))
Puppet::ModuleTool::Applications::Unpacker.run(filename, :target_dir => target)
- File.should be_directory(File.join(target, 'mytarball'))
+ expect(File).to be_directory(File.join(target, 'mytarball'))
end
it "should warn about symlinks in subdirectories", :if => Puppet.features.manages_symlinks? do
untar = mock('Tar')
untar.expects(:unpack).with(filename, anything()) do |src, dest, _|
FileUtils.mkdir(File.join(dest, 'extractedmodule'))
File.open(File.join(dest, 'extractedmodule', 'metadata.json'), 'w+') do |file|
file.puts JSON.generate('name' => module_name, 'version' => '1.0.0')
end
FileUtils.mkdir(File.join(dest, 'extractedmodule/manifests'))
FileUtils.touch(File.join(dest, 'extractedmodule/manifests/tempfile'))
Puppet::FileSystem.symlink(File.join(dest, 'extractedmodule/manifests/tempfile'), File.join(dest, 'extractedmodule/manifests/tempfile2'))
true
end
Puppet::ModuleTool::Tar.expects(:instance).returns(untar)
Puppet.expects(:warning).with(regexp_matches(/symlinks/i))
Puppet::ModuleTool::Applications::Unpacker.run(filename, :target_dir => target)
- File.should be_directory(File.join(target, 'mytarball'))
+ expect(File).to be_directory(File.join(target, 'mytarball'))
end
end
diff --git a/spec/unit/module_tool/applications/upgrader_spec.rb b/spec/unit/module_tool/applications/upgrader_spec.rb
index 382e45a75..139992441 100644
--- a/spec/unit/module_tool/applications/upgrader_spec.rb
+++ b/spec/unit/module_tool/applications/upgrader_spec.rb
@@ -1,324 +1,324 @@
require 'spec_helper'
require 'puppet/module_tool/applications'
require 'puppet_spec/module_tool/shared_functions'
require 'puppet_spec/module_tool/stub_source'
require 'semver'
describe Puppet::ModuleTool::Applications::Upgrader do
include PuppetSpec::ModuleTool::SharedFunctions
include PuppetSpec::Files
before do
FileUtils.mkdir_p(primary_dir)
FileUtils.mkdir_p(secondary_dir)
end
let(:vardir) { tmpdir('upgrader') }
let(:primary_dir) { File.join(vardir, "primary") }
let(:secondary_dir) { File.join(vardir, "secondary") }
let(:remote_source) { PuppetSpec::ModuleTool::StubSource.new }
let(:environment) do
Puppet.lookup(:current_environment).override_with(
:vardir => vardir,
:modulepath => [ primary_dir, secondary_dir ]
)
end
before do
Semantic::Dependency.clear_sources
installer = Puppet::ModuleTool::Applications::Upgrader.any_instance
installer.stubs(:module_repository).returns(remote_source)
end
def upgrader(name, options = {})
Puppet::ModuleTool.set_option_defaults(options)
Puppet::ModuleTool::Applications::Upgrader.new(name, options)
end
describe '#run' do
let(:module) { 'pmtacceptance-stdlib' }
def options
{ :environment => environment }
end
let(:application) { upgrader(self.module, options) }
subject { application.run }
it 'fails if the module is not already installed' do
- subject.should include :result => :failure
- subject[:error].should include :oneline => "Could not upgrade '#{self.module}'; module is not installed"
+ expect(subject).to include :result => :failure
+ expect(subject[:error]).to include :oneline => "Could not upgrade '#{self.module}'; module is not installed"
end
context 'for an installed module' do
context 'with only one version' do
before { preinstall('puppetlabs-oneversion', '0.0.1') }
let(:module) { 'puppetlabs-oneversion' }
it 'declines to upgrade' do
- subject.should include :result => :noop
- subject[:error][:multiline].should =~ /already the latest version/
+ expect(subject).to include :result => :noop
+ expect(subject[:error][:multiline]).to match(/already the latest version/)
end
end
context 'without dependencies' do
before { preinstall('pmtacceptance-stdlib', '1.0.0') }
context 'without options' do
it 'properly upgrades the module to the greatest version' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('4.1.0')
end
end
context 'with version range' do
def options
super.merge(:version => '3.x')
end
context 'not matching the installed version' do
it 'properly upgrades the module to the greatest version within that range' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('3.2.0')
end
end
context 'matching the installed version' do
context 'with more recent version' do
before { preinstall('pmtacceptance-stdlib', '3.0.0')}
it 'properly upgrades the module to the greatest version within that range' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('3.0.0') => v('3.2.0')
end
end
context 'without more recent version' do
before { preinstall('pmtacceptance-stdlib', '3.2.0')}
context 'without options' do
it 'declines to upgrade' do
- subject.should include :result => :noop
- subject[:error][:multiline].should =~ /already the latest version/
+ expect(subject).to include :result => :noop
+ expect(subject[:error][:multiline]).to match(/already the latest version/)
end
end
context 'with --force' do
def options
super.merge(:force => true)
end
it 'overwrites the installed module with the greatest version matching that range' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('3.2.0') => v('3.2.0')
end
end
end
end
end
end
context 'that is depended upon' do
# pmtacceptance-keystone depends on pmtacceptance-mysql >=0.6.1 <1.0.0
before { preinstall('pmtacceptance-keystone', '2.1.0') }
before { preinstall('pmtacceptance-mysql', '0.9.0') }
let(:module) { 'pmtacceptance-mysql' }
context 'and out of date' do
before { preinstall('pmtacceptance-mysql', '0.8.0') }
it 'properly upgrades to the greatest version matching the dependency' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-mysql', v('0.8.0') => v('0.9.0')
end
end
context 'and up to date' do
it 'declines to upgrade' do
- subject.should include :result => :failure
+ expect(subject).to include :result => :failure
end
end
context 'when specifying a violating version range' do
def options
super.merge(:version => '2.1.0')
end
it 'fails to upgrade the module' do
# TODO: More helpful error message?
- subject.should include :result => :failure
- subject[:error].should include :oneline => "Could not upgrade '#{self.module}' (v0.9.0 -> v2.1.0); no version satisfies all dependencies"
+ expect(subject).to include :result => :failure
+ expect(subject[:error]).to include :oneline => "Could not upgrade '#{self.module}' (v0.9.0 -> v2.1.0); no version satisfies all dependencies"
end
context 'using --force' do
def options
super.merge(:force => true)
end
it 'overwrites the installed module with the specified version' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-mysql', v('0.9.0') => v('2.1.0')
end
end
end
end
context 'with local changes' do
before { preinstall('pmtacceptance-stdlib', '1.0.0') }
before do
release = application.send(:installed_modules)['pmtacceptance-stdlib']
mark_changed(release.mod.path)
end
it 'fails to upgrade' do
- subject.should include :result => :failure
- subject[:error].should include :oneline => "Could not upgrade '#{self.module}'; module has had changes made locally"
+ expect(subject).to include :result => :failure
+ expect(subject[:error]).to include :oneline => "Could not upgrade '#{self.module}'; module has had changes made locally"
end
context 'with --ignore-changes' do
def options
super.merge(:ignore_changes => true)
end
it 'overwrites the installed module with the greatest version matching that range' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('4.1.0')
end
end
end
context 'with dependencies' do
context 'that are unsatisfied' do
def options
super.merge(:version => '0.1.1')
end
before { preinstall('pmtacceptance-apache', '0.0.3') }
let(:module) { 'pmtacceptance-apache' }
it 'upgrades the module and installs the missing dependencies' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.1.1')
graph_should_include 'pmtacceptance-stdlib', nil => v('4.1.0'), :action => :install
end
end
context 'with older major versions' do
# pmtacceptance-apache 0.0.4 has no dependency on pmtacceptance-stdlib
# the next available version (0.1.1) and all subsequent versions depend on pmtacceptance-stdlib >= 2.2.1
before { preinstall('pmtacceptance-apache', '0.0.3') }
before { preinstall('pmtacceptance-stdlib', '1.0.0') }
let(:module) { 'pmtacceptance-apache' }
it 'refuses to upgrade the installed dependency to a new major version, but upgrades the module to the greatest compatible version' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.0.4')
end
context 'using --ignore_dependencies' do
def options
super.merge(:ignore_dependencies => true)
end
it 'upgrades the module to the greatest available version' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0')
end
end
end
context 'with satisfying major versions' do
before { preinstall('pmtacceptance-apache', '0.0.3') }
before { preinstall('pmtacceptance-stdlib', '2.0.0') }
let(:module) { 'pmtacceptance-apache' }
it 'upgrades the module and its dependencies to their greatest compatible versions' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', v('2.0.0') => v('2.6.0')
end
end
context 'with satisfying versions' do
before { preinstall('pmtacceptance-apache', '0.0.3') }
before { preinstall('pmtacceptance-stdlib', '2.4.0') }
let(:module) { 'pmtacceptance-apache' }
it 'upgrades the module to the greatest available version' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', nil
end
end
context 'with current versions' do
before { preinstall('pmtacceptance-apache', '0.0.3') }
before { preinstall('pmtacceptance-stdlib', '2.6.0') }
let(:module) { 'pmtacceptance-apache' }
it 'upgrades the module to the greatest available version' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', nil
end
end
context 'with shared dependencies' do
# bacula 0.0.3 depends on stdlib >= 2.2.0 and pmtacceptance/mysql >= 1.0.0
# bacula 0.0.2 depends on stdlib >= 2.2.0 and pmtacceptance/mysql >= 0.0.1
# bacula 0.0.1 depends on stdlib >= 2.2.0
# keystone 2.1.0 depends on pmtacceptance/stdlib >= 2.5.0 and pmtacceptance/mysql >=0.6.1 <1.0.0
before { preinstall('pmtacceptance-bacula', '0.0.1') }
before { preinstall('pmtacceptance-mysql', '0.9.0') }
before { preinstall('pmtacceptance-keystone', '2.1.0') }
let(:module) { 'pmtacceptance-bacula' }
it 'upgrades the module to the greatest version compatible with all other installed modules' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-bacula', v('0.0.1') => v('0.0.2')
end
context 'using --force' do
def options
super.merge(:force => true)
end
it 'upgrades the module to the greatest version available' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-bacula', v('0.0.1') => v('0.0.3')
end
end
end
context 'in other modulepath directories' do
before { preinstall('pmtacceptance-apache', '0.0.3') }
before { preinstall('pmtacceptance-stdlib', '1.0.0', :into => secondary_dir) }
let(:module) { 'pmtacceptance-apache' }
context 'with older major versions' do
it 'upgrades the module to the greatest version compatible with the installed modules' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.0.4')
graph_should_include 'pmtacceptance-stdlib', nil
end
end
context 'with satisfying major versions' do
before { preinstall('pmtacceptance-stdlib', '2.0.0', :into => secondary_dir) }
it 'upgrades the module and its dependencies to their greatest compatible versions, in-place' do
- subject.should include :result => :success
+ expect(subject).to include :result => :success
graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0')
graph_should_include 'pmtacceptance-stdlib', v('2.0.0') => v('2.6.0'), :path => secondary_dir
end
end
end
end
end
end
end
diff --git a/spec/unit/module_tool/install_directory_spec.rb b/spec/unit/module_tool/install_directory_spec.rb
index 4a2759565..7a913d101 100644
--- a/spec/unit/module_tool/install_directory_spec.rb
+++ b/spec/unit/module_tool/install_directory_spec.rb
@@ -1,70 +1,70 @@
require 'spec_helper'
require 'puppet/module_tool/install_directory'
describe Puppet::ModuleTool::InstallDirectory do
def expect_normal_results
results = installer.run
- results[:installed_modules].length.should eq 1
- results[:installed_modules][0][:module].should == "pmtacceptance-stdlib"
- results[:installed_modules][0][:version][:vstring].should == "1.0.0"
+ expect(results[:installed_modules].length).to eq 1
+ expect(results[:installed_modules][0][:module]).to eq("pmtacceptance-stdlib")
+ expect(results[:installed_modules][0][:version][:vstring]).to eq("1.0.0")
results
end
it "(#15202) creates the install directory" do
target_dir = the_directory('foo', :directory? => false, :exist? => false)
target_dir.expects(:mkpath)
install = Puppet::ModuleTool::InstallDirectory.new(target_dir)
install.prepare('pmtacceptance-stdlib', '1.0.0')
end
it "(#15202) errors when the directory is not accessible" do
target_dir = the_directory('foo', :directory? => false, :exist? => false)
target_dir.expects(:mkpath).raises(Errno::EACCES)
install = Puppet::ModuleTool::InstallDirectory.new(target_dir)
expect {
install.prepare('module', '1.0.1')
}.to raise_error(
Puppet::ModuleTool::Errors::PermissionDeniedCreateInstallDirectoryError
)
end
it "(#15202) errors when an entry along the path is not a directory" do
target_dir = the_directory("foo/bar", :exist? => false, :directory? => false)
target_dir.expects(:mkpath).raises(Errno::EEXIST)
install = Puppet::ModuleTool::InstallDirectory.new(target_dir)
expect {
install.prepare('module', '1.0.1')
}.to raise_error(Puppet::ModuleTool::Errors::InstallPathExistsNotDirectoryError)
end
it "(#15202) simply re-raises an unknown error" do
target_dir = the_directory("foo/bar", :exist? => false, :directory? => false)
target_dir.expects(:mkpath).raises("unknown error")
install = Puppet::ModuleTool::InstallDirectory.new(target_dir)
expect { install.prepare('module', '1.0.1') }.to raise_error("unknown error")
end
it "(#15202) simply re-raises an unknown system call error" do
target_dir = the_directory("foo/bar", :exist? => false, :directory? => false)
target_dir.expects(:mkpath).raises(SystemCallError, "unknown")
install = Puppet::ModuleTool::InstallDirectory.new(target_dir)
expect { install.prepare('module', '1.0.1') }.to raise_error(SystemCallError)
end
def the_directory(name, options)
dir = mock("Pathname<#{name}>")
dir.stubs(:exist?).returns(options.fetch(:exist?, true))
dir.stubs(:directory?).returns(options.fetch(:directory?, true))
dir
end
end
diff --git a/spec/unit/module_tool/metadata_spec.rb b/spec/unit/module_tool/metadata_spec.rb
index 8cdb6918f..e455315ca 100644
--- a/spec/unit/module_tool/metadata_spec.rb
+++ b/spec/unit/module_tool/metadata_spec.rb
@@ -1,301 +1,301 @@
require 'spec_helper'
require 'puppet/module_tool'
describe Puppet::ModuleTool::Metadata do
let(:data) { {} }
let(:metadata) { Puppet::ModuleTool::Metadata.new }
describe 'property lookups' do
subject { metadata }
%w[ name version author summary license source project_page issues_url
dependencies dashed_name release_name description ].each do |prop|
describe "##{prop}" do
it "responds to the property" do
subject.send(prop)
end
end
end
end
describe "#update" do
subject { metadata.update(data) }
context "with a valid name" do
let(:data) { { 'name' => 'billgates-mymodule' } }
it "extracts the author name from the name field" do
- subject.to_hash['author'].should == 'billgates'
+ expect(subject.to_hash['author']).to eq('billgates')
end
it "extracts a module name from the name field" do
- subject.module_name.should == 'mymodule'
+ expect(subject.module_name).to eq('mymodule')
end
context "and existing author" do
before { metadata.update('author' => 'foo') }
it "avoids overwriting the existing author" do
- subject.to_hash['author'].should == 'foo'
+ expect(subject.to_hash['author']).to eq('foo')
end
end
end
context "with a valid name and author" do
let(:data) { { 'name' => 'billgates-mymodule', 'author' => 'foo' } }
it "use the author name from the author field" do
- subject.to_hash['author'].should == 'foo'
+ expect(subject.to_hash['author']).to eq('foo')
end
context "and preexisting author" do
before { metadata.update('author' => 'bar') }
it "avoids overwriting the existing author" do
- subject.to_hash['author'].should == 'foo'
+ expect(subject.to_hash['author']).to eq('foo')
end
end
end
context "with an invalid name" do
context "(short module name)" do
let(:data) { { 'name' => 'mymodule' } }
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the field must be a namespaced module name")
end
end
context "(missing namespace)" do
let(:data) { { 'name' => '/mymodule' } }
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the field must be a namespaced module name")
end
end
context "(missing module name)" do
let(:data) { { 'name' => 'namespace/' } }
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the field must be a namespaced module name")
end
end
context "(invalid namespace)" do
let(:data) { { 'name' => "dolla'bill$-mymodule" } }
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the namespace contains non-alphanumeric characters")
end
end
context "(non-alphanumeric module name)" do
let(:data) { { 'name' => "dollabils-fivedolla'" } }
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the module name contains non-alphanumeric (or underscore) characters")
end
end
context "(module name starts with a number)" do
let(:data) { { 'name' => "dollabills-5dollars" } }
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the module name must begin with a letter")
end
end
end
context "with an invalid version" do
let(:data) { { 'version' => '3.0' } }
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError, "Invalid 'version' field in metadata.json: version string cannot be parsed as a valid Semantic Version")
end
end
context "with a valid source" do
context "which is a GitHub URL" do
context "with a scheme" do
before { metadata.update('source' => 'https://github.com/billgates/amazingness') }
it "predicts a default project_page" do
- subject.to_hash['project_page'].should == 'https://github.com/billgates/amazingness'
+ expect(subject.to_hash['project_page']).to eq('https://github.com/billgates/amazingness')
end
it "predicts a default issues_url" do
- subject.to_hash['issues_url'].should == 'https://github.com/billgates/amazingness/issues'
+ expect(subject.to_hash['issues_url']).to eq('https://github.com/billgates/amazingness/issues')
end
end
context "without a scheme" do
before { metadata.update('source' => 'github.com/billgates/amazingness') }
it "predicts a default project_page" do
- subject.to_hash['project_page'].should == 'https://github.com/billgates/amazingness'
+ expect(subject.to_hash['project_page']).to eq('https://github.com/billgates/amazingness')
end
it "predicts a default issues_url" do
- subject.to_hash['issues_url'].should == 'https://github.com/billgates/amazingness/issues'
+ expect(subject.to_hash['issues_url']).to eq('https://github.com/billgates/amazingness/issues')
end
end
end
context "which is not a GitHub URL" do
before { metadata.update('source' => 'https://notgithub.com/billgates/amazingness') }
it "does not predict a default project_page" do
- subject.to_hash['project_page'].should be nil
+ expect(subject.to_hash['project_page']).to be nil
end
it "does not predict a default issues_url" do
- subject.to_hash['issues_url'].should be nil
+ expect(subject.to_hash['issues_url']).to be nil
end
end
context "which is not a URL" do
before { metadata.update('source' => 'my brain') }
it "does not predict a default project_page" do
- subject.to_hash['project_page'].should be nil
+ expect(subject.to_hash['project_page']).to be nil
end
it "does not predict a default issues_url" do
- subject.to_hash['issues_url'].should be nil
+ expect(subject.to_hash['issues_url']).to be nil
end
end
end
context "with a valid dependency" do
let(:data) { {'dependencies' => [{'name' => 'puppetlabs-goodmodule'}] }}
it "adds the dependency" do
- subject.dependencies.size.should == 1
+ expect(subject.dependencies.size).to eq(1)
end
end
context "with a invalid dependency name" do
let(:data) { {'dependencies' => [{'name' => 'puppetlabsbadmodule'}] }}
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError)
end
end
context "with a valid dependency version range" do
let(:data) { {'dependencies' => [{'name' => 'puppetlabs-badmodule', 'version_requirement' => '>= 2.0.0'}] }}
it "adds the dependency" do
- subject.dependencies.size.should == 1
+ expect(subject.dependencies.size).to eq(1)
end
end
context "with a invalid version range" do
let(:data) { {'dependencies' => [{'name' => 'puppetlabsbadmodule', 'version_requirement' => '>= banana'}] }}
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError)
end
end
context "with duplicate dependencies" do
let(:data) { {'dependencies' => [{'name' => 'puppetlabs-dupmodule', 'version_requirement' => '1.0.0'},
{'name' => 'puppetlabs-dupmodule', 'version_requirement' => '0.0.1'}] }
}
it "raises an exception" do
expect { subject }.to raise_error(ArgumentError)
end
end
context "adding a duplicate dependency" do
let(:data) { {'dependencies' => [{'name' => 'puppetlabs-origmodule', 'version_requirement' => '1.0.0'}] }}
it "with a different version raises an exception" do
metadata.add_dependency('puppetlabs-origmodule', '>= 0.0.1')
expect { subject }.to raise_error(ArgumentError)
end
it "with the same version does not add another dependency" do
metadata.add_dependency('puppetlabs-origmodule', '1.0.0')
- subject.dependencies.size.should == 1
+ expect(subject.dependencies.size).to eq(1)
end
end
end
describe '#dashed_name' do
it 'returns nil in the absence of a module name' do
expect(metadata.update('version' => '1.0.0').release_name).to be_nil
end
it 'returns a hyphenated string containing namespace and module name' do
data = metadata.update('name' => 'foo-bar')
- data.dashed_name.should == 'foo-bar'
+ expect(data.dashed_name).to eq('foo-bar')
end
it 'properly handles slash-separated names' do
data = metadata.update('name' => 'foo/bar')
- data.dashed_name.should == 'foo-bar'
+ expect(data.dashed_name).to eq('foo-bar')
end
it 'is unaffected by author name' do
data = metadata.update('name' => 'foo/bar', 'author' => 'me')
- data.dashed_name.should == 'foo-bar'
+ expect(data.dashed_name).to eq('foo-bar')
end
end
describe '#release_name' do
it 'returns nil in the absence of a module name' do
expect(metadata.update('version' => '1.0.0').release_name).to be_nil
end
it 'returns nil in the absence of a version' do
expect(metadata.update('name' => 'foo/bar').release_name).to be_nil
end
it 'returns a hyphenated string containing module name and version' do
data = metadata.update('name' => 'foo/bar', 'version' => '1.0.0')
- data.release_name.should == 'foo-bar-1.0.0'
+ expect(data.release_name).to eq('foo-bar-1.0.0')
end
it 'is unaffected by author name' do
data = metadata.update('name' => 'foo/bar', 'version' => '1.0.0', 'author' => 'me')
- data.release_name.should == 'foo-bar-1.0.0'
+ expect(data.release_name).to eq('foo-bar-1.0.0')
end
end
describe "#to_hash" do
subject { metadata.to_hash }
it "contains the default set of keys" do
- subject.keys.sort.should == %w[ name version author summary license source issues_url project_page dependencies ].sort
+ expect(subject.keys.sort).to eq(%w[ name version author summary license source issues_url project_page dependencies ].sort)
end
describe "['license']" do
it "defaults to Apache 2" do
- subject['license'].should == "Apache-2.0"
+ expect(subject['license']).to eq("Apache-2.0")
end
end
describe "['dependencies']" do
it "defaults to an empty set" do
- subject['dependencies'].should == Set.new
+ expect(subject['dependencies']).to eq(Set.new)
end
end
context "when updated with non-default data" do
subject { metadata.update('license' => 'MIT', 'non-standard' => 'yup').to_hash }
it "overrides the defaults" do
- subject['license'].should == 'MIT'
+ expect(subject['license']).to eq('MIT')
end
it 'contains unanticipated values' do
- subject['non-standard'].should == 'yup'
+ expect(subject['non-standard']).to eq('yup')
end
end
end
end
diff --git a/spec/unit/module_tool/tar/mini_spec.rb b/spec/unit/module_tool/tar/mini_spec.rb
index 179952741..ef0d297a8 100644
--- a/spec/unit/module_tool/tar/mini_spec.rb
+++ b/spec/unit/module_tool/tar/mini_spec.rb
@@ -1,60 +1,60 @@
require 'spec_helper'
require 'puppet/module_tool'
describe Puppet::ModuleTool::Tar::Mini, :if => (Puppet.features.minitar? and Puppet.features.zlib?) do
let(:sourcefile) { '/the/module.tar.gz' }
let(:destdir) { File.expand_path '/the/dest/dir' }
let(:sourcedir) { '/the/src/dir' }
let(:destfile) { '/the/dest/file.tar.gz' }
let(:minitar) { described_class.new }
it "unpacks a tar file" do
unpacks_the_entry(:file_start, 'thefile')
minitar.unpack(sourcefile, destdir, 'uid')
end
it "does not allow an absolute path" do
unpacks_the_entry(:file_start, '/thefile')
expect {
minitar.unpack(sourcefile, destdir, 'uid')
}.to raise_error(Puppet::ModuleTool::Errors::InvalidPathInPackageError,
"Attempt to install file into \"/thefile\" under \"#{destdir}\"")
end
it "does not allow a file to be written outside the destination directory" do
unpacks_the_entry(:file_start, '../../thefile')
expect {
minitar.unpack(sourcefile, destdir, 'uid')
}.to raise_error(Puppet::ModuleTool::Errors::InvalidPathInPackageError,
"Attempt to install file into \"#{File.expand_path('/the/thefile')}\" under \"#{destdir}\"")
end
it "does not allow a directory to be written outside the destination directory" do
unpacks_the_entry(:dir, '../../thedir')
expect {
minitar.unpack(sourcefile, destdir, 'uid')
}.to raise_error(Puppet::ModuleTool::Errors::InvalidPathInPackageError,
"Attempt to install file into \"#{File.expand_path('/the/thedir')}\" under \"#{destdir}\"")
end
it "packs a tar file" do
- writer = mock('GzipWriter')
+ writer = stub('GzipWriter')
Zlib::GzipWriter.expects(:open).with(destfile).yields(writer)
Archive::Tar::Minitar.expects(:pack).with(sourcedir, writer)
minitar.pack(sourcedir, destfile)
end
def unpacks_the_entry(type, name)
- reader = mock('GzipReader')
+ reader = stub('GzipReader')
Zlib::GzipReader.expects(:open).with(sourcefile).yields(reader)
minitar.expects(:find_valid_files).with(reader).returns([name])
Archive::Tar::Minitar.expects(:unpack).with(reader, destdir, [name]).yields(type, name, nil)
end
end
diff --git a/spec/unit/module_tool/tar_spec.rb b/spec/unit/module_tool/tar_spec.rb
index 489c3f946..6bcc10fc1 100644
--- a/spec/unit/module_tool/tar_spec.rb
+++ b/spec/unit/module_tool/tar_spec.rb
@@ -1,31 +1,31 @@
require 'spec_helper'
require 'puppet/module_tool/tar'
describe Puppet::ModuleTool::Tar do
it "uses tar when present and not on Windows" do
Facter.stubs(:value).with('osfamily').returns 'ObscureLinuxDistro'
Puppet::Util.stubs(:which).with('tar').returns '/usr/bin/tar'
Puppet::Util::Platform.stubs(:windows?).returns false
- described_class.instance.should be_a_kind_of Puppet::ModuleTool::Tar::Gnu
+ expect(described_class.instance).to be_a_kind_of Puppet::ModuleTool::Tar::Gnu
end
it "falls back to minitar when it and zlib are present" do
Facter.stubs(:value).with('osfamily').returns 'Windows'
Puppet::Util.stubs(:which).with('tar')
Puppet::Util::Platform.stubs(:windows?).returns true
Puppet.stubs(:features).returns(stub(:minitar? => true, :zlib? => true))
- described_class.instance.should be_a_kind_of Puppet::ModuleTool::Tar::Mini
+ expect(described_class.instance).to be_a_kind_of Puppet::ModuleTool::Tar::Mini
end
it "fails when there is no possible implementation" do
Facter.stubs(:value).with('osfamily').returns 'Windows'
Puppet::Util.stubs(:which).with('tar')
Puppet::Util::Platform.stubs(:windows?).returns true
Puppet.stubs(:features).returns(stub(:minitar? => false, :zlib? => false))
expect { described_class.instance }.to raise_error RuntimeError, /No suitable tar/
end
end
diff --git a/spec/unit/module_tool_spec.rb b/spec/unit/module_tool_spec.rb
index 0eafb2e7d..fc303ba4a 100755
--- a/spec/unit/module_tool_spec.rb
+++ b/spec/unit/module_tool_spec.rb
@@ -1,327 +1,327 @@
#! /usr/bin/env ruby
# encoding: UTF-8
require 'spec_helper'
require 'puppet/module_tool'
describe Puppet::ModuleTool do
describe '.is_module_root?' do
it 'should return true if directory has a Modulefile file' do
FileTest.expects(:file?).with(responds_with(:to_s, '/a/b/c/metadata.json')).
returns(false)
FileTest.expects(:file?).with(responds_with(:to_s, '/a/b/c/Modulefile')).
returns(true)
- subject.is_module_root?(Pathname.new('/a/b/c')).should be_true
+ expect(subject.is_module_root?(Pathname.new('/a/b/c'))).to be_truthy
end
it 'should return true if directory has a metadata.json file' do
FileTest.expects(:file?).with(responds_with(:to_s, '/a/b/c/metadata.json')).
returns(true)
- subject.is_module_root?(Pathname.new('/a/b/c')).should be_true
+ expect(subject.is_module_root?(Pathname.new('/a/b/c'))).to be_truthy
end
it 'should return false if directory does not have a metadata.json or a Modulefile file' do
FileTest.expects(:file?).with(responds_with(:to_s, '/a/b/c/metadata.json')).
returns(false)
FileTest.expects(:file?).with(responds_with(:to_s, '/a/b/c/Modulefile')).
returns(false)
- subject.is_module_root?(Pathname.new('/a/b/c')).should be_false
+ expect(subject.is_module_root?(Pathname.new('/a/b/c'))).to be_falsey
end
end
describe '.find_module_root' do
let(:sample_path) { Pathname.new('/a/b/c').expand_path }
it 'should return the first path as a pathname when it contains a module file' do
Puppet::ModuleTool.expects(:is_module_root?).with(sample_path).
returns(true)
- subject.find_module_root(sample_path).should == sample_path
+ expect(subject.find_module_root(sample_path)).to eq(sample_path)
end
it 'should return a parent path as a pathname when it contains a module file' do
Puppet::ModuleTool.expects(:is_module_root?).
with(responds_with(:to_s, File.expand_path('/a/b/c'))).returns(false)
Puppet::ModuleTool.expects(:is_module_root?).
with(responds_with(:to_s, File.expand_path('/a/b'))).returns(true)
- subject.find_module_root(sample_path).should == Pathname.new('/a/b').expand_path
+ expect(subject.find_module_root(sample_path)).to eq(Pathname.new('/a/b').expand_path)
end
it 'should return nil when no module root can be found' do
Puppet::ModuleTool.expects(:is_module_root?).at_least_once.returns(false)
- subject.find_module_root(sample_path).should be_nil
+ expect(subject.find_module_root(sample_path)).to be_nil
end
end
describe '.format_tree' do
it 'should return an empty tree when given an empty list' do
- subject.format_tree([]).should == ''
+ expect(subject.format_tree([])).to eq('')
end
it 'should return a shallow when given a list without dependencies' do
list = [ { :text => 'first' }, { :text => 'second' }, { :text => 'third' } ]
- subject.format_tree(list).should == <<-TREE
+ expect(subject.format_tree(list)).to eq <<-TREE
├── first
├── second
└── third
TREE
end
it 'should return a deeply nested tree when given a list with deep dependencies' do
list = [
{
:text => 'first',
:dependencies => [
{
:text => 'second',
:dependencies => [
{ :text => 'third' }
]
}
]
},
]
- subject.format_tree(list).should == <<-TREE
+ expect(subject.format_tree(list)).to eq <<-TREE
└─┬ first
└─┬ second
└── third
TREE
end
it 'should show connectors when deep dependencies are not on the last node of the top level' do
list = [
{
:text => 'first',
:dependencies => [
{
:text => 'second',
:dependencies => [
{ :text => 'third' }
]
}
]
},
{ :text => 'fourth' }
]
- subject.format_tree(list).should == <<-TREE
+ expect(subject.format_tree(list)).to eq <<-TREE
├─┬ first
│ └─┬ second
│ └── third
└── fourth
TREE
end
it 'should show connectors when deep dependencies are not on the last node of any level' do
list = [
{
:text => 'first',
:dependencies => [
{
:text => 'second',
:dependencies => [
{ :text => 'third' }
]
},
{ :text => 'fourth' }
]
}
]
- subject.format_tree(list).should == <<-TREE
+ expect(subject.format_tree(list)).to eq <<-TREE
└─┬ first
├─┬ second
│ └── third
└── fourth
TREE
end
it 'should show connectors in every case when deep dependencies are not on the last node' do
list = [
{
:text => 'first',
:dependencies => [
{
:text => 'second',
:dependencies => [
{ :text => 'third' }
]
},
{ :text => 'fourth' }
]
},
{ :text => 'fifth' }
]
- subject.format_tree(list).should == <<-TREE
+ expect(subject.format_tree(list)).to eq <<-TREE
├─┬ first
│ ├─┬ second
│ │ └── third
│ └── fourth
└── fifth
TREE
end
end
describe '.set_option_defaults' do
let(:options) { {} }
let(:modulepath) { ['/env/module/path', '/global/module/path'] }
let(:environment_name) { :current_environment }
let(:environment) { Puppet::Node::Environment.create(environment_name, modulepath) }
subject do
described_class.set_option_defaults(options)
options
end
around do |example|
envs = Puppet::Environments::Static.new(environment)
Puppet.override(:environments => envs) do
example.run
end
end
describe ':environment' do
context 'as String' do
let(:options) { { :environment => "#{environment_name}" } }
it 'assigns the environment with the given name to :environment_instance' do
expect(subject).to include :environment_instance => environment
end
end
context 'as Symbol' do
let(:options) { { :environment => :"#{environment_name}" } }
it 'assigns the environment with the given name to :environment_instance' do
expect(subject).to include :environment_instance => environment
end
end
context 'as Puppet::Node::Environment' do
let(:env) { Puppet::Node::Environment.create('anonymous', []) }
let(:options) { { :environment => env } }
it 'assigns the given environment to :environment_instance' do
expect(subject).to include :environment_instance => env
end
end
end
describe ':modulepath' do
let(:options) do
{ :modulepath => %w[bar foo baz].join(File::PATH_SEPARATOR) }
end
let(:paths) { options[:modulepath].split(File::PATH_SEPARATOR).map { |dir| File.expand_path(dir) } }
it 'is expanded to an absolute path' do
expect(subject[:environment_instance].full_modulepath).to eql paths
end
it 'is used to compute :target_dir' do
expect(subject).to include :target_dir => paths.first
end
context 'conflicts with :environment' do
let(:options) do
{ :modulepath => %w[bar foo baz].join(File::PATH_SEPARATOR), :environment => environment_name }
end
it 'replaces the modulepath of the :environment_instance' do
expect(subject[:environment_instance].full_modulepath).to eql paths
end
it 'is used to compute :target_dir' do
expect(subject).to include :target_dir => paths.first
end
end
end
describe ':target_dir' do
let(:options) do
{ :target_dir => 'foo' }
end
let(:target) { File.expand_path(options[:target_dir]) }
it 'is expanded to an absolute path' do
expect(subject).to include :target_dir => target
end
it 'is prepended to the modulepath of the :environment_instance' do
expect(subject[:environment_instance].full_modulepath.first).to eql target
end
context 'conflicts with :modulepath' do
let(:options) do
{ :target_dir => 'foo', :modulepath => %w[bar foo baz].join(File::PATH_SEPARATOR) }
end
it 'is prepended to the modulepath of the :environment_instance' do
expect(subject[:environment_instance].full_modulepath.first).to eql target
end
it 'shares the provided :modulepath via the :environment_instance' do
paths = %w[foo] + options[:modulepath].split(File::PATH_SEPARATOR)
paths.map! { |dir| File.expand_path(dir) }
expect(subject[:environment_instance].full_modulepath).to eql paths
end
end
context 'conflicts with :environment' do
let(:options) do
{ :target_dir => 'foo', :environment => environment_name }
end
it 'is prepended to the modulepath of the :environment_instance' do
expect(subject[:environment_instance].full_modulepath.first).to eql target
end
it 'shares the provided :modulepath via the :environment_instance' do
paths = %w[foo] + environment.full_modulepath
paths.map! { |dir| File.expand_path(dir) }
expect(subject[:environment_instance].full_modulepath).to eql paths
end
end
context 'when not passed' do
it 'is populated with the first component of the modulepath' do
expect(subject).to include :target_dir => subject[:environment_instance].full_modulepath.first
end
end
end
end
describe '.parse_module_dependency' do
it 'parses a dependency without a version range expression' do
name, range, expr = subject.parse_module_dependency('source', 'name' => 'foo-bar')
expect(name).to eql('foo-bar')
expect(range).to eql(Semantic::VersionRange.parse('>= 0.0.0'))
expect(expr).to eql('>= 0.0.0')
end
it 'parses a dependency with a version range expression' do
name, range, expr = subject.parse_module_dependency('source', 'name' => 'foo-bar', 'version_requirement' => '1.2.x')
expect(name).to eql('foo-bar')
expect(range).to eql(Semantic::VersionRange.parse('1.2.x'))
expect(expr).to eql('1.2.x')
end
it 'parses a dependency with a version range expression in the (deprecated) versionRange key' do
name, range, expr = subject.parse_module_dependency('source', 'name' => 'foo-bar', 'versionRequirement' => '1.2.x')
expect(name).to eql('foo-bar')
expect(range).to eql(Semantic::VersionRange.parse('1.2.x'))
expect(expr).to eql('1.2.x')
end
it 'does not raise an error on invalid version range expressions' do
name, range, expr = subject.parse_module_dependency('source', 'name' => 'foo-bar', 'version_requirement' => 'nope')
expect(name).to eql('foo-bar')
expect(range).to eql(Semantic::VersionRange::EMPTY_RANGE)
expect(expr).to eql('nope')
end
end
end
diff --git a/spec/unit/network/auth_config_parser_spec.rb b/spec/unit/network/auth_config_parser_spec.rb
index 343e9af9c..2830ac986 100644
--- a/spec/unit/network/auth_config_parser_spec.rb
+++ b/spec/unit/network/auth_config_parser_spec.rb
@@ -1,101 +1,101 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/auth_config_parser'
require 'puppet/network/authconfig'
describe Puppet::Network::AuthConfigParser do
let(:fake_authconfig) do
"path ~ ^/catalog/([^/])\nmethod find\nallow *\n"
end
describe "Basic Parser" do
it "should accept a string by default" do
- described_class.new(fake_authconfig).parse.should be_a_kind_of Puppet::Network::AuthConfig
+ expect(described_class.new(fake_authconfig).parse).to be_a_kind_of Puppet::Network::AuthConfig
end
end
describe "when parsing rights" do
it "skips comments" do
- described_class.new(' # comment\n').parse_rights.should be_empty
+ expect(described_class.new(' # comment\n').parse_rights).to be_empty
end
it "increments line number even on commented lines" do
- described_class.new(" # comment\npath /").parse_rights['/'].line.should == 2
+ expect(described_class.new(" # comment\npath /").parse_rights['/'].line).to eq(2)
end
it "skips blank lines" do
- described_class.new(' ').parse_rights.should be_empty
+ expect(described_class.new(' ').parse_rights).to be_empty
end
it "increments line number even on blank lines" do
- described_class.new(" \npath /").parse_rights['/'].line.should == 2
+ expect(described_class.new(" \npath /").parse_rights['/'].line).to eq(2)
end
it "does not throw an error if the same path appears twice" do
expect {
described_class.new("path /hello\npath /hello").parse_rights
}.to_not raise_error
end
it "should create a new right for each found path line" do
- described_class.new('path /certificates').parse_rights['/certificates'].should be
+ expect(described_class.new('path /certificates').parse_rights['/certificates']).to be
end
it "should create a new right for each found regex line" do
- described_class.new('path ~ .rb$').parse_rights['.rb$'].should be
+ expect(described_class.new('path ~ .rb$').parse_rights['.rb$']).to be
end
it "should strip whitespace around ACE" do
Puppet::Network::Rights::Right.any_instance.expects(:allow).with('127.0.0.1')
Puppet::Network::Rights::Right.any_instance.expects(:allow).with('172.16.10.0')
described_class.new("path /\n allow 127.0.0.1 , 172.16.10.0 ").parse_rights
end
it "should allow ACE inline comments" do
Puppet::Network::Rights::Right.any_instance.expects(:allow).with('127.0.0.1')
described_class.new("path /\n allow 127.0.0.1 # will it work?").parse_rights
end
it "should create an allow ACE on each subsequent allow" do
Puppet::Network::Rights::Right.any_instance.expects(:allow).with('127.0.0.1')
described_class.new("path /\nallow 127.0.0.1").parse_rights
end
it "should create a deny ACE on each subsequent deny" do
Puppet::Network::Rights::Right.any_instance.expects(:deny).with('127.0.0.1')
described_class.new("path /\ndeny 127.0.0.1").parse_rights
end
it "should inform the current ACL if we get the 'method' directive" do
Puppet::Network::Rights::Right.any_instance.expects(:restrict_method).with('search')
Puppet::Network::Rights::Right.any_instance.expects(:restrict_method).with('find')
described_class.new("path /certificates\nmethod search,find").parse_rights
end
it "should inform the current ACL if we get the 'environment' directive" do
Puppet::Network::Rights::Right.any_instance.expects(:restrict_environment).with('production')
Puppet::Network::Rights::Right.any_instance.expects(:restrict_environment).with('development')
described_class.new("path /certificates\nenvironment production,development").parse_rights
end
it "should inform the current ACL if we get the 'auth' directive" do
Puppet::Network::Rights::Right.any_instance.expects(:restrict_authenticated).with('yes')
described_class.new("path /certificates\nauth yes").parse_rights
end
it "should also allow the long form 'authenticated' directive" do
Puppet::Network::Rights::Right.any_instance.expects(:restrict_authenticated).with('yes')
described_class.new("path /certificates\nauthenticated yes").parse_rights
end
end
end
diff --git a/spec/unit/network/authconfig_spec.rb b/spec/unit/network/authconfig_spec.rb
index 3795ed4a7..6948c7234 100755
--- a/spec/unit/network/authconfig_spec.rb
+++ b/spec/unit/network/authconfig_spec.rb
@@ -1,109 +1,109 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/authconfig'
describe Puppet::Network::AuthConfig do
before :each do
Puppet::FileSystem.stubs(:stat).returns stub('stat', :ctime => :now)
Time.stubs(:now).returns Time.now
Puppet::Network::AuthConfig.any_instance.stubs(:exists?).returns(true)
# FIXME @authconfig = Puppet::Network::AuthConfig.new("dummy")
end
describe "when initializing" do
it "inserts default ACLs after setting initial rights" do
Puppet::Network::AuthConfig.any_instance.expects(:insert_default_acl)
Puppet::Network::AuthConfig.new
end
end
describe "when defining an acl with mk_acl" do
before :each do
Puppet::Network::AuthConfig.any_instance.stubs(:insert_default_acl)
@authconfig = Puppet::Network::AuthConfig.new
end
it "should create a new right for each default acl" do
@authconfig.mk_acl(:acl => '/')
- @authconfig.rights['/'].should be
+ expect(@authconfig.rights['/']).to be
end
it "allows everyone for each default right" do
@authconfig.mk_acl(:acl => '/')
- @authconfig.rights['/'].should be_globalallow
+ expect(@authconfig.rights['/']).to be_globalallow
end
it "accepts an argument to restrict the method" do
@authconfig.mk_acl(:acl => '/', :method => :find)
- @authconfig.rights['/'].methods.should == [:find]
+ expect(@authconfig.rights['/'].methods).to eq([:find])
end
it "creates rights with authentication set to true by default" do
@authconfig.mk_acl(:acl => '/')
- @authconfig.rights['/'].authentication.should be_true
+ expect(@authconfig.rights['/'].authentication).to be_truthy
end
it "accepts an argument to set the authentication requirement" do
@authconfig.mk_acl(:acl => '/', :authenticated => :any)
- @authconfig.rights['/'].authentication.should be_false
+ expect(@authconfig.rights['/'].authentication).to be_falsey
end
end
describe "when adding default ACLs" do
before :each do
Puppet::Network::AuthConfig.any_instance.stubs(:insert_default_acl)
@authconfig = Puppet::Network::AuthConfig.new
Puppet::Network::AuthConfig.any_instance.unstub(:insert_default_acl)
end
Puppet::Network::AuthConfig::default_acl.each do |acl|
it "should create a default right for #{acl[:acl]}" do
@authconfig.stubs(:mk_acl)
@authconfig.expects(:mk_acl).with(acl)
@authconfig.insert_default_acl
end
end
it "should log at info loglevel" do
Puppet.expects(:info).at_least_once
@authconfig.insert_default_acl
end
it "creates an empty catch-all rule for '/' for any authentication request state" do
@authconfig.stubs(:mk_acl)
@authconfig.insert_default_acl
- @authconfig.rights['/'].should be_empty
- @authconfig.rights['/'].authentication.should be_false
+ expect(@authconfig.rights['/']).to be_empty
+ expect(@authconfig.rights['/'].authentication).to be_falsey
end
it '(CVE-2013-2275) allows report submission only for the node matching the certname by default' do
acl = {
:acl => "~ ^#{Puppet::Network::HTTP::MASTER_URL_PREFIX}\/v3\/report\/([^\/]+)$",
:method => :save,
:allow => '$1',
:authenticated => true
}
@authconfig.stubs(:mk_acl)
@authconfig.expects(:mk_acl).with(acl)
@authconfig.insert_default_acl
end
end
describe "when checking authorization" do
it "should ask for authorization to the ACL subsystem" do
params = {
:ip => "127.0.0.1",
:node => "me",
:environment => :env,
:authenticated => true
}
Puppet::Network::Rights.any_instance.expects(:is_request_forbidden_and_why?).with(:save, "/path/to/resource", params)
described_class.new.check_authorization(:save, "/path/to/resource", params)
end
end
end
diff --git a/spec/unit/network/authstore_spec.rb b/spec/unit/network/authstore_spec.rb
index 75ea2c13e..bba64a9e6 100755
--- a/spec/unit/network/authstore_spec.rb
+++ b/spec/unit/network/authstore_spec.rb
@@ -1,424 +1,423 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'rbconfig'
require 'puppet/network/authconfig'
describe Puppet::Network::AuthStore do
before :each do
@authstore = Puppet::Network::AuthStore.new
@authstore.reset_interpolation
end
describe "when checking if the acl has some entries" do
it "should be empty if no ACE have been entered" do
- @authstore.should be_empty
+ expect(@authstore).to be_empty
end
it "should not be empty if it is a global allow" do
@authstore.allow('*')
- @authstore.should_not be_empty
+ expect(@authstore).not_to be_empty
end
it "should not be empty if at least one allow has been entered" do
@authstore.allow_ip('1.1.1.*')
- @authstore.should_not be_empty
+ expect(@authstore).not_to be_empty
end
it "should not be empty if at least one deny has been entered" do
@authstore.deny_ip('1.1.1.*')
- @authstore.should_not be_empty
+ expect(@authstore).not_to be_empty
end
end
describe "when checking global allow" do
it "should not be enabled by default" do
- @authstore.should_not be_globalallow
- @authstore.should_not be_allowed('foo.bar.com', '192.168.1.1')
+ expect(@authstore).not_to be_globalallow
+ expect(@authstore).not_to be_allowed('foo.bar.com', '192.168.1.1')
end
it "should always allow when enabled" do
@authstore.allow('*')
- @authstore.should be_globalallow
- @authstore.should be_allowed('foo.bar.com', '192.168.1.1')
+ expect(@authstore).to be_globalallow
+ expect(@authstore).to be_allowed('foo.bar.com', '192.168.1.1')
end
end
describe "when checking a regex type of allow" do
before :each do
@authstore.allow('/^(test-)?host[0-9]+\.other-domain\.(com|org|net)$|some-domain\.com/')
@ip = '192.168.1.1'
end
['host5.other-domain.com', 'test-host12.other-domain.net', 'foo.some-domain.com'].each { |name|
it "should allow the host #{name}" do
- @authstore.should be_allowed(name, @ip)
+ expect(@authstore).to be_allowed(name, @ip)
end
}
['host0.some-other-domain.com',''].each { |name|
it "should not allow the host #{name}" do
- @authstore.should_not be_allowed(name, @ip)
+ expect(@authstore).not_to be_allowed(name, @ip)
end
}
end
end
describe Puppet::Network::AuthStore::Declaration do
['100.101.99.98','100.100.100.100','1.2.3.4','11.22.33.44'].each { |ip|
describe "when the pattern is a simple numeric IP such as #{ip}" do
before :each do
@declaration = Puppet::Network::AuthStore::Declaration.new(:allow_ip,ip)
end
it "should match the specified IP" do
- @declaration.should be_match('www.testsite.org',ip)
+ expect(@declaration).to be_match('www.testsite.org',ip)
end
it "should not match other IPs" do
- @declaration.should_not be_match('www.testsite.org','200.101.99.98')
+ expect(@declaration).not_to be_match('www.testsite.org','200.101.99.98')
end
end
(1..3).each { |n|
describe "when the pattern is an IP mask with #{n} numeric segments and a *" do
before :each do
@ip_pattern = ip.split('.')[0,n].join('.')+'.*'
@declaration = Puppet::Network::AuthStore::Declaration.new(:allow_ip,@ip_pattern)
end
it "should match an IP in the range" do
- @declaration.should be_match('www.testsite.org',ip)
+ expect(@declaration).to be_match('www.testsite.org',ip)
end
it "should not match other IPs" do
- @declaration.should_not be_match('www.testsite.org','200.101.99.98')
+ expect(@declaration).not_to be_match('www.testsite.org','200.101.99.98')
end
it "should not match IPs that differ in the last non-wildcard segment" do
other = ip.split('.')
other[n-1].succ!
- @declaration.should_not be_match('www.testsite.org',other.join('.'))
+ expect(@declaration).not_to be_match('www.testsite.org',other.join('.'))
end
end
}
}
describe "when the pattern is a numeric IP with a back reference" do
pending("implementation of backreferences for IP") do
before :each do
@ip = '100.101.$1'
@declaration = Puppet::Network::AuthStore::Declaration.new(:allow_ip,@ip).interpolate('12.34'.match(/(.*)/))
end
it "should match an IP with the appropriate interpolation" do
@declaration.should be_match('www.testsite.org',@ip.sub(/\$1/,'12.34'))
end
it "should not match other IPs" do
@declaration.should_not be_match('www.testsite.org',@ip.sub(/\$1/,'66.34'))
end
end
end
[
"02001:0000:1234:0000:0000:C1C0:ABCD:0876",
"2001:0000:1234:0000:00001:C1C0:ABCD:0876",
" 2001:0000:1234:0000:0000:C1C0:ABCD:0876 0",
"2001:0000:1234: 0000:0000:C1C0:ABCD:0876",
"3ffe:0b00:0000:0001:0000:0000:000a",
"FF02:0000:0000:0000:0000:0000:0000:0000:0001",
"3ffe:b00::1::a",
"1:2:3::4:5::7:8",
"12345::6:7:8",
"1::5:400.2.3.4",
"1::5:260.2.3.4",
"1::5:256.2.3.4",
"1::5:1.256.3.4",
"1::5:1.2.256.4",
"1::5:1.2.3.256",
"1::5:300.2.3.4",
"1::5:1.300.3.4",
"1::5:1.2.300.4",
"1::5:1.2.3.300",
"1::5:900.2.3.4",
"1::5:1.900.3.4",
"1::5:1.2.900.4",
"1::5:1.2.3.900",
"1::5:300.300.300.300",
"1::5:3000.30.30.30",
"1::400.2.3.4",
"1::260.2.3.4",
"1::256.2.3.4",
"1::1.256.3.4",
"1::1.2.256.4",
"1::1.2.3.256",
"1::300.2.3.4",
"1::1.300.3.4",
"1::1.2.300.4",
"1::1.2.3.300",
"1::900.2.3.4",
"1::1.900.3.4",
"1::1.2.900.4",
"1::1.2.3.900",
"1::300.300.300.300",
"1::3000.30.30.30",
"::400.2.3.4",
"::260.2.3.4",
"::256.2.3.4",
"::1.256.3.4",
"::1.2.256.4",
"::1.2.3.256",
"::300.2.3.4",
"::1.300.3.4",
"::1.2.300.4",
"::1.2.3.300",
"::900.2.3.4",
"::1.900.3.4",
"::1.2.900.4",
"::1.2.3.900",
"::300.300.300.300",
"::3000.30.30.30",
"2001:DB8:0:0:8:800:200C:417A:221", # unicast, full
"FF01::101::2" # multicast, compressed
].each { |invalid_ip|
describe "when the pattern is an invalid IPv6 address such as #{invalid_ip}" do
it "should raise an exception" do
- lambda { Puppet::Network::AuthStore::Declaration.new(:allow,invalid_ip) }.should raise_error
+ expect { Puppet::Network::AuthStore::Declaration.new(:allow,invalid_ip) }.to raise_error
end
end
}
[
"1.2.3.4",
"2001:0000:1234:0000:0000:C1C0:ABCD:0876",
"3ffe:0b00:0000:0000:0001:0000:0000:000a",
"FF02:0000:0000:0000:0000:0000:0000:0001",
"0000:0000:0000:0000:0000:0000:0000:0001",
"0000:0000:0000:0000:0000:0000:0000:0000",
"::ffff:192.168.1.26",
"2::10",
"ff02::1",
"fe80::",
"2002::",
"2001:db8::",
"2001:0db8:1234::",
"::ffff:0:0",
"::1",
"::ffff:192.168.1.1",
"1:2:3:4:5:6:7:8",
"1:2:3:4:5:6::8",
"1:2:3:4:5::8",
"1:2:3:4::8",
"1:2:3::8",
"1:2::8",
"1::8",
"1::2:3:4:5:6:7",
"1::2:3:4:5:6",
"1::2:3:4:5",
"1::2:3:4",
"1::2:3",
"1::8",
"::2:3:4:5:6:7",
"::2:3:4:5:6",
"::2:3:4:5",
"::2:3:4",
"::2:3",
"::8",
"1:2:3:4:5:6::",
"1:2:3:4:5::",
"1:2:3:4::",
"1:2:3::",
"1:2::",
"1::",
"1:2:3:4:5::7:8",
"1:2:3:4::7:8",
"1:2:3::7:8",
"1:2::7:8",
"1::7:8",
"1:2:3:4:5:6:1.2.3.4",
"1:2:3:4:5::1.2.3.4",
"1:2:3:4::1.2.3.4",
"1:2:3::1.2.3.4",
"1:2::1.2.3.4",
"1::1.2.3.4",
"1:2:3:4::5:1.2.3.4",
"1:2:3::5:1.2.3.4",
"1:2::5:1.2.3.4",
"1::5:1.2.3.4",
"1::5:11.22.33.44",
"fe80::217:f2ff:254.7.237.98",
"fe80::217:f2ff:fe07:ed62",
"2001:DB8:0:0:8:800:200C:417A", # unicast, full
"FF01:0:0:0:0:0:0:101", # multicast, full
"0:0:0:0:0:0:0:1", # loopback, full
"0:0:0:0:0:0:0:0", # unspecified, full
"2001:DB8::8:800:200C:417A", # unicast, compressed
"FF01::101", # multicast, compressed
"::1", # loopback, compressed, non-routable
"::", # unspecified, compressed, non-routable
"0:0:0:0:0:0:13.1.68.3", # IPv4-compatible IPv6 address, full, deprecated
"0:0:0:0:0:FFFF:129.144.52.38", # IPv4-mapped IPv6 address, full
"::13.1.68.3", # IPv4-compatible IPv6 address, compressed, deprecated
"::FFFF:129.144.52.38", # IPv4-mapped IPv6 address, compressed
"2001:0DB8:0000:CD30:0000:0000:0000:0000/60", # full, with prefix
"2001:0DB8::CD30:0:0:0:0/60", # compressed, with prefix
"2001:0DB8:0:CD30::/60", # compressed, with prefix #2
"::/128", # compressed, unspecified address type, non-routable
"::1/128", # compressed, loopback address type, non-routable
"FF00::/8", # compressed, multicast address type
"FE80::/10", # compressed, link-local unicast, non-routable
"FEC0::/10", # compressed, site-local unicast, deprecated
"127.0.0.1", # standard IPv4, loopback, non-routable
"0.0.0.0", # standard IPv4, unspecified, non-routable
"255.255.255.255", # standard IPv4
"fe80:0000:0000:0000:0204:61ff:fe9d:f156",
"fe80:0:0:0:204:61ff:fe9d:f156",
"fe80::204:61ff:fe9d:f156",
"fe80:0000:0000:0000:0204:61ff:254.157.241.086",
"fe80:0:0:0:204:61ff:254.157.241.86",
"fe80::204:61ff:254.157.241.86",
"::1",
"fe80::",
"fe80::1"
].each { |ip|
describe "when the pattern is a valid IP such as #{ip}" do
before :each do
@declaration = Puppet::Network::AuthStore::Declaration.new(:allow_ip,ip)
end
it "should match the specified IP" do
- @declaration.should be_match('www.testsite.org',ip)
+ expect(@declaration).to be_match('www.testsite.org',ip)
end
it "should not match other IPs" do
- @declaration.should_not be_match('www.testsite.org','200.101.99.98')
+ expect(@declaration).not_to be_match('www.testsite.org','200.101.99.98')
end
end unless ip =~ /:.*\./ # Hybrid IPs aren't supported by ruby's ipaddr
}
[
"::2:3:4:5:6:7:8",
].each { |ip|
describe "when the pattern is a valid IP such as #{ip}" do
let(:declaration) do
Puppet::Network::AuthStore::Declaration.new(:allow_ip,ip)
end
issue_7477 = !(IPAddr.new(ip) rescue false)
- it "should match the specified IP" do
- pending "resolution of ruby issue [7477](http://goo.gl/Bb1LU)", :if => issue_7477
- declaration.should be_match('www.testsite.org',ip)
- end
- it "should not match other IPs" do
- pending "resolution of ruby issue [7477](http://goo.gl/Bb1LU)", :if => issue_7477
- declaration.should_not be_match('www.testsite.org','200.101.99.98')
- end
+ describe "on rubies with a fix for issue [7477](http://goo.gl/Bb1LU)", :if => issue_7477
+ it "should match the specified IP" do
+ expect(declaration).to be_match('www.testsite.org',ip)
+ end
+ it "should not match other IPs" do
+ expect(declaration).not_to be_match('www.testsite.org','200.101.99.98')
+ end
end
}
{
'spirit.mars.nasa.gov' => 'a PQDN',
'ratchet.2ndsiteinc.com' => 'a PQDN with digits',
'a.c.ru' => 'a PQDN with short segments',
}.each {|pqdn,desc|
describe "when the pattern is #{desc}" do
before :each do
@host = pqdn
@declaration = Puppet::Network::AuthStore::Declaration.new(:allow,@host)
end
it "should match the specified PQDN" do
- @declaration.should be_match(@host,'200.101.99.98')
+ expect(@declaration).to be_match(@host,'200.101.99.98')
end
it "should not match a similar FQDN" do
pending "FQDN consensus"
- @declaration.should_not be_match(@host+'.','200.101.99.98')
+ expect(@declaration).not_to be_match(@host+'.','200.101.99.98')
end
end
}
['abc.12seps.edu.phisher.biz','www.google.com','slashdot.org'].each { |host|
(1...(host.split('.').length)).each { |n|
describe "when the pattern is #{"*."+host.split('.')[-n,n].join('.')}" do
before :each do
@pattern = "*."+host.split('.')[-n,n].join('.')
@declaration = Puppet::Network::AuthStore::Declaration.new(:allow,@pattern)
end
it "should match #{host}" do
- @declaration.should be_match(host,'1.2.3.4')
+ expect(@declaration).to be_match(host,'1.2.3.4')
end
it "should not match www.testsite.gov" do
- @declaration.should_not be_match('www.testsite.gov','200.101.99.98')
+ expect(@declaration).not_to be_match('www.testsite.gov','200.101.99.98')
end
it "should not match hosts that differ in the first non-wildcard segment" do
other = host.split('.')
other[-n].succ!
- @declaration.should_not be_match(other.join('.'),'1.2.3.4')
+ expect(@declaration).not_to be_match(other.join('.'),'1.2.3.4')
end
end
}
}
describe "when the pattern is a FQDN" do
before :each do
@host = 'spirit.mars.nasa.gov.'
@declaration = Puppet::Network::AuthStore::Declaration.new(:allow,@host)
end
it "should match the specified FQDN" do
pending "FQDN consensus"
- @declaration.should be_match(@host,'200.101.99.98')
+ expect(@declaration).to be_match(@host,'200.101.99.98')
end
it "should not match a similar PQDN" do
- @declaration.should_not be_match(@host[0..-2],'200.101.99.98')
+ expect(@declaration).not_to be_match(@host[0..-2],'200.101.99.98')
end
end
describe "when the pattern is an opaque string with a back reference" do
before :each do
@host = 'c216f41a-f902-4bfb-a222-850dd957bebb'
@item = "/catalog/#{@host}"
@pattern = %{^/catalog/([^/]+)$}
@declaration = Puppet::Network::AuthStore::Declaration.new(:allow,'$1')
end
it "should match an IP with the appropriate interpolation" do
- @declaration.interpolate(@item.match(@pattern)).should be_match(@host,'10.0.0.5')
+ expect(@declaration.interpolate(@item.match(@pattern))).to be_match(@host,'10.0.0.5')
end
end
describe "when the pattern is an opaque string with a back reference and the matched data contains dots" do
before :each do
@host = 'admin.mgmt.nym1'
@item = "/catalog/#{@host}"
@pattern = %{^/catalog/([^/]+)$}
@declaration = Puppet::Network::AuthStore::Declaration.new(:allow,'$1')
end
it "should match a name with the appropriate interpolation" do
- @declaration.interpolate(@item.match(@pattern)).should be_match(@host,'10.0.0.5')
+ expect(@declaration.interpolate(@item.match(@pattern))).to be_match(@host,'10.0.0.5')
end
end
describe "when the pattern is an opaque string with a back reference and the matched data contains dots with an initial prefix that looks like an IP address" do
before :each do
@host = '01.admin.mgmt.nym1'
@item = "/catalog/#{@host}"
@pattern = %{^/catalog/([^/]+)$}
@declaration = Puppet::Network::AuthStore::Declaration.new(:allow,'$1')
end
it "should match a name with the appropriate interpolation" do
- @declaration.interpolate(@item.match(@pattern)).should be_match(@host,'10.0.0.5')
+ expect(@declaration.interpolate(@item.match(@pattern))).to be_match(@host,'10.0.0.5')
end
end
describe "when comparing patterns" do
before :each do
@ip = Puppet::Network::AuthStore::Declaration.new(:allow,'127.0.0.1')
@host_name = Puppet::Network::AuthStore::Declaration.new(:allow,'www.hard_knocks.edu')
@opaque = Puppet::Network::AuthStore::Declaration.new(:allow,'hey_dude')
end
it "should consider ip addresses before host names" do
- (@ip < @host_name).should be_true
+ expect(@ip < @host_name).to be_truthy
end
it "should consider ip addresses before opaque strings" do
- (@ip < @opaque).should be_true
+ expect(@ip < @opaque).to be_truthy
end
it "should consider host_names before opaque strings" do
- (@host_name < @opaque).should be_true
+ expect(@host_name < @opaque).to be_truthy
end
end
end
diff --git a/spec/unit/network/format_handler_spec.rb b/spec/unit/network/format_handler_spec.rb
index 1716a7296..7d861db02 100755
--- a/spec/unit/network/format_handler_spec.rb
+++ b/spec/unit/network/format_handler_spec.rb
@@ -1,94 +1,94 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/format_handler'
describe Puppet::Network::FormatHandler do
before(:each) do
@saved_formats = Puppet::Network::FormatHandler.instance_variable_get(:@formats).dup
Puppet::Network::FormatHandler.instance_variable_set(:@formats, {})
end
after(:each) do
Puppet::Network::FormatHandler.instance_variable_set(:@formats, @saved_formats)
end
describe "when creating formats" do
it "should instance_eval any block provided when creating a format" do
format = Puppet::Network::FormatHandler.create(:test_format) do
def asdfghjkl; end
end
- format.should respond_to(:asdfghjkl)
+ expect(format).to respond_to(:asdfghjkl)
end
end
describe "when retrieving formats" do
let!(:format) { Puppet::Network::FormatHandler.create(:the_format, :extension => "foo", :mime => "foo/bar") }
it "should be able to retrieve a format by name" do
- Puppet::Network::FormatHandler.format(:the_format).should equal(format)
+ expect(Puppet::Network::FormatHandler.format(:the_format)).to equal(format)
end
it "should be able to retrieve a format by extension" do
- Puppet::Network::FormatHandler.format_by_extension("foo").should equal(format)
+ expect(Puppet::Network::FormatHandler.format_by_extension("foo")).to equal(format)
end
it "should return nil if asked to return a format by an unknown extension" do
- Puppet::Network::FormatHandler.format_by_extension("yayness").should be_nil
+ expect(Puppet::Network::FormatHandler.format_by_extension("yayness")).to be_nil
end
it "should be able to retrieve formats by name irrespective of case" do
- Puppet::Network::FormatHandler.format(:The_Format).should equal(format)
+ expect(Puppet::Network::FormatHandler.format(:The_Format)).to equal(format)
end
it "should be able to retrieve a format by mime type" do
- Puppet::Network::FormatHandler.mime("foo/bar").should equal(format)
+ expect(Puppet::Network::FormatHandler.mime("foo/bar")).to equal(format)
end
it "should be able to retrieve a format by mime type irrespective of case" do
- Puppet::Network::FormatHandler.mime("Foo/Bar").should equal(format)
+ expect(Puppet::Network::FormatHandler.mime("Foo/Bar")).to equal(format)
end
end
describe "#most_suitable_format_for" do
before :each do
Puppet::Network::FormatHandler.create(:one, :extension => "foo", :mime => "text/one")
Puppet::Network::FormatHandler.create(:two, :extension => "bar", :mime => "application/two")
end
let(:format_one) { Puppet::Network::FormatHandler.format(:one) }
let(:format_two) { Puppet::Network::FormatHandler.format(:two) }
def suitable_in_setup_formats(accepted)
Puppet::Network::FormatHandler.most_suitable_format_for(accepted, [:one, :two])
end
it "finds the most preferred format when anything is acceptable" do
- Puppet::Network::FormatHandler.most_suitable_format_for(["*/*"], [:two, :one]).should == format_two
+ expect(Puppet::Network::FormatHandler.most_suitable_format_for(["*/*"], [:two, :one])).to eq(format_two)
end
it "finds no format when none are acceptable" do
- suitable_in_setup_formats(["three"]).should be_nil
+ expect(suitable_in_setup_formats(["three"])).to be_nil
end
it "skips unsupported, but accepted, formats" do
- suitable_in_setup_formats(["three", "two"]).should == format_two
+ expect(suitable_in_setup_formats(["three", "two"])).to eq(format_two)
end
it "gives the first acceptable and suitable format" do
- suitable_in_setup_formats(["three", "one", "two"]).should == format_one
+ expect(suitable_in_setup_formats(["three", "one", "two"])).to eq(format_one)
end
it "allows specifying acceptable formats by mime type" do
- suitable_in_setup_formats(["text/one"]).should == format_one
+ expect(suitable_in_setup_formats(["text/one"])).to eq(format_one)
end
it "ignores quality specifiers" do
- suitable_in_setup_formats(["two;q=0.8", "text/one;q=0.9"]).should == format_two
+ expect(suitable_in_setup_formats(["two;q=0.8", "text/one;q=0.9"])).to eq(format_two)
end
it "allows specifying acceptable formats by canonical name" do
- suitable_in_setup_formats([:one]).should == format_one
+ expect(suitable_in_setup_formats([:one])).to eq(format_one)
end
end
end
diff --git a/spec/unit/network/format_spec.rb b/spec/unit/network/format_spec.rb
index 198294edc..93a553846 100755
--- a/spec/unit/network/format_spec.rb
+++ b/spec/unit/network/format_spec.rb
@@ -1,197 +1,197 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/format'
# A class with all of the necessary
# hooks.
class FormatRenderer
def self.to_multiple_my_format(list)
end
def self.from_multiple_my_format(text)
end
def self.from_my_format(text)
end
def to_my_format
end
end
describe Puppet::Network::Format do
describe "when initializing" do
it "should require a name" do
- lambda { Puppet::Network::Format.new }.should raise_error(ArgumentError)
+ expect { Puppet::Network::Format.new }.to raise_error(ArgumentError)
end
it "should be able to provide its name" do
- Puppet::Network::Format.new(:my_format).name.should == :my_format
+ expect(Puppet::Network::Format.new(:my_format).name).to eq(:my_format)
end
it "should always convert its name to a downcased symbol" do
- Puppet::Network::Format.new(:My_Format).name.should == :my_format
+ expect(Puppet::Network::Format.new(:My_Format).name).to eq(:my_format)
end
it "should be able to set its downcased mime type at initialization" do
format = Puppet::Network::Format.new(:my_format, :mime => "Foo/Bar")
- format.mime.should == "foo/bar"
+ expect(format.mime).to eq("foo/bar")
end
it "should default to text plus the name of the format as the mime type" do
- Puppet::Network::Format.new(:my_format).mime.should == "text/my_format"
+ expect(Puppet::Network::Format.new(:my_format).mime).to eq("text/my_format")
end
it "should fail if unsupported options are provided" do
- lambda { Puppet::Network::Format.new(:my_format, :foo => "bar") }.should raise_error(ArgumentError)
+ expect { Puppet::Network::Format.new(:my_format, :foo => "bar") }.to raise_error(ArgumentError)
end
end
describe "instances" do
before do
@format = Puppet::Network::Format.new(:my_format)
end
it "should support being confined" do
- @format.should respond_to(:confine)
+ expect(@format).to respond_to(:confine)
end
it "should not be considered suitable if confinement conditions are not met" do
@format.confine :true => false
- @format.should_not be_suitable
+ expect(@format).not_to be_suitable
end
it "should be able to determine if a class is supported" do
- @format.should respond_to(:supported?)
+ expect(@format).to respond_to(:supported?)
end
it "should consider a class to be supported if it has the individual and multiple methods for rendering and interning" do
- @format.should be_supported(FormatRenderer)
+ expect(@format).to be_supported(FormatRenderer)
end
it "should default to its required methods being the individual and multiple methods for rendering and interning" do
- Puppet::Network::Format.new(:foo).required_methods.sort { |a,b| a.to_s <=> b.to_s }.should == [:intern_method, :intern_multiple_method, :render_multiple_method, :render_method].sort { |a,b| a.to_s <=> b.to_s }
+ expect(Puppet::Network::Format.new(:foo).required_methods.sort { |a,b| a.to_s <=> b.to_s }).to eq([:intern_method, :intern_multiple_method, :render_multiple_method, :render_method].sort { |a,b| a.to_s <=> b.to_s })
end
it "should consider a class supported if the provided class has all required methods present" do
format = Puppet::Network::Format.new(:foo)
[:intern_method, :intern_multiple_method, :render_multiple_method, :render_method].each do |method|
format.expects(:required_method_present?).with { |name, klass, type| name == method and klass == String }.returns true
end
- format.should be_required_methods_present(String)
+ expect(format).to be_required_methods_present(String)
end
it "should consider a class not supported if any required methods are missing from the provided class" do
format = Puppet::Network::Format.new(:foo)
format.stubs(:required_method_present?).returns true
format.expects(:required_method_present?).with { |name, *args| name == :intern_method }.returns false
- format.should_not be_required_methods_present(String)
+ expect(format).not_to be_required_methods_present(String)
end
it "should be able to specify the methods required for support" do
- Puppet::Network::Format.new(:foo, :required_methods => [:render_method, :intern_method]).required_methods.should == [:render_method, :intern_method]
+ expect(Puppet::Network::Format.new(:foo, :required_methods => [:render_method, :intern_method]).required_methods).to eq([:render_method, :intern_method])
end
it "should only test for required methods if specific methods are specified as required" do
format = Puppet::Network::Format.new(:foo, :required_methods => [:intern_method])
format.expects(:required_method_present?).with { |name, klass, type| name == :intern_method }
format.required_methods_present?(String)
end
it "should not consider a class supported unless the format is suitable" do
@format.expects(:suitable?).returns false
- @format.should_not be_supported(FormatRenderer)
+ expect(@format).not_to be_supported(FormatRenderer)
end
it "should always downcase mimetypes" do
@format.mime = "Foo/Bar"
- @format.mime.should == "foo/bar"
+ expect(@format.mime).to eq("foo/bar")
end
it "should support having a weight" do
- @format.should respond_to(:weight)
+ expect(@format).to respond_to(:weight)
end
it "should default to a weight of of 5" do
- @format.weight.should == 5
+ expect(@format.weight).to eq(5)
end
it "should be able to override its weight at initialization" do
- Puppet::Network::Format.new(:foo, :weight => 1).weight.should == 1
+ expect(Puppet::Network::Format.new(:foo, :weight => 1).weight).to eq(1)
end
it "should default to its extension being equal to its name" do
- Puppet::Network::Format.new(:foo).extension.should == "foo"
+ expect(Puppet::Network::Format.new(:foo).extension).to eq("foo")
end
it "should support overriding the extension" do
- Puppet::Network::Format.new(:foo, :extension => "bar").extension.should == "bar"
+ expect(Puppet::Network::Format.new(:foo, :extension => "bar").extension).to eq("bar")
end
[:intern_method, :intern_multiple_method, :render_multiple_method, :render_method].each do |method|
it "should allow assignment of the #{method}" do
- Puppet::Network::Format.new(:foo, method => :foo).send(method).should == :foo
+ expect(Puppet::Network::Format.new(:foo, method => :foo).send(method)).to eq(:foo)
end
end
end
describe "when converting between instances and formatted text" do
before do
@format = Puppet::Network::Format.new(:my_format)
@instance = FormatRenderer.new
end
it "should have a method for rendering a single instance" do
- @format.should respond_to(:render)
+ expect(@format).to respond_to(:render)
end
it "should have a method for rendering multiple instances" do
- @format.should respond_to(:render_multiple)
+ expect(@format).to respond_to(:render_multiple)
end
it "should have a method for interning text" do
- @format.should respond_to(:intern)
+ expect(@format).to respond_to(:intern)
end
it "should have a method for interning text into multiple instances" do
- @format.should respond_to(:intern_multiple)
+ expect(@format).to respond_to(:intern_multiple)
end
it "should return the results of calling the instance-specific render method if the method is present" do
@instance.expects(:to_my_format).returns "foo"
- @format.render(@instance).should == "foo"
+ expect(@format.render(@instance)).to eq("foo")
end
it "should return the results of calling the class-specific render_multiple method if the method is present" do
@instance.class.expects(:to_multiple_my_format).returns ["foo"]
- @format.render_multiple([@instance]).should == ["foo"]
+ expect(@format.render_multiple([@instance])).to eq(["foo"])
end
it "should return the results of calling the class-specific intern method if the method is present" do
FormatRenderer.expects(:from_my_format).with("foo").returns @instance
- @format.intern(FormatRenderer, "foo").should equal(@instance)
+ expect(@format.intern(FormatRenderer, "foo")).to equal(@instance)
end
it "should return the results of calling the class-specific intern_multiple method if the method is present" do
FormatRenderer.expects(:from_multiple_my_format).with("foo").returns [@instance]
- @format.intern_multiple(FormatRenderer, "foo").should == [@instance]
+ expect(@format.intern_multiple(FormatRenderer, "foo")).to eq([@instance])
end
it "should fail if asked to render and the instance does not respond to 'to_<format>'" do
- lambda { @format.render("foo") }.should raise_error(NotImplementedError)
+ expect { @format.render("foo") }.to raise_error(NotImplementedError)
end
it "should fail if asked to intern and the class does not respond to 'from_<format>'" do
- lambda { @format.intern(String, "foo") }.should raise_error(NotImplementedError)
+ expect { @format.intern(String, "foo") }.to raise_error(NotImplementedError)
end
it "should fail if asked to intern multiple and the class does not respond to 'from_multiple_<format>'" do
- lambda { @format.intern_multiple(String, "foo") }.should raise_error(NotImplementedError)
+ expect { @format.intern_multiple(String, "foo") }.to raise_error(NotImplementedError)
end
it "should fail if asked to render multiple and the instance does not respond to 'to_multiple_<format>'" do
- lambda { @format.render_multiple(["foo", "bar"]) }.should raise_error(NotImplementedError)
+ expect { @format.render_multiple(["foo", "bar"]) }.to raise_error(NotImplementedError)
end
end
end
diff --git a/spec/unit/network/format_support_spec.rb b/spec/unit/network/format_support_spec.rb
index 8e43ae135..4c4d6131e 100644
--- a/spec/unit/network/format_support_spec.rb
+++ b/spec/unit/network/format_support_spec.rb
@@ -1,199 +1,199 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/format_handler'
require 'puppet/network/format_support'
class FormatTester
include Puppet::Network::FormatSupport
end
describe Puppet::Network::FormatHandler do
before(:each) do
@saved_formats = Puppet::Network::FormatHandler.instance_variable_get(:@formats).dup
Puppet::Network::FormatHandler.instance_variable_set(:@formats, {})
end
after(:each) do
Puppet::Network::FormatHandler.instance_variable_set(:@formats, @saved_formats)
end
describe "when listing formats" do
before(:each) do
one = Puppet::Network::FormatHandler.create(:one, :weight => 1)
one.stubs(:supported?).returns(true)
two = Puppet::Network::FormatHandler.create(:two, :weight => 6)
two.stubs(:supported?).returns(true)
three = Puppet::Network::FormatHandler.create(:three, :weight => 2)
three.stubs(:supported?).returns(true)
four = Puppet::Network::FormatHandler.create(:four, :weight => 8)
four.stubs(:supported?).returns(false)
end
it "should return all supported formats in decreasing order of weight" do
- FormatTester.supported_formats.should == [:two, :three, :one]
+ expect(FormatTester.supported_formats).to eq([:two, :three, :one])
end
end
it "should return the first format as the default format" do
FormatTester.expects(:supported_formats).returns [:one, :two]
- FormatTester.default_format.should == :one
+ expect(FormatTester.default_format).to eq(:one)
end
describe "with a preferred serialization format setting" do
before do
one = Puppet::Network::FormatHandler.create(:one, :weight => 1)
one.stubs(:supported?).returns(true)
two = Puppet::Network::FormatHandler.create(:two, :weight => 6)
two.stubs(:supported?).returns(true)
end
describe "that is supported" do
before do
Puppet[:preferred_serialization_format] = :one
end
it "should return the preferred serialization format first" do
- FormatTester.supported_formats.should == [:one, :two]
+ expect(FormatTester.supported_formats).to eq([:one, :two])
end
end
describe "that is not supported" do
before do
Puppet[:preferred_serialization_format] = :unsupported
end
it "should return the default format first" do
- FormatTester.supported_formats.should == [:two, :one]
+ expect(FormatTester.supported_formats).to eq([:two, :one])
end
it "should log a debug message" do
Puppet.expects(:debug).with("Value of 'preferred_serialization_format' (unsupported) is invalid for FormatTester, using default (two)")
Puppet.expects(:debug).with("FormatTester supports formats: two one")
FormatTester.supported_formats
end
end
end
describe "when using formats" do
let(:format) { Puppet::Network::FormatHandler.create(:my_format, :mime => "text/myformat") }
it "should use the Format to determine whether a given format is supported" do
format.expects(:supported?).with(FormatTester)
FormatTester.support_format?(:my_format)
end
it "should call the format-specific converter when asked to convert from a given format" do
format.expects(:intern).with(FormatTester, "mydata")
FormatTester.convert_from(:my_format, "mydata")
end
it "should call the format-specific converter when asked to convert from a given format by mime-type" do
format.expects(:intern).with(FormatTester, "mydata")
FormatTester.convert_from("text/myformat", "mydata")
end
it "should call the format-specific converter when asked to convert from a given format by format instance" do
format.expects(:intern).with(FormatTester, "mydata")
FormatTester.convert_from(format, "mydata")
end
it "should raise a FormatError when an exception is encountered when converting from a format" do
format.expects(:intern).with(FormatTester, "mydata").raises "foo"
expect do
FormatTester.convert_from(:my_format, "mydata")
end.to raise_error(
Puppet::Network::FormatHandler::FormatError,
'Could not intern from my_format: foo'
)
end
it "should be able to use a specific hook for converting into multiple instances" do
format.expects(:intern_multiple).with(FormatTester, "mydata")
FormatTester.convert_from_multiple(:my_format, "mydata")
end
it "should raise a FormatError when an exception is encountered when converting multiple items from a format" do
format.expects(:intern_multiple).with(FormatTester, "mydata").raises "foo"
expect do
FormatTester.convert_from_multiple(:my_format, "mydata")
end.to raise_error(Puppet::Network::FormatHandler::FormatError, 'Could not intern_multiple from my_format: foo')
end
it "should be able to use a specific hook for rendering multiple instances" do
format.expects(:render_multiple).with("mydata")
FormatTester.render_multiple(:my_format, "mydata")
end
it "should raise a FormatError when an exception is encountered when rendering multiple items into a format" do
format.expects(:render_multiple).with("mydata").raises "foo"
expect do
FormatTester.render_multiple(:my_format, "mydata")
end.to raise_error(Puppet::Network::FormatHandler::FormatError, 'Could not render_multiple to my_format: foo')
end
end
describe "when an instance" do
let(:format) { Puppet::Network::FormatHandler.create(:foo, :mime => "text/foo") }
it "should list as supported a format that reports itself supported" do
format.expects(:supported?).returns true
- FormatTester.new.support_format?(:foo).should be_true
+ expect(FormatTester.new.support_format?(:foo)).to be_truthy
end
it "should raise a FormatError when a rendering error is encountered" do
tester = FormatTester.new
format.expects(:render).with(tester).raises "eh"
expect do
tester.render(:foo)
end.to raise_error(Puppet::Network::FormatHandler::FormatError, 'Could not render to foo: eh')
end
it "should call the format-specific converter when asked to convert to a given format" do
tester = FormatTester.new
format.expects(:render).with(tester).returns "foo"
- tester.render(:foo).should == "foo"
+ expect(tester.render(:foo)).to eq("foo")
end
it "should call the format-specific converter when asked to convert to a given format by mime-type" do
tester = FormatTester.new
format.expects(:render).with(tester).returns "foo"
- tester.render("text/foo").should == "foo"
+ expect(tester.render("text/foo")).to eq("foo")
end
it "should call the format converter when asked to convert to a given format instance" do
tester = FormatTester.new
format.expects(:render).with(tester).returns "foo"
- tester.render(format).should == "foo"
+ expect(tester.render(format)).to eq("foo")
end
it "should render to the default format if no format is provided when rendering" do
FormatTester.expects(:default_format).returns :foo
tester = FormatTester.new
format.expects(:render).with(tester)
tester.render
end
it "should call the format-specific converter when asked for the mime-type of a given format" do
tester = FormatTester.new
format.expects(:mime).returns "text/foo"
- tester.mime(:foo).should == "text/foo"
+ expect(tester.mime(:foo)).to eq("text/foo")
end
it "should return the default format mime-type if no format is provided" do
FormatTester.expects(:default_format).returns :foo
tester = FormatTester.new
format.expects(:mime).returns "text/foo"
- tester.mime.should == "text/foo"
+ expect(tester.mime).to eq("text/foo")
end
end
end
diff --git a/spec/unit/network/formats_spec.rb b/spec/unit/network/formats_spec.rb
index 9fe9d1352..65253acc1 100755
--- a/spec/unit/network/formats_spec.rb
+++ b/spec/unit/network/formats_spec.rb
@@ -1,330 +1,330 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/formats'
class PsonTest
attr_accessor :string
def ==(other)
string == other.string
end
def self.from_data_hash(data)
new(data)
end
def initialize(string)
@string = string
end
def to_pson(*args)
{
'type' => self.class.name,
'data' => @string
}.to_pson(*args)
end
end
describe "Puppet Network Format" do
it "should include a msgpack format", :if => Puppet.features.msgpack? do
- Puppet::Network::FormatHandler.format(:msgpack).should_not be_nil
+ expect(Puppet::Network::FormatHandler.format(:msgpack)).not_to be_nil
end
describe "msgpack", :if => Puppet.features.msgpack? do
before do
@msgpack = Puppet::Network::FormatHandler.format(:msgpack)
end
it "should have its mime type set to application/x-msgpack" do
- @msgpack.mime.should == "application/x-msgpack"
+ expect(@msgpack.mime).to eq("application/x-msgpack")
end
it "should have a weight of 20" do
- @msgpack.weight.should == 20
+ expect(@msgpack.weight).to eq(20)
end
it "should fail when one element does not have a from_data_hash" do
expect do
@msgpack.intern_multiple(Hash, MessagePack.pack(["foo"]))
end.to raise_error(NoMethodError)
end
it "should be able to serialize a catalog" do
cat = Puppet::Resource::Catalog.new('foo', Puppet::Node::Environment.create(:testing, []))
cat.add_resource(Puppet::Resource.new(:file, 'my_file'))
catunpack = MessagePack.unpack(cat.to_msgpack)
- catunpack.should include(
+ expect(catunpack).to include(
"tags"=>[],
"name"=>"foo",
"version"=>nil,
"environment"=>"testing",
"edges"=>[],
"classes"=>[]
)
- catunpack["resources"][0].should include(
+ expect(catunpack["resources"][0]).to include(
"type"=>"File",
"title"=>"my_file",
"exported"=>false
)
- catunpack["resources"][0]["tags"].should include(
+ expect(catunpack["resources"][0]["tags"]).to include(
"file",
"my_file"
)
end
end
describe "yaml" do
before do
@yaml = Puppet::Network::FormatHandler.format(:yaml)
end
it "should have its mime type set to text/yaml" do
- @yaml.mime.should == "text/yaml"
+ expect(@yaml.mime).to eq("text/yaml")
end
it "should be supported on Strings" do
- @yaml.should be_supported(String)
+ expect(@yaml).to be_supported(String)
end
it "should render by calling 'to_yaml' on the instance" do
instance = mock 'instance'
instance.expects(:to_yaml).returns "foo"
- @yaml.render(instance).should == "foo"
+ expect(@yaml.render(instance)).to eq("foo")
end
it "should render multiple instances by calling 'to_yaml' on the array" do
instances = [mock('instance')]
instances.expects(:to_yaml).returns "foo"
- @yaml.render_multiple(instances).should == "foo"
+ expect(@yaml.render_multiple(instances)).to eq("foo")
end
it "should deserialize YAML" do
- @yaml.intern(String, YAML.dump("foo")).should == "foo"
+ expect(@yaml.intern(String, YAML.dump("foo"))).to eq("foo")
end
it "should deserialize symbols as strings" do
expect { @yaml.intern(String, YAML.dump(:foo))}.to raise_error(Puppet::Network::FormatHandler::FormatError)
end
it "should load from yaml when deserializing an array" do
text = YAML.dump(["foo"])
- @yaml.intern_multiple(String, text).should == ["foo"]
+ expect(@yaml.intern_multiple(String, text)).to eq(["foo"])
end
it "fails intelligibly instead of calling to_pson with something other than a hash" do
expect do
@yaml.intern(Puppet::Node, '')
end.to raise_error(Puppet::Network::FormatHandler::FormatError, /did not contain a valid instance/)
end
it "fails intelligibly when intern_multiple is called and yaml doesn't decode to an array" do
expect do
@yaml.intern_multiple(Puppet::Node, '')
end.to raise_error(Puppet::Network::FormatHandler::FormatError, /did not contain a collection/)
end
it "fails intelligibly instead of calling to_pson with something other than a hash when interning multiple" do
expect do
@yaml.intern_multiple(Puppet::Node, YAML.dump(["hello"]))
end.to raise_error(Puppet::Network::FormatHandler::FormatError, /did not contain a valid instance/)
end
end
describe "plaintext" do
before do
@text = Puppet::Network::FormatHandler.format(:s)
end
it "should have its mimetype set to text/plain" do
- @text.mime.should == "text/plain"
+ expect(@text.mime).to eq("text/plain")
end
it "should use 'txt' as its extension" do
- @text.extension.should == "txt"
+ expect(@text.extension).to eq("txt")
end
end
describe "dot" do
before do
@dot = Puppet::Network::FormatHandler.format(:dot)
end
it "should have its mimetype set to text/dot" do
- @dot.mime.should == "text/dot"
+ expect(@dot.mime).to eq("text/dot")
end
end
describe Puppet::Network::FormatHandler.format(:raw) do
before do
@format = Puppet::Network::FormatHandler.format(:raw)
end
it "should exist" do
- @format.should_not be_nil
+ expect(@format).not_to be_nil
end
it "should have its mimetype set to application/x-raw" do
- @format.mime.should == "application/x-raw"
+ expect(@format.mime).to eq("application/x-raw")
end
it "should always be supported" do
- @format.should be_supported(String)
+ expect(@format).to be_supported(String)
end
it "should fail if its multiple_render method is used" do
- lambda { @format.render_multiple("foo") }.should raise_error(NotImplementedError)
+ expect { @format.render_multiple("foo") }.to raise_error(NotImplementedError)
end
it "should fail if its multiple_intern method is used" do
- lambda { @format.intern_multiple(String, "foo") }.should raise_error(NotImplementedError)
+ expect { @format.intern_multiple(String, "foo") }.to raise_error(NotImplementedError)
end
it "should have a weight of 1" do
- @format.weight.should == 1
+ expect(@format.weight).to eq(1)
end
end
it "should include a pson format" do
- Puppet::Network::FormatHandler.format(:pson).should_not be_nil
+ expect(Puppet::Network::FormatHandler.format(:pson)).not_to be_nil
end
describe "pson" do
before do
@pson = Puppet::Network::FormatHandler.format(:pson)
end
it "should have its mime type set to text/pson" do
- Puppet::Network::FormatHandler.format(:pson).mime.should == "text/pson"
+ expect(Puppet::Network::FormatHandler.format(:pson).mime).to eq("text/pson")
end
it "should require the :render_method" do
- Puppet::Network::FormatHandler.format(:pson).required_methods.should be_include(:render_method)
+ expect(Puppet::Network::FormatHandler.format(:pson).required_methods).to be_include(:render_method)
end
it "should require the :intern_method" do
- Puppet::Network::FormatHandler.format(:pson).required_methods.should be_include(:intern_method)
+ expect(Puppet::Network::FormatHandler.format(:pson).required_methods).to be_include(:intern_method)
end
it "should have a weight of 10" do
- @pson.weight.should == 10
+ expect(@pson.weight).to eq(10)
end
describe "when supported" do
it "should render by calling 'to_pson' on the instance" do
instance = PsonTest.new("foo")
instance.expects(:to_pson).returns "foo"
- @pson.render(instance).should == "foo"
+ expect(@pson.render(instance)).to eq("foo")
end
it "should render multiple instances by calling 'to_pson' on the array" do
instances = [mock('instance')]
instances.expects(:to_pson).returns "foo"
- @pson.render_multiple(instances).should == "foo"
+ expect(@pson.render_multiple(instances)).to eq("foo")
end
it "should intern by calling 'PSON.parse' on the text and then using from_data_hash to convert the data into an instance" do
text = "foo"
PSON.expects(:parse).with("foo").returns("type" => "PsonTest", "data" => "foo")
PsonTest.expects(:from_data_hash).with("foo").returns "parsed_pson"
- @pson.intern(PsonTest, text).should == "parsed_pson"
+ expect(@pson.intern(PsonTest, text)).to eq("parsed_pson")
end
it "should not render twice if 'PSON.parse' creates the appropriate instance" do
text = "foo"
instance = PsonTest.new("foo")
PSON.expects(:parse).with("foo").returns(instance)
PsonTest.expects(:from_data_hash).never
- @pson.intern(PsonTest, text).should equal(instance)
+ expect(@pson.intern(PsonTest, text)).to equal(instance)
end
it "should intern by calling 'PSON.parse' on the text and then using from_data_hash to convert the actual into an instance if the pson has no class/data separation" do
text = "foo"
PSON.expects(:parse).with("foo").returns("foo")
PsonTest.expects(:from_data_hash).with("foo").returns "parsed_pson"
- @pson.intern(PsonTest, text).should == "parsed_pson"
+ expect(@pson.intern(PsonTest, text)).to eq("parsed_pson")
end
it "should intern multiples by parsing the text and using 'class.intern' on each resulting data structure" do
text = "foo"
PSON.expects(:parse).with("foo").returns ["bar", "baz"]
PsonTest.expects(:from_data_hash).with("bar").returns "BAR"
PsonTest.expects(:from_data_hash).with("baz").returns "BAZ"
- @pson.intern_multiple(PsonTest, text).should == %w{BAR BAZ}
+ expect(@pson.intern_multiple(PsonTest, text)).to eq(%w{BAR BAZ})
end
it "fails intelligibly when given invalid data" do
expect do
@pson.intern(Puppet::Node, '')
end.to raise_error(PSON::ParserError, /source did not contain any PSON/)
end
end
end
describe ":console format" do
subject { Puppet::Network::FormatHandler.format(:console) }
- it { should be_an_instance_of Puppet::Network::Format }
+ it { is_expected.to be_an_instance_of Puppet::Network::Format }
let :json do Puppet::Network::FormatHandler.format(:pson) end
[:intern, :intern_multiple].each do |method|
it "should not implement #{method}" do
expect { subject.send(method, String, 'blah') }.to raise_error NotImplementedError
end
end
["hello", 1, 1.0].each do |input|
it "should just return a #{input.inspect}" do
- subject.render(input).should == input
+ expect(subject.render(input)).to eq(input)
end
end
[[1, 2], ["one"], [{ 1 => 1 }]].each do |input|
it "should render #{input.inspect} as one item per line" do
- subject.render(input).should == input.collect { |item| item.to_s + "\n" }.join('')
+ expect(subject.render(input)).to eq(input.collect { |item| item.to_s + "\n" }.join(''))
end
end
it "should render empty hashes as empty strings" do
- subject.render({}).should == ''
+ expect(subject.render({})).to eq('')
end
it "should render a non-trivially-keyed Hash as JSON" do
hash = { [1,2] => 3, [2,3] => 5, [3,4] => 7 }
- subject.render(hash).should == json.render(hash).chomp
+ expect(subject.render(hash)).to eq(json.render(hash).chomp)
end
it "should render a {String,Numeric}-keyed Hash into a table" do
object = Object.new
hash = { "one" => 1, "two" => [], "three" => {}, "four" => object,
5 => 5, 6.0 => 6 }
# Gotta love ASCII-betical sort order. Hope your objects are better
# structured for display than my test one is. --daniel 2011-04-18
- subject.render(hash).should == <<EOT
+ expect(subject.render(hash)).to eq <<EOT
5 5
6.0 6
four #{json.render(object).chomp}
one 1
three {}
two []
EOT
end
it "should render a hash nicely with a multi-line value" do
pending "Moving to PSON rather than PP makes this unsupportable."
hash = {
"number" => { "1" => '1' * 40, "2" => '2' * 40, '3' => '3' * 40 },
"text" => { "a" => 'a' * 40, 'b' => 'b' * 40, 'c' => 'c' * 40 }
}
- subject.render(hash).should == <<EOT
+ expect(subject.render(hash)).to eq <<EOT
number {"1"=>"1111111111111111111111111111111111111111",
"2"=>"2222222222222222222222222222222222222222",
"3"=>"3333333333333333333333333333333333333333"}
text {"a"=>"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"b"=>"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"c"=>"cccccccccccccccccccccccccccccccccccccccc"}
EOT
end
end
end
diff --git a/spec/unit/network/http/api/indirected_routes_spec.rb b/spec/unit/network/http/api/indirected_routes_spec.rb
index 2a0e84641..97b5de61b 100644
--- a/spec/unit/network/http/api/indirected_routes_spec.rb
+++ b/spec/unit/network/http/api/indirected_routes_spec.rb
@@ -1,516 +1,516 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/http'
require 'puppet/network/http/api/indirected_routes'
require 'puppet/indirector_testing'
describe Puppet::Network::HTTP::API::IndirectedRoutes do
let(:not_found_code) { Puppet::Network::HTTP::Error::HTTPNotFoundError::CODE }
let(:not_acceptable_code) { Puppet::Network::HTTP::Error::HTTPNotAcceptableError::CODE }
let(:bad_request_code) { Puppet::Network::HTTP::Error::HTTPBadRequestError::CODE }
let(:not_authorized_code) { Puppet::Network::HTTP::Error::HTTPNotAuthorizedError::CODE }
let(:indirection) { Puppet::IndirectorTesting.indirection }
let(:handler) { Puppet::Network::HTTP::API::IndirectedRoutes.new }
let(:response) { Puppet::Network::HTTP::MemoryResponse.new }
let(:params) { { :environment => "production" } }
let(:master_url_prefix) { "#{Puppet::Network::HTTP::MASTER_URL_PREFIX}/v3"}
let(:ca_url_prefix) { "#{Puppet::Network::HTTP::CA_URL_PREFIX}/v1"}
def a_request_that_heads(data, request = {})
Puppet::Network::HTTP::Request.from_hash({
:headers => {
'accept' => request[:accept_header],
'content-type' => "text/pson", },
:method => "HEAD",
:path => "#{master_url_prefix}/#{indirection.name}/#{data.value}",
:params => params,
})
end
def a_request_that_submits(data, request = {})
Puppet::Network::HTTP::Request.from_hash({
:headers => {
'accept' => request[:accept_header],
'content-type' => request[:content_type_header] || "text/pson", },
:method => "PUT",
:path => "#{master_url_prefix}/#{indirection.name}/#{data.value}",
:params => params,
:body => request[:body].nil? ? data.render("pson") : request[:body]
})
end
def a_request_that_destroys(data, request = {})
Puppet::Network::HTTP::Request.from_hash({
:headers => {
'accept' => request[:accept_header],
'content-type' => "text/pson", },
:method => "DELETE",
:path => "#{master_url_prefix}/#{indirection.name}/#{data.value}",
:params => params,
:body => ''
})
end
def a_request_that_finds(data, request = {})
Puppet::Network::HTTP::Request.from_hash({
:headers => {
'accept' => request[:accept_header],
'content-type' => "text/pson", },
:method => "GET",
:path => "#{master_url_prefix}/#{indirection.name}/#{data.value}",
:params => params,
:body => ''
})
end
def a_request_that_searches(key, request = {})
Puppet::Network::HTTP::Request.from_hash({
:headers => {
'accept' => request[:accept_header],
'content-type' => "text/pson", },
:method => "GET",
:path => "#{master_url_prefix}/#{indirection.name}s/#{key}",
:params => params,
:body => ''
})
end
before do
Puppet::IndirectorTesting.indirection.terminus_class = :memory
Puppet::IndirectorTesting.indirection.terminus.clear
handler.stubs(:check_authorization)
handler.stubs(:warn_if_near_expiration)
end
describe "when converting a URI into a request" do
let(:environment) { Puppet::Node::Environment.create(:env, []) }
let(:env_loaders) { Puppet::Environments::Static.new(environment) }
let(:params) { { :environment => "env" } }
before do
handler.stubs(:handler).returns "foo"
end
around do |example|
Puppet.override(:environments => env_loaders) do
example.run
end
end
it "should get the environment from a query parameter" do
- handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[3][:environment].to_s.should == "env"
+ expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[3][:environment].to_s).to eq("env")
end
it "should fail if there is no environment specified" do
- lambda { handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", {}) }.should raise_error(ArgumentError)
+ expect(lambda { handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", {}) }).to raise_error(ArgumentError)
end
it "should fail if the environment is not alphanumeric" do
- lambda { handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", {:environment => "env ness"}) }.should raise_error(ArgumentError)
+ expect(lambda { handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", {:environment => "env ness"}) }).to raise_error(ArgumentError)
end
it "should fail if the indirection does not match the prefix" do
- lambda { handler.uri2indirection("GET", "#{master_url_prefix}/certificate/foo", params) }.should raise_error(ArgumentError)
+ expect(lambda { handler.uri2indirection("GET", "#{master_url_prefix}/certificate/foo", params) }).to raise_error(ArgumentError)
end
it "should fail if the indirection does not have the correct version" do
- lambda { handler.uri2indirection("GET", "#{Puppet::Network::HTTP::CA_URL_PREFIX}/v3/certificate/foo", params) }.should raise_error(ArgumentError)
+ expect(lambda { handler.uri2indirection("GET", "#{Puppet::Network::HTTP::CA_URL_PREFIX}/v3/certificate/foo", params) }).to raise_error(ArgumentError)
end
it "should not pass a buck_path parameter through (See Bugs #13553, #13518, #13511)" do
- handler.uri2indirection("GET", "#{master_url_prefix}/node/bar",
+ expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bar",
{ :environment => "env",
- :bucket_path => "/malicious/path" })[3].should_not include({ :bucket_path => "/malicious/path" })
+ :bucket_path => "/malicious/path" })[3]).not_to include({ :bucket_path => "/malicious/path" })
end
it "should pass allowed parameters through" do
- handler.uri2indirection("GET", "#{master_url_prefix}/node/bar",
+ expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bar",
{ :environment => "env",
- :allowed_param => "value" })[3].should include({ :allowed_param => "value" })
+ :allowed_param => "value" })[3]).to include({ :allowed_param => "value" })
end
it "should return the environment as a Puppet::Node::Environment" do
- handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[3][:environment].should be_a(Puppet::Node::Environment)
+ expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[3][:environment]).to be_a(Puppet::Node::Environment)
end
it "should use the first field of the URI as the indirection name" do
- handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[0].name.should == :node
+ expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[0].name).to eq(:node)
end
it "should fail if the indirection name is not alphanumeric" do
- lambda { handler.uri2indirection("GET", "#{master_url_prefix}/foo ness/bar", params) }.should raise_error(ArgumentError)
+ expect(lambda { handler.uri2indirection("GET", "#{master_url_prefix}/foo ness/bar", params) }).to raise_error(ArgumentError)
end
it "should use the remainder of the URI as the indirection key" do
- handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[2].should == "bar"
+ expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[2]).to eq("bar")
end
it "should support the indirection key being a /-separated file path" do
- handler.uri2indirection("GET", "#{master_url_prefix}/node/bee/baz/bomb", params)[2].should == "bee/baz/bomb"
+ expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bee/baz/bomb", params)[2]).to eq("bee/baz/bomb")
end
it "should fail if no indirection key is specified" do
- lambda { handler.uri2indirection("GET", "#{master_url_prefix}/node", params) }.should raise_error(ArgumentError)
+ expect(lambda { handler.uri2indirection("GET", "#{master_url_prefix}/node", params) }).to raise_error(ArgumentError)
end
it "should choose 'find' as the indirection method if the http method is a GET and the indirection name is singular" do
- handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[1].should == :find
+ expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[1]).to eq(:find)
end
it "should choose 'find' as the indirection method if the http method is a POST and the indirection name is singular" do
- handler.uri2indirection("POST", "#{master_url_prefix}/node/bar", params)[1].should == :find
+ expect(handler.uri2indirection("POST", "#{master_url_prefix}/node/bar", params)[1]).to eq(:find)
end
it "should choose 'head' as the indirection method if the http method is a HEAD and the indirection name is singular" do
- handler.uri2indirection("HEAD", "#{master_url_prefix}/node/bar", params)[1].should == :head
+ expect(handler.uri2indirection("HEAD", "#{master_url_prefix}/node/bar", params)[1]).to eq(:head)
end
it "should choose 'search' as the indirection method if the http method is a GET and the indirection name is plural" do
- handler.uri2indirection("GET", "#{master_url_prefix}/nodes/bar", params)[1].should == :search
+ expect(handler.uri2indirection("GET", "#{master_url_prefix}/nodes/bar", params)[1]).to eq(:search)
end
it "should change indirection name to 'status' if the http method is a GET and the indirection name is statuses" do
- handler.uri2indirection("GET", "#{master_url_prefix}/statuses/bar", params)[0].name.should == :status
+ expect(handler.uri2indirection("GET", "#{master_url_prefix}/statuses/bar", params)[0].name).to eq(:status)
end
it "should change indirection name to 'node' if the http method is a GET and the indirection name is nodes" do
- handler.uri2indirection("GET", "#{master_url_prefix}/nodes/bar", params)[0].name.should == :node
+ expect(handler.uri2indirection("GET", "#{master_url_prefix}/nodes/bar", params)[0].name).to eq(:node)
end
it "should choose 'delete' as the indirection method if the http method is a DELETE and the indirection name is singular" do
- handler.uri2indirection("DELETE", "#{master_url_prefix}/node/bar", params)[1].should == :destroy
+ expect(handler.uri2indirection("DELETE", "#{master_url_prefix}/node/bar", params)[1]).to eq(:destroy)
end
it "should choose 'save' as the indirection method if the http method is a PUT and the indirection name is singular" do
- handler.uri2indirection("PUT", "#{master_url_prefix}/node/bar", params)[1].should == :save
+ expect(handler.uri2indirection("PUT", "#{master_url_prefix}/node/bar", params)[1]).to eq(:save)
end
it "should fail if an indirection method cannot be picked" do
- lambda { handler.uri2indirection("UPDATE", "#{master_url_prefix}/node/bar", params) }.should raise_error(ArgumentError)
+ expect(lambda { handler.uri2indirection("UPDATE", "#{master_url_prefix}/node/bar", params) }).to raise_error(ArgumentError)
end
it "should URI unescape the indirection key" do
escaped = URI.escape("foo bar")
indirection, method, key, final_params = handler.uri2indirection("GET", "#{master_url_prefix}/node/#{escaped}", params)
- key.should == "foo bar"
+ expect(key).to eq("foo bar")
end
end
describe "when converting a request into a URI" do
let(:environment) { Puppet::Node::Environment.create(:myenv, []) }
let(:request) { Puppet::Indirector::Request.new(:foo, :find, "with spaces", nil, :foo => :bar, :environment => environment) }
before do
handler.stubs(:handler).returns "foo"
end
it "should include the environment in the query string of the URI" do
- handler.class.request_to_uri(request).should == "#{master_url_prefix}/foo/with%20spaces?environment=myenv&foo=bar"
+ expect(handler.class.request_to_uri(request)).to eq("#{master_url_prefix}/foo/with%20spaces?environment=myenv&foo=bar")
end
it "should include the correct url prefix if it is a ca request" do
request.stubs(:indirection_name).returns("certificate")
- handler.class.request_to_uri(request).should == "#{ca_url_prefix}/certificate/with%20spaces?environment=myenv&foo=bar"
+ expect(handler.class.request_to_uri(request)).to eq("#{ca_url_prefix}/certificate/with%20spaces?environment=myenv&foo=bar")
end
it "should pluralize the indirection name if the method is 'search'" do
request.stubs(:method).returns :search
- handler.class.request_to_uri(request).split("/")[3].should == "foos"
+ expect(handler.class.request_to_uri(request).split("/")[3]).to eq("foos")
end
it "should add the query string to the URI" do
request.expects(:query_string).returns "query"
- handler.class.request_to_uri(request).should =~ /\&query$/
+ expect(handler.class.request_to_uri(request)).to match(/\&query$/)
end
end
describe "when converting a request into a URI with body" do
let(:environment) { Puppet::Node::Environment.create(:myenv, []) }
let(:request) { Puppet::Indirector::Request.new(:foo, :find, "with spaces", nil, :foo => :bar, :environment => environment) }
it "should use the indirection as the first field of the URI" do
- handler.class.request_to_uri_and_body(request).first.split("/")[3].should == "foo"
+ expect(handler.class.request_to_uri_and_body(request).first.split("/")[3]).to eq("foo")
end
it "should use the escaped key as the remainder of the URI" do
escaped = URI.escape("with spaces")
- handler.class.request_to_uri_and_body(request).first.split("/")[4].sub(/\?.+/, '').should == escaped
+ expect(handler.class.request_to_uri_and_body(request).first.split("/")[4].sub(/\?.+/, '')).to eq(escaped)
end
it "should include the correct url prefix if it is a master request" do
- handler.class.request_to_uri_and_body(request).first.should == "#{master_url_prefix}/foo/with%20spaces"
+ expect(handler.class.request_to_uri_and_body(request).first).to eq("#{master_url_prefix}/foo/with%20spaces")
end
it "should include the correct url prefix if it is a ca request" do
request.stubs(:indirection_name).returns("certificate")
- handler.class.request_to_uri_and_body(request).first.should == "#{ca_url_prefix}/certificate/with%20spaces"
+ expect(handler.class.request_to_uri_and_body(request).first).to eq("#{ca_url_prefix}/certificate/with%20spaces")
end
it "should return the URI and body separately" do
- handler.class.request_to_uri_and_body(request).should == ["#{master_url_prefix}/foo/with%20spaces", "environment=myenv&foo=bar"]
+ expect(handler.class.request_to_uri_and_body(request)).to eq(["#{master_url_prefix}/foo/with%20spaces", "environment=myenv&foo=bar"])
end
end
describe "when processing a request" do
it "should return not_authorized_code if the request is not authorized" do
request = a_request_that_heads(Puppet::IndirectorTesting.new("my data"))
handler.expects(:check_authorization).raises(Puppet::Network::AuthorizationError.new("forbidden"))
handler.call(request, response)
expect(response.code).to eq(not_authorized_code)
end
it "should return 'not found' if the indirection does not support remote requests" do
request = a_request_that_heads(Puppet::IndirectorTesting.new("my data"))
indirection.expects(:allow_remote_requests?).returns(false)
handler.call(request, response)
expect(response.code).to eq(not_found_code)
end
it "should return 'bad request' if the environment does not exist" do
Puppet.override(:environments => Puppet::Environments::Static.new()) do
request = a_request_that_heads(Puppet::IndirectorTesting.new("my data"))
handler.call(request, response)
expect(response.code).to eq(bad_request_code)
end
end
it "should serialize a controller exception when an exception is thrown while finding the model instance" do
request = a_request_that_finds(Puppet::IndirectorTesting.new("key"))
handler.expects(:do_find).raises(ArgumentError, "The exception")
handler.call(request, response)
expect(response.code).to eq(bad_request_code)
expect(response.body).to eq("The exception")
expect(response.type).to eq("text/plain")
end
end
describe "when finding a model instance" do
it "uses the first supported format for the response" do
data = Puppet::IndirectorTesting.new("my data")
indirection.save(data, "my data")
request = a_request_that_finds(data, :accept_header => "unknown, pson")
handler.call(request, response)
expect(response.body).to eq(data.render(:pson))
expect(response.type).to eq(Puppet::Network::FormatHandler.format(:pson))
end
it "responds with a not_acceptable_code error when no accept header is provided" do
data = Puppet::IndirectorTesting.new("my data")
indirection.save(data, "my data")
request = a_request_that_finds(data, :accept_header => nil)
handler.call(request, response)
expect(response.code).to eq(not_acceptable_code)
end
it "raises an error when no accepted formats are known" do
data = Puppet::IndirectorTesting.new("my data")
indirection.save(data, "my data")
request = a_request_that_finds(data, :accept_header => "unknown, also/unknown")
handler.call(request, response)
expect(response.code).to eq(not_acceptable_code)
end
it "should pass the result through without rendering it if the result is a string" do
data = Puppet::IndirectorTesting.new("my data")
data_string = "my data string"
request = a_request_that_finds(data, :accept_header => "text/pson")
indirection.expects(:find).returns(data_string)
handler.call(request, response)
expect(response.body).to eq(data_string)
expect(response.type).to eq(Puppet::Network::FormatHandler.format(:pson))
end
it "should return a not_found_code when no model instance can be found" do
data = Puppet::IndirectorTesting.new("my data")
request = a_request_that_finds(data, :accept_header => "unknown, text/pson")
handler.call(request, response)
expect(response.code).to eq(not_found_code)
end
end
describe "when searching for model instances" do
it "uses the first supported format for the response" do
data = Puppet::IndirectorTesting.new("my data")
indirection.save(data, "my data")
request = a_request_that_searches("my", :accept_header => "unknown, text/pson")
handler.call(request, response)
expect(response.type).to eq(Puppet::Network::FormatHandler.format(:pson))
expect(response.body).to eq(Puppet::IndirectorTesting.render_multiple(:pson, [data]))
end
it "should return [] when searching returns an empty array" do
request = a_request_that_searches("nothing", :accept_header => "unknown, text/pson")
handler.call(request, response)
expect(response.body).to eq("[]")
expect(response.type).to eq(Puppet::Network::FormatHandler.format(:pson))
end
it "should return a not_found_code when searching returns nil" do
request = a_request_that_searches("nothing", :accept_header => "unknown, text/pson")
indirection.expects(:search).returns(nil)
handler.call(request, response)
expect(response.code).to eq(not_found_code)
end
end
describe "when destroying a model instance" do
it "destroys the data indicated in the request" do
data = Puppet::IndirectorTesting.new("my data")
indirection.save(data, "my data")
request = a_request_that_destroys(data)
handler.call(request, response)
- Puppet::IndirectorTesting.indirection.find("my data").should be_nil
+ expect(Puppet::IndirectorTesting.indirection.find("my data")).to be_nil
end
it "responds with pson when no Accept header is given" do
data = Puppet::IndirectorTesting.new("my data")
indirection.save(data, "my data")
request = a_request_that_destroys(data, :accept_header => nil)
handler.call(request, response)
expect(response.body).to eq(data.render(:pson))
expect(response.type).to eq(Puppet::Network::FormatHandler.format(:pson))
end
it "uses the first supported format for the response" do
data = Puppet::IndirectorTesting.new("my data")
indirection.save(data, "my data")
request = a_request_that_destroys(data, :accept_header => "unknown, text/pson")
handler.call(request, response)
expect(response.body).to eq(data.render(:pson))
expect(response.type).to eq(Puppet::Network::FormatHandler.format(:pson))
end
it "raises an error and does not destroy when no accepted formats are known" do
data = Puppet::IndirectorTesting.new("my data")
indirection.save(data, "my data")
request = a_request_that_destroys(data, :accept_header => "unknown, also/unknown")
handler.call(request, response)
expect(response.code).to eq(not_acceptable_code)
- Puppet::IndirectorTesting.indirection.find("my data").should_not be_nil
+ expect(Puppet::IndirectorTesting.indirection.find("my data")).not_to be_nil
end
end
describe "when saving a model instance" do
it "allows an empty body when the format supports it" do
class Puppet::IndirectorTesting::Nonvalidatingmemory < Puppet::IndirectorTesting::Memory
def validate_key(_)
# nothing
end
end
indirection.terminus_class = :nonvalidatingmemory
data = Puppet::IndirectorTesting.new("test")
request = a_request_that_submits(data,
:content_type_header => "application/x-raw",
:body => '')
handler.call(request, response)
# PUP-3272 this test fails when yaml is removed and pson is used. Instead of returning an
# empty string, the a string '""' is returned - Don't know what the expecation is, if this is
# corrent or not.
# (helindbe)
#
- Puppet::IndirectorTesting.indirection.find("test").name.should == ''
+ expect(Puppet::IndirectorTesting.indirection.find("test").name).to eq('')
end
it "saves the data sent in the request" do
data = Puppet::IndirectorTesting.new("my data")
request = a_request_that_submits(data)
handler.call(request, response)
saved = Puppet::IndirectorTesting.indirection.find("my data")
expect(saved.name).to eq(data.name)
end
it "responds with pson when no Accept header is given" do
data = Puppet::IndirectorTesting.new("my data")
request = a_request_that_submits(data, :accept_header => nil)
handler.call(request, response)
expect(response.body).to eq(data.render(:pson))
expect(response.type).to eq(Puppet::Network::FormatHandler.format(:pson))
end
it "uses the first supported format for the response" do
data = Puppet::IndirectorTesting.new("my data")
request = a_request_that_submits(data, :accept_header => "unknown, text/pson")
handler.call(request, response)
expect(response.body).to eq(data.render(:pson))
expect(response.type).to eq(Puppet::Network::FormatHandler.format(:pson))
end
it "raises an error and does not save when no accepted formats are known" do
data = Puppet::IndirectorTesting.new("my data")
request = a_request_that_submits(data, :accept_header => "unknown, also/unknown")
handler.call(request, response)
expect(Puppet::IndirectorTesting.indirection.find("my data")).to be_nil
expect(response.code).to eq(not_acceptable_code)
end
end
describe "when performing head operation" do
it "should not generate a response when a model head call succeeds" do
data = Puppet::IndirectorTesting.new("my data")
indirection.save(data, "my data")
request = a_request_that_heads(data)
handler.call(request, response)
expect(response.code).to eq(nil)
end
it "should return a not_found_code when the model head call returns false" do
data = Puppet::IndirectorTesting.new("my data")
request = a_request_that_heads(data)
handler.call(request, response)
expect(response.code).to eq(not_found_code)
expect(response.type).to eq("text/plain")
expect(response.body).to eq("Not Found: Could not find indirector_testing my data")
end
end
end
diff --git a/spec/unit/network/http/compression_spec.rb b/spec/unit/network/http/compression_spec.rb
index c6ae09c71..436707fa7 100755
--- a/spec/unit/network/http/compression_spec.rb
+++ b/spec/unit/network/http/compression_spec.rb
@@ -1,190 +1,190 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "http compression" do
describe "when zlib is not available" do
before(:each) do
Puppet.features.stubs(:zlib?).returns false
require 'puppet/network/http/compression'
class HttpUncompressor
include Puppet::Network::HTTP::Compression::None
end
@uncompressor = HttpUncompressor.new
end
it "should have a module function that returns the None underlying module" do
- Puppet::Network::HTTP::Compression.module.should == Puppet::Network::HTTP::Compression::None
+ expect(Puppet::Network::HTTP::Compression.module).to eq(Puppet::Network::HTTP::Compression::None)
end
it "should not add any Accept-Encoding header" do
- @uncompressor.add_accept_encoding({}).should == {}
+ expect(@uncompressor.add_accept_encoding({})).to eq({})
end
it "should not tamper the body" do
response = stub 'response', :body => "data"
- @uncompressor.uncompress_body(response).should == "data"
+ expect(@uncompressor.uncompress_body(response)).to eq("data")
end
it "should yield an identity uncompressor" do
response = stub 'response'
@uncompressor.uncompress(response) { |u|
- u.should be_instance_of(Puppet::Network::HTTP::Compression::IdentityAdapter)
+ expect(u).to be_instance_of(Puppet::Network::HTTP::Compression::IdentityAdapter)
}
end
end
describe "when zlib is available" do
before(:each) do
Puppet.features.stubs(:zlib?).returns true
require 'puppet/network/http/compression'
class HttpUncompressor
include Puppet::Network::HTTP::Compression::Active
end
@uncompressor = HttpUncompressor.new
end
it "should have a module function that returns the Active underlying module" do
- Puppet::Network::HTTP::Compression.module.should == Puppet::Network::HTTP::Compression::Active
+ expect(Puppet::Network::HTTP::Compression.module).to eq(Puppet::Network::HTTP::Compression::Active)
end
it "should add an Accept-Encoding header supporting compression" do
headers = @uncompressor.add_accept_encoding({})
- headers.should have_key('accept-encoding')
- headers['accept-encoding'].should =~ /gzip/
- headers['accept-encoding'].should =~ /deflate/
- headers['accept-encoding'].should =~ /identity/
+ expect(headers).to have_key('accept-encoding')
+ expect(headers['accept-encoding']).to match(/gzip/)
+ expect(headers['accept-encoding']).to match(/deflate/)
+ expect(headers['accept-encoding']).to match(/identity/)
end
describe "when uncompressing response body" do
before do
@response = stub 'response'
@response.stubs(:[]).with('content-encoding')
@response.stubs(:body).returns("mydata")
end
it "should return untransformed response body with no content-encoding" do
- @uncompressor.uncompress_body(@response).should == "mydata"
+ expect(@uncompressor.uncompress_body(@response)).to eq("mydata")
end
it "should return untransformed response body with 'identity' content-encoding" do
@response.stubs(:[]).with('content-encoding').returns('identity')
- @uncompressor.uncompress_body(@response).should == "mydata"
+ expect(@uncompressor.uncompress_body(@response)).to eq("mydata")
end
it "should use a Zlib inflater with 'deflate' content-encoding" do
@response.stubs(:[]).with('content-encoding').returns('deflate')
inflater = stub 'inflater'
Zlib::Inflate.expects(:new).returns(inflater)
inflater.expects(:inflate).with("mydata").returns "uncompresseddata"
- @uncompressor.uncompress_body(@response).should == "uncompresseddata"
+ expect(@uncompressor.uncompress_body(@response)).to eq("uncompresseddata")
end
it "should use a GzipReader with 'gzip' content-encoding" do
@response.stubs(:[]).with('content-encoding').returns('gzip')
io = stub 'io'
StringIO.expects(:new).with("mydata").returns io
reader = stub 'gzip reader'
Zlib::GzipReader.expects(:new).with(io).returns(reader)
reader.expects(:read).returns "uncompresseddata"
- @uncompressor.uncompress_body(@response).should == "uncompresseddata"
+ expect(@uncompressor.uncompress_body(@response)).to eq("uncompresseddata")
end
end
describe "when uncompressing by chunk" do
before do
@response = stub 'response'
@response.stubs(:[]).with('content-encoding')
@inflater = stub_everything 'inflater'
Zlib::Inflate.stubs(:new).returns(@inflater)
end
it "should yield an identity uncompressor with no content-encoding" do
@uncompressor.uncompress(@response) { |u|
- u.should be_instance_of(Puppet::Network::HTTP::Compression::IdentityAdapter)
+ expect(u).to be_instance_of(Puppet::Network::HTTP::Compression::IdentityAdapter)
}
end
it "should yield an identity uncompressor with 'identity' content-encoding" do
@response.stubs(:[]).with('content-encoding').returns 'identity'
@uncompressor.uncompress(@response) { |u|
- u.should be_instance_of(Puppet::Network::HTTP::Compression::IdentityAdapter)
+ expect(u).to be_instance_of(Puppet::Network::HTTP::Compression::IdentityAdapter)
}
end
%w{gzip deflate}.each do |c|
it "should yield a Zlib uncompressor with '#{c}' content-encoding" do
@response.stubs(:[]).with('content-encoding').returns c
@uncompressor.uncompress(@response) { |u|
- u.should be_instance_of(Puppet::Network::HTTP::Compression::Active::ZlibAdapter)
+ expect(u).to be_instance_of(Puppet::Network::HTTP::Compression::Active::ZlibAdapter)
}
end
end
it "should close the underlying adapter" do
adapter = stub_everything 'adapter'
Puppet::Network::HTTP::Compression::IdentityAdapter.expects(:new).returns(adapter)
adapter.expects(:close)
@uncompressor.uncompress(@response) { |u| }
end
end
describe "zlib adapter" do
before do
@inflater = stub_everything 'inflater'
Zlib::Inflate.stubs(:new).returns(@inflater)
@adapter = Puppet::Network::HTTP::Compression::Active::ZlibAdapter.new
end
it "should initialize the underlying inflater with gzip/zlib header parsing" do
Zlib::Inflate.expects(:new).with(15+32)
Puppet::Network::HTTP::Compression::Active::ZlibAdapter.new
end
it "should inflate the given chunk" do
@inflater.expects(:inflate).with("chunk")
@adapter.uncompress("chunk")
end
it "should return the inflated chunk" do
@inflater.stubs(:inflate).with("chunk").returns("uncompressed")
- @adapter.uncompress("chunk").should == "uncompressed"
+ expect(@adapter.uncompress("chunk")).to eq("uncompressed")
end
it "should try a 'regular' inflater on Zlib::DataError" do
@inflater.expects(:inflate).raises(Zlib::DataError.new("not a zlib stream"))
inflater = stub_everything 'inflater2'
inflater.expects(:inflate).with("chunk").returns("uncompressed")
Zlib::Inflate.expects(:new).with.returns(inflater)
@adapter.uncompress("chunk")
end
it "should raise the error the second time" do
@inflater.stubs(:inflate).raises(Zlib::DataError.new("not a zlib stream"))
Zlib::Inflate.expects(:new).with.returns(@inflater)
- lambda { @adapter.uncompress("chunk") }.should raise_error
+ expect { @adapter.uncompress("chunk") }.to raise_error
end
it "should finish the stream on close" do
@inflater.expects(:finish)
@adapter.close
end
it "should close the stream on close" do
@inflater.expects(:close)
@adapter.close
end
end
end
end
diff --git a/spec/unit/network/http/connection_spec.rb b/spec/unit/network/http/connection_spec.rb
index 79956d7e7..93cb592ba 100755
--- a/spec/unit/network/http/connection_spec.rb
+++ b/spec/unit/network/http/connection_spec.rb
@@ -1,303 +1,303 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/http/connection'
describe Puppet::Network::HTTP::Connection do
let (:host) { "me" }
let (:port) { 54321 }
subject { Puppet::Network::HTTP::Connection.new(host, port, :verify => Puppet::SSL::Validator.no_validator) }
let (:httpok) { Net::HTTPOK.new('1.1', 200, '') }
context "when providing HTTP connections" do
context "when initializing http instances" do
it "should return an http instance created with the passed host and port" do
conn = Puppet::Network::HTTP::Connection.new(host, port, :verify => Puppet::SSL::Validator.no_validator)
expect(conn.address).to eq(host)
expect(conn.port).to eq(port)
end
it "should enable ssl on the http instance by default" do
conn = Puppet::Network::HTTP::Connection.new(host, port, :verify => Puppet::SSL::Validator.no_validator)
expect(conn).to be_use_ssl
end
it "can disable ssl using an option" do
conn = Puppet::Network::HTTP::Connection.new(host, port, :use_ssl => false, :verify => Puppet::SSL::Validator.no_validator)
expect(conn).to_not be_use_ssl
end
it "can enable ssl using an option" do
conn = Puppet::Network::HTTP::Connection.new(host, port, :use_ssl => true, :verify => Puppet::SSL::Validator.no_validator)
expect(conn).to be_use_ssl
end
it "should raise Puppet::Error when invalid options are specified" do
expect { Puppet::Network::HTTP::Connection.new(host, port, :invalid_option => nil) }.to raise_error(Puppet::Error, 'Unrecognized option(s): :invalid_option')
end
end
end
context "when methods that accept a block are called with a block" do
let (:host) { "my_server" }
let (:port) { 8140 }
let (:subject) { Puppet::Network::HTTP::Connection.new(host, port, :use_ssl => false, :verify => Puppet::SSL::Validator.no_validator) }
before :each do
httpok.stubs(:body).returns ""
# This stubbing relies a bit more on knowledge of the internals of Net::HTTP
# than I would prefer, but it works on ruby 1.8.7 and 1.9.3, and it seems
# valuable enough to have tests for blocks that this is probably warranted.
socket = stub_everything("socket")
TCPSocket.stubs(:open).returns(socket)
Net::HTTP::Post.any_instance.stubs(:exec).returns("")
Net::HTTP::Head.any_instance.stubs(:exec).returns("")
Net::HTTP::Get.any_instance.stubs(:exec).returns("")
Net::HTTPResponse.stubs(:read_new).returns(httpok)
end
[:request_get, :request_head, :request_post].each do |method|
context "##{method}" do
it "should yield to the block" do
block_executed = false
subject.send(method, "/foo", {}) do |response|
block_executed = true
end
- block_executed.should == true
+ expect(block_executed).to eq(true)
end
end
end
end
class ConstantErrorValidator
def initialize(args)
@fails_with = args[:fails_with]
@error_string = args[:error_string] || ""
@peer_certs = args[:peer_certs] || []
end
def setup_connection(connection)
connection.stubs(:start).raises(OpenSSL::SSL::SSLError.new(@fails_with))
end
def peer_certs
@peer_certs
end
def verify_errors
[@error_string]
end
end
class NoProblemsValidator
def initialize(cert)
@cert = cert
end
def setup_connection(connection)
end
def peer_certs
[@cert]
end
def verify_errors
[]
end
end
shared_examples_for 'ssl verifier' do
include PuppetSpec::Files
let (:host) { "my_server" }
let (:port) { 8140 }
it "should provide a useful error message when one is available and certificate validation fails", :unless => Puppet.features.microsoft_windows? do
connection = Puppet::Network::HTTP::Connection.new(
host, port,
:verify => ConstantErrorValidator.new(:fails_with => 'certificate verify failed',
:error_string => 'shady looking signature'))
expect do
connection.get('request')
end.to raise_error(Puppet::Error, "certificate verify failed: [shady looking signature]")
end
it "should provide a helpful error message when hostname was not match with server certificate", :unless => Puppet.features.microsoft_windows? do
Puppet[:confdir] = tmpdir('conf')
connection = Puppet::Network::HTTP::Connection.new(
host, port,
:verify => ConstantErrorValidator.new(
:fails_with => 'hostname was not match with server certificate',
:peer_certs => [Puppet::SSL::CertificateAuthority.new.generate(
'not_my_server', :dns_alt_names => 'foo,bar,baz')]))
expect do
connection.get('request')
end.to raise_error(Puppet::Error) do |error|
error.message =~ /Server hostname 'my_server' did not match server certificate; expected one of (.+)/
- $1.split(', ').should =~ %w[DNS:foo DNS:bar DNS:baz DNS:not_my_server not_my_server]
+ expect($1.split(', ')).to match_array(%w[DNS:foo DNS:bar DNS:baz DNS:not_my_server not_my_server])
end
end
it "should pass along the error message otherwise" do
connection = Puppet::Network::HTTP::Connection.new(
host, port,
:verify => ConstantErrorValidator.new(:fails_with => 'some other message'))
expect do
connection.get('request')
end.to raise_error(/some other message/)
end
it "should check all peer certificates for upcoming expiration", :unless => Puppet.features.microsoft_windows? do
Puppet[:confdir] = tmpdir('conf')
cert = Puppet::SSL::CertificateAuthority.new.generate(
'server', :dns_alt_names => 'foo,bar,baz')
connection = Puppet::Network::HTTP::Connection.new(
host, port,
:verify => NoProblemsValidator.new(cert))
Net::HTTP.any_instance.stubs(:start)
Net::HTTP.any_instance.stubs(:request).returns(httpok)
connection.get('request')
end
end
context "when using single use HTTPS connections" do
it_behaves_like 'ssl verifier' do
end
end
context "when using persistent HTTPS connections" do
around :each do |example|
pool = Puppet::Network::HTTP::Pool.new
Puppet.override(:http_pool => pool) do
example.run
end
pool.close
end
it_behaves_like 'ssl verifier' do
end
end
context "when response is a redirect" do
let (:site) { Puppet::Network::HTTP::Site.new('http', 'my_server', 8140) }
let (:other_site) { Puppet::Network::HTTP::Site.new('http', 'redirected', 9292) }
let (:other_path) { "other-path" }
let (:verify) { Puppet::SSL::Validator.no_validator }
let (:subject) { Puppet::Network::HTTP::Connection.new(site.host, site.port, :use_ssl => false, :verify => verify) }
let (:httpredirection) do
response = Net::HTTPFound.new('1.1', 302, 'Moved Temporarily')
response['location'] = "#{other_site.addr}/#{other_path}"
response.stubs(:read_body).returns("This resource has moved")
response
end
def create_connection(site, options)
options[:use_ssl] = site.use_ssl?
Puppet::Network::HTTP::Connection.new(site.host, site.port, options)
end
it "should redirect to the final resource location" do
http = stub('http')
http.stubs(:request).returns(httpredirection).then.returns(httpok)
seq = sequence('redirection')
pool = Puppet.lookup(:http_pool)
pool.expects(:with_connection).with(site, anything).yields(http).in_sequence(seq)
pool.expects(:with_connection).with(other_site, anything).yields(http).in_sequence(seq)
conn = create_connection(site, :verify => verify)
conn.get('/foo')
end
def expects_redirection(conn, &block)
http = stub('http')
http.stubs(:request).returns(httpredirection)
pool = Puppet.lookup(:http_pool)
pool.expects(:with_connection).with(site, anything).yields(http)
pool
end
def expects_limit_exceeded(conn)
expect {
conn.get('/')
}.to raise_error(Puppet::Network::HTTP::RedirectionLimitExceededException)
end
it "should not redirect when the limit is 0" do
conn = create_connection(site, :verify => verify, :redirect_limit => 0)
pool = expects_redirection(conn)
pool.expects(:with_connection).with(other_site, anything).never
expects_limit_exceeded(conn)
end
it "should redirect only once" do
conn = create_connection(site, :verify => verify, :redirect_limit => 1)
pool = expects_redirection(conn)
pool.expects(:with_connection).with(other_site, anything).once
expects_limit_exceeded(conn)
end
it "should raise an exception when the redirect limit is exceeded" do
conn = create_connection(site, :verify => verify, :redirect_limit => 3)
pool = expects_redirection(conn)
pool.expects(:with_connection).with(other_site, anything).times(3)
expects_limit_exceeded(conn)
end
end
it "allows setting basic auth on get requests" do
expect_request_with_basic_auth
subject.get('/path', nil, :basic_auth => { :user => 'user', :password => 'password' })
end
it "allows setting basic auth on post requests" do
expect_request_with_basic_auth
subject.post('/path', 'data', nil, :basic_auth => { :user => 'user', :password => 'password' })
end
it "allows setting basic auth on head requests" do
expect_request_with_basic_auth
subject.head('/path', nil, :basic_auth => { :user => 'user', :password => 'password' })
end
it "allows setting basic auth on delete requests" do
expect_request_with_basic_auth
subject.delete('/path', nil, :basic_auth => { :user => 'user', :password => 'password' })
end
it "allows setting basic auth on put requests" do
expect_request_with_basic_auth
subject.put('/path', 'data', nil, :basic_auth => { :user => 'user', :password => 'password' })
end
def expect_request_with_basic_auth
Net::HTTP.any_instance.expects(:request).with do |request|
expect(request['authorization']).to match(/^Basic/)
end.returns(httpok)
end
end
diff --git a/spec/unit/network/http/factory_spec.rb b/spec/unit/network/http/factory_spec.rb
index 58ab56fbd..d9dbbd38a 100755
--- a/spec/unit/network/http/factory_spec.rb
+++ b/spec/unit/network/http/factory_spec.rb
@@ -1,80 +1,80 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/http'
describe Puppet::Network::HTTP::Factory do
before :each do
Puppet::SSL::Key.indirection.terminus_class = :memory
Puppet::SSL::CertificateRequest.indirection.terminus_class = :memory
end
let(:site) { Puppet::Network::HTTP::Site.new('https', 'www.example.com', 443) }
def create_connection(site)
factory = Puppet::Network::HTTP::Factory.new
factory.create_connection(site)
end
it 'creates a connection for the site' do
conn = create_connection(site)
- expect(conn.use_ssl?).to be_true
+ expect(conn.use_ssl?).to be_truthy
expect(conn.address).to eq(site.host)
expect(conn.port).to eq(site.port)
end
it 'creates a connection that has not yet been started' do
conn = create_connection(site)
expect(conn).to_not be_started
end
it 'creates a connection supporting at least HTTP 1.1' do
conn = create_connection(site)
- expect(any_of(conn.class.version_1_1?, conn.class.version_1_1?)).to be_true
+ expect(any_of(conn.class.version_1_1?, conn.class.version_1_1?)).to be_truthy
end
context "proxy settings" do
let(:proxy_host) { 'myhost' }
let(:proxy_port) { 432 }
it "should not set a proxy if the value is 'none'" do
Puppet[:http_proxy_host] = 'none'
conn = create_connection(site)
expect(conn.proxy_address).to be_nil
end
it 'sets proxy_address' do
Puppet[:http_proxy_host] = proxy_host
conn = create_connection(site)
expect(conn.proxy_address).to eq(proxy_host)
end
it 'sets proxy address and port' do
Puppet[:http_proxy_host] = proxy_host
Puppet[:http_proxy_port] = proxy_port
conn = create_connection(site)
expect(conn.proxy_port).to eq(proxy_port)
end
context 'socket timeouts' do
it 'sets open timeout' do
Puppet[:http_connect_timeout] = "10s"
conn = create_connection(site)
expect(conn.open_timeout).to eq(10)
end
it 'sets read timeout' do
Puppet[:http_read_timeout] = "2m"
conn = create_connection(site)
expect(conn.read_timeout).to eq(120)
end
end
end
end
diff --git a/spec/unit/network/http/handler_spec.rb b/spec/unit/network/http/handler_spec.rb
index 17c9e8958..29f7c0818 100755
--- a/spec/unit/network/http/handler_spec.rb
+++ b/spec/unit/network/http/handler_spec.rb
@@ -1,179 +1,179 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/handler'
require 'puppet/indirector_testing'
require 'puppet/network/authorization'
require 'puppet/network/http'
describe Puppet::Network::HTTP::Handler do
before :each do
Puppet::IndirectorTesting.indirection.terminus_class = :memory
end
let(:indirection) { Puppet::IndirectorTesting.indirection }
def a_request(method = "HEAD", path = "/production/#{indirection.name}/unknown")
{
:accept_header => "pson",
:content_type_header => "text/pson",
:method => method,
:path => path,
:params => {},
:client_cert => nil,
:headers => {},
:body => nil
}
end
let(:handler) { PuppetSpec::Handler.new() }
describe "the HTTP Handler" do
def respond(text)
lambda { |req, res| res.respond_with(200, "text/plain", text) }
end
it "hands the request to the first route that matches the request path" do
handler = PuppetSpec::Handler.new(
Puppet::Network::HTTP::Route.path(%r{^/foo}).get(respond("skipped")),
Puppet::Network::HTTP::Route.path(%r{^/vtest}).get(respond("used")),
Puppet::Network::HTTP::Route.path(%r{^/vtest/foo}).get(respond("ignored")))
req = a_request("GET", "/vtest/foo")
res = {}
handler.process(req, res)
expect(res[:body]).to eq("used")
end
it "raises an error if multiple routes with the same path regex are registered" do
expect do
handler = PuppetSpec::Handler.new(
Puppet::Network::HTTP::Route.path(%r{^/foo}).get(respond("ignored")),
Puppet::Network::HTTP::Route.path(%r{^/foo}).post(respond("also ignored")))
end.to raise_error(ArgumentError)
end
it "raises an HTTP not found error if no routes match" do
handler = PuppetSpec::Handler.new
req = a_request("GET", "/vtest/foo")
res = {}
handler.process(req, res)
res_body = JSON(res[:body])
expect(res[:content_type_header]).to eq("application/json")
expect(res_body["issue_kind"]).to eq("HANDLER_NOT_FOUND")
expect(res_body["message"]).to eq("Not Found: No route for GET /vtest/foo")
expect(res[:status]).to eq(404)
end
it "returns a structured error response with a stacktrace when the server encounters an internal error" do
handler = PuppetSpec::Handler.new(
Puppet::Network::HTTP::Route.path(/.*/).get(lambda { |_, _| raise StandardError.new("the sky is falling!")}))
req = a_request("GET", "/vtest/foo")
res = {}
handler.process(req, res)
res_body = JSON(res[:body])
expect(res[:content_type_header]).to eq("application/json")
expect(res_body["issue_kind"]).to eq(Puppet::Network::HTTP::Issues::RUNTIME_ERROR.to_s)
expect(res_body["message"]).to eq("Server Error: the sky is falling!")
- expect(res_body["stacktrace"].is_a?(Array) && !res_body["stacktrace"].empty?).to be_true
+ expect(res_body["stacktrace"].is_a?(Array) && !res_body["stacktrace"].empty?).to be_truthy
expect(res_body["stacktrace"][0]).to match("spec/unit/network/http/handler_spec.rb")
expect(res[:status]).to eq(500)
end
end
describe "when processing a request" do
let(:response) do
{ :status => 200 }
end
before do
handler.stubs(:check_authorization)
handler.stubs(:warn_if_near_expiration)
end
it "should setup a profiler when the puppet-profiling header exists" do
request = a_request
request[:headers][Puppet::Network::HTTP::HEADER_ENABLE_PROFILING.downcase] = "true"
p = PuppetSpec::HandlerProfiler.new
Puppet::Util::Profiler.expects(:add_profiler).with { |profiler|
profiler.is_a? Puppet::Util::Profiler::WallClock
}.returns(p)
Puppet::Util::Profiler.expects(:remove_profiler).with { |profiler|
profiler == p
}
handler.process(request, response)
end
it "should not setup profiler when the profile parameter is missing" do
request = a_request
request[:params] = { }
Puppet::Util::Profiler.expects(:add_profiler).never
handler.process(request, response)
end
it "should raise an error if the request is formatted in an unknown format" do
handler.stubs(:content_type_header).returns "unknown format"
- lambda { handler.request_format(request) }.should raise_error
+ expect { handler.request_format(request) }.to raise_error
end
it "should still find the correct format if content type contains charset information" do
request = Puppet::Network::HTTP::Request.new({ 'content-type' => "text/plain; charset=UTF-8" },
{}, 'GET', '/', nil)
- request.format.should == "s"
+ expect(request.format).to eq("s")
end
# PUP-3272
# This used to be for YAML, and doing a to_yaml on an array.
# The result with to_pson is something different, the result is a string
# Which seems correct. Looks like this was some kind of nesting option "yaml inside yaml" ?
# Removing the test
# it "should deserialize PSON parameters" do
# params = {'my_param' => [1,2,3].to_pson}
#
# decoded_params = handler.send(:decode_params, params)
#
# decoded_params.should == {:my_param => [1,2,3]}
# end
end
describe "when resolving node" do
it "should use a look-up from the ip address" do
Resolv.expects(:getname).with("1.2.3.4").returns("host.domain.com")
handler.resolve_node(:ip => "1.2.3.4")
end
it "should return the look-up result" do
Resolv.stubs(:getname).with("1.2.3.4").returns("host.domain.com")
- handler.resolve_node(:ip => "1.2.3.4").should == "host.domain.com"
+ expect(handler.resolve_node(:ip => "1.2.3.4")).to eq("host.domain.com")
end
it "should return the ip address if resolving fails" do
Resolv.stubs(:getname).with("1.2.3.4").raises(RuntimeError, "no such host")
- handler.resolve_node(:ip => "1.2.3.4").should == "1.2.3.4"
+ expect(handler.resolve_node(:ip => "1.2.3.4")).to eq("1.2.3.4")
end
end
end
diff --git a/spec/unit/network/http/rack/rest_spec.rb b/spec/unit/network/http/rack/rest_spec.rb
index f4125f170..d0306e0e4 100755
--- a/spec/unit/network/http/rack/rest_spec.rb
+++ b/spec/unit/network/http/rack/rest_spec.rb
@@ -1,318 +1,318 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/http/rack' if Puppet.features.rack?
require 'puppet/network/http/rack/rest'
describe "Puppet::Network::HTTP::RackREST", :if => Puppet.features.rack? do
it "should include the Puppet::Network::HTTP::Handler module" do
- Puppet::Network::HTTP::RackREST.ancestors.should be_include(Puppet::Network::HTTP::Handler)
+ expect(Puppet::Network::HTTP::RackREST.ancestors).to be_include(Puppet::Network::HTTP::Handler)
end
describe "when serving a request" do
before :all do
@model_class = stub('indirected model class')
Puppet::Indirector::Indirection.stubs(:model).with(:foo).returns(@model_class)
end
before :each do
@response = Rack::Response.new
@handler = Puppet::Network::HTTP::RackREST.new(:handler => :foo)
end
def mk_req(uri, opts = {})
env = Rack::MockRequest.env_for(uri, opts)
Rack::Request.new(env)
end
let(:minimal_certificate) do
key = OpenSSL::PKey::RSA.new(512)
signer = Puppet::SSL::CertificateSigner.new
cert = OpenSSL::X509::Certificate.new
cert.version = 2
cert.serial = 0
cert.not_before = Time.now
cert.not_after = Time.now + 3600
cert.public_key = key
cert.subject = OpenSSL::X509::Name.parse("/CN=testing")
signer.sign(cert, key)
cert
end
describe "#headers" do
it "should return the headers (parsed from env with prefix 'HTTP_')" do
req = mk_req('/', {'HTTP_Accept' => 'myaccept',
'HTTP_X_Custom_Header' => 'mycustom',
'NOT_HTTP_foo' => 'not an http header'})
- @handler.headers(req).should == {"accept" => 'myaccept',
+ expect(@handler.headers(req)).to eq({"accept" => 'myaccept',
"x-custom-header" => 'mycustom',
- "content-type" => nil }
+ "content-type" => nil })
end
end
describe "and using the HTTP Handler interface" do
it "should return the CONTENT_TYPE parameter as the content type header" do
req = mk_req('/', 'CONTENT_TYPE' => 'mycontent')
- @handler.headers(req)['content-type'].should == "mycontent"
+ expect(@handler.headers(req)['content-type']).to eq("mycontent")
end
it "should use the REQUEST_METHOD as the http method" do
req = mk_req('/', :method => 'MYMETHOD')
- @handler.http_method(req).should == "MYMETHOD"
+ expect(@handler.http_method(req)).to eq("MYMETHOD")
end
it "should return the request path as the path" do
req = mk_req('/foo/bar')
- @handler.path(req).should == "/foo/bar"
+ expect(@handler.path(req)).to eq("/foo/bar")
end
it "should return the request body as the body" do
req = mk_req('/foo/bar', :input => 'mybody')
- @handler.body(req).should == "mybody"
+ expect(@handler.body(req)).to eq("mybody")
end
it "should return the an Puppet::SSL::Certificate instance as the client_cert" do
req = mk_req('/foo/bar', 'SSL_CLIENT_CERT' => minimal_certificate.to_pem)
expect(@handler.client_cert(req).content.to_pem).to eq(minimal_certificate.to_pem)
end
it "returns nil when SSL_CLIENT_CERT is empty" do
req = mk_req('/foo/bar', 'SSL_CLIENT_CERT' => '')
- @handler.client_cert(req).should be_nil
+ expect(@handler.client_cert(req)).to be_nil
end
it "should set the response's content-type header when setting the content type" do
@header = mock 'header'
@response.expects(:header).returns @header
@header.expects(:[]=).with('Content-Type', "mytype")
@handler.set_content_type(@response, "mytype")
end
it "should set the status and write the body when setting the response for a request" do
@response.expects(:status=).with(400)
@response.expects(:write).with("mybody")
@handler.set_response(@response, "mybody", 400)
end
describe "when result is a File" do
before :each do
stat = stub 'stat', :size => 100
@file = stub 'file', :stat => stat, :path => "/tmp/path"
@file.stubs(:is_a?).with(File).returns(true)
end
it "should set the Content-Length header as a string" do
@response.expects(:[]=).with("Content-Length", '100')
@handler.set_response(@response, @file, 200)
end
it "should return a RackFile adapter as body" do
@response.expects(:body=).with { |val| val.is_a?(Puppet::Network::HTTP::RackREST::RackFile) }
@handler.set_response(@response, @file, 200)
end
end
it "should ensure the body has been read on success" do
req = mk_req('/production/report/foo', :method => 'PUT')
req.body.expects(:read).at_least_once
Puppet::Transaction::Report.stubs(:save)
@handler.process(req, @response)
end
it "should ensure the body has been partially read on failure" do
req = mk_req('/production/report/foo')
req.body.expects(:read).with(1)
@handler.stubs(:headers).raises(StandardError)
@handler.process(req, @response)
end
end
describe "and determining the request parameters" do
it "should include the HTTP request parameters, with the keys as symbols" do
req = mk_req('/?foo=baz&bar=xyzzy')
result = @handler.params(req)
- result[:foo].should == "baz"
- result[:bar].should == "xyzzy"
+ expect(result[:foo]).to eq("baz")
+ expect(result[:bar]).to eq("xyzzy")
end
it "should return multi-values params as an array of the values" do
req = mk_req('/?foo=baz&foo=xyzzy')
result = @handler.params(req)
- result[:foo].should == ["baz", "xyzzy"]
+ expect(result[:foo]).to eq(["baz", "xyzzy"])
end
it "should return parameters from the POST body" do
req = mk_req("/", :method => 'POST', :input => 'foo=baz&bar=xyzzy')
result = @handler.params(req)
- result[:foo].should == "baz"
- result[:bar].should == "xyzzy"
+ expect(result[:foo]).to eq("baz")
+ expect(result[:bar]).to eq("xyzzy")
end
it "should not return multi-valued params in a POST body as an array of values" do
req = mk_req("/", :method => 'POST', :input => 'foo=baz&foo=xyzzy')
result = @handler.params(req)
- result[:foo].should be_one_of("baz", "xyzzy")
+ expect(result[:foo]).to be_one_of("baz", "xyzzy")
end
it "should CGI-decode the HTTP parameters" do
encoding = CGI.escape("foo bar")
req = mk_req("/?foo=#{encoding}")
result = @handler.params(req)
- result[:foo].should == "foo bar"
+ expect(result[:foo]).to eq("foo bar")
end
it "should convert the string 'true' to the boolean" do
req = mk_req("/?foo=true")
result = @handler.params(req)
- result[:foo].should be_true
+ expect(result[:foo]).to be_truthy
end
it "should convert the string 'false' to the boolean" do
req = mk_req("/?foo=false")
result = @handler.params(req)
- result[:foo].should be_false
+ expect(result[:foo]).to be_falsey
end
it "should convert integer arguments to Integers" do
req = mk_req("/?foo=15")
result = @handler.params(req)
- result[:foo].should == 15
+ expect(result[:foo]).to eq(15)
end
it "should convert floating point arguments to Floats" do
req = mk_req("/?foo=1.5")
result = @handler.params(req)
- result[:foo].should == 1.5
+ expect(result[:foo]).to eq(1.5)
end
it "should treat YAML encoded parameters like it was any string" do
escaping = CGI.escape(YAML.dump(%w{one two}))
req = mk_req("/?foo=#{escaping}")
- @handler.params(req)[:foo].should == "---\n- one\n- two\n"
+ expect(@handler.params(req)[:foo]).to eq("---\n- one\n- two\n")
end
it "should not allow the client to set the node via the query string" do
req = mk_req("/?node=foo")
- @handler.params(req)[:node].should be_nil
+ expect(@handler.params(req)[:node]).to be_nil
end
it "should not allow the client to set the IP address via the query string" do
req = mk_req("/?ip=foo")
- @handler.params(req)[:ip].should be_nil
+ expect(@handler.params(req)[:ip]).to be_nil
end
it "should pass the client's ip address to model find" do
req = mk_req("/", 'REMOTE_ADDR' => 'ipaddress')
- @handler.params(req)[:ip].should == "ipaddress"
+ expect(@handler.params(req)[:ip]).to eq("ipaddress")
end
it "should set 'authenticated' to false if no certificate is present" do
req = mk_req('/')
- @handler.params(req)[:authenticated].should be_false
+ expect(@handler.params(req)[:authenticated]).to be_falsey
end
end
describe "with pre-validated certificates" do
it "should retrieve the hostname by finding the CN given in :ssl_client_header, in the format returned by Apache (RFC2253)" do
Puppet[:ssl_client_header] = "myheader"
req = mk_req('/', "myheader" => "O=Foo\\, Inc,CN=host.domain.com")
- @handler.params(req)[:node].should == "host.domain.com"
+ expect(@handler.params(req)[:node]).to eq("host.domain.com")
end
it "should retrieve the hostname by finding the CN given in :ssl_client_header, in the format returned by nginx" do
Puppet[:ssl_client_header] = "myheader"
req = mk_req('/', "myheader" => "/CN=host.domain.com")
- @handler.params(req)[:node].should == "host.domain.com"
+ expect(@handler.params(req)[:node]).to eq("host.domain.com")
end
it "should retrieve the hostname by finding the CN given in :ssl_client_header, ignoring other fields" do
Puppet[:ssl_client_header] = "myheader"
req = mk_req('/', "myheader" => 'ST=Denial,CN=host.domain.com,O=Domain\\, Inc.')
- @handler.params(req)[:node].should == "host.domain.com"
+ expect(@handler.params(req)[:node]).to eq("host.domain.com")
end
it "should use the :ssl_client_header to determine the parameter for checking whether the host certificate is valid" do
Puppet[:ssl_client_header] = "certheader"
Puppet[:ssl_client_verify_header] = "myheader"
req = mk_req('/', "myheader" => "SUCCESS", "certheader" => "CN=host.domain.com")
- @handler.params(req)[:authenticated].should be_true
+ expect(@handler.params(req)[:authenticated]).to be_truthy
end
it "should consider the host unauthenticated if the validity parameter does not contain 'SUCCESS'" do
Puppet[:ssl_client_header] = "certheader"
Puppet[:ssl_client_verify_header] = "myheader"
req = mk_req('/', "myheader" => "whatever", "certheader" => "CN=host.domain.com")
- @handler.params(req)[:authenticated].should be_false
+ expect(@handler.params(req)[:authenticated]).to be_falsey
end
it "should consider the host unauthenticated if no certificate information is present" do
Puppet[:ssl_client_header] = "certheader"
Puppet[:ssl_client_verify_header] = "myheader"
req = mk_req('/', "myheader" => nil, "certheader" => "CN=host.domain.com")
- @handler.params(req)[:authenticated].should be_false
+ expect(@handler.params(req)[:authenticated]).to be_falsey
end
it "should resolve the node name with an ip address look-up if no certificate is present" do
Puppet[:ssl_client_header] = "myheader"
req = mk_req('/', "myheader" => nil)
@handler.expects(:resolve_node).returns("host.domain.com")
- @handler.params(req)[:node].should == "host.domain.com"
+ expect(@handler.params(req)[:node]).to eq("host.domain.com")
end
it "should resolve the node name with an ip address look-up if a certificate without a CN is present" do
Puppet[:ssl_client_header] = "myheader"
req = mk_req('/', "myheader" => "O=no CN")
@handler.expects(:resolve_node).returns("host.domain.com")
- @handler.params(req)[:node].should == "host.domain.com"
+ expect(@handler.params(req)[:node]).to eq("host.domain.com")
end
it "should not allow authentication via the verify header if there is no CN available" do
Puppet[:ssl_client_header] = "dn_header"
Puppet[:ssl_client_verify_header] = "verify_header"
req = mk_req('/', "dn_header" => "O=no CN", "verify_header" => 'SUCCESS')
@handler.expects(:resolve_node).returns("host.domain.com")
- @handler.params(req)[:authenticated].should be_false
+ expect(@handler.params(req)[:authenticated]).to be_falsey
end
end
end
end
describe Puppet::Network::HTTP::RackREST::RackFile do
before(:each) do
stat = stub 'stat', :size => 100
@file = stub 'file', :stat => stat, :path => "/tmp/path"
@rackfile = Puppet::Network::HTTP::RackREST::RackFile.new(@file)
end
it "should have an each method" do
- @rackfile.should be_respond_to(:each)
+ expect(@rackfile).to be_respond_to(:each)
end
it "should yield file chunks by chunks" do
@file.expects(:read).times(3).with(8192).returns("1", "2", nil)
i = 1
@rackfile.each do |chunk|
- chunk.to_i.should == i
+ expect(chunk.to_i).to eq(i)
i += 1
end
end
it "should have a close method" do
- @rackfile.should be_respond_to(:close)
+ expect(@rackfile).to be_respond_to(:close)
end
it "should delegate close to File close" do
@file.expects(:close)
@rackfile.close
end
end
diff --git a/spec/unit/network/http/rack_spec.rb b/spec/unit/network/http/rack_spec.rb
index 7450f3af5..894c75dcf 100755
--- a/spec/unit/network/http/rack_spec.rb
+++ b/spec/unit/network/http/rack_spec.rb
@@ -1,43 +1,43 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/http/rack' if Puppet.features.rack?
describe "Puppet::Network::HTTP::Rack", :if => Puppet.features.rack? do
describe "when called" do
before :all do
@app = Puppet::Network::HTTP::Rack.new()
# let's use Rack::Lint to verify that we're OK with the rack specification
@linted = Rack::Lint.new(@app)
end
before :each do
@env = Rack::MockRequest.env_for('/')
end
it "should create a Request object" do
request = Rack::Request.new(@env)
Rack::Request.expects(:new).returns request
@linted.call(@env)
end
it "should create a Response object" do
Rack::Response.expects(:new).returns stub_everything
@app.call(@env) # can't lint when Rack::Response is a stub
end
it "should let RackREST process the request" do
Puppet::Network::HTTP::RackREST.any_instance.expects(:process).once
@linted.call(@env)
end
it "should catch unhandled exceptions from RackREST" do
Puppet::Network::HTTP::RackREST.any_instance.expects(:process).raises(ArgumentError, 'test error')
- Proc.new { @linted.call(@env) }.should_not raise_error
+ expect { @linted.call(@env) }.not_to raise_error
end
it "should finish() the Response" do
Rack::Response.any_instance.expects(:finish).once
@app.call(@env) # can't lint when finish is a stub
end
end
end
diff --git a/spec/unit/network/http/route_spec.rb b/spec/unit/network/http/route_spec.rb
index 04f8f8388..6f32c9bab 100644
--- a/spec/unit/network/http/route_spec.rb
+++ b/spec/unit/network/http/route_spec.rb
@@ -1,91 +1,91 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector_testing'
require 'puppet/network/http'
describe Puppet::Network::HTTP::Route do
def request(method, path)
Puppet::Network::HTTP::Request.from_hash({
:method => method,
:path => path,
:routing_path => path })
end
def respond(text)
lambda { |req, res| res.respond_with(200, "text/plain", text) }
end
let(:req) { request("GET", "/vtest/foo") }
let(:res) { Puppet::Network::HTTP::MemoryResponse.new }
describe "an HTTP Route" do
it "can match a request" do
route = Puppet::Network::HTTP::Route.path(%r{^/vtest})
- expect(route.matches?(req)).to be_true
+ expect(route.matches?(req)).to be_truthy
end
it "will raise a Method Not Allowed error when no handler for the request's method is given" do
route = Puppet::Network::HTTP::Route.path(%r{^/vtest}).post(respond("ignored"))
expect do
route.process(req, res)
end.to raise_error(Puppet::Network::HTTP::Error::HTTPMethodNotAllowedError)
end
it "can match any HTTP method" do
route = Puppet::Network::HTTP::Route.path(%r{^/vtest/foo}).any(respond("used"))
- expect(route.matches?(req)).to be_true
+ expect(route.matches?(req)).to be_truthy
route.process(req, res)
expect(res.body).to eq("used")
end
it "processes DELETE requests" do
route = Puppet::Network::HTTP::Route.path(%r{^/vtest/foo}).delete(respond("used"))
route.process(request("DELETE", "/vtest/foo"), res)
expect(res.body).to eq("used")
end
it "does something when it doesn't know the verb" do
route = Puppet::Network::HTTP::Route.path(%r{^/vtest/foo})
expect do
route.process(request("UNKNOWN", "/vtest/foo"), res)
end.to raise_error(Puppet::Network::HTTP::Error::HTTPMethodNotAllowedError, /UNKNOWN/)
end
it "calls the method handlers in turn" do
call_count = 0
handler = lambda { |request, response| call_count += 1 }
route = Puppet::Network::HTTP::Route.path(%r{^/vtest/foo}).get(handler, handler)
route.process(req, res)
expect(call_count).to eq(2)
end
it "stops calling handlers if one of them raises an error" do
ignored_called = false
ignored = lambda { |req, res| ignored_called = true }
raise_error = lambda { |req, res| raise Puppet::Network::HTTP::Error::HTTPNotAuthorizedError, "go away" }
route = Puppet::Network::HTTP::Route.path(%r{^/vtest/foo}).get(raise_error, ignored)
expect do
route.process(req, res)
end.to raise_error(Puppet::Network::HTTP::Error::HTTPNotAuthorizedError)
- expect(ignored_called).to be_false
+ expect(ignored_called).to be_falsey
end
it "chains to other routes after calling its handlers" do
inner_route = Puppet::Network::HTTP::Route.path(%r{^/inner}).any(respond("inner"))
unused_inner_route = Puppet::Network::HTTP::Route.path(%r{^/unused_inner}).any(respond("unused"))
top_route = Puppet::Network::HTTP::Route.path(%r{^/vtest}).any(respond("top")).chain(unused_inner_route, inner_route)
top_route.process(request("GET", "/vtest/inner"), res)
expect(res.body).to eq("topinner")
end
end
end
diff --git a/spec/unit/network/http/session_spec.rb b/spec/unit/network/http/session_spec.rb
index 4eba67d7d..3de88fedb 100755
--- a/spec/unit/network/http/session_spec.rb
+++ b/spec/unit/network/http/session_spec.rb
@@ -1,43 +1,43 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/http'
describe Puppet::Network::HTTP::Session do
let(:connection) { stub('connection') }
def create_session(connection, expiration_time = nil)
expiration_time ||= Time.now + 60 * 60
Puppet::Network::HTTP::Session.new(connection, expiration_time)
end
it 'provides access to its connection' do
session = create_session(connection)
- session.connection.should == connection
+ expect(session.connection).to eq(connection)
end
it 'expires a connection whose expiration time is in the past' do
now = Time.now
past = now - 1
session = create_session(connection, past)
- session.expired?(now).should be_true
+ expect(session.expired?(now)).to be_truthy
end
it 'expires a connection whose expiration time is now' do
now = Time.now
session = create_session(connection, now)
- session.expired?(now).should be_true
+ expect(session.expired?(now)).to be_truthy
end
it 'does not expire a connection whose expiration time is in the future' do
now = Time.now
future = now + 1
session = create_session(connection, future)
- session.expired?(now).should be_false
+ expect(session.expired?(now)).to be_falsey
end
end
diff --git a/spec/unit/network/http/site_spec.rb b/spec/unit/network/http/site_spec.rb
index 06fcbf83d..e740b5c9f 100755
--- a/spec/unit/network/http/site_spec.rb
+++ b/spec/unit/network/http/site_spec.rb
@@ -1,90 +1,90 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/http'
describe Puppet::Network::HTTP::Site do
let(:scheme) { 'https' }
let(:host) { 'rubygems.org' }
let(:port) { 443 }
def create_site(scheme, host, port)
Puppet::Network::HTTP::Site.new(scheme, host, port)
end
it 'accepts scheme, host, and port' do
site = create_site(scheme, host, port)
expect(site.scheme).to eq(scheme)
expect(site.host).to eq(host)
expect(site.port).to eq(port)
end
it 'generates an external URI string' do
site = create_site(scheme, host, port)
expect(site.addr).to eq("https://rubygems.org:443")
end
it 'considers sites to be different when the scheme is different' do
https_site = create_site('https', host, port)
http_site = create_site('http', host, port)
expect(https_site).to_not eq(http_site)
end
it 'considers sites to be different when the host is different' do
rubygems_site = create_site(scheme, 'rubygems.org', port)
github_site = create_site(scheme, 'github.com', port)
expect(rubygems_site).to_not eq(github_site)
end
it 'considers sites to be different when the port is different' do
site_443 = create_site(scheme, host, 443)
site_80 = create_site(scheme, host, 80)
expect(site_443).to_not eq(site_80)
end
it 'compares values when determining equality' do
site = create_site(scheme, host, port)
sites = {}
sites[site] = site
another_site = create_site(scheme, host, port)
- expect(sites.include?(another_site)).to be_true
+ expect(sites.include?(another_site)).to be_truthy
end
it 'computes the same hash code for equivalent objects' do
site = create_site(scheme, host, port)
same_site = create_site(scheme, host, port)
expect(site.hash).to eq(same_site.hash)
end
it 'uses ssl with https' do
site = create_site('https', host, port)
expect(site).to be_use_ssl
end
it 'does not use ssl with http' do
site = create_site('http', host, port)
expect(site).to_not be_use_ssl
end
it 'moves to a new URI location' do
site = create_site('http', 'host1', 80)
uri = URI.parse('https://host2:443/some/where/else')
new_site = site.move_to(uri)
expect(new_site.scheme).to eq('https')
expect(new_site.host).to eq('host2')
expect(new_site.port).to eq(443)
end
end
diff --git a/spec/unit/network/http/webrick/rest_spec.rb b/spec/unit/network/http/webrick/rest_spec.rb
index 72e810b01..ba8941a14 100755
--- a/spec/unit/network/http/webrick/rest_spec.rb
+++ b/spec/unit/network/http/webrick/rest_spec.rb
@@ -1,231 +1,231 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/http'
require 'webrick'
require 'puppet/network/http/webrick/rest'
describe Puppet::Network::HTTP::WEBrickREST do
it "should include the Puppet::Network::HTTP::Handler module" do
- Puppet::Network::HTTP::WEBrickREST.ancestors.should be_include(Puppet::Network::HTTP::Handler)
+ expect(Puppet::Network::HTTP::WEBrickREST.ancestors).to be_include(Puppet::Network::HTTP::Handler)
end
describe "when receiving a request" do
before do
@request = stub('webrick http request', :query => {},
:query_string => 'environment=production',
:peeraddr => %w{eh boo host ip},
:request_method => 'GET',
:client_cert => nil)
@response = mock('webrick http response')
@model_class = stub('indirected model class')
@webrick = stub('webrick http server', :mount => true, :[] => {})
Puppet::Indirector::Indirection.stubs(:model).with(:foo).returns(@model_class)
@handler = Puppet::Network::HTTP::WEBrickREST.new(@webrick)
end
it "should delegate its :service method to its :process method" do
@handler.expects(:process).with(@request, @response).returns "stuff"
- @handler.service(@request, @response).should == "stuff"
+ expect(@handler.service(@request, @response)).to eq("stuff")
end
describe "#headers" do
let(:fake_request) { {"Foo" => "bar", "BAZ" => "bam" } }
it "should iterate over the request object using #each" do
fake_request.expects(:each)
@handler.headers(fake_request)
end
it "should return a hash with downcased header names" do
result = @handler.headers(fake_request)
- result.should == fake_request.inject({}) { |m,(k,v)| m[k.downcase] = v; m }
+ expect(result).to eq(fake_request.inject({}) { |m,(k,v)| m[k.downcase] = v; m })
end
end
describe "when using the Handler interface" do
it "should use the request method as the http method" do
@request.expects(:request_method).returns "FOO"
- @handler.http_method(@request).should == "FOO"
+ expect(@handler.http_method(@request)).to eq("FOO")
end
it "should return the request path as the path" do
@request.expects(:path).returns "/foo/bar"
- @handler.path(@request).should == "/foo/bar"
+ expect(@handler.path(@request)).to eq("/foo/bar")
end
it "should return the request body as the body" do
@request.stubs(:request_method).returns "POST"
@request.expects(:body).returns "my body"
- @handler.body(@request).should == "my body"
+ expect(@handler.body(@request)).to eq("my body")
end
it "should set the response's 'content-type' header when setting the content type" do
@response.expects(:[]=).with("content-type", "text/html")
@handler.set_content_type(@response, "text/html")
end
it "should set the status and body on the response when setting the response for a successful query" do
@response.expects(:status=).with 200
@response.expects(:body=).with "mybody"
@handler.set_response(@response, "mybody", 200)
end
it "serves a file" do
stat = stub 'stat', :size => 100
@file = stub 'file', :stat => stat, :path => "/tmp/path"
@file.stubs(:is_a?).with(File).returns(true)
@response.expects(:[]=).with('content-length', 100)
@response.expects(:status=).with 200
@response.expects(:body=).with @file
@handler.set_response(@response, @file, 200)
end
it "should set the status and message on the response when setting the response for a failed query" do
@response.expects(:status=).with 400
@response.expects(:body=).with "mybody"
@handler.set_response(@response, "mybody", 400)
end
end
describe "and determining the request parameters" do
def query_of(options)
request = Puppet::Indirector::Request.new(:myind, :find, "my key", nil, options)
WEBrick::HTTPUtils.parse_query(request.query_string.sub(/^\?/, ''))
end
def a_request_querying(query_data)
@request.expects(:query).returns(query_of(query_data))
@request
end
def certificate_with_subject(subj)
cert = OpenSSL::X509::Certificate.new
cert.subject = OpenSSL::X509::Name.parse(subj)
cert
end
it "has no parameters when there is no query string" do
only_server_side_information = [:authenticated, :ip, :node]
@request.stubs(:query).returns(nil)
result = @handler.params(@request)
- result.keys.sort.should == only_server_side_information
+ expect(result.keys.sort).to eq(only_server_side_information)
end
it "should prefer duplicate params from the body over the query string" do
@request.stubs(:request_method).returns "PUT"
@request.stubs(:query).returns(WEBrick::HTTPUtils.parse_query("foo=bar&environment=posted_env"))
- @handler.params(@request)[:environment].should == "posted_env"
+ expect(@handler.params(@request)[:environment]).to eq("posted_env")
end
it "should include the HTTP request parameters, with the keys as symbols" do
request = a_request_querying("foo" => "baz", "bar" => "xyzzy")
result = @handler.params(request)
- result[:foo].should == "baz"
- result[:bar].should == "xyzzy"
+ expect(result[:foo]).to eq("baz")
+ expect(result[:bar]).to eq("xyzzy")
end
it "should handle parameters with no value" do
request = a_request_querying('foo' => "")
result = @handler.params(request)
- result[:foo].should == ""
+ expect(result[:foo]).to eq("")
end
it "should convert the string 'true' to the boolean" do
request = a_request_querying('foo' => "true")
result = @handler.params(request)
- result[:foo].should == true
+ expect(result[:foo]).to eq(true)
end
it "should convert the string 'false' to the boolean" do
request = a_request_querying('foo' => "false")
result = @handler.params(request)
- result[:foo].should == false
+ expect(result[:foo]).to eq(false)
end
it "should reconstruct arrays" do
request = a_request_querying('foo' => ["a", "b", "c"])
result = @handler.params(request)
- result[:foo].should == ["a", "b", "c"]
+ expect(result[:foo]).to eq(["a", "b", "c"])
end
it "should convert values inside arrays into primitive types" do
request = a_request_querying('foo' => ["true", "false", "1", "1.2"])
result = @handler.params(request)
- result[:foo].should == [true, false, 1, 1.2]
+ expect(result[:foo]).to eq([true, false, 1, 1.2])
end
it "should treat YAML-load values that are YAML-encoded as any other String" do
request = a_request_querying('foo' => YAML.dump(%w{one two}))
- @handler.params(request)[:foo].should == "---\n- one\n- two\n"
+ expect(@handler.params(request)[:foo]).to eq("---\n- one\n- two\n")
end
it "should not allow clients to set the node via the request parameters" do
request = a_request_querying("node" => "foo")
@handler.stubs(:resolve_node)
- @handler.params(request)[:node].should be_nil
+ expect(@handler.params(request)[:node]).to be_nil
end
it "should not allow clients to set the IP via the request parameters" do
request = a_request_querying("ip" => "foo")
- @handler.params(request)[:ip].should_not == "foo"
+ expect(@handler.params(request)[:ip]).not_to eq("foo")
end
it "should pass the client's ip address to model find" do
@request.stubs(:peeraddr).returns(%w{noidea dunno hostname ipaddress})
- @handler.params(@request)[:ip].should == "ipaddress"
+ expect(@handler.params(@request)[:ip]).to eq("ipaddress")
end
it "should set 'authenticated' to true if a certificate is present" do
cert = stub 'cert', :subject => [%w{CN host.domain.com}]
@request.stubs(:client_cert).returns cert
- @handler.params(@request)[:authenticated].should be_true
+ expect(@handler.params(@request)[:authenticated]).to be_truthy
end
it "should set 'authenticated' to false if no certificate is present" do
@request.stubs(:client_cert).returns nil
- @handler.params(@request)[:authenticated].should be_false
+ expect(@handler.params(@request)[:authenticated]).to be_falsey
end
it "should pass the client's certificate name to model method if a certificate is present" do
@request.stubs(:client_cert).returns(certificate_with_subject("/CN=host.domain.com"))
- @handler.params(@request)[:node].should == "host.domain.com"
+ expect(@handler.params(@request)[:node]).to eq("host.domain.com")
end
it "should resolve the node name with an ip address look-up if no certificate is present" do
@request.stubs(:client_cert).returns nil
@handler.expects(:resolve_node).returns(:resolved_node)
- @handler.params(@request)[:node].should == :resolved_node
+ expect(@handler.params(@request)[:node]).to eq(:resolved_node)
end
it "should resolve the node name with an ip address look-up if CN parsing fails" do
@request.stubs(:client_cert).returns(certificate_with_subject("/C=company"))
@handler.expects(:resolve_node).returns(:resolved_node)
- @handler.params(@request)[:node].should == :resolved_node
+ expect(@handler.params(@request)[:node]).to eq(:resolved_node)
end
end
end
end
diff --git a/spec/unit/network/http/webrick_spec.rb b/spec/unit/network/http/webrick_spec.rb
index 15821fb93..150c2f3a0 100755
--- a/spec/unit/network/http/webrick_spec.rb
+++ b/spec/unit/network/http/webrick_spec.rb
@@ -1,279 +1,279 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/http'
require 'puppet/network/http/webrick'
describe Puppet::Network::HTTP::WEBrick, "after initializing" do
it "should not be listening" do
- Puppet::Network::HTTP::WEBrick.new.should_not be_listening
+ expect(Puppet::Network::HTTP::WEBrick.new).not_to be_listening
end
end
describe Puppet::Network::HTTP::WEBrick do
include PuppetSpec::Files
let(:address) { '127.0.0.1' }
let(:port) { 31337 }
let(:server) do
s = Puppet::Network::HTTP::WEBrick.new
s.stubs(:setup_logger).returns(Hash.new)
s.stubs(:setup_ssl).returns(Hash.new)
s
end
let(:mock_ssl_context) do
stub('ssl_context', :ciphers= => nil)
end
let(:mock_webrick) do
stub('webrick',
:[] => {},
:listeners => [],
:status => :Running,
:mount => nil,
:start => nil,
:shutdown => nil,
:ssl_context => mock_ssl_context)
end
before :each do
WEBrick::HTTPServer.stubs(:new).returns(mock_webrick)
end
describe "when turning on listening" do
it "should fail if already listening" do
server.listen(address, port)
expect { server.listen(address, port) }.to raise_error(RuntimeError, /server is already listening/)
end
it "should tell webrick to listen on the specified address and port" do
WEBrick::HTTPServer.expects(:new).with(
has_entries(:Port => 31337, :BindAddress => "127.0.0.1")
).returns(mock_webrick)
server.listen(address, port)
end
it "should not perform reverse lookups" do
WEBrick::HTTPServer.expects(:new).with(
has_entry(:DoNotReverseLookup => true)
).returns(mock_webrick)
BasicSocket.expects(:do_not_reverse_lookup=).with(true)
server.listen(address, port)
end
it "should configure a logger for webrick" do
server.expects(:setup_logger).returns(:Logger => :mylogger)
WEBrick::HTTPServer.expects(:new).with {|args|
args[:Logger] == :mylogger
}.returns(mock_webrick)
server.listen(address, port)
end
it "should configure SSL for webrick" do
server.expects(:setup_ssl).returns(:Ssl => :testing, :Other => :yay)
WEBrick::HTTPServer.expects(:new).with {|args|
args[:Ssl] == :testing and args[:Other] == :yay
}.returns(mock_webrick)
server.listen(address, port)
end
it "should be listening" do
server.listen(address, port)
- server.should be_listening
+ expect(server).to be_listening
end
describe "when the REST protocol is requested" do
it "should register the REST handler at /" do
# We don't care about the options here.
mock_webrick.expects(:mount).with("/", Puppet::Network::HTTP::WEBrickREST, anything)
server.listen(address, port)
end
end
end
describe "when turning off listening" do
it "should fail unless listening" do
expect { server.unlisten }.to raise_error(RuntimeError, /server is not listening/)
end
it "should order webrick server to stop" do
mock_webrick.expects(:shutdown)
server.listen(address, port)
server.unlisten
end
it "should no longer be listening" do
server.listen(address, port)
server.unlisten
- server.should_not be_listening
+ expect(server).not_to be_listening
end
end
describe "when configuring an http logger" do
let(:server) { Puppet::Network::HTTP::WEBrick.new }
before :each do
Puppet.settings.stubs(:use)
@filehandle = stub 'handle', :fcntl => nil, :sync= => nil
File.stubs(:open).returns @filehandle
end
it "should use the settings for :main, :ssl, and :application" do
Puppet.settings.expects(:use).with(:main, :ssl, :application)
server.setup_logger
end
it "should use the masterhttplog" do
log = make_absolute("/master/log")
Puppet[:masterhttplog] = log
File.expects(:open).with(log, "a+").returns @filehandle
server.setup_logger
end
describe "and creating the logging filehandle" do
it "should set the close-on-exec flag if supported" do
if defined? Fcntl::FD_CLOEXEC
@filehandle.expects(:fcntl).with(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
else
@filehandle.expects(:fcntl).never
end
server.setup_logger
end
it "should sync the filehandle" do
@filehandle.expects(:sync=).with(true)
server.setup_logger
end
end
it "should create a new WEBrick::Log instance with the open filehandle" do
WEBrick::Log.expects(:new).with(@filehandle)
server.setup_logger
end
it "should set debugging if the current loglevel is :debug" do
Puppet::Util::Log.expects(:level).returns :debug
WEBrick::Log.expects(:new).with { |handle, debug| debug == WEBrick::Log::DEBUG }
server.setup_logger
end
it "should return the logger as the main log" do
logger = mock 'logger'
WEBrick::Log.expects(:new).returns logger
- server.setup_logger[:Logger].should == logger
+ expect(server.setup_logger[:Logger]).to eq(logger)
end
it "should return the logger as the access log using both the Common and Referer log format" do
logger = mock 'logger'
WEBrick::Log.expects(:new).returns logger
- server.setup_logger[:AccessLog].should == [
+ expect(server.setup_logger[:AccessLog]).to eq([
[logger, WEBrick::AccessLog::COMMON_LOG_FORMAT],
[logger, WEBrick::AccessLog::REFERER_LOG_FORMAT]
- ]
+ ])
end
end
describe "when configuring ssl" do
let(:server) { Puppet::Network::HTTP::WEBrick.new }
let(:localcacert) { make_absolute("/ca/crt") }
let(:ssl_server_ca_auth) { make_absolute("/ca/ssl_server_auth_file") }
let(:key) { stub 'key', :content => "mykey" }
let(:cert) { stub 'cert', :content => "mycert" }
let(:host) { stub 'host', :key => key, :certificate => cert, :name => "yay", :ssl_store => "mystore" }
before :each do
Puppet::SSL::Certificate.indirection.stubs(:find).with('ca').returns cert
Puppet::SSL::Host.stubs(:localhost).returns host
end
it "should use the key from the localhost SSL::Host instance" do
Puppet::SSL::Host.expects(:localhost).returns host
host.expects(:key).returns key
- server.setup_ssl[:SSLPrivateKey].should == "mykey"
+ expect(server.setup_ssl[:SSLPrivateKey]).to eq("mykey")
end
it "should configure the certificate" do
- server.setup_ssl[:SSLCertificate].should == "mycert"
+ expect(server.setup_ssl[:SSLCertificate]).to eq("mycert")
end
it "should fail if no CA certificate can be found" do
Puppet::SSL::Certificate.indirection.stubs(:find).with('ca').returns nil
expect { server.setup_ssl }.to raise_error(Puppet::Error, /Could not find CA certificate/)
end
it "should specify the path to the CA certificate" do
Puppet.settings[:hostcrl] = 'false'
Puppet.settings[:localcacert] = localcacert
- server.setup_ssl[:SSLCACertificateFile].should == localcacert
+ expect(server.setup_ssl[:SSLCACertificateFile]).to eq(localcacert)
end
it "should specify the path to the CA certificate" do
Puppet.settings[:hostcrl] = 'false'
Puppet.settings[:localcacert] = localcacert
Puppet.settings[:ssl_server_ca_auth] = ssl_server_ca_auth
- server.setup_ssl[:SSLCACertificateFile].should == ssl_server_ca_auth
+ expect(server.setup_ssl[:SSLCACertificateFile]).to eq(ssl_server_ca_auth)
end
it "should start ssl immediately" do
- server.setup_ssl[:SSLStartImmediately].should be_true
+ expect(server.setup_ssl[:SSLStartImmediately]).to be_truthy
end
it "should enable ssl" do
- server.setup_ssl[:SSLEnable].should be_true
+ expect(server.setup_ssl[:SSLEnable]).to be_truthy
end
it "should reject SSLv2" do
options = server.setup_ssl[:SSLOptions]
expect(options & OpenSSL::SSL::OP_NO_SSLv2).to eq(OpenSSL::SSL::OP_NO_SSLv2)
end
it "should reject SSLv3" do
options = server.setup_ssl[:SSLOptions]
expect(options & OpenSSL::SSL::OP_NO_SSLv3).to eq(OpenSSL::SSL::OP_NO_SSLv3)
end
it "should configure the verification method as 'OpenSSL::SSL::VERIFY_PEER'" do
- server.setup_ssl[:SSLVerifyClient].should == OpenSSL::SSL::VERIFY_PEER
+ expect(server.setup_ssl[:SSLVerifyClient]).to eq(OpenSSL::SSL::VERIFY_PEER)
end
it "should add an x509 store" do
host.expects(:ssl_store).returns "mystore"
- server.setup_ssl[:SSLCertificateStore].should == "mystore"
+ expect(server.setup_ssl[:SSLCertificateStore]).to eq("mystore")
end
it "should set the certificate name to 'nil'" do
- server.setup_ssl[:SSLCertName].should be_nil
+ expect(server.setup_ssl[:SSLCertName]).to be_nil
end
it "specifies the allowable ciphers" do
mock_ssl_context.expects(:ciphers=).with(server.class::CIPHERS)
server.create_server('localhost', '8888')
end
end
end
diff --git a/spec/unit/network/http_pool_spec.rb b/spec/unit/network/http_pool_spec.rb
index a9c5783f2..1aeb362d3 100755
--- a/spec/unit/network/http_pool_spec.rb
+++ b/spec/unit/network/http_pool_spec.rb
@@ -1,98 +1,98 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/http_pool'
describe Puppet::Network::HttpPool do
before :each do
Puppet::SSL::Key.indirection.terminus_class = :memory
Puppet::SSL::CertificateRequest.indirection.terminus_class = :memory
end
describe "when managing http instances" do
it "should return an http instance created with the passed host and port" do
http = Puppet::Network::HttpPool.http_instance("me", 54321)
- http.should be_an_instance_of Puppet::Network::HTTP::Connection
- http.address.should == 'me'
- http.port.should == 54321
+ expect(http).to be_an_instance_of Puppet::Network::HTTP::Connection
+ expect(http.address).to eq('me')
+ expect(http.port).to eq(54321)
end
it "should support using an alternate http client implementation" do
begin
class FooClient
def initialize(host, port, options = {})
@host = host
@port = port
end
attr_reader :host, :port
end
orig_class = Puppet::Network::HttpPool.http_client_class
Puppet::Network::HttpPool.http_client_class = FooClient
http = Puppet::Network::HttpPool.http_instance("me", 54321)
- http.should be_an_instance_of FooClient
- http.host.should == 'me'
- http.port.should == 54321
+ expect(http).to be_an_instance_of FooClient
+ expect(http.host).to eq('me')
+ expect(http.port).to eq(54321)
ensure
Puppet::Network::HttpPool.http_client_class = orig_class
end
end
it "should enable ssl on the http instance by default" do
- Puppet::Network::HttpPool.http_instance("me", 54321).should be_use_ssl
+ expect(Puppet::Network::HttpPool.http_instance("me", 54321)).to be_use_ssl
end
it "can set ssl using an option" do
- Puppet::Network::HttpPool.http_instance("me", 54321, false).should_not be_use_ssl
- Puppet::Network::HttpPool.http_instance("me", 54321, true).should be_use_ssl
+ expect(Puppet::Network::HttpPool.http_instance("me", 54321, false)).not_to be_use_ssl
+ expect(Puppet::Network::HttpPool.http_instance("me", 54321, true)).to be_use_ssl
end
describe 'peer verification' do
def setup_standard_ssl_configuration
ca_cert_file = File.expand_path('/path/to/ssl/certs/ca_cert.pem')
Puppet[:ssl_client_ca_auth] = ca_cert_file
Puppet::FileSystem.stubs(:exist?).with(ca_cert_file).returns(true)
end
def setup_standard_hostcert
host_cert_file = File.expand_path('/path/to/ssl/certs/host_cert.pem')
Puppet::FileSystem.stubs(:exist?).with(host_cert_file).returns(true)
Puppet[:hostcert] = host_cert_file
end
def setup_standard_ssl_host
cert = stub('cert', :content => 'real_cert')
key = stub('key', :content => 'real_key')
host = stub('host', :certificate => cert, :key => key, :ssl_store => stub('store'))
Puppet::SSL::Host.stubs(:localhost).returns(host)
end
before do
setup_standard_ssl_configuration
setup_standard_hostcert
setup_standard_ssl_host
end
it 'enables peer verification by default' do
response = Net::HTTPOK.new('1.1', 200, 'body')
conn = Puppet::Network::HttpPool.http_instance("me", 54321, true)
conn.expects(:execute_request).with { |http, request| expect(http.verify_mode).to eq(OpenSSL::SSL::VERIFY_PEER) }.returns(response)
conn.get('/')
end
it 'can disable peer verification' do
response = Net::HTTPOK.new('1.1', 200, 'body')
conn = Puppet::Network::HttpPool.http_instance("me", 54321, true, false)
conn.expects(:execute_request).with { |http, request| expect(http.verify_mode).to eq(OpenSSL::SSL::VERIFY_NONE) }.returns(response)
conn.get('/')
end
end
it "should not cache http instances" do
- Puppet::Network::HttpPool.http_instance("me", 54321).
- should_not equal(Puppet::Network::HttpPool.http_instance("me", 54321))
+ expect(Puppet::Network::HttpPool.http_instance("me", 54321)).
+ not_to equal(Puppet::Network::HttpPool.http_instance("me", 54321))
end
end
end
diff --git a/spec/unit/network/resolver_spec.rb b/spec/unit/network/resolver_spec.rb
index 1ccc10280..883ab8046 100755
--- a/spec/unit/network/resolver_spec.rb
+++ b/spec/unit/network/resolver_spec.rb
@@ -1,207 +1,207 @@
#!/usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/resolver'
describe Puppet::Network::Resolver do
before do
@dns_mock_object = mock('dns')
Resolv::DNS.stubs(:new).returns(@dns_mock_object)
@rr_type = Resolv::DNS::Resource::IN::SRV
@test_srv_domain = "domain.com"
@test_a_hostname = "puppet.domain.com"
@test_port = 1000
# The records we should use.
@test_records = [
# priority, weight, port, hostname
Resolv::DNS::Resource::IN::SRV.new(0, 20, 8140, "puppet1.domain.com"),
Resolv::DNS::Resource::IN::SRV.new(0, 80, 8140, "puppet2.domain.com"),
Resolv::DNS::Resource::IN::SRV.new(1, 1, 8140, "puppet3.domain.com"),
Resolv::DNS::Resource::IN::SRV.new(4, 1, 8140, "puppet4.domain.com")
]
end
describe 'when the domain is not known' do
before :each do
@dns_mock_object.stubs(:getresources).returns(@test_records)
end
describe 'because domain is nil' do
it 'does not yield' do
Puppet::Network::Resolver.each_srv_record(nil) do |_,_,_|
raise Exception.new("nil domain caused SRV lookup")
end
end
end
describe 'because domain is an empty string' do
it 'does not yield' do
Puppet::Network::Resolver.each_srv_record('') do |_,_,_|
raise Exception.new("nil domain caused SRV lookup")
end
end
end
end
describe "when resolving a host without SRV records" do
it "should not yield anything" do
# No records returned for a DNS entry without any SRV records
@dns_mock_object.expects(:getresources).with(
"_x-puppet._tcp.#{@test_a_hostname}",
@rr_type
).returns([])
Puppet::Network::Resolver.each_srv_record(@test_a_hostname) do |hostname, port, remaining|
raise Exception.new("host with no records passed block")
end
end
end
describe "when resolving a host with SRV records" do
it "should iterate through records in priority order" do
# The order of the records that should be returned,
# an array means unordered (for weight)
order = {
0 => ["puppet1.domain.com", "puppet2.domain.com"],
1 => ["puppet3.domain.com"],
2 => ["puppet4.domain.com"]
}
@dns_mock_object.expects(:getresources).with(
"_x-puppet._tcp.#{@test_srv_domain}",
@rr_type
).returns(@test_records)
Puppet::Network::Resolver.each_srv_record(@test_srv_domain) do |hostname, port|
expected_priority = order.keys.min
- order[expected_priority].should include(hostname)
- port.should_not be(@test_port)
+ expect(order[expected_priority]).to include(hostname)
+ expect(port).not_to be(@test_port)
# Remove the host from our expected hosts
order[expected_priority].delete hostname
# Remove this priority level if we're done with it
order.delete expected_priority if order[expected_priority] == []
end
end
it "should fall back to the :puppet service if no records are found for a more specific service" do
# The order of the records that should be returned,
# an array means unordered (for weight)
order = {
0 => ["puppet1.domain.com", "puppet2.domain.com"],
1 => ["puppet3.domain.com"],
2 => ["puppet4.domain.com"]
}
@dns_mock_object.expects(:getresources).with(
"_x-puppet-report._tcp.#{@test_srv_domain}",
@rr_type
).returns([])
@dns_mock_object.expects(:getresources).with(
"_x-puppet._tcp.#{@test_srv_domain}",
@rr_type
).returns(@test_records)
Puppet::Network::Resolver.each_srv_record(@test_srv_domain, :report) do |hostname, port|
expected_priority = order.keys.min
- order[expected_priority].should include(hostname)
- port.should_not be(@test_port)
+ expect(order[expected_priority]).to include(hostname)
+ expect(port).not_to be(@test_port)
# Remove the host from our expected hosts
order[expected_priority].delete hostname
# Remove this priority level if we're done with it
order.delete expected_priority if order[expected_priority] == []
end
end
it "should use SRV records from the specific service if they exist" do
# The order of the records that should be returned,
# an array means unordered (for weight)
order = {
0 => ["puppet1.domain.com", "puppet2.domain.com"],
1 => ["puppet3.domain.com"],
2 => ["puppet4.domain.com"]
}
bad_records = [
# priority, weight, port, hostname
Resolv::DNS::Resource::IN::SRV.new(0, 20, 8140, "puppet1.bad.domain.com"),
Resolv::DNS::Resource::IN::SRV.new(0, 80, 8140, "puppet2.bad.domain.com"),
Resolv::DNS::Resource::IN::SRV.new(1, 1, 8140, "puppet3.bad.domain.com"),
Resolv::DNS::Resource::IN::SRV.new(4, 1, 8140, "puppet4.bad.domain.com")
]
@dns_mock_object.expects(:getresources).with(
"_x-puppet-report._tcp.#{@test_srv_domain}",
@rr_type
).returns(@test_records)
@dns_mock_object.stubs(:getresources).with(
"_x-puppet._tcp.#{@test_srv_domain}",
@rr_type
).returns(bad_records)
Puppet::Network::Resolver.each_srv_record(@test_srv_domain, :report) do |hostname, port|
expected_priority = order.keys.min
- order[expected_priority].should include(hostname)
- port.should_not be(@test_port)
+ expect(order[expected_priority]).to include(hostname)
+ expect(port).not_to be(@test_port)
# Remove the host from our expected hosts
order[expected_priority].delete hostname
# Remove this priority level if we're done with it
order.delete expected_priority if order[expected_priority] == []
end
end
end
describe "when finding weighted servers" do
it "should return nil when no records were found" do
- Puppet::Network::Resolver.find_weighted_server([]).should == nil
+ expect(Puppet::Network::Resolver.find_weighted_server([])).to eq(nil)
end
it "should return the first record when one record is passed" do
result = Puppet::Network::Resolver.find_weighted_server([@test_records.first])
- result.should == @test_records.first
+ expect(result).to eq(@test_records.first)
end
{
"all have weights" => [1, 3, 2, 4],
"some have weights" => [2, 0, 1, 0],
"none have weights" => [0, 0, 0, 0],
}.each do |name, weights|
it "should return correct results when #{name}" do
records = []
count = 0
weights.each do |w|
count += 1
# priority, weight, port, server
records << Resolv::DNS::Resource::IN::SRV.new(0, w, 1, count.to_s)
end
seen = Hash.new(0)
total_weight = records.inject(0) do |sum, record|
sum + Puppet::Network::Resolver.weight(record)
end
total_weight.times do |n|
Kernel.expects(:rand).once.with(total_weight).returns(n)
server = Puppet::Network::Resolver.find_weighted_server(records)
seen[server] += 1
end
- seen.length.should == records.length
+ expect(seen.length).to eq(records.length)
records.each do |record|
- seen[record].should == Puppet::Network::Resolver.weight(record)
+ expect(seen[record]).to eq(Puppet::Network::Resolver.weight(record))
end
end
end
end
end
diff --git a/spec/unit/network/rights_spec.rb b/spec/unit/network/rights_spec.rb
index 08e8f775a..f4356da37 100755
--- a/spec/unit/network/rights_spec.rb
+++ b/spec/unit/network/rights_spec.rb
@@ -1,440 +1,440 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/rights'
describe Puppet::Network::Rights do
before do
@right = Puppet::Network::Rights.new
end
describe "when validating a :head request" do
[:find, :save].each do |allowed_method|
it "should allow the request if only #{allowed_method} is allowed" do
rights = Puppet::Network::Rights.new
right = rights.newright("/")
right.allow("*")
right.restrict_method(allowed_method)
right.restrict_authenticated(:any)
- rights.is_request_forbidden_and_why?(:head, "/indirection_name/key", {}).should == nil
+ expect(rights.is_request_forbidden_and_why?(:head, "/indirection_name/key", {})).to eq(nil)
end
end
it "should disallow the request if neither :find nor :save is allowed" do
rights = Puppet::Network::Rights.new
why_forbidden = rights.is_request_forbidden_and_why?(:head, "/indirection_name/key", {})
- why_forbidden.should be_instance_of(Puppet::Network::AuthorizationError)
- why_forbidden.to_s.should == "Forbidden request: access to /indirection_name/key [find]"
+ expect(why_forbidden).to be_instance_of(Puppet::Network::AuthorizationError)
+ expect(why_forbidden.to_s).to eq("Forbidden request: access to /indirection_name/key [find]")
end
end
it "should throw an error if type can't be determined" do
- lambda { @right.newright("name") }.should raise_error
+ expect { @right.newright("name") }.to raise_error
end
describe "when creating new path ACLs" do
it "should not throw an error if the ACL already exists" do
@right.newright("/name")
- lambda { @right.newright("/name")}.should_not raise_error
+ expect { @right.newright("/name")}.not_to raise_error
end
it "should throw an error if the acl uri path is not absolute" do
- lambda { @right.newright("name")}.should raise_error
+ expect { @right.newright("name")}.to raise_error
end
it "should create a new ACL with the correct path" do
@right.newright("/name")
- @right["/name"].should_not be_nil
+ expect(@right["/name"]).not_to be_nil
end
it "should create an ACL of type Puppet::Network::AuthStore" do
@right.newright("/name")
- @right["/name"].should be_a_kind_of(Puppet::Network::AuthStore)
+ expect(@right["/name"]).to be_a_kind_of(Puppet::Network::AuthStore)
end
end
describe "when creating new regex ACLs" do
it "should not throw an error if the ACL already exists" do
@right.newright("~ .rb$")
- lambda { @right.newright("~ .rb$")}.should_not raise_error
+ expect { @right.newright("~ .rb$")}.not_to raise_error
end
it "should create a new ACL with the correct regex" do
@right.newright("~ .rb$")
- @right.include?(".rb$").should_not be_nil
+ expect(@right.include?(".rb$")).not_to be_nil
end
it "should be able to lookup the regex" do
@right.newright("~ .rb$")
- @right[".rb$"].should_not be_nil
+ expect(@right[".rb$"]).not_to be_nil
end
it "should be able to lookup the regex by its full name" do
@right.newright("~ .rb$")
- @right["~ .rb$"].should_not be_nil
+ expect(@right["~ .rb$"]).not_to be_nil
end
it "should create an ACL of type Puppet::Network::AuthStore" do
- @right.newright("~ .rb$").should be_a_kind_of(Puppet::Network::AuthStore)
+ expect(@right.newright("~ .rb$")).to be_a_kind_of(Puppet::Network::AuthStore)
end
end
describe "when checking ACLs existence" do
it "should return false if there are no matching rights" do
- @right.include?("name").should be_false
+ expect(@right.include?("name")).to be_falsey
end
it "should return true if a path right exists" do
@right.newright("/name")
- @right.include?("/name").should be_true
+ expect(@right.include?("/name")).to be_truthy
end
it "should return false if no matching path rights exist" do
@right.newright("/name")
- @right.include?("/differentname").should be_false
+ expect(@right.include?("/differentname")).to be_falsey
end
it "should return true if a regex right exists" do
@right.newright("~ .rb$")
- @right.include?(".rb$").should be_true
+ expect(@right.include?(".rb$")).to be_truthy
end
it "should return false if no matching path rights exist" do
@right.newright("~ .rb$")
- @right.include?(".pp$").should be_false
+ expect(@right.include?(".pp$")).to be_falsey
end
end
describe "when checking if right is allowed" do
before :each do
@right.stubs(:right).returns(nil)
@pathacl = stub 'pathacl', :"<=>" => 1, :line => 0, :file => 'dummy'
Puppet::Network::Rights::Right.stubs(:new).returns(@pathacl)
end
it "should delegate to is_forbidden_and_why?" do
@right.expects(:is_forbidden_and_why?).with("namespace", :node => "host.domain.com", :ip => "127.0.0.1").returns(nil)
@right.allowed?("namespace", "host.domain.com", "127.0.0.1")
end
it "should return true if is_forbidden_and_why? returns nil" do
@right.stubs(:is_forbidden_and_why?).returns(nil)
- @right.allowed?("namespace", :args).should be_true
+ expect(@right.allowed?("namespace", :args)).to be_truthy
end
it "should return false if is_forbidden_and_why? returns an AuthorizationError" do
@right.stubs(:is_forbidden_and_why?).returns(Puppet::Network::AuthorizationError.new("forbidden"))
- @right.allowed?("namespace", :args1, :args2).should be_false
+ expect(@right.allowed?("namespace", :args1, :args2)).to be_falsey
end
it "should pass the match? return to allowed?" do
@right.newright("/path/to/there")
@pathacl.expects(:match?).returns(:match)
@pathacl.expects(:allowed?).with { |node,ip,h| h[:match] == :match }.returns(true)
- @right.is_forbidden_and_why?("/path/to/there", {}).should == nil
+ expect(@right.is_forbidden_and_why?("/path/to/there", {})).to eq(nil)
end
describe "with path acls" do
before :each do
@long_acl = stub 'longpathacl', :name => "/path/to/there", :line => 0, :file => 'dummy'
Puppet::Network::Rights::Right.stubs(:new).with("/path/to/there", 0, nil).returns(@long_acl)
@short_acl = stub 'shortpathacl', :name => "/path/to", :line => 0, :file => 'dummy'
Puppet::Network::Rights::Right.stubs(:new).with("/path/to", 0, nil).returns(@short_acl)
@long_acl.stubs(:"<=>").with(@short_acl).returns(0)
@short_acl.stubs(:"<=>").with(@long_acl).returns(0)
end
it "should select the first match" do
@right.newright("/path/to", 0)
@right.newright("/path/to/there", 0)
@long_acl.stubs(:match?).returns(true)
@short_acl.stubs(:match?).returns(true)
@short_acl.expects(:allowed?).returns(true)
@long_acl.expects(:allowed?).never
- @right.is_forbidden_and_why?("/path/to/there/and/there", {}).should == nil
+ expect(@right.is_forbidden_and_why?("/path/to/there/and/there", {})).to eq(nil)
end
it "should select the first match that doesn't return :dunno" do
@right.newright("/path/to/there", 0, nil)
@right.newright("/path/to", 0, nil)
@long_acl.stubs(:match?).returns(true)
@short_acl.stubs(:match?).returns(true)
@long_acl.expects(:allowed?).returns(:dunno)
@short_acl.expects(:allowed?).returns(true)
- @right.is_forbidden_and_why?("/path/to/there/and/there", {}).should == nil
+ expect(@right.is_forbidden_and_why?("/path/to/there/and/there", {})).to eq(nil)
end
it "should not select an ACL that doesn't match" do
@right.newright("/path/to/there", 0)
@right.newright("/path/to", 0)
@long_acl.stubs(:match?).returns(false)
@short_acl.stubs(:match?).returns(true)
@long_acl.expects(:allowed?).never
@short_acl.expects(:allowed?).returns(true)
- @right.is_forbidden_and_why?("/path/to/there/and/there", {}).should == nil
+ expect(@right.is_forbidden_and_why?("/path/to/there/and/there", {})).to eq(nil)
end
it "should not raise an AuthorizationError if allowed" do
@right.newright("/path/to/there", 0)
@long_acl.stubs(:match?).returns(true)
@long_acl.stubs(:allowed?).returns(true)
- @right.is_forbidden_and_why?("/path/to/there/and/there", {}).should == nil
+ expect(@right.is_forbidden_and_why?("/path/to/there/and/there", {})).to eq(nil)
end
it "should raise an AuthorizationError if the match is denied" do
@right.newright("/path/to/there", 0, nil)
@long_acl.stubs(:match?).returns(true)
@long_acl.stubs(:allowed?).returns(false)
- @right.is_forbidden_and_why?("/path/to/there", {}).should be_instance_of(Puppet::Network::AuthorizationError)
+ expect(@right.is_forbidden_and_why?("/path/to/there", {})).to be_instance_of(Puppet::Network::AuthorizationError)
end
it "should raise an AuthorizationError if no path match" do
- @right.is_forbidden_and_why?("/nomatch", {}).should be_instance_of(Puppet::Network::AuthorizationError)
+ expect(@right.is_forbidden_and_why?("/nomatch", {})).to be_instance_of(Puppet::Network::AuthorizationError)
end
end
describe "with regex acls" do
before :each do
@regex_acl1 = stub 'regex_acl1', :name => "/files/(.*)/myfile", :line => 0, :file => 'dummy'
Puppet::Network::Rights::Right.stubs(:new).with("~ /files/(.*)/myfile", 0, nil).returns(@regex_acl1)
@regex_acl2 = stub 'regex_acl2', :name => "/files/(.*)/myfile/", :line => 0, :file => 'dummy'
Puppet::Network::Rights::Right.stubs(:new).with("~ /files/(.*)/myfile/", 0, nil).returns(@regex_acl2)
@regex_acl1.stubs(:"<=>").with(@regex_acl2).returns(0)
@regex_acl2.stubs(:"<=>").with(@regex_acl1).returns(0)
end
it "should select the first match" do
@right.newright("~ /files/(.*)/myfile", 0)
@right.newright("~ /files/(.*)/myfile/", 0)
@regex_acl1.stubs(:match?).returns(true)
@regex_acl2.stubs(:match?).returns(true)
@regex_acl1.expects(:allowed?).returns(true)
@regex_acl2.expects(:allowed?).never
- @right.is_forbidden_and_why?("/files/repository/myfile/other", {}).should == nil
+ expect(@right.is_forbidden_and_why?("/files/repository/myfile/other", {})).to eq(nil)
end
it "should select the first match that doesn't return :dunno" do
@right.newright("~ /files/(.*)/myfile", 0)
@right.newright("~ /files/(.*)/myfile/", 0)
@regex_acl1.stubs(:match?).returns(true)
@regex_acl2.stubs(:match?).returns(true)
@regex_acl1.expects(:allowed?).returns(:dunno)
@regex_acl2.expects(:allowed?).returns(true)
- @right.is_forbidden_and_why?("/files/repository/myfile/other", {}).should == nil
+ expect(@right.is_forbidden_and_why?("/files/repository/myfile/other", {})).to eq(nil)
end
it "should not select an ACL that doesn't match" do
@right.newright("~ /files/(.*)/myfile", 0)
@right.newright("~ /files/(.*)/myfile/", 0)
@regex_acl1.stubs(:match?).returns(false)
@regex_acl2.stubs(:match?).returns(true)
@regex_acl1.expects(:allowed?).never
@regex_acl2.expects(:allowed?).returns(true)
- @right.is_forbidden_and_why?("/files/repository/myfile/other", {}).should == nil
+ expect(@right.is_forbidden_and_why?("/files/repository/myfile/other", {})).to eq(nil)
end
it "should not raise an AuthorizationError if allowed" do
@right.newright("~ /files/(.*)/myfile", 0)
@regex_acl1.stubs(:match?).returns(true)
@regex_acl1.stubs(:allowed?).returns(true)
- @right.is_forbidden_and_why?("/files/repository/myfile/other", {}).should == nil
+ expect(@right.is_forbidden_and_why?("/files/repository/myfile/other", {})).to eq(nil)
end
it "should raise an error if no regex acl match" do
- @right.is_forbidden_and_why?("/path", {}).should be_instance_of(Puppet::Network::AuthorizationError)
+ expect(@right.is_forbidden_and_why?("/path", {})).to be_instance_of(Puppet::Network::AuthorizationError)
end
it "should raise an AuthorizedError on deny" do
- @right.is_forbidden_and_why?("/path", {}).should be_instance_of(Puppet::Network::AuthorizationError)
+ expect(@right.is_forbidden_and_why?("/path", {})).to be_instance_of(Puppet::Network::AuthorizationError)
end
end
end
describe Puppet::Network::Rights::Right do
before :each do
@acl = Puppet::Network::Rights::Right.new("/path",0, nil)
end
describe "with path" do
it "should match up to its path length" do
- @acl.match?("/path/that/works").should_not be_nil
+ expect(@acl.match?("/path/that/works")).not_to be_nil
end
it "should match up to its path length" do
- @acl.match?("/paththatalsoworks").should_not be_nil
+ expect(@acl.match?("/paththatalsoworks")).not_to be_nil
end
it "should return nil if no match" do
- @acl.match?("/notpath").should be_nil
+ expect(@acl.match?("/notpath")).to be_nil
end
end
describe "with regex" do
before :each do
@acl = Puppet::Network::Rights::Right.new("~ .rb$",0, nil)
end
it "should match as a regex" do
- @acl.match?("this should work.rb").should_not be_nil
+ expect(@acl.match?("this should work.rb")).not_to be_nil
end
it "should return nil if no match" do
- @acl.match?("do not match").should be_nil
+ expect(@acl.match?("do not match")).to be_nil
end
end
it "should allow all rest methods by default" do
- @acl.methods.should == Puppet::Network::Rights::Right::ALL
+ expect(@acl.methods).to eq(Puppet::Network::Rights::Right::ALL)
end
it "should allow only authenticated request by default" do
- @acl.authentication.should be_true
+ expect(@acl.authentication).to be_truthy
end
it "should allow modification of the methods filters" do
@acl.restrict_method(:save)
- @acl.methods.should == [:save]
+ expect(@acl.methods).to eq([:save])
end
it "should stack methods filters" do
@acl.restrict_method(:save)
@acl.restrict_method(:destroy)
- @acl.methods.should == [:save, :destroy]
+ expect(@acl.methods).to eq([:save, :destroy])
end
it "should raise an error if the method is already filtered" do
@acl.restrict_method(:save)
- lambda { @acl.restrict_method(:save) }.should raise_error
+ expect { @acl.restrict_method(:save) }.to raise_error
end
it "should allow setting an environment filters" do
env = Puppet::Node::Environment.create(:acltest, [])
Puppet.override(:environments => Puppet::Environments::Static.new(env)) do
@acl.restrict_environment(:acltest)
- @acl.environment.should == [env]
+ expect(@acl.environment).to eq([env])
end
end
["on", "yes", "true", true].each do |auth|
it "should allow filtering on authenticated requests with '#{auth}'" do
@acl.restrict_authenticated(auth)
- @acl.authentication.should be_true
+ expect(@acl.authentication).to be_truthy
end
end
["off", "no", "false", false, "all", "any", :all, :any].each do |auth|
it "should allow filtering on authenticated or unauthenticated requests with '#{auth}'" do
@acl.restrict_authenticated(auth)
- @acl.authentication.should be_false
+ expect(@acl.authentication).to be_falsey
end
end
describe "when checking right authorization" do
it "should return :dunno if this right is not restricted to the given method" do
@acl.restrict_method(:destroy)
- @acl.allowed?("me","127.0.0.1", { :method => :save } ).should == :dunno
+ expect(@acl.allowed?("me","127.0.0.1", { :method => :save } )).to eq(:dunno)
end
it "should return true if this right is restricted to the given method" do
@acl.restrict_method(:save)
@acl.allow("me")
- @acl.allowed?("me","127.0.0.1", { :method => :save, :authenticated => true }).should eq true
+ expect(@acl.allowed?("me","127.0.0.1", { :method => :save, :authenticated => true })).to eq true
end
it "should return :dunno if this right is not restricted to the given environment" do
prod = Puppet::Node::Environment.create(:production, [])
dev = Puppet::Node::Environment.create(:development, [])
Puppet.override(:environments => Puppet::Environments::Static.new(prod, dev)) do
@acl.restrict_environment(:production)
- @acl.allowed?("me","127.0.0.1", { :method => :save, :environment => dev }).should == :dunno
+ expect(@acl.allowed?("me","127.0.0.1", { :method => :save, :environment => dev })).to eq(:dunno)
end
end
it "returns true if the request is permitted for this environment" do
@acl.allow("me")
prod = Puppet::Node::Environment.create(:production, [])
Puppet.override(:environments => Puppet::Environments::Static.new(prod)) do
@acl.restrict_environment(:production)
expect(@acl.allowed?("me", "127.0.0.1", { :method => :save, :authenticated => true, :environment => prod })).to eq true
end
end
it "should return :dunno if this right is not restricted to the given request authentication state" do
@acl.restrict_authenticated(true)
- @acl.allowed?("me","127.0.0.1", { :method => :save, :authenticated => false }).should == :dunno
+ expect(@acl.allowed?("me","127.0.0.1", { :method => :save, :authenticated => false })).to eq(:dunno)
end
it "returns true if this right is restricted to the given request authentication state" do
@acl.restrict_authenticated(false)
@acl.allow("me")
- @acl.allowed?("me","127.0.0.1", {:method => :save, :authenticated => false }).should eq true
+ expect(@acl.allowed?("me","127.0.0.1", {:method => :save, :authenticated => false })).to eq true
end
it "should interpolate allow/deny patterns with the given match" do
@acl.expects(:interpolate).with(:match)
@acl.allowed?("me","127.0.0.1", { :method => :save, :match => :match, :authenticated => true })
end
it "should reset interpolation after the match" do
@acl.expects(:reset_interpolation)
@acl.allowed?("me","127.0.0.1", { :method => :save, :match => :match, :authenticated => true })
end
end
end
end
diff --git a/spec/unit/network/server_spec.rb b/spec/unit/network/server_spec.rb
index 941e94015..253b4b52f 100755
--- a/spec/unit/network/server_spec.rb
+++ b/spec/unit/network/server_spec.rb
@@ -1,95 +1,95 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/server'
describe Puppet::Network::Server do
let(:port) { 8140 }
let(:address) { '0.0.0.0' }
let(:server) { Puppet::Network::Server.new(address, port) }
before do
@mock_http_server = mock('http server')
Puppet.settings.stubs(:use)
Puppet::Network::HTTP::WEBrick.stubs(:new).returns(@mock_http_server)
end
describe "when initializing" do
before do
Puppet[:masterport] = ''
end
it "should not be listening after initialization" do
- Puppet::Network::Server.new(address, port).should_not be_listening
+ expect(Puppet::Network::Server.new(address, port)).not_to be_listening
end
it "should use the :main setting section" do
Puppet.settings.expects(:use).with { |*args| args.include?(:main) }
Puppet::Network::Server.new(address, port)
end
it "should use the :application setting section" do
Puppet.settings.expects(:use).with { |*args| args.include?(:application) }
Puppet::Network::Server.new(address, port)
end
end
describe "when not yet started" do
before do
@mock_http_server.stubs(:listen)
end
it "should indicate that it is not listening" do
- server.should_not be_listening
+ expect(server).not_to be_listening
end
it "should not allow server to be stopped" do
expect { server.stop }.to raise_error(RuntimeError)
end
it "should allow server to be started" do
expect { server.start }.to_not raise_error
end
end
describe "when server is on" do
before do
@mock_http_server.stubs(:listen)
@mock_http_server.stubs(:unlisten)
server.start
end
it "should indicate that it is listening" do
- server.should be_listening
+ expect(server).to be_listening
end
it "should not allow server to be started again" do
expect { server.start }.to raise_error(RuntimeError)
end
it "should allow server to be stopped" do
expect { server.stop }.to_not raise_error
end
end
describe "when server is being started" do
it "should cause the HTTP server to listen" do
server = Puppet::Network::Server.new(address, port)
@mock_http_server.expects(:listen).with(address, port)
server.start
end
end
describe "when server is being stopped" do
before do
@mock_http_server.stubs(:listen)
server.stubs(:http_server).returns(@mock_http_server)
server.start
end
it "should cause the HTTP server to stop listening" do
@mock_http_server.expects(:unlisten)
server.stop
end
end
end
diff --git a/spec/unit/node/environment_spec.rb b/spec/unit/node/environment_spec.rb
index 74238542f..848dd1e30 100755
--- a/spec/unit/node/environment_spec.rb
+++ b/spec/unit/node/environment_spec.rb
@@ -1,483 +1,483 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'tmpdir'
require 'puppet/node/environment'
require 'puppet/util/execution'
require 'puppet_spec/modules'
require 'puppet/parser/parser_factory'
describe Puppet::Node::Environment do
let(:env) { Puppet::Node::Environment.create("testing", []) }
include PuppetSpec::Files
context 'the environment' do
it "converts an environment to string when converting to YAML" do
- env.to_yaml.should match(/--- testing/)
+ expect(env.to_yaml).to match(/--- testing/)
end
describe ".create" do
it "creates equivalent environments whether specifying name as a symbol or a string" do
expect(Puppet::Node::Environment.create(:one, [])).to eq(Puppet::Node::Environment.create("one", []))
end
it "interns name" do
expect(Puppet::Node::Environment.create("one", []).name).to equal(:one)
end
it "does not produce environment singletons" do
expect(Puppet::Node::Environment.create("one", [])).to_not equal(Puppet::Node::Environment.create("one", []))
end
end
it "returns its name when converted to a string" do
expect(env.to_s).to eq("testing")
end
it "has an inspect method for debugging" do
e = Puppet::Node::Environment.create(:test, ['/modules/path', '/other/modules'], '/manifests/path')
expect("a #{e} env").to eq("a test env")
expect(e.inspect).to match(%r{<Puppet::Node::Environment:\w* @name="test" @manifest="#{File.expand_path('/manifests/path')}" @modulepath="#{File.expand_path('/modules/path')}:#{File.expand_path('/other/modules')}" >})
end
describe "equality" do
it "works as a hash key" do
base = Puppet::Node::Environment.create(:first, ["modules"], "manifests")
same = Puppet::Node::Environment.create(:first, ["modules"], "manifests")
different = Puppet::Node::Environment.create(:first, ["different"], "manifests")
hash = {}
hash[base] = "base env"
hash[same] = "same env"
hash[different] = "different env"
expect(hash[base]).to eq("same env")
expect(hash[different]).to eq("different env")
expect(hash).to have(2).item
end
it "is equal when name, modules, and manifests are the same" do
base = Puppet::Node::Environment.create(:base, ["modules"], "manifests")
different_name = Puppet::Node::Environment.create(:different, base.full_modulepath, base.manifest)
expect(base).to_not eq("not an environment")
expect(base).to eq(base)
expect(base.hash).to eq(base.hash)
expect(base.override_with(:modulepath => ["different"])).to_not eq(base)
expect(base.override_with(:modulepath => ["different"]).hash).to_not eq(base.hash)
expect(base.override_with(:manifest => "different")).to_not eq(base)
expect(base.override_with(:manifest => "different").hash).to_not eq(base.hash)
expect(different_name).to_not eq(base)
expect(different_name.hash).to_not eq(base.hash)
end
end
describe "overriding an existing environment" do
let(:original_path) { [tmpdir('original')] }
let(:new_path) { [tmpdir('new')] }
let(:environment) { Puppet::Node::Environment.create(:overridden, original_path, 'orig.pp', '/config/script') }
it "overrides modulepath" do
overridden = environment.override_with(:modulepath => new_path)
expect(overridden).to_not be_equal(environment)
expect(overridden.name).to eq(:overridden)
expect(overridden.manifest).to eq(File.expand_path('orig.pp'))
expect(overridden.modulepath).to eq(new_path)
expect(overridden.config_version).to eq('/config/script')
end
it "overrides manifest" do
overridden = environment.override_with(:manifest => 'new.pp')
expect(overridden).to_not be_equal(environment)
expect(overridden.name).to eq(:overridden)
expect(overridden.manifest).to eq(File.expand_path('new.pp'))
expect(overridden.modulepath).to eq(original_path)
expect(overridden.config_version).to eq('/config/script')
end
it "overrides config_version" do
overridden = environment.override_with(:config_version => '/new/script')
expect(overridden).to_not be_equal(environment)
expect(overridden.name).to eq(:overridden)
expect(overridden.manifest).to eq(File.expand_path('orig.pp'))
expect(overridden.modulepath).to eq(original_path)
expect(overridden.config_version).to eq('/new/script')
end
end
describe "when managing known resource types" do
before do
env.stubs(:perform_initial_import).returns(Puppet::Parser::AST::Hostclass.new(''))
end
it "creates a resource type collection if none exists" do
expect(env.known_resource_types).to be_kind_of(Puppet::Resource::TypeCollection)
end
it "memoizes resource type collection" do
expect(env.known_resource_types).to equal(env.known_resource_types)
end
it "performs the initial import when creating a new collection" do
env.expects(:perform_initial_import).returns(Puppet::Parser::AST::Hostclass.new(''))
env.known_resource_types
end
it "generates a new TypeCollection if the current one requires reparsing" do
old_type_collection = env.known_resource_types
old_type_collection.stubs(:parse_failed?).returns true
env.check_for_reparse
new_type_collection = env.known_resource_types
expect(new_type_collection).to be_a Puppet::Resource::TypeCollection
expect(new_type_collection).to_not equal(old_type_collection)
end
end
it "validates the modulepath directories" do
real_file = tmpdir('moduledir')
path = ['/one', '/two', real_file]
env = Puppet::Node::Environment.create(:test, path)
expect(env.modulepath).to eq([real_file])
end
it "prefixes the value of the 'PUPPETLIB' environment variable to the module path if present" do
first_puppetlib = tmpdir('puppetlib1')
second_puppetlib = tmpdir('puppetlib2')
first_moduledir = tmpdir('moduledir1')
second_moduledir = tmpdir('moduledir2')
Puppet::Util.withenv("PUPPETLIB" => [first_puppetlib, second_puppetlib].join(File::PATH_SEPARATOR)) do
env = Puppet::Node::Environment.create(:testing, [first_moduledir, second_moduledir])
expect(env.modulepath).to eq([first_puppetlib, second_puppetlib, first_moduledir, second_moduledir])
end
end
describe "validating manifest settings" do
before(:each) do
Puppet[:default_manifest] = "/default/manifests/site.pp"
end
it "has no validation errors when disable_per_environment_manifest is false" do
expect(Puppet::Node::Environment.create(:directory, [], '/some/non/default/manifest.pp').validation_errors).to be_empty
end
context "when disable_per_environment_manifest is true" do
let(:config) { mock('config') }
let(:global_modulepath) { ["/global/modulepath"] }
let(:envconf) { Puppet::Settings::EnvironmentConf.new("/some/direnv", config, global_modulepath) }
before(:each) do
Puppet[:disable_per_environment_manifest] = true
end
def assert_manifest_conflict(expectation, envconf_manifest_value)
config.expects(:setting).with(:manifest).returns(
mock('setting', :value => envconf_manifest_value)
)
environment = Puppet::Node::Environment.create(:directory, [], '/default/manifests/site.pp')
loader = Puppet::Environments::Static.new(environment)
loader.stubs(:get_conf).returns(envconf)
Puppet.override(:environments => loader) do
if expectation
expect(environment.validation_errors).to have_matching_element(/The 'disable_per_environment_manifest' setting is true.*and the.*environment.*conflicts/)
else
expect(environment.validation_errors).to be_empty
end
end
end
it "has conflicting_manifest_settings when environment.conf manifest was set" do
assert_manifest_conflict(true, '/some/envconf/manifest/site.pp')
end
it "does not have conflicting_manifest_settings when environment.conf manifest is empty" do
assert_manifest_conflict(false, '')
end
it "does not have conflicting_manifest_settings when environment.conf manifest is nil" do
assert_manifest_conflict(false, nil)
end
it "does not have conflicting_manifest_settings when environment.conf manifest is an exact, uninterpolated match of default_manifest" do
assert_manifest_conflict(false, '/default/manifests/site.pp')
end
end
end
describe "when modeling a specific environment" do
let(:first_modulepath) { tmpdir('firstmodules') }
let(:second_modulepath) { tmpdir('secondmodules') }
let(:env) { Puppet::Node::Environment.create(:modules_test, [first_modulepath, second_modulepath]) }
let(:module_options) {
{
:environment => env,
:metadata => {
:author => 'puppetlabs',
},
}
}
describe "module data" do
describe ".module" do
it "returns an individual module that exists in its module path" do
one = PuppetSpec::Modules.create('one', first_modulepath, module_options)
expect(env.module('one')).to eq(one)
end
it "returns nil if asked for a module that does not exist in its path" do
expect(env.module("doesnotexist")).to be_nil
end
end
describe "#modules_by_path" do
it "returns an empty list if there are no modules" do
expect(env.modules_by_path).to eq({
first_modulepath => [],
second_modulepath => []
})
end
it "includes modules even if they exist in multiple dirs in the modulepath" do
one = PuppetSpec::Modules.create('one', first_modulepath, module_options)
two = PuppetSpec::Modules.create('two', second_modulepath, module_options)
expect(env.modules_by_path).to eq({
first_modulepath => [one],
second_modulepath => [two],
})
end
it "ignores modules with invalid names" do
PuppetSpec::Modules.generate_files('foo', first_modulepath)
PuppetSpec::Modules.generate_files('foo2', first_modulepath)
PuppetSpec::Modules.generate_files('foo-bar', first_modulepath)
PuppetSpec::Modules.generate_files('foo_bar', first_modulepath)
PuppetSpec::Modules.generate_files('foo=bar', first_modulepath)
PuppetSpec::Modules.generate_files('foo bar', first_modulepath)
PuppetSpec::Modules.generate_files('foo.bar', first_modulepath)
PuppetSpec::Modules.generate_files('-foo', first_modulepath)
PuppetSpec::Modules.generate_files('foo-', first_modulepath)
PuppetSpec::Modules.generate_files('foo--bar', first_modulepath)
expect(env.modules_by_path[first_modulepath].collect{|mod| mod.name}.sort).to eq(%w{foo foo-bar foo2 foo_bar})
end
end
describe "#module_requirements" do
it "returns a list of what modules depend on other modules" do
PuppetSpec::Modules.create(
'foo',
first_modulepath,
:metadata => {
:author => 'puppetlabs',
:dependencies => [{ 'name' => 'puppetlabs/bar', "version_requirement" => ">= 1.0.0" }]
}
)
PuppetSpec::Modules.create(
'bar',
second_modulepath,
:metadata => {
:author => 'puppetlabs',
:dependencies => [{ 'name' => 'puppetlabs/foo', "version_requirement" => "<= 2.0.0" }]
}
)
PuppetSpec::Modules.create(
'baz',
first_modulepath,
:metadata => {
:author => 'puppetlabs',
:dependencies => [{ 'name' => 'puppetlabs-bar', "version_requirement" => "3.0.0" }]
}
)
PuppetSpec::Modules.create(
'alpha',
first_modulepath,
:metadata => {
:author => 'puppetlabs',
:dependencies => [{ 'name' => 'puppetlabs/bar', "version_requirement" => "~3.0.0" }]
}
)
expect(env.module_requirements).to eq({
'puppetlabs/alpha' => [],
'puppetlabs/foo' => [
{
"name" => "puppetlabs/bar",
"version" => "9.9.9",
"version_requirement" => "<= 2.0.0"
}
],
'puppetlabs/bar' => [
{
"name" => "puppetlabs/alpha",
"version" => "9.9.9",
"version_requirement" => "~3.0.0"
},
{
"name" => "puppetlabs/baz",
"version" => "9.9.9",
"version_requirement" => "3.0.0"
},
{
"name" => "puppetlabs/foo",
"version" => "9.9.9",
"version_requirement" => ">= 1.0.0"
}
],
'puppetlabs/baz' => []
})
end
end
describe ".module_by_forge_name" do
it "finds modules by forge_name" do
mod = PuppetSpec::Modules.create(
'baz',
first_modulepath,
module_options
)
expect(env.module_by_forge_name('puppetlabs/baz')).to eq(mod)
end
it "does not find modules with same name by the wrong author" do
mod = PuppetSpec::Modules.create(
'baz',
first_modulepath,
:metadata => {:author => 'sneakylabs'},
:environment => env
)
expect(env.module_by_forge_name('puppetlabs/baz')).to eq(nil)
end
it "returns nil when the module can't be found" do
expect(env.module_by_forge_name('ima/nothere')).to be_nil
end
end
describe ".modules" do
it "returns an empty list if there are no modules" do
expect(env.modules).to eq([])
end
it "returns a module named for every directory in each module path" do
%w{foo bar}.each do |mod_name|
PuppetSpec::Modules.generate_files(mod_name, first_modulepath)
end
%w{bee baz}.each do |mod_name|
PuppetSpec::Modules.generate_files(mod_name, second_modulepath)
end
expect(env.modules.collect{|mod| mod.name}.sort).to eq(%w{foo bar bee baz}.sort)
end
it "removes duplicates" do
PuppetSpec::Modules.generate_files('foo', first_modulepath)
PuppetSpec::Modules.generate_files('foo', second_modulepath)
expect(env.modules.collect{|mod| mod.name}.sort).to eq(%w{foo})
end
it "ignores modules with invalid names" do
PuppetSpec::Modules.generate_files('foo', first_modulepath)
PuppetSpec::Modules.generate_files('foo2', first_modulepath)
PuppetSpec::Modules.generate_files('foo-bar', first_modulepath)
PuppetSpec::Modules.generate_files('foo_bar', first_modulepath)
PuppetSpec::Modules.generate_files('foo=bar', first_modulepath)
PuppetSpec::Modules.generate_files('foo bar', first_modulepath)
expect(env.modules.collect{|mod| mod.name}.sort).to eq(%w{foo foo-bar foo2 foo_bar})
end
it "creates modules with the correct environment" do
PuppetSpec::Modules.generate_files('foo', first_modulepath)
env.modules.each do |mod|
expect(mod.environment).to eq(env)
end
end
it "logs an exception if a module contains invalid metadata" do
PuppetSpec::Modules.generate_files(
'foo',
first_modulepath,
:metadata => {
:author => 'puppetlabs'
# missing source, version, etc
}
)
Puppet.expects(:log_exception).with(is_a(Puppet::Module::MissingMetadata))
env.modules
end
end
end
end
describe "when performing initial import" do
it "loads from Puppet[:code]" do
Puppet[:code] = "define foo {}"
krt = env.known_resource_types
expect(krt.find_definition('foo')).to be_kind_of(Puppet::Resource::Type)
end
it "parses from the the environment's manifests if Puppet[:code] is not set" do
filename = tmpfile('a_manifest.pp')
File.open(filename, 'w') do |f|
f.puts("define from_manifest {}")
end
env = Puppet::Node::Environment.create(:testing, [], filename)
krt = env.known_resource_types
expect(krt.find_definition('from_manifest')).to be_kind_of(Puppet::Resource::Type)
end
it "prefers Puppet[:code] over manifest files" do
Puppet[:code] = "define from_code_setting {}"
filename = tmpfile('a_manifest.pp')
File.open(filename, 'w') do |f|
f.puts("define from_manifest {}")
end
env = Puppet::Node::Environment.create(:testing, [], filename)
krt = env.known_resource_types
expect(krt.find_definition('from_code_setting')).to be_kind_of(Puppet::Resource::Type)
end
it "initial import proceeds even if manifest file does not exist on disk" do
filename = tmpfile('a_manifest.pp')
env = Puppet::Node::Environment.create(:testing, [], filename)
expect(env.known_resource_types).to be_kind_of(Puppet::Resource::TypeCollection)
end
it "returns an empty TypeCollection if neither code nor manifests is present" do
expect(env.known_resource_types).to be_kind_of(Puppet::Resource::TypeCollection)
end
it "fails helpfully if there is an error importing" do
Puppet[:code] = "oops {"
expect do
env.known_resource_types
end.to raise_error(Puppet::Error, /Could not parse for environment #{env.name}/)
end
it "should mark the type collection as needing a reparse when there is an error parsing" do
Puppet[:code] = "oops {"
expect do
env.known_resource_types
end.to raise_error(Puppet::Error, /Syntax error at .../)
- expect(env.known_resource_types.parse_failed?).to be_true
+ expect(env.known_resource_types.parse_failed?).to be_truthy
end
end
end
end
diff --git a/spec/unit/node/facts_spec.rb b/spec/unit/node/facts_spec.rb
index 20e87435f..05fd8f2bb 100755
--- a/spec/unit/node/facts_spec.rb
+++ b/spec/unit/node/facts_spec.rb
@@ -1,212 +1,213 @@
#! /usr/bin/env ruby
+
require 'spec_helper'
require 'puppet/node/facts'
require 'matchers/json'
describe Puppet::Node::Facts, "when indirecting" do
include JSONMatchers
before do
@facts = Puppet::Node::Facts.new("me")
end
describe "adding local facts" do
it "should add the node's certificate name as the 'clientcert' fact" do
@facts.add_local_facts
- @facts.values["clientcert"].should == Puppet.settings[:certname]
+ expect(@facts.values["clientcert"]).to eq(Puppet.settings[:certname])
end
it "adds the Puppet version as a 'clientversion' fact" do
@facts.add_local_facts
- @facts.values["clientversion"].should == Puppet.version.to_s
+ expect(@facts.values["clientversion"]).to eq(Puppet.version.to_s)
end
it "adds the agent side noop setting as 'clientnoop'" do
@facts.add_local_facts
- @facts.values["clientnoop"].should == Puppet.settings[:noop]
+ expect(@facts.values["clientnoop"]).to eq(Puppet.settings[:noop])
end
it "doesn't add the current environment" do
@facts.add_local_facts
- @facts.values.should_not include("environment")
+ expect(@facts.values).not_to include("environment")
end
it "doesn't replace any existing environment fact when adding local facts" do
@facts.values["environment"] = "foo"
@facts.add_local_facts
- @facts.values["environment"].should == "foo"
+ expect(@facts.values["environment"]).to eq("foo")
end
end
describe "when sanitizing facts" do
it "should convert fact values if needed" do
@facts.values["test"] = /foo/
@facts.sanitize
- @facts.values["test"].should == "(?-mix:foo)"
+ expect(@facts.values["test"]).to eq("(?-mix:foo)")
end
it "should convert hash keys if needed" do
@facts.values["test"] = {/foo/ => "bar"}
@facts.sanitize
- @facts.values["test"].should == {"(?-mix:foo)" => "bar"}
+ expect(@facts.values["test"]).to eq({"(?-mix:foo)" => "bar"})
end
it "should convert hash values if needed" do
@facts.values["test"] = {"foo" => /bar/}
@facts.sanitize
- @facts.values["test"].should == {"foo" => "(?-mix:bar)"}
+ expect(@facts.values["test"]).to eq({"foo" => "(?-mix:bar)"})
end
it "should convert array elements if needed" do
@facts.values["test"] = [1, "foo", /bar/]
@facts.sanitize
- @facts.values["test"].should == [1, "foo", "(?-mix:bar)"]
+ expect(@facts.values["test"]).to eq([1, "foo", "(?-mix:bar)"])
end
it "should handle nested arrays" do
@facts.values["test"] = [1, "foo", [/bar/]]
@facts.sanitize
- @facts.values["test"].should == [1, "foo", ["(?-mix:bar)"]]
+ expect(@facts.values["test"]).to eq([1, "foo", ["(?-mix:bar)"]])
end
it "should handle nested hashes" do
@facts.values["test"] = {/foo/ => {"bar" => /baz/}}
@facts.sanitize
- @facts.values["test"].should == {"(?-mix:foo)" => {"bar" => "(?-mix:baz)"}}
+ expect(@facts.values["test"]).to eq({"(?-mix:foo)" => {"bar" => "(?-mix:baz)"}})
end
it "should handle nester arrays and hashes" do
@facts.values["test"] = {/foo/ => ["bar", /baz/]}
@facts.sanitize
- @facts.values["test"].should == {"(?-mix:foo)" => ["bar", "(?-mix:baz)"]}
+ expect(@facts.values["test"]).to eq({"(?-mix:foo)" => ["bar", "(?-mix:baz)"]})
end
end
describe "when indirecting" do
before do
@indirection = stub 'indirection', :request => mock('request'), :name => :facts
@facts = Puppet::Node::Facts.new("me", "one" => "two")
end
it "should redirect to the specified fact store for storage" do
Puppet::Node::Facts.stubs(:indirection).returns(@indirection)
@indirection.expects(:save)
Puppet::Node::Facts.indirection.save(@facts)
end
describe "when the Puppet application is 'master'" do
it "should default to the 'yaml' terminus" do
pending "Cannot test the behavior of defaults in defaults.rb"
- # Puppet::Node::Facts.indirection.terminus_class.should == :yaml
+ expect(Puppet::Node::Facts.indirection.terminus_class).to eq(:yaml)
end
end
describe "when the Puppet application is not 'master'" do
it "should default to the 'facter' terminus" do
pending "Cannot test the behavior of defaults in defaults.rb"
- # Puppet::Node::Facts.indirection.terminus_class.should == :facter
+ expect(Puppet::Node::Facts.indirection.terminus_class).to eq(:facter)
end
end
end
describe "when storing and retrieving" do
it "doesn't manufacture a `_timestamp` fact value" do
values = {"one" => "two", "three" => "four"}
facts = Puppet::Node::Facts.new("mynode", values)
expect(facts.values).to eq(values)
end
describe "when deserializing from yaml" do
let(:timestamp) { Time.parse("Thu Oct 28 11:16:31 -0700 2010") }
let(:expiration) { Time.parse("Thu Oct 28 11:21:31 -0700 2010") }
def create_facts(values = {})
Puppet::Node::Facts.new('mynode', values)
end
def deserialize_yaml_facts(facts)
format = Puppet::Network::FormatHandler.format('yaml')
format.intern(Puppet::Node::Facts, facts.to_yaml)
end
it 'preserves `_timestamp` value' do
facts = deserialize_yaml_facts(create_facts('_timestamp' => timestamp))
expect(facts.timestamp).to eq(timestamp)
end
it "doesn't preserve the `_timestamp` fact" do
facts = deserialize_yaml_facts(create_facts('_timestamp' => timestamp))
expect(facts.values['_timestamp']).to be_nil
end
it 'preserves expiration time if present' do
old_facts = create_facts
old_facts.expiration = expiration
facts = deserialize_yaml_facts(old_facts)
expect(facts.expiration).to eq(expiration)
end
it 'ignores expiration time if absent' do
facts = deserialize_yaml_facts(create_facts)
expect(facts.expiration).to be_nil
end
end
describe "using pson" do
before :each do
@timestamp = Time.parse("Thu Oct 28 11:16:31 -0700 2010")
@expiration = Time.parse("Thu Oct 28 11:21:31 -0700 2010")
end
it "should accept properly formatted pson" do
pson = %Q({"name": "foo", "expiration": "#{@expiration}", "timestamp": "#{@timestamp}", "values": {"a": "1", "b": "2", "c": "3"}})
format = Puppet::Network::FormatHandler.format('pson')
facts = format.intern(Puppet::Node::Facts,pson)
- facts.name.should == 'foo'
- facts.expiration.should == @expiration
- facts.timestamp.should == @timestamp
- facts.values.should == {'a' => '1', 'b' => '2', 'c' => '3'}
+ expect(facts.name).to eq('foo')
+ expect(facts.expiration).to eq(@expiration)
+ expect(facts.timestamp).to eq(@timestamp)
+ expect(facts.values).to eq({'a' => '1', 'b' => '2', 'c' => '3'})
end
it "should generate properly formatted pson" do
Time.stubs(:now).returns(@timestamp)
facts = Puppet::Node::Facts.new("foo", {'a' => 1, 'b' => 2, 'c' => 3})
facts.expiration = @expiration
result = PSON.parse(facts.to_pson)
- result['name'].should == facts.name
- result['values'].should == facts.values
- result['timestamp'].should == facts.timestamp.iso8601(9)
- result['expiration'].should == facts.expiration.iso8601(9)
+ expect(result['name']).to eq(facts.name)
+ expect(result['values']).to eq(facts.values)
+ expect(result['timestamp']).to eq(facts.timestamp.iso8601(9))
+ expect(result['expiration']).to eq(facts.expiration.iso8601(9))
end
it "should generate valid facts data against the facts schema" do
Time.stubs(:now).returns(@timestamp)
facts = Puppet::Node::Facts.new("foo", {'a' => 1, 'b' => 2, 'c' => 3})
facts.expiration = @expiration
expect(facts.to_pson).to validate_against('api/schemas/facts.json')
end
it "should not include nil values" do
facts = Puppet::Node::Facts.new("foo", {'a' => 1, 'b' => 2, 'c' => 3})
pson = PSON.parse(facts.to_pson)
- pson.should_not be_include("expiration")
+ expect(pson).not_to be_include("expiration")
end
it "should be able to handle nil values" do
pson = %Q({"name": "foo", "values": {"a": "1", "b": "2", "c": "3"}})
format = Puppet::Network::FormatHandler.format('pson')
facts = format.intern(Puppet::Node::Facts,pson)
- facts.name.should == 'foo'
- facts.expiration.should be_nil
+ expect(facts.name).to eq('foo')
+ expect(facts.expiration).to be_nil
end
end
end
end
diff --git a/spec/unit/other/selinux_spec.rb b/spec/unit/other/selinux_spec.rb
index e5b5ac03b..44b03441e 100755
--- a/spec/unit/other/selinux_spec.rb
+++ b/spec/unit/other/selinux_spec.rb
@@ -1,99 +1,99 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/type/selboolean'
require 'puppet/type/selmodule'
describe Puppet::Type.type(:file), " when manipulating file contexts" do
include PuppetSpec::Files
before :each do
@file = Puppet::Type::File.new(
:name => make_absolute("/tmp/foo"),
:ensure => "file",
:seluser => "user_u",
:selrole => "role_r",
:seltype => "type_t")
end
it "should use :seluser to get/set an SELinux user file context attribute" do
expect(@file[:seluser]).to eq("user_u")
end
it "should use :selrole to get/set an SELinux role file context attribute" do
expect(@file[:selrole]).to eq("role_r")
end
it "should use :seltype to get/set an SELinux user file context attribute" do
expect(@file[:seltype]).to eq("type_t")
end
end
describe Puppet::Type.type(:selboolean), " when manipulating booleans" do
before :each do
provider_class = Puppet::Type::Selboolean.provider(Puppet::Type::Selboolean.providers[0])
Puppet::Type::Selboolean.stubs(:defaultprovider).returns provider_class
@bool = Puppet::Type::Selboolean.new(
:name => "foo",
:value => "on",
:persistent => true )
end
it "should be able to access :name" do
- @bool[:name].should == "foo"
+ expect(@bool[:name]).to eq("foo")
end
it "should be able to access :value" do
expect(@bool.property(:value).should).to eq(:on)
end
it "should set :value to off" do
@bool[:value] = :off
expect(@bool.property(:value).should).to eq(:off)
end
it "should be able to access :persistent" do
- @bool[:persistent].should == :true
+ expect(@bool[:persistent]).to eq(:true)
end
it "should set :persistent to false" do
@bool[:persistent] = false
- @bool[:persistent].should == :false
+ expect(@bool[:persistent]).to eq(:false)
end
end
describe Puppet::Type.type(:selmodule), " when checking policy modules" do
before :each do
provider_class = Puppet::Type::Selmodule.provider(Puppet::Type::Selmodule.providers[0])
Puppet::Type::Selmodule.stubs(:defaultprovider).returns provider_class
@module = Puppet::Type::Selmodule.new(
:name => "foo",
:selmoduledir => "/some/path",
:selmodulepath => "/some/path/foo.pp",
:syncversion => true)
end
it "should be able to access :name" do
- @module[:name].should == "foo"
+ expect(@module[:name]).to eq("foo")
end
it "should be able to access :selmoduledir" do
- @module[:selmoduledir].should == "/some/path"
+ expect(@module[:selmoduledir]).to eq("/some/path")
end
it "should be able to access :selmodulepath" do
- @module[:selmodulepath].should == "/some/path/foo.pp"
+ expect(@module[:selmodulepath]).to eq("/some/path/foo.pp")
end
it "should be able to access :syncversion" do
expect(@module[:syncversion]).to eq(:true)
end
it "should set the syncversion value to false" do
@module[:syncversion] = :false
expect(@module[:syncversion]).to eq(:false)
end
end
diff --git a/spec/unit/parameter/boolean_spec.rb b/spec/unit/parameter/boolean_spec.rb
index 505bc561f..86467db45 100644
--- a/spec/unit/parameter/boolean_spec.rb
+++ b/spec/unit/parameter/boolean_spec.rb
@@ -1,35 +1,36 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet'
require 'puppet/parameter/boolean'
describe Puppet::Parameter::Boolean do
let (:resource) { mock('resource') }
describe "after initvars" do
before { described_class.initvars }
it "should have the correct value_collection" do
- described_class.value_collection.values.sort.should ==
+ expect(described_class.value_collection.values.sort).to eq(
[:true, :false, :yes, :no].sort
+ )
end
end
describe "instances" do
subject { described_class.new(:resource => resource) }
[ true, :true, 'true', :yes, 'yes', 'TrUe', 'yEs' ].each do |arg|
it "should munge #{arg.inspect} as true" do
- subject.munge(arg).should == true
+ expect(subject.munge(arg)).to eq(true)
end
end
[ false, :false, 'false', :no, 'no', 'FaLSE', 'nO' ].each do |arg|
it "should munge #{arg.inspect} as false" do
- subject.munge(arg).should == false
+ expect(subject.munge(arg)).to eq(false)
end
end
[ nil, :undef, 'undef', '0', 0, '1', 1, 9284 ].each do |arg|
it "should fail to munge #{arg.inspect}" do
expect { subject.munge(arg) }.to raise_error Puppet::Error
end
end
end
end
diff --git a/spec/unit/parameter/package_options_spec.rb b/spec/unit/parameter/package_options_spec.rb
index 21117ac32..b640354b0 100644
--- a/spec/unit/parameter/package_options_spec.rb
+++ b/spec/unit/parameter/package_options_spec.rb
@@ -1,44 +1,44 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/parameter/package_options'
describe Puppet::Parameter::PackageOptions do
let (:resource) { mock('resource') }
let (:param) { described_class.new(:resource => resource) }
let (:arg) { '/S' }
let (:key) { 'INSTALLDIR' }
let (:value) { 'C:/mydir' }
context '#munge' do
# The parser automatically converts single element arrays to just
# a single element, why it does this is beyond me. See 46252b5bb8
it 'should accept a string' do
- param.munge(arg).should == [arg]
+ expect(param.munge(arg)).to eq([arg])
end
it 'should accept a hash' do
- param.munge({key => value}).should == [{key => value}]
+ expect(param.munge({key => value})).to eq([{key => value}])
end
it 'should accept an array of strings and hashes' do
munged = param.munge([arg, {key => value}, '/NCRC', {'CONF' => 'C:\datadir'}])
- munged.should == [arg, {key => value}, '/NCRC', {'CONF' => 'C:\datadir'}]
+ expect(munged).to eq([arg, {key => value}, '/NCRC', {'CONF' => 'C:\datadir'}])
end
it 'should quote strings' do
- param.munge('arg one').should == ["\"arg one\""]
+ expect(param.munge('arg one')).to eq(["\"arg one\""])
end
it 'should quote hash pairs' do
munged = param.munge({'INSTALL DIR' => 'C:\Program Files'})
- munged.should == [{"\"INSTALL DIR\"" => "\"C:\\Program Files\""}]
+ expect(munged).to eq([{"\"INSTALL DIR\"" => "\"C:\\Program Files\""}])
end
it 'should reject symbols' do
expect {
param.munge([:symbol])
}.to raise_error(Puppet::Error, /Expected either a string or hash of options/)
end
end
end
diff --git a/spec/unit/parameter/value_collection_spec.rb b/spec/unit/parameter/value_collection_spec.rb
index 16632ec97..e00d830a0 100755
--- a/spec/unit/parameter/value_collection_spec.rb
+++ b/spec/unit/parameter/value_collection_spec.rb
@@ -1,166 +1,166 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/parameter'
describe Puppet::Parameter::ValueCollection do
before do
@collection = Puppet::Parameter::ValueCollection.new
end
it "should have a method for defining new values" do
- @collection.should respond_to(:newvalues)
+ expect(@collection).to respond_to(:newvalues)
end
it "should have a method for adding individual values" do
- @collection.should respond_to(:newvalue)
+ expect(@collection).to respond_to(:newvalue)
end
it "should be able to retrieve individual values" do
value = @collection.newvalue(:foo)
- @collection.value(:foo).should equal(value)
+ expect(@collection.value(:foo)).to equal(value)
end
it "should be able to add an individual value with a block" do
@collection.newvalue(:foo) { raise "testing" }
- @collection.value(:foo).block.should be_instance_of(Proc)
+ expect(@collection.value(:foo).block).to be_instance_of(Proc)
end
it "should be able to add values that are empty strings" do
expect { @collection.newvalue('') }.to_not raise_error
end
it "should be able to add values that are empty strings" do
value = @collection.newvalue('')
- @collection.match?('').should equal(value)
+ expect(@collection.match?('')).to equal(value)
end
it "should set :call to :none when adding a value with no block" do
value = @collection.newvalue(:foo)
- value.call.should == :none
+ expect(value.call).to eq(:none)
end
describe "when adding a value with a block" do
it "should set the method name to 'set_' plus the value name" do
value = @collection.newvalue(:myval) { raise "testing" }
- value.method.should == "set_myval"
+ expect(value.method).to eq("set_myval")
end
end
it "should be able to add an individual value with options" do
value = @collection.newvalue(:foo, :call => :bar)
- value.call.should == :bar
+ expect(value.call).to eq(:bar)
end
it "should have a method for validating a value" do
- @collection.should respond_to(:validate)
+ expect(@collection).to respond_to(:validate)
end
it "should have a method for munging a value" do
- @collection.should respond_to(:munge)
+ expect(@collection).to respond_to(:munge)
end
it "should be able to generate documentation when it has both values and regexes" do
@collection.newvalues :foo, "bar", %r{test}
- @collection.doc.should be_instance_of(String)
+ expect(@collection.doc).to be_instance_of(String)
end
it "should correctly generate documentation for values" do
@collection.newvalues :foo
- @collection.doc.should be_include("Valid values are `foo`")
+ expect(@collection.doc).to be_include("Valid values are `foo`")
end
it "should correctly generate documentation for regexes" do
@collection.newvalues %r{\w+}
- @collection.doc.should be_include("Values can match `/\\w+/`")
+ expect(@collection.doc).to be_include("Values can match `/\\w+/`")
end
it "should be able to find the first matching value" do
@collection.newvalues :foo, :bar
- @collection.match?("foo").should be_instance_of(Puppet::Parameter::Value)
+ expect(@collection.match?("foo")).to be_instance_of(Puppet::Parameter::Value)
end
it "should be able to match symbols" do
@collection.newvalues :foo, :bar
- @collection.match?(:foo).should be_instance_of(Puppet::Parameter::Value)
+ expect(@collection.match?(:foo)).to be_instance_of(Puppet::Parameter::Value)
end
it "should be able to match symbols when a regex is provided" do
@collection.newvalues %r{.}
- @collection.match?(:foo).should be_instance_of(Puppet::Parameter::Value)
+ expect(@collection.match?(:foo)).to be_instance_of(Puppet::Parameter::Value)
end
it "should be able to match values using regexes" do
@collection.newvalues %r{.}
- @collection.match?("foo").should_not be_nil
+ expect(@collection.match?("foo")).not_to be_nil
end
it "should prefer value matches to regex matches" do
@collection.newvalues %r{.}, :foo
- @collection.match?("foo").name.should == :foo
+ expect(@collection.match?("foo").name).to eq(:foo)
end
describe "when validating values" do
it "should do nothing if no values or regexes have been defined" do
@collection.validate("foo")
end
it "should fail if the value is not a defined value or alias and does not match a regex" do
@collection.newvalues :foo
expect { @collection.validate("bar") }.to raise_error(ArgumentError)
end
it "should succeed if the value is one of the defined values" do
@collection.newvalues :foo
expect { @collection.validate(:foo) }.to_not raise_error
end
it "should succeed if the value is one of the defined values even if the definition uses a symbol and the validation uses a string" do
@collection.newvalues :foo
expect { @collection.validate("foo") }.to_not raise_error
end
it "should succeed if the value is one of the defined values even if the definition uses a string and the validation uses a symbol" do
@collection.newvalues "foo"
expect { @collection.validate(:foo) }.to_not raise_error
end
it "should succeed if the value is one of the defined aliases" do
@collection.newvalues :foo
@collection.aliasvalue :bar, :foo
expect { @collection.validate("bar") }.to_not raise_error
end
it "should succeed if the value matches one of the regexes" do
@collection.newvalues %r{\d}
expect { @collection.validate("10") }.to_not raise_error
end
end
describe "when munging values" do
it "should do nothing if no values or regexes have been defined" do
- @collection.munge("foo").should == "foo"
+ expect(@collection.munge("foo")).to eq("foo")
end
it "should return return any matching defined values" do
@collection.newvalues :foo, :bar
- @collection.munge("foo").should == :foo
+ expect(@collection.munge("foo")).to eq(:foo)
end
it "should return any matching aliases" do
@collection.newvalues :foo
@collection.aliasvalue :bar, :foo
- @collection.munge("bar").should == :foo
+ expect(@collection.munge("bar")).to eq(:foo)
end
it "should return the value if it matches a regex" do
@collection.newvalues %r{\w}
- @collection.munge("bar").should == "bar"
+ expect(@collection.munge("bar")).to eq("bar")
end
it "should return the value if no other option is matched" do
@collection.newvalues :foo
- @collection.munge("bar").should == "bar"
+ expect(@collection.munge("bar")).to eq("bar")
end
end
end
diff --git a/spec/unit/parameter/value_spec.rb b/spec/unit/parameter/value_spec.rb
index 605664d6c..a2af83de4 100755
--- a/spec/unit/parameter/value_spec.rb
+++ b/spec/unit/parameter/value_spec.rb
@@ -1,87 +1,87 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/parameter'
describe Puppet::Parameter::Value do
it "should require a name" do
- lambda { Puppet::Parameter::Value.new }.should raise_error(ArgumentError)
+ expect { Puppet::Parameter::Value.new }.to raise_error(ArgumentError)
end
it "should set its name" do
- Puppet::Parameter::Value.new(:foo).name.should == :foo
+ expect(Puppet::Parameter::Value.new(:foo).name).to eq(:foo)
end
it "should support regexes as names" do
- lambda { Puppet::Parameter::Value.new(%r{foo}) }.should_not raise_error
+ expect { Puppet::Parameter::Value.new(%r{foo}) }.not_to raise_error
end
it "should mark itself as a regex if its name is a regex" do
- Puppet::Parameter::Value.new(%r{foo}).should be_regex
+ expect(Puppet::Parameter::Value.new(%r{foo})).to be_regex
end
it "should always convert its name to a symbol if it is not a regex" do
- Puppet::Parameter::Value.new("foo").name.should == :foo
- Puppet::Parameter::Value.new(true).name.should == :true
+ expect(Puppet::Parameter::Value.new("foo").name).to eq(:foo)
+ expect(Puppet::Parameter::Value.new(true).name).to eq(:true)
end
it "should support adding aliases" do
- Puppet::Parameter::Value.new("foo").should respond_to(:alias)
+ expect(Puppet::Parameter::Value.new("foo")).to respond_to(:alias)
end
it "should be able to return its aliases" do
value = Puppet::Parameter::Value.new("foo")
value.alias("bar")
value.alias("baz")
- value.aliases.should == [:bar, :baz]
+ expect(value.aliases).to eq([:bar, :baz])
end
[:block, :call, :method, :event, :required_features].each do |attr|
it "should support a #{attr} attribute" do
value = Puppet::Parameter::Value.new("foo")
- value.should respond_to(attr.to_s + "=")
- value.should respond_to(attr)
+ expect(value).to respond_to(attr.to_s + "=")
+ expect(value).to respond_to(attr)
end
end
it "should default to :instead for :call if a block is provided" do
- Puppet::Parameter::Value.new("foo").call.should == :instead
+ expect(Puppet::Parameter::Value.new("foo").call).to eq(:instead)
end
it "should always return events as symbols" do
value = Puppet::Parameter::Value.new("foo")
value.event = "foo_test"
- value.event.should == :foo_test
+ expect(value.event).to eq(:foo_test)
end
describe "when matching" do
describe "a regex" do
it "should return true if the regex matches the value" do
- Puppet::Parameter::Value.new(/\w/).should be_match("foo")
+ expect(Puppet::Parameter::Value.new(/\w/)).to be_match("foo")
end
it "should return false if the regex does not match the value" do
- Puppet::Parameter::Value.new(/\d/).should_not be_match("foo")
+ expect(Puppet::Parameter::Value.new(/\d/)).not_to be_match("foo")
end
end
describe "a non-regex" do
it "should return true if the value, converted to a symbol, matches the name" do
- Puppet::Parameter::Value.new("foo").should be_match("foo")
- Puppet::Parameter::Value.new(:foo).should be_match(:foo)
- Puppet::Parameter::Value.new(:foo).should be_match("foo")
- Puppet::Parameter::Value.new("foo").should be_match(:foo)
+ expect(Puppet::Parameter::Value.new("foo")).to be_match("foo")
+ expect(Puppet::Parameter::Value.new(:foo)).to be_match(:foo)
+ expect(Puppet::Parameter::Value.new(:foo)).to be_match("foo")
+ expect(Puppet::Parameter::Value.new("foo")).to be_match(:foo)
end
it "should return false if the value, converted to a symbol, does not match the name" do
- Puppet::Parameter::Value.new(:foo).should_not be_match(:bar)
+ expect(Puppet::Parameter::Value.new(:foo)).not_to be_match(:bar)
end
it "should return true if any of its aliases match" do
value = Puppet::Parameter::Value.new("foo")
value.alias("bar")
- value.should be_match("bar")
+ expect(value).to be_match("bar")
end
end
end
end
diff --git a/spec/unit/parameter_spec.rb b/spec/unit/parameter_spec.rb
index bde4d22eb..2d9db47a1 100755
--- a/spec/unit/parameter_spec.rb
+++ b/spec/unit/parameter_spec.rb
@@ -1,193 +1,193 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/parameter'
describe Puppet::Parameter do
before do
@class = Class.new(Puppet::Parameter) do
@name = :foo
end
@class.initvars
@resource = mock 'resource'
@resource.stub_everything
@parameter = @class.new :resource => @resource
end
it "should create a value collection" do
@class = Class.new(Puppet::Parameter)
- @class.value_collection.should be_nil
+ expect(@class.value_collection).to be_nil
@class.initvars
- @class.value_collection.should be_instance_of(Puppet::Parameter::ValueCollection)
+ expect(@class.value_collection).to be_instance_of(Puppet::Parameter::ValueCollection)
end
it "should return its name as a string when converted to a string" do
- @parameter.to_s.should == @parameter.name.to_s
+ expect(@parameter.to_s).to eq(@parameter.name.to_s)
end
[:line, :file, :version].each do |data|
it "should return its resource's #{data} as its #{data}" do
@resource.expects(data).returns "foo"
- @parameter.send(data).should == "foo"
+ expect(@parameter.send(data)).to eq("foo")
end
end
it "should return the resource's tags plus its name as its tags" do
@resource.expects(:tags).returns %w{one two}
- @parameter.tags.should == %w{one two foo}
+ expect(@parameter.tags).to eq(%w{one two foo})
end
it "should have a path" do
- @parameter.path.should == "//foo"
+ expect(@parameter.path).to eq("//foo")
end
describe "when returning the value" do
it "should return nil if no value is set" do
- @parameter.value.should be_nil
+ expect(@parameter.value).to be_nil
end
it "should validate the value" do
@parameter.expects(:validate).with("foo")
@parameter.value = "foo"
end
it "should munge the value and use any result as the actual value" do
@parameter.expects(:munge).with("foo").returns "bar"
@parameter.value = "foo"
- @parameter.value.should == "bar"
+ expect(@parameter.value).to eq("bar")
end
it "should unmunge the value when accessing the actual value" do
@parameter.class.unmunge do |value| value.to_sym end
@parameter.value = "foo"
- @parameter.value.should == :foo
+ expect(@parameter.value).to eq(:foo)
end
it "should return the actual value by default when unmunging" do
- @parameter.unmunge("bar").should == "bar"
+ expect(@parameter.unmunge("bar")).to eq("bar")
end
it "should return any set value" do
@parameter.value = "foo"
- @parameter.value.should == "foo"
+ expect(@parameter.value).to eq("foo")
end
end
describe "when validating values" do
it "should do nothing if no values or regexes have been defined" do
@parameter.validate("foo")
end
it "should catch abnormal failures thrown during validation" do
@class.validate { |v| raise "This is broken" }
expect { @parameter.validate("eh") }.to raise_error(Puppet::DevError)
end
it "should fail if the value is not a defined value or alias and does not match a regex" do
@class.newvalues :foo
expect { @parameter.validate("bar") }.to raise_error(Puppet::Error)
end
it "should succeed if the value is one of the defined values" do
@class.newvalues :foo
expect { @parameter.validate(:foo) }.to_not raise_error
end
it "should succeed if the value is one of the defined values even if the definition uses a symbol and the validation uses a string" do
@class.newvalues :foo
expect { @parameter.validate("foo") }.to_not raise_error
end
it "should succeed if the value is one of the defined values even if the definition uses a string and the validation uses a symbol" do
@class.newvalues "foo"
expect { @parameter.validate(:foo) }.to_not raise_error
end
it "should succeed if the value is one of the defined aliases" do
@class.newvalues :foo
@class.aliasvalue :bar, :foo
expect { @parameter.validate("bar") }.to_not raise_error
end
it "should succeed if the value matches one of the regexes" do
@class.newvalues %r{\d}
expect { @parameter.validate("10") }.to_not raise_error
end
end
describe "when munging values" do
it "should do nothing if no values or regexes have been defined" do
- @parameter.munge("foo").should == "foo"
+ expect(@parameter.munge("foo")).to eq("foo")
end
it "should catch abnormal failures thrown during munging" do
@class.munge { |v| raise "This is broken" }
expect { @parameter.munge("eh") }.to raise_error(Puppet::DevError)
end
it "should return return any matching defined values" do
@class.newvalues :foo, :bar
- @parameter.munge("foo").should == :foo
+ expect(@parameter.munge("foo")).to eq(:foo)
end
it "should return any matching aliases" do
@class.newvalues :foo
@class.aliasvalue :bar, :foo
- @parameter.munge("bar").should == :foo
+ expect(@parameter.munge("bar")).to eq(:foo)
end
it "should return the value if it matches a regex" do
@class.newvalues %r{\w}
- @parameter.munge("bar").should == "bar"
+ expect(@parameter.munge("bar")).to eq("bar")
end
it "should return the value if no other option is matched" do
@class.newvalues :foo
- @parameter.munge("bar").should == "bar"
+ expect(@parameter.munge("bar")).to eq("bar")
end
end
describe "when logging" do
it "should use its resource's log level and the provided message" do
@resource.expects(:[]).with(:loglevel).returns :notice
@parameter.expects(:send_log).with(:notice, "mymessage")
@parameter.log "mymessage"
end
end
describe ".format_value_for_display" do
it 'should format strings appropriately' do
- described_class.format_value_for_display('foo').should == "'foo'"
+ expect(described_class.format_value_for_display('foo')).to eq("'foo'")
end
it 'should format numbers appropriately' do
- described_class.format_value_for_display(1).should == "'1'"
+ expect(described_class.format_value_for_display(1)).to eq("'1'")
end
it 'should format symbols appropriately' do
- described_class.format_value_for_display(:bar).should == "'bar'"
+ expect(described_class.format_value_for_display(:bar)).to eq("'bar'")
end
it 'should format arrays appropriately' do
- described_class.format_value_for_display([1, 'foo', :bar]).should == "['1', 'foo', 'bar']"
+ expect(described_class.format_value_for_display([1, 'foo', :bar])).to eq("['1', 'foo', 'bar']")
end
it 'should format hashes appropriately' do
- described_class.format_value_for_display(
+ expect(described_class.format_value_for_display(
{1 => 'foo', :bar => 2, 'baz' => :qux}
- ).should == "{'1' => 'foo', 'bar' => '2', 'baz' => 'qux'}"
+ )).to eq("{'1' => 'foo', 'bar' => '2', 'baz' => 'qux'}")
end
it 'should format arrays with nested data appropriately' do
- described_class.format_value_for_display(
+ expect(described_class.format_value_for_display(
[1, 'foo', :bar, [1, 2, 3], {1 => 2, 3 => 4}]
- ).should == "['1', 'foo', 'bar', ['1', '2', '3'], {'1' => '2', '3' => '4'}]"
+ )).to eq("['1', 'foo', 'bar', ['1', '2', '3'], {'1' => '2', '3' => '4'}]")
end
it 'should format hashes with nested data appropriately' do
- described_class.format_value_for_display(
+ expect(described_class.format_value_for_display(
{1 => 'foo', :bar => [2, 3, 4], 'baz' => {:qux => 1, :quux => 'two'}}
- ).should == "{'1' => 'foo', 'bar' => ['2', '3', '4'], 'baz' => {'quux' => 'two', 'qux' => '1'}}"
+ )).to eq("{'1' => 'foo', 'bar' => ['2', '3', '4'], 'baz' => {'quux' => 'two', 'qux' => '1'}}")
end
end
end
diff --git a/spec/unit/parser/ast/block_expression_spec.rb b/spec/unit/parser/ast/block_expression_spec.rb
index 8440fb669..49ebe7d38 100644
--- a/spec/unit/parser/ast/block_expression_spec.rb
+++ b/spec/unit/parser/ast/block_expression_spec.rb
@@ -1,68 +1,68 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/parser/ast/block_expression'
describe 'Puppet::Parser::AST::BlockExpression' do
class StackDepthAST < Puppet::Parser::AST
attr_reader :call_depth
def evaluate(*options)
@call_depth = caller.length
end
end
NO_SCOPE = nil
def depth_probe
StackDepthAST.new({})
end
def sequence_probe(name, sequence)
probe = mock("Sequence Probe #{name}")
probe.expects(:safeevaluate).in_sequence(sequence)
probe
end
def block_of(children)
Puppet::Parser::AST::BlockExpression.new(:children => children)
end
def assert_all_at_same_depth(*probes)
depth0 = probes[0].call_depth
probes.drop(1).each do |p|
- p.call_depth.should == depth0
+ expect(p.call_depth).to eq(depth0)
end
end
it "evaluates all its children at the same stack depth" do
depth_probes = [depth_probe, depth_probe]
expr = block_of(depth_probes)
expr.evaluate(NO_SCOPE)
assert_all_at_same_depth(*depth_probes)
end
it "evaluates sequenced children at the same stack depth" do
depth1 = depth_probe
depth2 = depth_probe
depth3 = depth_probe
expr1 = block_of([depth1])
expr2 = block_of([depth2])
expr3 = block_of([depth3])
expr1.sequence_with(expr2).sequence_with(expr3).evaluate(NO_SCOPE)
assert_all_at_same_depth(depth1, depth2, depth3)
end
it "evaluates sequenced children in order" do
evaluation_order = sequence("Child evaluation order")
expr1 = block_of([sequence_probe("Step 1", evaluation_order)])
expr2 = block_of([sequence_probe("Step 2", evaluation_order)])
expr3 = block_of([sequence_probe("Step 3", evaluation_order)])
expr1.sequence_with(expr2).sequence_with(expr3).evaluate(NO_SCOPE)
end
end
diff --git a/spec/unit/parser/ast/leaf_spec.rb b/spec/unit/parser/ast/leaf_spec.rb
index c6804cad5..8dddafcf1 100755
--- a/spec/unit/parser/ast/leaf_spec.rb
+++ b/spec/unit/parser/ast/leaf_spec.rb
@@ -1,138 +1,138 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Parser::AST::Leaf do
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
@value = stub 'value'
@leaf = Puppet::Parser::AST::Leaf.new(:value => @value)
end
describe "when converting to string" do
it "should transform its value to string" do
value = stub 'value', :is_a? => true
value.expects(:to_s)
Puppet::Parser::AST::Leaf.new( :value => value ).to_s
end
end
it "should have a match method" do
- @leaf.should respond_to(:match)
+ expect(@leaf).to respond_to(:match)
end
it "should delegate match to ==" do
@value.expects(:==).with("value")
@leaf.match("value")
end
end
describe Puppet::Parser::AST::Regex do
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
end
describe "when initializing" do
it "should create a Regexp with its content when value is not a Regexp" do
Regexp.expects(:new).with("/ab/")
Puppet::Parser::AST::Regex.new :value => "/ab/"
end
it "should not create a Regexp with its content when value is a Regexp" do
value = Regexp.new("/ab/")
Regexp.expects(:new).with("/ab/").never
Puppet::Parser::AST::Regex.new :value => value
end
end
describe "when evaluating" do
it "should return self" do
val = Puppet::Parser::AST::Regex.new :value => "/ab/"
- val.evaluate(@scope).should === val
+ expect(val.evaluate(@scope)).to be === val
end
end
it "should return the regex source with to_s" do
regex = stub 'regex'
Regexp.stubs(:new).returns(regex)
val = Puppet::Parser::AST::Regex.new :value => "/ab/"
regex.expects(:source)
val.to_s
end
it "should delegate match to the underlying regexp match method" do
regex = Regexp.new("/ab/")
val = Puppet::Parser::AST::Regex.new :value => regex
regex.expects(:match).with("value")
val.match("value")
end
end
describe Puppet::Parser::AST::HostName do
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
@value = 'value'
@value.stubs(:to_s).returns(@value)
@value.stubs(:downcase).returns(@value)
@host = Puppet::Parser::AST::HostName.new(:value => @value)
end
it "should raise an error if hostname is not valid" do
- lambda { Puppet::Parser::AST::HostName.new( :value => "not a hostname!" ) }.should raise_error
+ expect { Puppet::Parser::AST::HostName.new( :value => "not a hostname!" ) }.to raise_error
end
it "should not raise an error if hostname is a regex" do
- lambda { Puppet::Parser::AST::HostName.new( :value => Puppet::Parser::AST::Regex.new(:value => "/test/") ) }.should_not raise_error
+ expect { Puppet::Parser::AST::HostName.new( :value => Puppet::Parser::AST::Regex.new(:value => "/test/") ) }.not_to raise_error
end
it "should stringify the value" do
value = stub 'value', :=~ => false
value.expects(:to_s).returns("test")
Puppet::Parser::AST::HostName.new(:value => value)
end
it "should downcase the value" do
value = stub 'value', :=~ => false
value.stubs(:to_s).returns("UPCASED")
host = Puppet::Parser::AST::HostName.new(:value => value)
host.value == "upcased"
end
it "should evaluate to its value" do
- @host.evaluate(@scope).should == @value
+ expect(@host.evaluate(@scope)).to eq(@value)
end
it "should delegate eql? to the underlying value if it is an HostName" do
@value.expects(:eql?).with("value")
@host.eql?("value")
end
it "should delegate eql? to the underlying value if it is not an HostName" do
value = stub 'compared', :is_a? => true, :value => "value"
@value.expects(:eql?).with("value")
@host.eql?(value)
end
it "should delegate hash to the underlying value" do
@value.expects(:hash)
@host.hash
end
end
diff --git a/spec/unit/parser/compiler_spec.rb b/spec/unit/parser/compiler_spec.rb
index 40ad20130..176ede8f4 100755
--- a/spec/unit/parser/compiler_spec.rb
+++ b/spec/unit/parser/compiler_spec.rb
@@ -1,911 +1,911 @@
require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
class CompilerTestResource
attr_accessor :builtin, :virtual, :evaluated, :type, :title
def initialize(type, title)
@type = type
@title = title
end
def [](attr)
return nil if attr == :stage
:main
end
def ref
"#{type.to_s.capitalize}[#{title}]"
end
def evaluated?
@evaluated
end
def builtin_type?
@builtin
end
def virtual?
@virtual
end
def class?
false
end
def stage?
false
end
def evaluate
end
def file
"/fake/file/goes/here"
end
def line
"42"
end
end
describe Puppet::Parser::Compiler do
include PuppetSpec::Files
include Matchers::Resource
def resource(type, title)
Puppet::Parser::Resource.new(type, title, :scope => @scope)
end
let(:environment) { Puppet::Node::Environment.create(:testing, []) }
before :each do
# Push me faster, I wanna go back in time! (Specifically, freeze time
# across the test since we have a bunch of version == timestamp code
# hidden away in the implementation and we keep losing the race.)
# --daniel 2011-04-21
now = Time.now
Time.stubs(:now).returns(now)
@node = Puppet::Node.new("testnode",
:facts => Puppet::Node::Facts.new("facts", {}),
:environment => environment)
@known_resource_types = environment.known_resource_types
@compiler = Puppet::Parser::Compiler.new(@node)
@scope = Puppet::Parser::Scope.new(@compiler, :source => stub('source'))
@scope_resource = Puppet::Parser::Resource.new(:file, "/my/file", :scope => @scope)
@scope.resource = @scope_resource
end
it "should fail intelligently when a class-level compile fails" do
Puppet::Parser::Compiler.expects(:new).raises ArgumentError
- lambda { Puppet::Parser::Compiler.compile(@node) }.should raise_error(Puppet::Error)
+ expect { Puppet::Parser::Compiler.compile(@node) }.to raise_error(Puppet::Error)
end
it "should use the node's environment as its environment" do
- @compiler.environment.should equal(@node.environment)
+ expect(@compiler.environment).to equal(@node.environment)
end
it "fails if the node's environment has validation errors" do
conflicted_environment = Puppet::Node::Environment.create(:testing, [], '/some/environment.conf/manifest.pp')
conflicted_environment.stubs(:validation_errors).returns(['bad environment'])
@node.environment = conflicted_environment
expect { Puppet::Parser::Compiler.compile(@node) }.to raise_error(Puppet::Error, /Compilation has been halted because.*bad environment/)
end
it "should include the resource type collection helper" do
- Puppet::Parser::Compiler.ancestors.should be_include(Puppet::Resource::TypeCollectionHelper)
+ expect(Puppet::Parser::Compiler.ancestors).to be_include(Puppet::Resource::TypeCollectionHelper)
end
it "should be able to return a class list containing all added classes" do
@compiler.add_class ""
@compiler.add_class "one"
@compiler.add_class "two"
- @compiler.classlist.sort.should == %w{one two}.sort
+ expect(@compiler.classlist.sort).to eq(%w{one two}.sort)
end
describe "when initializing" do
it "should set its node attribute" do
- @compiler.node.should equal(@node)
+ expect(@compiler.node).to equal(@node)
end
it "should detect when ast nodes are absent" do
- @compiler.ast_nodes?.should be_false
+ expect(@compiler.ast_nodes?).to be_falsey
end
it "should detect when ast nodes are present" do
@known_resource_types.expects(:nodes?).returns true
- @compiler.ast_nodes?.should be_true
+ expect(@compiler.ast_nodes?).to be_truthy
end
it "should copy the known_resource_types version to the catalog" do
- @compiler.catalog.version.should == @known_resource_types.version
+ expect(@compiler.catalog.version).to eq(@known_resource_types.version)
end
it "should copy any node classes into the class list" do
node = Puppet::Node.new("mynode")
node.classes = %w{foo bar}
compiler = Puppet::Parser::Compiler.new(node)
- compiler.classlist.should =~ ['foo', 'bar']
+ expect(compiler.classlist).to match_array(['foo', 'bar'])
end
it "should transform node class hashes into a class list" do
node = Puppet::Node.new("mynode")
node.classes = {'foo'=>{'one'=>'p1'}, 'bar'=>{'two'=>'p2'}}
compiler = Puppet::Parser::Compiler.new(node)
- compiler.classlist.should =~ ['foo', 'bar']
+ expect(compiler.classlist).to match_array(['foo', 'bar'])
end
it "should add a 'main' stage to the catalog" do
- @compiler.catalog.resource(:stage, :main).should be_instance_of(Puppet::Parser::Resource)
+ expect(@compiler.catalog.resource(:stage, :main)).to be_instance_of(Puppet::Parser::Resource)
end
end
describe "when managing scopes" do
it "should create a top scope" do
- @compiler.topscope.should be_instance_of(Puppet::Parser::Scope)
+ expect(@compiler.topscope).to be_instance_of(Puppet::Parser::Scope)
end
it "should be able to create new scopes" do
- @compiler.newscope(@compiler.topscope).should be_instance_of(Puppet::Parser::Scope)
+ expect(@compiler.newscope(@compiler.topscope)).to be_instance_of(Puppet::Parser::Scope)
end
it "should set the parent scope of the new scope to be the passed-in parent" do
scope = mock 'scope'
newscope = @compiler.newscope(scope)
- newscope.parent.should equal(scope)
+ expect(newscope.parent).to equal(scope)
end
it "should set the parent scope of the new scope to its topscope if the parent passed in is nil" do
scope = mock 'scope'
newscope = @compiler.newscope(nil)
- newscope.parent.should equal(@compiler.topscope)
+ expect(newscope.parent).to equal(@compiler.topscope)
end
end
describe "when compiling" do
def compile_methods
[:set_node_parameters, :evaluate_main, :evaluate_ast_node, :evaluate_node_classes, :evaluate_generators, :fail_on_unevaluated,
:finish, :store, :extract, :evaluate_relationships]
end
# Stub all of the main compile methods except the ones we're specifically interested in.
def compile_stub(*except)
(compile_methods - except).each { |m| @compiler.stubs(m) }
end
it "should set node parameters as variables in the top scope" do
params = {"a" => "b", "c" => "d"}
@node.stubs(:parameters).returns(params)
compile_stub(:set_node_parameters)
@compiler.compile
- @compiler.topscope['a'].should == "b"
- @compiler.topscope['c'].should == "d"
+ expect(@compiler.topscope['a']).to eq("b")
+ expect(@compiler.topscope['c']).to eq("d")
end
it "should set the client and server versions on the catalog" do
params = {"clientversion" => "2", "serverversion" => "3"}
@node.stubs(:parameters).returns(params)
compile_stub(:set_node_parameters)
@compiler.compile
- @compiler.catalog.client_version.should == "2"
- @compiler.catalog.server_version.should == "3"
+ expect(@compiler.catalog.client_version).to eq("2")
+ expect(@compiler.catalog.server_version).to eq("3")
end
it "should evaluate the main class if it exists" do
compile_stub(:evaluate_main)
main_class = @known_resource_types.add Puppet::Resource::Type.new(:hostclass, "")
main_class.expects(:evaluate_code).with { |r| r.is_a?(Puppet::Parser::Resource) }
@compiler.topscope.expects(:source=).with(main_class)
@compiler.compile
end
it "should create a new, empty 'main' if no main class exists" do
compile_stub(:evaluate_main)
@compiler.compile
- @known_resource_types.find_hostclass("").should be_instance_of(Puppet::Resource::Type)
+ expect(@known_resource_types.find_hostclass("")).to be_instance_of(Puppet::Resource::Type)
end
it "should add an edge between the main stage and main class" do
@compiler.compile
- (stage = @compiler.catalog.resource(:stage, "main")).should be_instance_of(Puppet::Parser::Resource)
- (klass = @compiler.catalog.resource(:class, "")).should be_instance_of(Puppet::Parser::Resource)
+ expect(stage = @compiler.catalog.resource(:stage, "main")).to be_instance_of(Puppet::Parser::Resource)
+ expect(klass = @compiler.catalog.resource(:class, "")).to be_instance_of(Puppet::Parser::Resource)
- @compiler.catalog.edge?(stage, klass).should be_true
+ expect(@compiler.catalog.edge?(stage, klass)).to be_truthy
end
it "should evaluate all added collections" do
colls = []
# And when the collections fail to evaluate.
colls << mock("coll1-false")
colls << mock("coll2-false")
colls.each { |c| c.expects(:evaluate).returns(false) }
@compiler.add_collection(colls[0])
@compiler.add_collection(colls[1])
compile_stub(:evaluate_generators)
@compiler.compile
end
it "should ignore builtin resources" do
resource = resource(:file, "testing")
@compiler.add_resource(@scope, resource)
resource.expects(:evaluate).never
@compiler.compile
end
it "should evaluate unevaluated resources" do
resource = CompilerTestResource.new(:file, "testing")
@compiler.add_resource(@scope, resource)
# We have to now mark the resource as evaluated
resource.expects(:evaluate).with { |*whatever| resource.evaluated = true }
@compiler.compile
end
it "should not evaluate already-evaluated resources" do
resource = resource(:file, "testing")
resource.stubs(:evaluated?).returns true
@compiler.add_resource(@scope, resource)
resource.expects(:evaluate).never
@compiler.compile
end
it "should evaluate unevaluated resources created by evaluating other resources" do
resource = CompilerTestResource.new(:file, "testing")
@compiler.add_resource(@scope, resource)
resource2 = CompilerTestResource.new(:file, "other")
# We have to now mark the resource as evaluated
resource.expects(:evaluate).with { |*whatever| resource.evaluated = true; @compiler.add_resource(@scope, resource2) }
resource2.expects(:evaluate).with { |*whatever| resource2.evaluated = true }
@compiler.compile
end
describe "when finishing" do
before do
@compiler.send(:evaluate_main)
@catalog = @compiler.catalog
end
def add_resource(name, parent = nil)
resource = Puppet::Parser::Resource.new "file", name, :scope => @scope
@compiler.add_resource(@scope, resource)
@catalog.add_edge(parent, resource) if parent
resource
end
it "should call finish() on all resources" do
# Add a resource that does respond to :finish
resource = Puppet::Parser::Resource.new "file", "finish", :scope => @scope
resource.expects(:finish)
@compiler.add_resource(@scope, resource)
# And one that does not
dnf_resource = stub_everything "dnf", :ref => "File[dnf]", :type => "file"
@compiler.add_resource(@scope, dnf_resource)
@compiler.send(:finish)
end
it "should call finish() in add_resource order" do
resources = sequence('resources')
resource1 = add_resource("finish1")
resource1.expects(:finish).in_sequence(resources)
resource2 = add_resource("finish2")
resource2.expects(:finish).in_sequence(resources)
@compiler.send(:finish)
end
it "should add each container's metaparams to its contained resources" do
main = @catalog.resource(:class, :main)
main[:noop] = true
resource1 = add_resource("meh", main)
@compiler.send(:finish)
- resource1[:noop].should be_true
+ expect(resource1[:noop]).to be_truthy
end
it "should add metaparams recursively" do
main = @catalog.resource(:class, :main)
main[:noop] = true
resource1 = add_resource("meh", main)
resource2 = add_resource("foo", resource1)
@compiler.send(:finish)
- resource2[:noop].should be_true
+ expect(resource2[:noop]).to be_truthy
end
it "should prefer metaparams from immediate parents" do
main = @catalog.resource(:class, :main)
main[:noop] = true
resource1 = add_resource("meh", main)
resource2 = add_resource("foo", resource1)
resource1[:noop] = false
@compiler.send(:finish)
- resource2[:noop].should be_false
+ expect(resource2[:noop]).to be_falsey
end
it "should merge tags downward" do
main = @catalog.resource(:class, :main)
main.tag("one")
resource1 = add_resource("meh", main)
resource1.tag "two"
resource2 = add_resource("foo", resource1)
@compiler.send(:finish)
- resource2.tags.should be_include("one")
- resource2.tags.should be_include("two")
+ expect(resource2.tags).to be_include("one")
+ expect(resource2.tags).to be_include("two")
end
it "should work if only middle resources have metaparams set" do
main = @catalog.resource(:class, :main)
resource1 = add_resource("meh", main)
resource1[:noop] = true
resource2 = add_resource("foo", resource1)
@compiler.send(:finish)
- resource2[:noop].should be_true
+ expect(resource2[:noop]).to be_truthy
end
end
it "should return added resources in add order" do
resource1 = resource(:file, "yay")
@compiler.add_resource(@scope, resource1)
resource2 = resource(:file, "youpi")
@compiler.add_resource(@scope, resource2)
- @compiler.resources.should == [resource1, resource2]
+ expect(@compiler.resources).to eq([resource1, resource2])
end
it "should add resources that do not conflict with existing resources" do
resource = resource(:file, "yay")
@compiler.add_resource(@scope, resource)
- @compiler.catalog.should be_vertex(resource)
+ expect(@compiler.catalog).to be_vertex(resource)
end
it "should fail to add resources that conflict with existing resources" do
path = make_absolute("/foo")
file1 = resource(:file, path)
file2 = resource(:file, path)
@compiler.add_resource(@scope, file1)
- lambda { @compiler.add_resource(@scope, file2) }.should raise_error(Puppet::Resource::Catalog::DuplicateResourceError)
+ expect { @compiler.add_resource(@scope, file2) }.to raise_error(Puppet::Resource::Catalog::DuplicateResourceError)
end
it "should add an edge from the scope resource to the added resource" do
resource = resource(:file, "yay")
@compiler.add_resource(@scope, resource)
- @compiler.catalog.should be_edge(@scope.resource, resource)
+ expect(@compiler.catalog).to be_edge(@scope.resource, resource)
end
it "should not add non-class resources that don't specify a stage to the 'main' stage" do
main = @compiler.catalog.resource(:stage, :main)
resource = resource(:file, "foo")
@compiler.add_resource(@scope, resource)
- @compiler.catalog.should_not be_edge(main, resource)
+ expect(@compiler.catalog).not_to be_edge(main, resource)
end
it "should not add any parent-edges to stages" do
stage = resource(:stage, "other")
@compiler.add_resource(@scope, stage)
@scope.resource = resource(:class, "foo")
- @compiler.catalog.edge?(@scope.resource, stage).should be_false
+ expect(@compiler.catalog.edge?(@scope.resource, stage)).to be_falsey
end
it "should not attempt to add stages to other stages" do
other_stage = resource(:stage, "other")
second_stage = resource(:stage, "second")
@compiler.add_resource(@scope, other_stage)
@compiler.add_resource(@scope, second_stage)
second_stage[:stage] = "other"
- @compiler.catalog.edge?(other_stage, second_stage).should be_false
+ expect(@compiler.catalog.edge?(other_stage, second_stage)).to be_falsey
end
it "should have a method for looking up resources" do
resource = resource(:yay, "foo")
@compiler.add_resource(@scope, resource)
- @compiler.findresource("Yay[foo]").should equal(resource)
+ expect(@compiler.findresource("Yay[foo]")).to equal(resource)
end
it "should be able to look resources up by type and title" do
resource = resource(:yay, "foo")
@compiler.add_resource(@scope, resource)
- @compiler.findresource("Yay", "foo").should equal(resource)
+ expect(@compiler.findresource("Yay", "foo")).to equal(resource)
end
it "should not evaluate virtual defined resources" do
resource = resource(:file, "testing")
resource.virtual = true
@compiler.add_resource(@scope, resource)
resource.expects(:evaluate).never
@compiler.compile
end
end
describe "when evaluating collections" do
it "should evaluate each collection" do
2.times { |i|
coll = mock 'coll%s' % i
@compiler.add_collection(coll)
# This is the hard part -- we have to emulate the fact that
# collections delete themselves if they are done evaluating.
coll.expects(:evaluate).with do
@compiler.delete_collection(coll)
end
}
@compiler.compile
end
it "should not fail when there are unevaluated resource collections that do not refer to specific resources" do
coll = stub 'coll', :evaluate => false
coll.expects(:unresolved_resources).returns(nil)
@compiler.add_collection(coll)
- lambda { @compiler.compile }.should_not raise_error
+ expect { @compiler.compile }.not_to raise_error
end
it "should fail when there are unevaluated resource collections that refer to a specific resource" do
coll = stub 'coll', :evaluate => false
coll.expects(:unresolved_resources).returns(:something)
@compiler.add_collection(coll)
- lambda { @compiler.compile }.should raise_error(Puppet::ParseError, 'Failed to realize virtual resources something')
+ expect { @compiler.compile }.to raise_error(Puppet::ParseError, 'Failed to realize virtual resources something')
end
it "should fail when there are unevaluated resource collections that refer to multiple specific resources" do
coll = stub 'coll', :evaluate => false
coll.expects(:unresolved_resources).returns([:one, :two])
@compiler.add_collection(coll)
- lambda { @compiler.compile }.should raise_error(Puppet::ParseError, 'Failed to realize virtual resources one, two')
+ expect { @compiler.compile }.to raise_error(Puppet::ParseError, 'Failed to realize virtual resources one, two')
end
end
describe "when evaluating relationships" do
it "should evaluate each relationship with its catalog" do
dep = stub 'dep'
dep.expects(:evaluate).with(@compiler.catalog)
@compiler.add_relationship dep
@compiler.evaluate_relationships
end
end
describe "when told to evaluate missing classes" do
it "should fail if there's no source listed for the scope" do
scope = stub 'scope', :source => nil
- proc { @compiler.evaluate_classes(%w{one two}, scope) }.should raise_error(Puppet::DevError)
+ expect { @compiler.evaluate_classes(%w{one two}, scope) }.to raise_error(Puppet::DevError)
end
it "should raise an error if a class is not found" do
@scope.expects(:find_hostclass).with("notfound").returns(nil)
- lambda{ @compiler.evaluate_classes(%w{notfound}, @scope) }.should raise_error(Puppet::Error, /Could not find class/)
+ expect{ @compiler.evaluate_classes(%w{notfound}, @scope) }.to raise_error(Puppet::Error, /Could not find class/)
end
it "should raise an error when it can't find class" do
klasses = {'foo'=>nil}
@node.classes = klasses
@compiler.topscope.expects(:find_hostclass).with('foo').returns(nil)
- lambda{ @compiler.compile }.should raise_error(Puppet::Error, /Could not find class foo for testnode/)
+ expect{ @compiler.compile }.to raise_error(Puppet::Error, /Could not find class foo for testnode/)
end
end
describe "when evaluating found classes" do
before do
Puppet.settings[:data_binding_terminus] = "none"
@class = stub 'class', :name => "my::class"
@scope.stubs(:find_hostclass).with("myclass").returns(@class)
@resource = stub 'resource', :ref => "Class[myclass]", :type => "file"
end
around do |example|
Puppet.override(
:environments => Puppet::Environments::Static.new(environment),
:description => "Static loader for specs"
) do
example.run
end
end
it "should evaluate each class" do
@compiler.catalog.stubs(:tag)
@class.expects(:ensure_in_catalog).with(@scope)
@scope.stubs(:class_scope).with(@class)
@compiler.evaluate_classes(%w{myclass}, @scope)
end
describe "and the classes are specified as a hash with parameters" do
before do
@node.classes = {}
@ast_obj = Puppet::Parser::AST::Leaf.new(:value => 'foo')
end
# Define the given class with default parameters
def define_class(name, parameters)
@node.classes[name] = parameters
klass = Puppet::Resource::Type.new(:hostclass, name, :arguments => {'p1' => @ast_obj, 'p2' => @ast_obj})
@compiler.topscope.known_resource_types.add klass
end
def compile
@catalog = @compiler.compile
end
it "should record which classes are evaluated" do
classes = {'foo'=>{}, 'bar::foo'=>{}, 'bar'=>{}}
classes.each { |c, params| define_class(c, params) }
compile()
- classes.each { |name, p| @catalog.classes.should include(name) }
+ classes.each { |name, p| expect(@catalog.classes).to include(name) }
end
it "should provide default values for parameters that have no values specified" do
define_class('foo', {})
compile()
- @catalog.resource(:class, 'foo')['p1'].should == "foo"
+ expect(@catalog.resource(:class, 'foo')['p1']).to eq("foo")
end
it "should use any provided values" do
define_class('foo', {'p1' => 'real_value'})
compile()
- @catalog.resource(:class, 'foo')['p1'].should == "real_value"
+ expect(@catalog.resource(:class, 'foo')['p1']).to eq("real_value")
end
it "should support providing some but not all values" do
define_class('foo', {'p1' => 'real_value'})
compile()
- @catalog.resource(:class, 'Foo')['p1'].should == "real_value"
- @catalog.resource(:class, 'Foo')['p2'].should == "foo"
+ expect(@catalog.resource(:class, 'Foo')['p1']).to eq("real_value")
+ expect(@catalog.resource(:class, 'Foo')['p2']).to eq("foo")
end
it "should ensure each node class is in catalog and has appropriate tags" do
klasses = ['bar::foo']
@node.classes = klasses
ast_obj = Puppet::Parser::AST::Leaf.new(:value => 'foo')
klasses.each do |name|
klass = Puppet::Resource::Type.new(:hostclass, name, :arguments => {'p1' => ast_obj, 'p2' => ast_obj})
@compiler.topscope.known_resource_types.add klass
end
catalog = @compiler.compile
r2 = catalog.resources.detect {|r| r.title == 'Bar::Foo' }
- r2.tags.should == Puppet::Util::TagSet.new(['bar::foo', 'class', 'bar', 'foo'])
+ expect(r2.tags).to eq(Puppet::Util::TagSet.new(['bar::foo', 'class', 'bar', 'foo']))
end
end
it "should fail if required parameters are missing" do
klass = {'foo'=>{'a'=>'one'}}
@node.classes = klass
klass = Puppet::Resource::Type.new(:hostclass, 'foo', :arguments => {'a' => nil, 'b' => nil})
@compiler.topscope.known_resource_types.add klass
- lambda { @compiler.compile }.should raise_error(Puppet::ParseError, "Must pass b to Class[Foo]")
+ expect { @compiler.compile }.to raise_error(Puppet::ParseError, "Must pass b to Class[Foo]")
end
it "should fail if invalid parameters are passed" do
klass = {'foo'=>{'3'=>'one'}}
@node.classes = klass
klass = Puppet::Resource::Type.new(:hostclass, 'foo', :arguments => {})
@compiler.topscope.known_resource_types.add klass
- lambda { @compiler.compile }.should raise_error(Puppet::ParseError, "Invalid parameter: '3' on Class[Foo]")
+ expect { @compiler.compile }.to raise_error(Puppet::ParseError, "Invalid parameter: '3' on Class[Foo]")
end
it "should ensure class is in catalog without params" do
@node.classes = klasses = {'foo'=>nil}
foo = Puppet::Resource::Type.new(:hostclass, 'foo')
@compiler.topscope.known_resource_types.add foo
catalog = @compiler.compile
- catalog.classes.should include 'foo'
+ expect(catalog.classes).to include 'foo'
end
it "should not evaluate the resources created for found classes unless asked" do
@compiler.catalog.stubs(:tag)
@resource.expects(:evaluate).never
@class.expects(:ensure_in_catalog).returns(@resource)
@scope.stubs(:class_scope).with(@class)
@compiler.evaluate_classes(%w{myclass}, @scope)
end
it "should immediately evaluate the resources created for found classes when asked" do
@compiler.catalog.stubs(:tag)
@resource.expects(:evaluate)
@class.expects(:ensure_in_catalog).returns(@resource)
@scope.stubs(:class_scope).with(@class)
@compiler.evaluate_classes(%w{myclass}, @scope, false)
end
it "should skip classes that have already been evaluated" do
@compiler.catalog.stubs(:tag)
@scope.stubs(:class_scope).with(@class).returns(@scope)
@compiler.expects(:add_resource).never
@resource.expects(:evaluate).never
Puppet::Parser::Resource.expects(:new).never
@compiler.evaluate_classes(%w{myclass}, @scope, false)
end
it "should skip classes previously evaluated with different capitalization" do
@compiler.catalog.stubs(:tag)
@scope.stubs(:find_hostclass).with("MyClass").returns(@class)
@scope.stubs(:class_scope).with(@class).returns(@scope)
@compiler.expects(:add_resource).never
@resource.expects(:evaluate).never
Puppet::Parser::Resource.expects(:new).never
@compiler.evaluate_classes(%w{MyClass}, @scope, false)
end
end
describe "when evaluating AST nodes with no AST nodes present" do
it "should do nothing" do
@compiler.expects(:ast_nodes?).returns(false)
@compiler.known_resource_types.expects(:nodes).never
Puppet::Parser::Resource.expects(:new).never
@compiler.send(:evaluate_ast_node)
end
end
describe "when evaluating AST nodes with AST nodes present" do
before do
@compiler.known_resource_types.stubs(:nodes?).returns true
# Set some names for our test
@node.stubs(:names).returns(%w{a b c})
@compiler.known_resource_types.stubs(:node).with("a").returns(nil)
@compiler.known_resource_types.stubs(:node).with("b").returns(nil)
@compiler.known_resource_types.stubs(:node).with("c").returns(nil)
# It should check this last, of course.
@compiler.known_resource_types.stubs(:node).with("default").returns(nil)
end
it "should fail if the named node cannot be found" do
- proc { @compiler.send(:evaluate_ast_node) }.should raise_error(Puppet::ParseError)
+ expect { @compiler.send(:evaluate_ast_node) }.to raise_error(Puppet::ParseError)
end
it "should evaluate the first node class matching the node name" do
node_class = stub 'node', :name => "c", :evaluate_code => nil
@compiler.known_resource_types.stubs(:node).with("c").returns(node_class)
node_resource = stub 'node resource', :ref => "Node[c]", :evaluate => nil, :type => "node"
node_class.expects(:ensure_in_catalog).returns(node_resource)
@compiler.compile
end
it "should match the default node if no matching node can be found" do
node_class = stub 'node', :name => "default", :evaluate_code => nil
@compiler.known_resource_types.stubs(:node).with("default").returns(node_class)
node_resource = stub 'node resource', :ref => "Node[default]", :evaluate => nil, :type => "node"
node_class.expects(:ensure_in_catalog).returns(node_resource)
@compiler.compile
end
it "should evaluate the node resource immediately rather than using lazy evaluation" do
node_class = stub 'node', :name => "c"
@compiler.known_resource_types.stubs(:node).with("c").returns(node_class)
node_resource = stub 'node resource', :ref => "Node[c]", :type => "node"
node_class.expects(:ensure_in_catalog).returns(node_resource)
node_resource.expects(:evaluate)
@compiler.send(:evaluate_ast_node)
end
end
describe "when evaluating node classes" do
include PuppetSpec::Compiler
describe "when provided classes in array format" do
let(:node) { Puppet::Node.new('someone', :classes => ['something']) }
describe "when the class exists" do
it "should succeed if the class is already included" do
manifest = <<-MANIFEST
class something {}
include something
MANIFEST
catalog = compile_to_catalog(manifest, node)
- catalog.resource('Class', 'Something').should_not be_nil
+ expect(catalog.resource('Class', 'Something')).not_to be_nil
end
it "should evaluate the class without parameters if it's not already included" do
manifest = "class something {}"
catalog = compile_to_catalog(manifest, node)
- catalog.resource('Class', 'Something').should_not be_nil
+ expect(catalog.resource('Class', 'Something')).not_to be_nil
end
end
it "should fail if the class doesn't exist" do
expect { compile_to_catalog('', node) }.to raise_error(Puppet::Error, /Could not find class something/)
end
end
describe "when provided classes in hash format" do
describe "for classes without parameters" do
let(:node) { Puppet::Node.new('someone', :classes => {'something' => {}}) }
describe "when the class exists" do
it "should succeed if the class is already included" do
manifest = <<-MANIFEST
class something {}
include something
MANIFEST
catalog = compile_to_catalog(manifest, node)
- catalog.resource('Class', 'Something').should_not be_nil
+ expect(catalog.resource('Class', 'Something')).not_to be_nil
end
it "should evaluate the class if it's not already included" do
manifest = <<-MANIFEST
class something {}
MANIFEST
catalog = compile_to_catalog(manifest, node)
- catalog.resource('Class', 'Something').should_not be_nil
+ expect(catalog.resource('Class', 'Something')).not_to be_nil
end
end
it "should fail if the class doesn't exist" do
expect { compile_to_catalog('', node) }.to raise_error(Puppet::Error, /Could not find class something/)
end
end
describe "for classes with parameters" do
let(:node) { Puppet::Node.new('someone', :classes => {'something' => {'configuron' => 'defrabulated'}}) }
describe "when the class exists" do
it "should fail if the class is already included" do
manifest = <<-MANIFEST
class something($configuron=frabulated) {}
include something
MANIFEST
expect { compile_to_catalog(manifest, node) }.to raise_error(Puppet::Error, /Class\[Something\] is already declared/)
end
it "should evaluate the class if it's not already included" do
manifest = <<-MANIFEST
class something($configuron=frabulated) {}
MANIFEST
catalog = compile_to_catalog(manifest, node)
resource = catalog.resource('Class', 'Something')
- resource['configuron'].should == 'defrabulated'
+ expect(resource['configuron']).to eq('defrabulated')
end
end
it "should fail if the class doesn't exist" do
expect { compile_to_catalog('', node) }.to raise_error(Puppet::Error, /Could not find class something/)
end
it 'evaluates classes declared with parameters before unparameterized classes' do
node = Puppet::Node.new('someone', :classes => { 'app::web' => {}, 'app' => { 'port' => 8080 } })
manifest = <<-MANIFEST
class app($port = 80) { }
class app::web($port = $app::port) inherits app {
notify { expected: message => "$port" }
}
MANIFEST
catalog = compile_to_catalog(manifest, node)
expect(catalog).to have_resource("Class[App]").with_parameter(:port, 8080)
expect(catalog).to have_resource("Class[App::Web]")
expect(catalog).to have_resource("Notify[expected]").with_parameter(:message, "8080")
end
end
end
end
describe "when managing resource overrides" do
before do
@override = stub 'override', :ref => "File[/foo]", :type => "my"
@resource = resource(:file, "/foo")
end
it "should be able to store overrides" do
- lambda { @compiler.add_override(@override) }.should_not raise_error
+ expect { @compiler.add_override(@override) }.not_to raise_error
end
it "should apply overrides to the appropriate resources" do
@compiler.add_resource(@scope, @resource)
@resource.expects(:merge).with(@override)
@compiler.add_override(@override)
@compiler.compile
end
it "should accept overrides before the related resource has been created" do
@resource.expects(:merge).with(@override)
# First store the override
@compiler.add_override(@override)
# Then the resource
@compiler.add_resource(@scope, @resource)
# And compile, so they get resolved
@compiler.compile
end
it "should fail if the compile is finished and resource overrides have not been applied" do
@compiler.add_override(@override)
- lambda { @compiler.compile }.should raise_error Puppet::ParseError, 'Could not find resource(s) File[/foo] for overriding'
+ expect { @compiler.compile }.to raise_error Puppet::ParseError, 'Could not find resource(s) File[/foo] for overriding'
end
end
end
diff --git a/spec/unit/parser/functions/create_resources_spec.rb b/spec/unit/parser/functions/create_resources_spec.rb
index 8bf38cf5a..4288912ca 100755
--- a/spec/unit/parser/functions/create_resources_spec.rb
+++ b/spec/unit/parser/functions/create_resources_spec.rb
@@ -1,213 +1,213 @@
require 'puppet'
require 'spec_helper'
require 'puppet_spec/compiler'
describe 'function for dynamically creating resources' do
include PuppetSpec::Compiler
before :each do
node = Puppet::Node.new("floppy", :environment => 'production')
@compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(@compiler)
@topscope = @scope.compiler.topscope
@scope.parent = @topscope
Puppet::Parser::Functions.function(:create_resources)
end
it "should exist" do
- Puppet::Parser::Functions.function(:create_resources).should == "function_create_resources"
+ expect(Puppet::Parser::Functions.function(:create_resources)).to eq("function_create_resources")
end
it 'should require two or three arguments' do
expect { @scope.function_create_resources(['foo']) }.to raise_error(ArgumentError, 'create_resources(): Wrong number of arguments given (1 for minimum 2)')
expect { @scope.function_create_resources(['foo', 'bar', 'blah', 'baz']) }.to raise_error(ArgumentError, 'create_resources(): wrong number of arguments (4; must be 2 or 3)')
end
it 'should require second argument to be a hash' do
expect { @scope.function_create_resources(['foo','bar']) }.to raise_error(ArgumentError, 'create_resources(): second argument must be a hash')
end
it 'should require optional third argument to be a hash' do
expect { @scope.function_create_resources(['foo',{},'foo']) }.to raise_error(ArgumentError, 'create_resources(): third argument, if provided, must be a hash')
end
describe 'when creating native types' do
it 'empty hash should not cause resources to be added' do
noop_catalog = compile_to_catalog("create_resources('file', {})")
empty_catalog = compile_to_catalog("")
- noop_catalog.resources.size.should == empty_catalog.resources.size
+ expect(noop_catalog.resources.size).to eq(empty_catalog.resources.size)
end
it 'should be able to add' do
catalog = compile_to_catalog("create_resources('file', {'/etc/foo'=>{'ensure'=>'present'}})")
- catalog.resource(:file, "/etc/foo")['ensure'].should == 'present'
+ expect(catalog.resource(:file, "/etc/foo")['ensure']).to eq('present')
end
it 'should be able to add virtual resources' do
catalog = compile_to_catalog("create_resources('@file', {'/etc/foo'=>{'ensure'=>'present'}})\nrealize(File['/etc/foo'])")
- catalog.resource(:file, "/etc/foo")['ensure'].should == 'present'
+ expect(catalog.resource(:file, "/etc/foo")['ensure']).to eq('present')
end
it 'should be able to add exported resources' do
catalog = compile_to_catalog("create_resources('@@file', {'/etc/foo'=>{'ensure'=>'present'}}) realize(File['/etc/foo'])")
- catalog.resource(:file, "/etc/foo")['ensure'].should == 'present'
- catalog.resource(:file, "/etc/foo").exported.should == true
+ expect(catalog.resource(:file, "/etc/foo")['ensure']).to eq('present')
+ expect(catalog.resource(:file, "/etc/foo").exported).to eq(true)
end
it 'should accept multiple types' do
catalog = compile_to_catalog("create_resources('notify', {'foo'=>{'message'=>'one'}, 'bar'=>{'message'=>'two'}})")
- catalog.resource(:notify, "foo")['message'].should == 'one'
- catalog.resource(:notify, "bar")['message'].should == 'two'
+ expect(catalog.resource(:notify, "foo")['message']).to eq('one')
+ expect(catalog.resource(:notify, "bar")['message']).to eq('two')
end
it 'should fail to add non-existing type' do
expect do
@scope.function_create_resources(['create-resource-foo', { 'foo' => {} }])
end.to raise_error(ArgumentError, /Invalid resource type create-resource-foo/)
end
it 'should be able to add edges' do
rg = compile_to_relationship_graph("notify { test: }\n create_resources('notify', {'foo'=>{'require'=>'Notify[test]'}})")
test = rg.vertices.find { |v| v.title == 'test' }
foo = rg.vertices.find { |v| v.title == 'foo' }
- test.must be
- foo.must be
- rg.path_between(test,foo).should be
+ expect(test).to be
+ expect(foo).to be
+ expect(rg.path_between(test,foo)).to be
end
it 'should account for default values' do
catalog = compile_to_catalog("create_resources('file', {'/etc/foo'=>{'ensure'=>'present'}, '/etc/baz'=>{'group'=>'food'}}, {'group' => 'bar'})")
- catalog.resource(:file, "/etc/foo")['group'].should == 'bar'
- catalog.resource(:file, "/etc/baz")['group'].should == 'food'
+ expect(catalog.resource(:file, "/etc/foo")['group']).to eq('bar')
+ expect(catalog.resource(:file, "/etc/baz")['group']).to eq('food')
end
end
describe 'when dynamically creating resource types' do
it 'should be able to create defined resource types' do
catalog = compile_to_catalog(<<-MANIFEST)
define foocreateresource($one) {
notify { $name: message => $one }
}
create_resources('foocreateresource', {'blah'=>{'one'=>'two'}})
MANIFEST
- catalog.resource(:notify, "blah")['message'].should == 'two'
+ expect(catalog.resource(:notify, "blah")['message']).to eq('two')
end
it 'should fail if defines are missing params' do
expect {
compile_to_catalog(<<-MANIFEST)
define foocreateresource($one) {
notify { $name: message => $one }
}
create_resources('foocreateresource', {'blah'=>{}})
MANIFEST
}.to raise_error(Puppet::Error, 'Must pass one to Foocreateresource[blah] on node foonode')
end
it 'should be able to add multiple defines' do
catalog = compile_to_catalog(<<-MANIFEST)
define foocreateresource($one) {
notify { $name: message => $one }
}
create_resources('foocreateresource', {'blah'=>{'one'=>'two'}, 'blaz'=>{'one'=>'three'}})
MANIFEST
- catalog.resource(:notify, "blah")['message'].should == 'two'
- catalog.resource(:notify, "blaz")['message'].should == 'three'
+ expect(catalog.resource(:notify, "blah")['message']).to eq('two')
+ expect(catalog.resource(:notify, "blaz")['message']).to eq('three')
end
it 'should be able to add edges' do
rg = compile_to_relationship_graph(<<-MANIFEST)
define foocreateresource($one) {
notify { $name: message => $one }
}
notify { test: }
create_resources('foocreateresource', {'blah'=>{'one'=>'two', 'require' => 'Notify[test]'}})
MANIFEST
test = rg.vertices.find { |v| v.title == 'test' }
blah = rg.vertices.find { |v| v.title == 'blah' }
- test.must be
- blah.must be
- rg.path_between(test,blah).should be
+ expect(test).to be
+ expect(blah).to be
+ expect(rg.path_between(test,blah)).to be
end
it 'should account for default values' do
catalog = compile_to_catalog(<<-MANIFEST)
define foocreateresource($one) {
notify { $name: message => $one }
}
create_resources('foocreateresource', {'blah'=>{}}, {'one' => 'two'})
MANIFEST
- catalog.resource(:notify, "blah")['message'].should == 'two'
+ expect(catalog.resource(:notify, "blah")['message']).to eq('two')
end
end
describe 'when creating classes' do
it 'should be able to create classes' do
catalog = compile_to_catalog(<<-MANIFEST)
class bar($one) {
notify { test: message => $one }
}
create_resources('class', {'bar'=>{'one'=>'two'}})
MANIFEST
- catalog.resource(:notify, "test")['message'].should == 'two'
- catalog.resource(:class, "bar").should_not be_nil
+ expect(catalog.resource(:notify, "test")['message']).to eq('two')
+ expect(catalog.resource(:class, "bar")).not_to be_nil
end
it 'should fail to create non-existing classes' do
expect do
compile_to_catalog(<<-MANIFEST)
create_resources('class', {'blah'=>{'one'=>'two'}})
MANIFEST
end.to raise_error(Puppet::Error, /Could not find declared class blah at line 1:11 on node foonode/)
end
it 'should be able to add edges' do
rg = compile_to_relationship_graph(<<-MANIFEST)
class bar($one) {
notify { test: message => $one }
}
notify { tester: }
create_resources('class', {'bar'=>{'one'=>'two', 'require' => 'Notify[tester]'}})
MANIFEST
test = rg.vertices.find { |v| v.title == 'test' }
tester = rg.vertices.find { |v| v.title == 'tester' }
- test.must be
- tester.must be
- rg.path_between(tester,test).should be
+ expect(test).to be
+ expect(tester).to be
+ expect(rg.path_between(tester,test)).to be
end
it 'should account for default values' do
catalog = compile_to_catalog(<<-MANIFEST)
class bar($one) {
notify { test: message => $one }
}
create_resources('class', {'bar'=>{}}, {'one' => 'two'})
MANIFEST
- catalog.resource(:notify, "test")['message'].should == 'two'
- catalog.resource(:class, "bar").should_not be_nil
+ expect(catalog.resource(:notify, "test")['message']).to eq('two')
+ expect(catalog.resource(:class, "bar")).not_to be_nil
end
it 'should fail with a correct error message if the syntax of an imported file is incorrect' do
expect{
Puppet[:modulepath] = my_fixture_dir
compile_to_catalog('include foo')
}.to raise_error(Puppet::Error, /Syntax error at.*/)
end
end
end
diff --git a/spec/unit/parser/functions/defined_spec.rb b/spec/unit/parser/functions/defined_spec.rb
index c3c0c8ce8..4f54d9606 100755
--- a/spec/unit/parser/functions/defined_spec.rb
+++ b/spec/unit/parser/functions/defined_spec.rb
@@ -1,115 +1,115 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/pops'
describe "the 'defined' function" do
before :each do
@compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("foo"))
@scope = Puppet::Parser::Scope.new(@compiler)
end
it "exists" do
expect(Puppet::Parser::Functions.function("defined")).to be_eql("function_defined")
end
it "is true when the name is defined as a class" do
@scope.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "yayness")
- expect(@scope.function_defined(["yayness"])).to be_true
+ expect(@scope.function_defined(["yayness"])).to be_truthy
end
it "is true when the name is defined as a definition" do
@scope.known_resource_types.add Puppet::Resource::Type.new(:definition, "yayness")
- expect(@scope.function_defined(["yayness"])).to be_true
+ expect(@scope.function_defined(["yayness"])).to be_truthy
end
it "is true when the name is defined as a builtin type" do
- expect(@scope.function_defined(["file"])).to be_true
+ expect(@scope.function_defined(["file"])).to be_truthy
end
it "is true when any of the provided names are defined" do
@scope.known_resource_types.add Puppet::Resource::Type.new(:definition, "yayness")
- expect(@scope.function_defined(["meh", "yayness", "booness"])).to be_true
+ expect(@scope.function_defined(["meh", "yayness", "booness"])).to be_truthy
end
it "is false when a single given name is not defined" do
- expect(@scope.function_defined(["meh"])).to be_false
+ expect(@scope.function_defined(["meh"])).to be_falsey
end
it "is false when none of the names are defined" do
- expect(@scope.function_defined(["meh", "yayness", "booness"])).to be_false
+ expect(@scope.function_defined(["meh", "yayness", "booness"])).to be_falsey
end
it "is true when a resource reference is provided and the resource is in the catalog" do
resource = Puppet::Resource.new("file", "/my/file")
@compiler.add_resource(@scope, resource)
- expect(@scope.function_defined([resource])).to be_true
+ expect(@scope.function_defined([resource])).to be_truthy
end
context "with string variable references" do
it "is true when variable exists in scope" do
@scope['x'] = 'something'
- expect(@scope.function_defined(['$x'])).to be_true
+ expect(@scope.function_defined(['$x'])).to be_truthy
end
it "is true when absolute referenced variable exists in scope" do
@compiler.topscope['x'] = 'something'
# Without this magic linking, scope cannot find the global scope via the name ''
# which is the name of "topscope". (This is one of many problems with the scope impl)
# When running real code, scopes are always linked up this way.
@scope.class_set('', @compiler.topscope)
- expect(@scope.function_defined(['$::x'])).to be_true
+ expect(@scope.function_defined(['$::x'])).to be_truthy
end
it "is true when at least one variable exists in scope" do
@scope['x'] = 'something'
- expect(@scope.function_defined(['$y', '$x', '$z'])).to be_true
+ expect(@scope.function_defined(['$y', '$x', '$z'])).to be_truthy
end
it "is false when variable does not exist in scope" do
- expect(@scope.function_defined(['$x'])).to be_false
+ expect(@scope.function_defined(['$x'])).to be_falsey
end
end
it "is true when a resource type reference is provided, and the resource is in the catalog" do
resource = Puppet::Resource.new("file", "/my/file")
@compiler.add_resource(@scope, resource)
resource_type = Puppet::Pops::Types::TypeFactory.resource('file', '/my/file')
- expect(@scope.function_defined([resource_type])).to be_true
+ expect(@scope.function_defined([resource_type])).to be_truthy
end
it "raises an argument error if you ask if Resource is defined" do
resource_type = Puppet::Pops::Types::TypeFactory.resource
expect { @scope.function_defined([resource_type]) }.to raise_error(ArgumentError, /reference to all.*type/)
end
it "is true if referencing a built in type" do
resource_type = Puppet::Pops::Types::TypeFactory.resource('file')
- expect(@scope.function_defined([resource_type])).to be_true
+ expect(@scope.function_defined([resource_type])).to be_truthy
end
it "is true if referencing a defined type" do
@scope.known_resource_types.add Puppet::Resource::Type.new(:definition, "yayness")
resource_type = Puppet::Pops::Types::TypeFactory.resource('yayness')
- expect(@scope.function_defined([resource_type])).to be_true
+ expect(@scope.function_defined([resource_type])).to be_truthy
end
it "is false if referencing an undefined type" do
resource_type = Puppet::Pops::Types::TypeFactory.resource('barbershops')
- expect(@scope.function_defined([resource_type])).to be_false
+ expect(@scope.function_defined([resource_type])).to be_falsey
end
it "is true when a class type is provided" do
@scope.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "cowabunga")
class_type = Puppet::Pops::Types::TypeFactory.host_class("cowabunga")
- expect(@scope.function_defined([class_type])).to be_true
+ expect(@scope.function_defined([class_type])).to be_truthy
end
it "raises an argument error if you ask if Class is defined" do
class_type = Puppet::Pops::Types::TypeFactory.host_class
expect { @scope.function_defined([class_type]) }.to raise_error(ArgumentError, /reference to all.*class/)
end
end
diff --git a/spec/unit/parser/functions/digest_spec.rb b/spec/unit/parser/functions/digest_spec.rb
index e3c0762d4..0c0d5b29a 100755
--- a/spec/unit/parser/functions/digest_spec.rb
+++ b/spec/unit/parser/functions/digest_spec.rb
@@ -1,31 +1,31 @@
#!/usr/bin/env rspec
require 'spec_helper'
describe "the digest function", :uses_checksums => true do
before :all do
Puppet::Parser::Functions.autoloader.loadall
end
before :each do
n = Puppet::Node.new('unnamed')
c = Puppet::Parser::Compiler.new(n)
@scope = Puppet::Parser::Scope.new(c)
end
it "should exist" do
- Puppet::Parser::Functions.function("digest").should == "function_digest"
+ expect(Puppet::Parser::Functions.function("digest")).to eq("function_digest")
end
with_digest_algorithms do
it "should use the proper digest function" do
result = @scope.function_digest([plaintext])
- result.should(eql( checksum ))
+ expect(result).to(eql( checksum ))
end
it "should only accept one parameter" do
expect do
@scope.function_digest(['foo', 'bar'])
end.to raise_error(ArgumentError)
end
end
end
diff --git a/spec/unit/parser/functions/fail_spec.rb b/spec/unit/parser/functions/fail_spec.rb
index 1e81a3c80..6717724bc 100755
--- a/spec/unit/parser/functions/fail_spec.rb
+++ b/spec/unit/parser/functions/fail_spec.rb
@@ -1,28 +1,28 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "the 'fail' parser function" do
before :all do
Puppet::Parser::Functions.autoloader.loadall
end
let :scope do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
scope = Puppet::Parser::Scope.new(compiler)
scope.stubs(:environment).returns(nil)
scope
end
it "should exist" do
- Puppet::Parser::Functions.function(:fail).should == "function_fail"
+ expect(Puppet::Parser::Functions.function(:fail)).to eq("function_fail")
end
it "should raise a parse error if invoked" do
expect { scope.function_fail([]) }.to raise_error Puppet::ParseError
end
it "should join arguments into a string in the error" do
expect { scope.function_fail(["hello", "world"]) }.to raise_error /hello world/
end
end
diff --git a/spec/unit/parser/functions/file_spec.rb b/spec/unit/parser/functions/file_spec.rb
index c5f157300..7406b3309 100755
--- a/spec/unit/parser/functions/file_spec.rb
+++ b/spec/unit/parser/functions/file_spec.rb
@@ -1,98 +1,98 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
describe "the 'file' function" do
include PuppetSpec::Files
before :all do
Puppet::Parser::Functions.autoloader.loadall
end
let :node do Puppet::Node.new('localhost') end
let :compiler do Puppet::Parser::Compiler.new(node) end
let :scope do Puppet::Parser::Scope.new(compiler) end
def with_file_content(content)
path = tmpfile('file-function')
file = File.new(path, 'w')
file.sync = true
file.print content
yield path
end
it "should read a file" do
with_file_content('file content') do |name|
- scope.function_file([name]).should == "file content"
+ expect(scope.function_file([name])).to eq("file content")
end
end
it "should read a file from a module path" do
with_file_content('file content') do |name|
mod = mock 'module'
mod.stubs(:file).with('myfile').returns(name)
compiler.environment.stubs(:module).with('mymod').returns(mod)
- scope.function_file(['mymod/myfile']).should == 'file content'
+ expect(scope.function_file(['mymod/myfile'])).to eq('file content')
end
end
it "should return the first file if given two files with absolute paths" do
with_file_content('one') do |one|
with_file_content('two') do |two|
- scope.function_file([one, two]).should == "one"
+ expect(scope.function_file([one, two])).to eq("one")
end
end
end
it "should return the first file if given two files with module paths" do
with_file_content('one') do |one|
with_file_content('two') do |two|
mod = mock 'module'
compiler.environment.expects(:module).with('mymod').returns(mod)
mod.expects(:file).with('one').returns(one)
mod.stubs(:file).with('two').returns(two)
- scope.function_file(['mymod/one','mymod/two']).should == 'one'
+ expect(scope.function_file(['mymod/one','mymod/two'])).to eq('one')
end
end
end
it "should return the first file if given two files with mixed paths, absolute first" do
with_file_content('one') do |one|
with_file_content('two') do |two|
mod = mock 'module'
compiler.environment.stubs(:module).with('mymod').returns(mod)
mod.stubs(:file).with('two').returns(two)
- scope.function_file([one,'mymod/two']).should == 'one'
+ expect(scope.function_file([one,'mymod/two'])).to eq('one')
end
end
end
it "should return the first file if given two files with mixed paths, module first" do
with_file_content('one') do |one|
with_file_content('two') do |two|
mod = mock 'module'
compiler.environment.expects(:module).with('mymod').returns(mod)
mod.stubs(:file).with('two').returns(two)
- scope.function_file(['mymod/two',one]).should == 'two'
+ expect(scope.function_file(['mymod/two',one])).to eq('two')
end
end
end
it "should not fail when some files are absent" do
expect {
with_file_content('one') do |one|
- scope.function_file([make_absolute("/should-not-exist"), one]).should == 'one'
+ expect(scope.function_file([make_absolute("/should-not-exist"), one])).to eq('one')
end
}.to_not raise_error
end
it "should fail when all files are absent" do
expect {
scope.function_file([File.expand_path('one')])
}.to raise_error(Puppet::ParseError, /Could not find any files/)
end
end
diff --git a/spec/unit/parser/functions/fqdn_rand_spec.rb b/spec/unit/parser/functions/fqdn_rand_spec.rb
index 49a169661..9f162f4a7 100755
--- a/spec/unit/parser/functions/fqdn_rand_spec.rb
+++ b/spec/unit/parser/functions/fqdn_rand_spec.rb
@@ -1,46 +1,46 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/scope'
describe "the fqdn_rand function" do
include PuppetSpec::Scope
it "provides a random number strictly less than the given max" do
- fqdn_rand(3).should satisfy {|n| n.to_i < 3 }
+ expect(fqdn_rand(3)).to satisfy {|n| n.to_i < 3 }
end
it "provides the same 'random' value on subsequent calls for the same host" do
- fqdn_rand(3).should eql(fqdn_rand(3))
+ expect(fqdn_rand(3)).to eql(fqdn_rand(3))
end
it "considers the same host and same extra arguments to have the same random sequence" do
first_random = fqdn_rand(3, :extra_identifier => [1, "same", "host"])
second_random = fqdn_rand(3, :extra_identifier => [1, "same", "host"])
- first_random.should eql(second_random)
+ expect(first_random).to eql(second_random)
end
it "allows extra arguments to control the random value on a single host" do
first_random = fqdn_rand(10000, :extra_identifier => [1, "different", "host"])
second_different_random = fqdn_rand(10000, :extra_identifier => [2, "different", "host"])
- first_random.should_not eql(second_different_random)
+ expect(first_random).not_to eql(second_different_random)
end
it "should return different sequences of value for different hosts" do
val1 = fqdn_rand(1000000000, :host => "first.host.com")
val2 = fqdn_rand(1000000000, :host => "second.host.com")
- val1.should_not eql(val2)
+ expect(val1).not_to eql(val2)
end
def fqdn_rand(max, args = {})
host = args[:host] || '127.0.0.1'
extra = args[:extra_identifier] || []
scope = create_test_scope_for_node('localhost')
scope.stubs(:[]).with("::fqdn").returns(host)
scope.function_fqdn_rand([max] + extra)
end
end
diff --git a/spec/unit/parser/functions/generate_spec.rb b/spec/unit/parser/functions/generate_spec.rb
index 99141fc34..91221e788 100755
--- a/spec/unit/parser/functions/generate_spec.rb
+++ b/spec/unit/parser/functions/generate_spec.rb
@@ -1,136 +1,136 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "the generate function" do
include PuppetSpec::Files
before :all do
Puppet::Parser::Functions.autoloader.loadall
end
let :node do Puppet::Node.new('localhost') end
let :compiler do Puppet::Parser::Compiler.new(node) end
let :scope do Puppet::Parser::Scope.new(compiler) end
it "should exist" do
- Puppet::Parser::Functions.function("generate").should == "function_generate"
+ expect(Puppet::Parser::Functions.function("generate")).to eq("function_generate")
end
it "accept a fully-qualified path as a command" do
command = File.expand_path('/command/foo')
Dir.expects(:chdir).with(File.dirname(command)).returns("yay")
- scope.function_generate([command]).should == "yay"
+ expect(scope.function_generate([command])).to eq("yay")
end
it "should not accept a relative path as a command" do
- lambda { scope.function_generate(["command"]) }.should raise_error(Puppet::ParseError)
+ expect { scope.function_generate(["command"]) }.to raise_error(Puppet::ParseError)
end
it "should not accept a command containing illegal characters" do
- lambda { scope.function_generate([File.expand_path('/##/command')]) }.should raise_error(Puppet::ParseError)
+ expect { scope.function_generate([File.expand_path('/##/command')]) }.to raise_error(Puppet::ParseError)
end
it "should not accept a command containing spaces" do
- lambda { scope.function_generate([File.expand_path('/com mand')]) }.should raise_error(Puppet::ParseError)
+ expect { scope.function_generate([File.expand_path('/com mand')]) }.to raise_error(Puppet::ParseError)
end
it "should not accept a command containing '..'" do
command = File.expand_path("/command/../")
- lambda { scope.function_generate([command]) }.should raise_error(Puppet::ParseError)
+ expect { scope.function_generate([command]) }.to raise_error(Puppet::ParseError)
end
it "should execute the generate script with the correct working directory" do
command = File.expand_path("/command")
Dir.expects(:chdir).with(File.dirname(command)).returns("yay")
- scope.function_generate([command]).should == 'yay'
+ expect(scope.function_generate([command])).to eq('yay')
end
describe "on Windows", :if => Puppet.features.microsoft_windows? do
it "should accept the tilde in the path" do
command = "C:/DOCUME~1/ADMINI~1/foo.bat"
Dir.expects(:chdir).with(File.dirname(command)).returns("yay")
- scope.function_generate([command]).should == 'yay'
+ expect(scope.function_generate([command])).to eq('yay')
end
it "should accept lower-case drive letters" do
command = 'd:/command/foo'
Dir.expects(:chdir).with(File.dirname(command)).returns("yay")
- scope.function_generate([command]).should == 'yay'
+ expect(scope.function_generate([command])).to eq('yay')
end
it "should accept upper-case drive letters" do
command = 'D:/command/foo'
Dir.expects(:chdir).with(File.dirname(command)).returns("yay")
- scope.function_generate([command]).should == 'yay'
+ expect(scope.function_generate([command])).to eq('yay')
end
it "should accept forward and backslashes in the path" do
command = 'D:\command/foo\bar'
Dir.expects(:chdir).with(File.dirname(command)).returns("yay")
- scope.function_generate([command]).should == 'yay'
+ expect(scope.function_generate([command])).to eq('yay')
end
it "should reject colons when not part of the drive letter" do
- lambda { scope.function_generate(['C:/com:mand']) }.should raise_error(Puppet::ParseError)
+ expect { scope.function_generate(['C:/com:mand']) }.to raise_error(Puppet::ParseError)
end
it "should reject root drives" do
- lambda { scope.function_generate(['C:/']) }.should raise_error(Puppet::ParseError)
+ expect { scope.function_generate(['C:/']) }.to raise_error(Puppet::ParseError)
end
end
describe "on POSIX", :if => Puppet.features.posix? do
it "should reject backslashes" do
- lambda { scope.function_generate(['/com\\mand']) }.should raise_error(Puppet::ParseError)
+ expect { scope.function_generate(['/com\\mand']) }.to raise_error(Puppet::ParseError)
end
it "should accept plus and dash" do
command = "/var/folders/9z/9zXImgchH8CZJh6SgiqS2U+++TM/-Tmp-/foo"
Dir.expects(:chdir).with(File.dirname(command)).returns("yay")
- scope.function_generate([command]).should == 'yay'
+ expect(scope.function_generate([command])).to eq('yay')
end
end
let :command do
cmd = tmpfile('function_generate')
if Puppet.features.microsoft_windows?
cmd += '.bat'
text = '@echo off' + "\n" + 'echo a-%1 b-%2'
else
text = '#!/bin/sh' + "\n" + 'echo a-$1 b-$2'
end
File.open(cmd, 'w') {|fh| fh.puts text }
File.chmod 0700, cmd
cmd
end
after :each do
File.delete(command) if Puppet::FileSystem.exist?(command)
end
it "returns the output as a String" do
- scope.function_generate([command]).class.should == String
+ expect(scope.function_generate([command]).class).to eq(String)
end
it "should call generator with no arguments" do
- scope.function_generate([command]).should == "a- b-\n"
+ expect(scope.function_generate([command])).to eq("a- b-\n")
end
it "should call generator with one argument" do
- scope.function_generate([command, 'one']).should == "a-one b-\n"
+ expect(scope.function_generate([command, 'one'])).to eq("a-one b-\n")
end
it "should call generator with wo arguments" do
- scope.function_generate([command, 'one', 'two']).should == "a-one b-two\n"
+ expect(scope.function_generate([command, 'one', 'two'])).to eq("a-one b-two\n")
end
it "should fail if generator is not absolute" do
expect { scope.function_generate(['boo']) }.to raise_error(Puppet::ParseError)
end
it "should fail if generator fails" do
expect { scope.function_generate(['/boo']) }.to raise_error(Puppet::ParseError)
end
end
diff --git a/spec/unit/parser/functions/hiera_array_spec.rb b/spec/unit/parser/functions/hiera_array_spec.rb
index ca9bb5c88..6ddaf2335 100644
--- a/spec/unit/parser/functions/hiera_array_spec.rb
+++ b/spec/unit/parser/functions/hiera_array_spec.rb
@@ -1,26 +1,26 @@
require 'spec_helper'
require 'puppet_spec/scope'
describe 'Puppet::Parser::Functions#hiera_array' do
include PuppetSpec::Scope
before :each do
Puppet[:hiera_config] = PuppetSpec::Files.tmpfile('hiera_config')
end
let :scope do create_test_scope_for_node('foo') end
it 'should require a key argument' do
expect { scope.function_hiera_array([]) }.to raise_error(ArgumentError)
end
it 'should raise a useful error when nil is returned' do
Hiera.any_instance.expects(:lookup).returns(nil)
expect { scope.function_hiera_array(["badkey"]) }.to raise_error(Puppet::ParseError, /Could not find data item badkey/ )
end
it 'should use the array resolution_type' do
- Hiera.any_instance.expects(:lookup).with() { |*args| args[4].should be(:array) }.returns([])
+ Hiera.any_instance.expects(:lookup).with() { |*args| expect(args[4]).to be(:array) }.returns([])
scope.function_hiera_array(['key'])
end
end
diff --git a/spec/unit/parser/functions/hiera_hash_spec.rb b/spec/unit/parser/functions/hiera_hash_spec.rb
index 9b89b2efd..d40521140 100644
--- a/spec/unit/parser/functions/hiera_hash_spec.rb
+++ b/spec/unit/parser/functions/hiera_hash_spec.rb
@@ -1,22 +1,22 @@
require 'spec_helper'
require 'puppet_spec/scope'
describe 'Puppet::Parser::Functions#hiera_hash' do
include PuppetSpec::Scope
let :scope do create_test_scope_for_node('foo') end
it 'should require a key argument' do
expect { scope.function_hiera_hash([]) }.to raise_error(ArgumentError)
end
it 'should raise a useful error when nil is returned' do
Hiera.any_instance.expects(:lookup).returns(nil)
expect { scope.function_hiera_hash(["badkey"]) }.to raise_error(Puppet::ParseError, /Could not find data item badkey/ )
end
it 'should use the hash resolution_type' do
- Hiera.any_instance.expects(:lookup).with() { |*args| args[4].should be :hash }.returns({})
+ Hiera.any_instance.expects(:lookup).with() { |*args| expect(args[4]).to be :hash }.returns({})
scope.function_hiera_hash(['key'])
end
end
diff --git a/spec/unit/parser/functions/hiera_include_spec.rb b/spec/unit/parser/functions/hiera_include_spec.rb
index cfa14b836..0bbfe609a 100644
--- a/spec/unit/parser/functions/hiera_include_spec.rb
+++ b/spec/unit/parser/functions/hiera_include_spec.rb
@@ -1,39 +1,39 @@
require 'spec_helper'
require 'puppet_spec/scope'
describe 'Puppet::Parser::Functions#hiera_include' do
include PuppetSpec::Scope
let :scope do create_test_scope_for_node('foo') end
before :each do
Puppet[:hiera_config] = PuppetSpec::Files.tmpfile('hiera_config')
end
it 'should require a key argument' do
expect { scope.function_hiera_include([]) }.to raise_error(ArgumentError)
end
it 'should raise a useful error when nil is returned' do
HieraPuppet.expects(:lookup).returns(nil)
expect { scope.function_hiera_include(["badkey"]) }.
to raise_error(Puppet::ParseError, /Could not find data item badkey/ )
end
it 'should use the array resolution_type' do
- HieraPuppet.expects(:lookup).with() { |*args| args[4].should be(:array) }.returns(['someclass'])
+ HieraPuppet.expects(:lookup).with() { |*args| expect(args[4]).to be(:array) }.returns(['someclass'])
expect { scope.function_hiera_include(['key']) }.to raise_error(Puppet::Error, /Could not find class ::someclass/)
end
it 'should call the `include` function with the classes' do
HieraPuppet.expects(:lookup).returns %w[foo bar baz]
scope.expects(:function_include).with([%w[foo bar baz]])
scope.function_hiera_include(['key'])
end
it 'should not raise an error if the resulting hiera lookup returns an empty array' do
HieraPuppet.expects(:lookup).returns []
expect { scope.function_hiera_include(['key']) }.to_not raise_error
end
end
diff --git a/spec/unit/parser/functions/hiera_spec.rb b/spec/unit/parser/functions/hiera_spec.rb
index db31fdf82..8d39d1d97 100755
--- a/spec/unit/parser/functions/hiera_spec.rb
+++ b/spec/unit/parser/functions/hiera_spec.rb
@@ -1,22 +1,22 @@
require 'spec_helper'
require 'puppet_spec/scope'
describe 'Puppet::Parser::Functions#hiera' do
include PuppetSpec::Scope
let :scope do create_test_scope_for_node('foo') end
it 'should require a key argument' do
expect { scope.function_hiera([]) }.to raise_error(ArgumentError)
end
it 'should raise a useful error when nil is returned' do
Hiera.any_instance.expects(:lookup).returns(nil)
expect { scope.function_hiera(["badkey"]) }.to raise_error(Puppet::ParseError, /Could not find data item badkey/ )
end
it 'should use the priority resolution_type' do
- Hiera.any_instance.expects(:lookup).with() { |*args| args[4].should be(:priority) }.returns('foo_result')
- scope.function_hiera(['key']).should == 'foo_result'
+ Hiera.any_instance.expects(:lookup).with() { |*args| expect(args[4]).to be(:priority) }.returns('foo_result')
+ expect(scope.function_hiera(['key'])).to eq('foo_result')
end
end
diff --git a/spec/unit/parser/functions/include_spec.rb b/spec/unit/parser/functions/include_spec.rb
index 8e4548025..0151492a9 100755
--- a/spec/unit/parser/functions/include_spec.rb
+++ b/spec/unit/parser/functions/include_spec.rb
@@ -1,55 +1,55 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'unit/parser/functions/shared'
require 'puppet_spec/compiler'
describe "the 'include' function" do
include PuppetSpec::Compiler
before :each do
@compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("foo"))
@scope = Puppet::Parser::Scope.new(@compiler)
end
it "should exist" do
- Puppet::Parser::Functions.function("include").should == "function_include"
+ expect(Puppet::Parser::Functions.function("include")).to eq("function_include")
end
it "should include a single class" do
inc = "::foo"
@compiler.expects(:evaluate_classes).with {|klasses,parser,lazy| klasses == [inc]}.returns([inc])
@scope.function_include(["foo"])
end
it "should include multiple classes" do
inc = ["::foo","::bar"]
@compiler.expects(:evaluate_classes).with {|klasses,parser,lazy| klasses == inc}.returns(inc)
@scope.function_include(["foo","bar"])
end
it "should include multiple classes passed in an array" do
inc = ["::foo","::bar"]
@compiler.expects(:evaluate_classes).with {|klasses,parser,lazy| klasses == inc}.returns(inc)
@scope.function_include([["foo","bar"]])
end
it "should flatten nested arrays" do
inc = ["::foo","::bar","::baz"]
@compiler.expects(:evaluate_classes).with {|klasses,parser,lazy| klasses == inc}.returns(inc)
@scope.function_include([["foo","bar"],"baz"])
end
it "should not lazily evaluate the included class" do
@compiler.expects(:evaluate_classes).with {|klasses,parser,lazy| lazy == false}.returns("foo")
@scope.function_include(["foo"])
end
it "should raise if the class is not found" do
@scope.stubs(:source).returns(true)
expect { @scope.function_include(["nosuchclass"]) }.to raise_error(Puppet::Error)
end
it_should_behave_like 'all functions transforming relative to absolute names', :function_include
it_should_behave_like 'an inclusion function, regardless of the type of class reference,', :include
end
diff --git a/spec/unit/parser/functions/inline_template_spec.rb b/spec/unit/parser/functions/inline_template_spec.rb
index ed0911e42..79d9d4b73 100755
--- a/spec/unit/parser/functions/inline_template_spec.rb
+++ b/spec/unit/parser/functions/inline_template_spec.rb
@@ -1,34 +1,34 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "the inline_template function" do
before :all do
Puppet::Parser::Functions.autoloader.loadall
end
let(:node) { Puppet::Node.new('localhost') }
let(:compiler) { Puppet::Parser::Compiler.new(node) }
let(:scope) { Puppet::Parser::Scope.new(compiler) }
it "should concatenate template wrapper outputs for multiple templates" do
- inline_template("template1", "template2").should == "template1template2"
+ expect(inline_template("template1", "template2")).to eq("template1template2")
end
it "should raise an error if the template raises an error" do
expect { inline_template("<% raise 'error' %>") }.to raise_error(Puppet::ParseError)
end
it "is not interfered with by a variable called 'string' (#14093)" do
scope['string'] = "this is a variable"
- inline_template("this is a template").should == "this is a template"
+ expect(inline_template("this is a template")).to eq("this is a template")
end
it "has access to a variable called 'string' (#14093)" do
scope['string'] = "this is a variable"
- inline_template("string was: <%= @string %>").should == "string was: this is a variable"
+ expect(inline_template("string was: <%= @string %>")).to eq("string was: this is a variable")
end
def inline_template(*templates)
scope.function_inline_template(templates)
end
end
diff --git a/spec/unit/parser/functions/regsubst_spec.rb b/spec/unit/parser/functions/regsubst_spec.rb
index 1c65b370a..929c3a643 100755
--- a/spec/unit/parser/functions/regsubst_spec.rb
+++ b/spec/unit/parser/functions/regsubst_spec.rb
@@ -1,196 +1,196 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "the regsubst function" do
before :all do
Puppet::Parser::Functions.autoloader.loadall
end
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
end
it "should exist" do
- Puppet::Parser::Functions.function("regsubst").should == "function_regsubst"
+ expect(Puppet::Parser::Functions.function("regsubst")).to eq("function_regsubst")
end
it "should raise an ArgumentError if there is less than 3 arguments" do
- lambda { @scope.function_regsubst(["foo", "bar"]) }.should( raise_error(ArgumentError))
+ expect { @scope.function_regsubst(["foo", "bar"]) }.to( raise_error(ArgumentError))
end
it "should raise an ArgumentError if there is more than 5 arguments" do
- lambda { @scope.function_regsubst(["foo", "bar", "gazonk", "del", "x", "y"]) }.should( raise_error(ArgumentError))
+ expect { @scope.function_regsubst(["foo", "bar", "gazonk", "del", "x", "y"]) }.to( raise_error(ArgumentError))
end
it "should raise a ParseError when given a bad flag" do
- lambda { @scope.function_regsubst(["foo", "bar", "gazonk", "X"]) }.should( raise_error(Puppet::ParseError))
+ expect { @scope.function_regsubst(["foo", "bar", "gazonk", "X"]) }.to( raise_error(Puppet::ParseError))
end
it "should raise a ParseError for non-string and non-array target" do
- lambda { @scope.function_regsubst([4711, "bar", "gazonk"]) }.should( raise_error(Puppet::ParseError))
+ expect { @scope.function_regsubst([4711, "bar", "gazonk"]) }.to( raise_error(Puppet::ParseError))
end
it "should raise a ParseError for array target with non-string element" do
- lambda { @scope.function_regsubst([["x", ["y"], "z"], "bar", "gazonk"]) }.should( raise_error(Puppet::ParseError))
+ expect { @scope.function_regsubst([["x", ["y"], "z"], "bar", "gazonk"]) }.to( raise_error(Puppet::ParseError))
end
it "should raise a ParseError for a bad regular expression" do
- lambda { @scope.function_regsubst(["foo", "(bar", "gazonk"]) }.should(
+ expect { @scope.function_regsubst(["foo", "(bar", "gazonk"]) }.to(
raise_error(Puppet::ParseError))
end
it "should raise a ParseError for a non-string regular expression" do
- lambda { @scope.function_regsubst(["foo", ["bar"], "gazonk"]) }.should( raise_error(Puppet::ParseError))
+ expect { @scope.function_regsubst(["foo", ["bar"], "gazonk"]) }.to( raise_error(Puppet::ParseError))
end
it "should handle groups" do
result = @scope.function_regsubst(
[ '130.236.254.10',
'^([0-9]+)[.]([0-9]+)[.]([0-9]+)[.]([0-9]+)$',
'\4-\3-\2-\1'
])
- result.should(eql("10-254-236-130"))
+ expect(result).to(eql("10-254-236-130"))
end
it "should handle simple regexps" do
result = @scope.function_regsubst(
[ "the monkey breaks banana trees",
"b[an]*a",
"coconut"
])
- result.should(eql("the monkey breaks coconut trees"))
+ expect(result).to(eql("the monkey breaks coconut trees"))
end
it "should handle case-sensitive regexps" do
result = @scope.function_regsubst(
[ "the monkey breaks baNAna trees",
"b[an]+a",
"coconut"
])
- result.should(eql("the monkey breaks baNAna trees"))
+ expect(result).to(eql("the monkey breaks baNAna trees"))
end
it "should handle case-insensitive regexps" do
result = @scope.function_regsubst(
[ "the monkey breaks baNAna trees",
"b[an]+a",
"coconut",
"I"
])
- result.should(eql("the monkey breaks coconut trees"))
+ expect(result).to(eql("the monkey breaks coconut trees"))
end
it "should handle global substitutions" do
result = @scope.function_regsubst(
[ "the monkey breaks\tbanana trees",
"[ \t]",
"--",
"G"
])
- result.should(eql("the--monkey--breaks--banana--trees"))
+ expect(result).to(eql("the--monkey--breaks--banana--trees"))
end
it "should handle global substitutions with groups" do
result = @scope.function_regsubst(
[ '130.236.254.10',
'([0-9]+)',
'<\1>',
'G'
])
- result.should(eql('<130>.<236>.<254>.<10>'))
+ expect(result).to(eql('<130>.<236>.<254>.<10>'))
end
it "should apply on all elements of an array" do
data = ['130.236.254.10', 'foo.example.com', 'coconut', '10.20.30.40']
result = @scope.function_regsubst([ data, '[.]', '-'])
- result.should(eql( ['130-236.254.10', 'foo-example.com', 'coconut', '10-20.30.40']))
+ expect(result).to(eql( ['130-236.254.10', 'foo-example.com', 'coconut', '10-20.30.40']))
end
it "should apply global substitutions on all elements of an array" do
data = ['130.236.254.10', 'foo.example.com', 'coconut', '10.20.30.40']
result = @scope.function_regsubst([ data, '[.]', '-', 'G'])
- result.should(eql( ['130-236-254-10', 'foo-example-com', 'coconut', '10-20-30-40']))
+ expect(result).to(eql( ['130-236-254-10', 'foo-example-com', 'coconut', '10-20-30-40']))
end
it "should handle groups on all elements of an array" do
data = ['130.236.254.10', 'foo.example.com', 'coconut', '10.20.30.40']
result = @scope.function_regsubst(
[ data,
'^([0-9]+)[.]([0-9]+)[.]([0-9]+)[.]([0-9]+)$',
'\4-\3-\2-\1'
])
- result.should(eql( ['10-254-236-130', 'foo.example.com', 'coconut', '40-30-20-10']))
+ expect(result).to(eql( ['10-254-236-130', 'foo.example.com', 'coconut', '40-30-20-10']))
end
it "should handle global substitutions with groups on all elements of an array" do
data = ['130.236.254.10', 'foo.example.com', 'coconut', '10.20.30.40']
result = @scope.function_regsubst(
[ data,
'([^.]+)',
'<\1>',
'G'
])
- result.should(eql(
+ expect(result).to(eql(
['<130>.<236>.<254>.<10>', '<foo>.<example>.<com>',
'<coconut>', '<10>.<20>.<30>.<40>']))
end
it "should return an array (not a string) for a single element array parameter" do
data = ['130.236.254.10']
result = @scope.function_regsubst(
[ data,
'([^.]+)',
'<\1>',
'G'
])
- result.should(eql(['<130>.<236>.<254>.<10>']))
+ expect(result).to(eql(['<130>.<236>.<254>.<10>']))
end
it "should return a string (not a one element array) for a simple string parameter" do
data = '130.236.254.10'
result = @scope.function_regsubst(
[ data,
'([^.]+)',
'<\1>',
'G'
])
- result.should(eql('<130>.<236>.<254>.<10>'))
+ expect(result).to(eql('<130>.<236>.<254>.<10>'))
end
end
diff --git a/spec/unit/parser/functions/require_spec.rb b/spec/unit/parser/functions/require_spec.rb
index bccd923b9..6dc15b861 100755
--- a/spec/unit/parser/functions/require_spec.rb
+++ b/spec/unit/parser/functions/require_spec.rb
@@ -1,68 +1,68 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'unit/parser/functions/shared'
require 'puppet_spec/compiler'
describe "the require function" do
include PuppetSpec::Compiler
# before :all do
# Puppet::Parser::Functions.autoloader.loadall
# end
before :each do
@catalog = stub 'catalog'
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
@scope.stubs(:findresource)
@klass = stub 'class', :name => "myclass"
@scope.stubs(:find_hostclass).returns(@klass)
@resource = Puppet::Parser::Resource.new(:file, "/my/file", :scope => @scope, :source => "source")
@scope.stubs(:resource).returns @resource
end
it "should exist" do
- Puppet::Parser::Functions.function("require").should == "function_require"
+ expect(Puppet::Parser::Functions.function("require")).to eq("function_require")
end
it "should delegate to the 'include' puppet function" do
@scope.compiler.expects(:evaluate_classes).with(["::myclass"], @scope, false)
@scope.function_require(["myclass"])
end
it "should set the 'require' parameter on the resource to a resource reference" do
@scope.compiler.stubs(:evaluate_classes)
@scope.function_require(["myclass"])
- @resource["require"].should be_instance_of(Array)
- @resource["require"][0].should be_instance_of(Puppet::Resource)
+ expect(@resource["require"]).to be_instance_of(Array)
+ expect(@resource["require"][0]).to be_instance_of(Puppet::Resource)
end
it "should lookup the absolute class path" do
@scope.compiler.stubs(:evaluate_classes)
@scope.expects(:find_hostclass).with("::myclass").returns(@klass)
@klass.expects(:name).returns("myclass")
@scope.function_require(["myclass"])
end
it "should append the required class to the require parameter" do
@scope.compiler.stubs(:evaluate_classes)
one = Puppet::Resource.new(:file, "/one")
@resource[:require] = one
@scope.function_require(["myclass"])
- @resource[:require].should be_include(one)
- @resource[:require].detect { |r| r.to_s == "Class[Myclass]" }.should be_instance_of(Puppet::Resource)
+ expect(@resource[:require]).to be_include(one)
+ expect(@resource[:require].detect { |r| r.to_s == "Class[Myclass]" }).to be_instance_of(Puppet::Resource)
end
it_should_behave_like 'all functions transforming relative to absolute names', :function_require
it_should_behave_like 'an inclusion function, regardless of the type of class reference,', :require
end
diff --git a/spec/unit/parser/functions/shellquote_spec.rb b/spec/unit/parser/functions/shellquote_spec.rb
index 6bcdc7a3e..4c869f4c6 100755
--- a/spec/unit/parser/functions/shellquote_spec.rb
+++ b/spec/unit/parser/functions/shellquote_spec.rb
@@ -1,67 +1,67 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "the shellquote function" do
let :node do Puppet::Node.new('localhost') end
let :compiler do Puppet::Parser::Compiler.new(node) end
let :scope do Puppet::Parser::Scope.new(compiler) end
it "should exist" do
- Puppet::Parser::Functions.function("shellquote").should == "function_shellquote"
+ expect(Puppet::Parser::Functions.function("shellquote")).to eq("function_shellquote")
end
it "should handle no arguments" do
- scope.function_shellquote([]).should == ""
+ expect(scope.function_shellquote([])).to eq("")
end
it "should handle several simple arguments" do
- scope.function_shellquote(
+ expect(scope.function_shellquote(
['foo', 'bar@example.com', 'localhost:/dev/null', 'xyzzy+-4711,23']
- ).should == 'foo bar@example.com localhost:/dev/null xyzzy+-4711,23'
+ )).to eq('foo bar@example.com localhost:/dev/null xyzzy+-4711,23')
end
it "should handle array arguments" do
- scope.function_shellquote(
+ expect(scope.function_shellquote(
['foo', ['bar@example.com', 'localhost:/dev/null'],
'xyzzy+-4711,23']
- ).should == 'foo bar@example.com localhost:/dev/null xyzzy+-4711,23'
+ )).to eq('foo bar@example.com localhost:/dev/null xyzzy+-4711,23')
end
it "should quote unsafe characters" do
- scope.function_shellquote(['/etc/passwd ', '(ls)', '*', '[?]', "'&'"]).
- should == '"/etc/passwd " "(ls)" "*" "[?]" "\'&\'"'
+ expect(scope.function_shellquote(['/etc/passwd ', '(ls)', '*', '[?]', "'&'"])).
+ to eq('"/etc/passwd " "(ls)" "*" "[?]" "\'&\'"')
end
it "should deal with double quotes" do
- scope.function_shellquote(['"foo"bar"']).should == '\'"foo"bar"\''
+ expect(scope.function_shellquote(['"foo"bar"'])).to eq('\'"foo"bar"\'')
end
it "should cope with dollar signs" do
- scope.function_shellquote(['$PATH', 'foo$bar', '"x$"']).
- should == "'$PATH' 'foo$bar' '\"x$\"'"
+ expect(scope.function_shellquote(['$PATH', 'foo$bar', '"x$"'])).
+ to eq("'$PATH' 'foo$bar' '\"x$\"'")
end
it "should deal with apostrophes (single quotes)" do
- scope.function_shellquote(["'foo'bar'", "`$'EDITOR'`"]).
- should == '"\'foo\'bar\'" "\\`\\$\'EDITOR\'\\`"'
+ expect(scope.function_shellquote(["'foo'bar'", "`$'EDITOR'`"])).
+ to eq('"\'foo\'bar\'" "\\`\\$\'EDITOR\'\\`"')
end
it "should cope with grave accents (backquotes)" do
- scope.function_shellquote(['`echo *`', '`ls "$MAILPATH"`']).
- should == "'`echo *`' '`ls \"$MAILPATH\"`'"
+ expect(scope.function_shellquote(['`echo *`', '`ls "$MAILPATH"`'])).
+ to eq("'`echo *`' '`ls \"$MAILPATH\"`'")
end
it "should deal with both single and double quotes" do
- scope.function_shellquote(['\'foo"bar"xyzzy\'', '"foo\'bar\'xyzzy"']).
- should == '"\'foo\\"bar\\"xyzzy\'" "\\"foo\'bar\'xyzzy\\""'
+ expect(scope.function_shellquote(['\'foo"bar"xyzzy\'', '"foo\'bar\'xyzzy"'])).
+ to eq('"\'foo\\"bar\\"xyzzy\'" "\\"foo\'bar\'xyzzy\\""')
end
it "should handle multiple quotes *and* dollars and backquotes" do
- scope.function_shellquote(['\'foo"$x`bar`"xyzzy\'']).
- should == '"\'foo\\"\\$x\\`bar\\`\\"xyzzy\'"'
+ expect(scope.function_shellquote(['\'foo"$x`bar`"xyzzy\''])).
+ to eq('"\'foo\\"\\$x\\`bar\\`\\"xyzzy\'"')
end
it "should handle linefeeds" do
- scope.function_shellquote(["foo \n bar"]).should == "\"foo \n bar\""
+ expect(scope.function_shellquote(["foo \n bar"])).to eq("\"foo \n bar\"")
end
end
diff --git a/spec/unit/parser/functions/split_spec.rb b/spec/unit/parser/functions/split_spec.rb
index 9a69c8f9f..4e42ae980 100755
--- a/spec/unit/parser/functions/split_spec.rb
+++ b/spec/unit/parser/functions/split_spec.rb
@@ -1,53 +1,53 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "the split function" do
before :all do
Puppet::Parser::Functions.autoloader.loadall
end
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
end
it "should exist" do
- Puppet::Parser::Functions.function("split").should == "function_split"
+ expect(Puppet::Parser::Functions.function("split")).to eq("function_split")
end
it "should raise an ArgumentError if there is less than 2 arguments" do
- lambda { @scope.function_split(["foo"]) }.should( raise_error(ArgumentError))
+ expect { @scope.function_split(["foo"]) }.to( raise_error(ArgumentError))
end
it "should raise an ArgumentError if there is more than 2 arguments" do
- lambda { @scope.function_split(["foo", "bar", "gazonk"]) }.should( raise_error(ArgumentError))
+ expect { @scope.function_split(["foo", "bar", "gazonk"]) }.to( raise_error(ArgumentError))
end
it "should raise a RegexpError if the regexp is malformed" do
- lambda { @scope.function_split(["foo", "("]) }.should(
+ expect { @scope.function_split(["foo", "("]) }.to(
raise_error(RegexpError))
end
it "should handle simple string without metacharacters" do
result = @scope.function_split([ "130;236;254;10", ";"])
- result.should(eql(["130", "236", "254", "10"]))
+ expect(result).to(eql(["130", "236", "254", "10"]))
end
it "should handle simple regexps" do
result = @scope.function_split([ "130.236;254.;10", "[.;]+"])
- result.should(eql(["130", "236", "254", "10"]))
+ expect(result).to(eql(["130", "236", "254", "10"]))
end
it "should handle groups" do
result = @scope.function_split([ "130.236;254.;10", "([.;]+)"])
- result.should(eql(["130", ".", "236", ";", "254", ".;", "10"]))
+ expect(result).to(eql(["130", ".", "236", ";", "254", ".;", "10"]))
end
it "should handle simple string without metacharacters" do
result = @scope.function_split([ "130.236.254.10", ";"])
- result.should(eql(["130.236.254.10"]))
+ expect(result).to(eql(["130.236.254.10"]))
end
end
diff --git a/spec/unit/parser/functions/sprintf_spec.rb b/spec/unit/parser/functions/sprintf_spec.rb
index d40695cf8..7da573db2 100755
--- a/spec/unit/parser/functions/sprintf_spec.rb
+++ b/spec/unit/parser/functions/sprintf_spec.rb
@@ -1,47 +1,47 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "the sprintf function" do
before :all do
Puppet::Parser::Functions.autoloader.loadall
end
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
end
it "should exist" do
- Puppet::Parser::Functions.function("sprintf").should == "function_sprintf"
+ expect(Puppet::Parser::Functions.function("sprintf")).to eq("function_sprintf")
end
it "should raise an ArgumentError if there is less than 1 argument" do
- lambda { @scope.function_sprintf([]) }.should( raise_error(ArgumentError))
+ expect { @scope.function_sprintf([]) }.to( raise_error(ArgumentError))
end
it "should format integers" do
result = @scope.function_sprintf(["%+05d", "23"])
- result.should(eql("+0023"))
+ expect(result).to(eql("+0023"))
end
it "should format floats" do
result = @scope.function_sprintf(["%+.2f", "2.7182818284590451"])
- result.should(eql("+2.72"))
+ expect(result).to(eql("+2.72"))
end
it "should format large floats" do
result = @scope.function_sprintf(["%+.2e", "27182818284590451"])
str =
"+2.72e+16"
- result.should(eql(str))
+ expect(result).to(eql(str))
end
it "should perform more complex formatting" do
result = @scope.function_sprintf(
[ "<%.8s:%#5o %#8X (%-8s)>",
"overlongstring", "23", "48879", "foo" ])
- result.should(eql("<overlong: 027 0XBEEF (foo )>"))
+ expect(result).to(eql("<overlong: 027 0XBEEF (foo )>"))
end
end
diff --git a/spec/unit/parser/functions/tag_spec.rb b/spec/unit/parser/functions/tag_spec.rb
index 367d7cce6..a3e95d7bd 100755
--- a/spec/unit/parser/functions/tag_spec.rb
+++ b/spec/unit/parser/functions/tag_spec.rb
@@ -1,28 +1,28 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "the 'tag' function" do
before :all do
Puppet::Parser::Functions.autoloader.loadall
end
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
end
it "should exist" do
- Puppet::Parser::Functions.function(:tag).should == "function_tag"
+ expect(Puppet::Parser::Functions.function(:tag)).to eq("function_tag")
end
it "should tag the resource with any provided tags" do
resource = Puppet::Parser::Resource.new(:file, "/file", :scope => @scope)
@scope.expects(:resource).returns resource
@scope.function_tag ["one", "two"]
- resource.should be_tagged("one")
- resource.should be_tagged("two")
+ expect(resource).to be_tagged("one")
+ expect(resource).to be_tagged("two")
end
end
diff --git a/spec/unit/parser/functions/template_spec.rb b/spec/unit/parser/functions/template_spec.rb
index befe29550..c48e061c7 100755
--- a/spec/unit/parser/functions/template_spec.rb
+++ b/spec/unit/parser/functions/template_spec.rb
@@ -1,89 +1,89 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "the template function" do
before :all do
Puppet::Parser::Functions.autoloader.loadall
end
let :node do Puppet::Node.new('localhost') end
let :compiler do Puppet::Parser::Compiler.new(node) end
let :scope do Puppet::Parser::Scope.new(compiler) end
it "concatenates outputs for multiple templates" do
tw1 = stub_everything "template_wrapper1"
tw2 = stub_everything "template_wrapper2"
Puppet::Parser::TemplateWrapper.stubs(:new).returns(tw1,tw2)
tw1.stubs(:file=).with("1")
tw2.stubs(:file=).with("2")
tw1.stubs(:result).returns("result1")
tw2.stubs(:result).returns("result2")
- scope.function_template(["1","2"]).should == "result1result2"
+ expect(scope.function_template(["1","2"])).to eq("result1result2")
end
it "raises an error if the template raises an error" do
tw = stub_everything 'template_wrapper'
Puppet::Parser::TemplateWrapper.stubs(:new).returns(tw)
tw.stubs(:result).raises
expect {
scope.function_template(["1"])
}.to raise_error(Puppet::ParseError, /Failed to parse template/)
end
context "when accessing scope variables via method calls (deprecated)" do
it "raises an error when accessing an undefined variable" do
expect {
eval_template("template <%= deprecated %>")
}.to raise_error(Puppet::ParseError, /undefined local variable or method `deprecated'/)
end
it "looks up the value from the scope" do
scope["deprecated"] = "deprecated value"
expect { eval_template("template <%= deprecated %>")}.to raise_error(/undefined local variable or method `deprecated'/)
end
it "still has access to Kernel methods" do
expect { eval_template("<%= binding %>") }.to_not raise_error
end
end
context "when accessing scope variables as instance variables" do
it "has access to values" do
scope['scope_var'] = "value"
- eval_template("<%= @scope_var %>").should == "value"
+ expect(eval_template("<%= @scope_var %>")).to eq("value")
end
it "get nil accessing a variable that does not exist" do
- eval_template("<%= @not_defined.nil? %>").should == "true"
+ expect(eval_template("<%= @not_defined.nil? %>")).to eq("true")
end
it "get nil accessing a variable that is undef" do
scope['undef_var'] = :undef
- eval_template("<%= @undef_var.nil? %>").should == "true"
+ expect(eval_template("<%= @undef_var.nil? %>")).to eq("true")
end
end
it "is not interfered with by having a variable named 'string' (#14093)" do
scope['string'] = "this output should not be seen"
- eval_template("some text that is static").should == "some text that is static"
+ expect(eval_template("some text that is static")).to eq("some text that is static")
end
it "has access to a variable named 'string' (#14093)" do
scope['string'] = "the string value"
- eval_template("string was: <%= @string %>").should == "string was: the string value"
+ expect(eval_template("string was: <%= @string %>")).to eq("string was: the string value")
end
it "does not have direct access to Scope#lookupvar" do
expect {
eval_template("<%= lookupvar('myvar') %>")
}.to raise_error(Puppet::ParseError, /undefined method `lookupvar'/)
end
def eval_template(content)
File.stubs(:read).with("template").returns(content)
Puppet::Parser::Files.stubs(:find_template).returns("template")
scope.function_template(['template'])
end
end
diff --git a/spec/unit/parser/functions/versioncmp_spec.rb b/spec/unit/parser/functions/versioncmp_spec.rb
index 626f71108..b9c879467 100755
--- a/spec/unit/parser/functions/versioncmp_spec.rb
+++ b/spec/unit/parser/functions/versioncmp_spec.rb
@@ -1,33 +1,33 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe "the versioncmp function" do
before :all do
Puppet::Parser::Functions.autoloader.loadall
end
before :each do
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(compiler)
end
it "should exist" do
- Puppet::Parser::Functions.function("versioncmp").should == "function_versioncmp"
+ expect(Puppet::Parser::Functions.function("versioncmp")).to eq("function_versioncmp")
end
it "should raise an ArgumentError if there is less than 2 arguments" do
- lambda { @scope.function_versioncmp(["1.2"]) }.should raise_error(ArgumentError)
+ expect { @scope.function_versioncmp(["1.2"]) }.to raise_error(ArgumentError)
end
it "should raise an ArgumentError if there is more than 2 arguments" do
- lambda { @scope.function_versioncmp(["1.2", "2.4.5", "3.5.6"]) }.should raise_error(ArgumentError)
+ expect { @scope.function_versioncmp(["1.2", "2.4.5", "3.5.6"]) }.to raise_error(ArgumentError)
end
it "should call Puppet::Util::Package.versioncmp (included in scope)" do
Puppet::Util::Package.expects(:versioncmp).with("1.2", "1.3").returns(-1)
@scope.function_versioncmp(["1.2", "1.3"])
end
end
diff --git a/spec/unit/parser/functions_spec.rb b/spec/unit/parser/functions_spec.rb
index 3c6266752..26cf2ec96 100755
--- a/spec/unit/parser/functions_spec.rb
+++ b/spec/unit/parser/functions_spec.rb
@@ -1,132 +1,132 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Parser::Functions do
def callable_functions_from(mod)
Class.new { include mod }.new
end
let(:function_module) { Puppet::Parser::Functions.environment_module(Puppet.lookup(:current_environment)) }
let(:environment) { Puppet::Node::Environment.create(:myenv, []) }
before do
Puppet::Parser::Functions.reset
end
it "should have a method for returning an environment-specific module" do
- Puppet::Parser::Functions.environment_module(environment).should be_instance_of(Module)
+ expect(Puppet::Parser::Functions.environment_module(environment)).to be_instance_of(Module)
end
describe "when calling newfunction" do
it "should create the function in the environment module" do
Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| }
- function_module.should be_method_defined :function_name
+ expect(function_module).to be_method_defined :function_name
end
it "should warn if the function already exists" do
Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| }
Puppet.expects(:warning)
Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| }
end
it "should raise an error if the function type is not correct" do
expect { Puppet::Parser::Functions.newfunction("name", :type => :unknown) { |args| } }.to raise_error Puppet::DevError, "Invalid statement type :unknown"
end
it "instruments the function to profile the execution" do
messages = []
Puppet::Util::Profiler.add_profiler(Puppet::Util::Profiler::WallClock.new(proc { |msg| messages << msg }, "id"))
Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| }
callable_functions_from(function_module).function_name([])
- messages.first.should =~ /Called name/
+ expect(messages.first).to match(/Called name/)
end
end
describe "when calling function to test function existence" do
it "should return false if the function doesn't exist" do
Puppet::Parser::Functions.autoloader.stubs(:load)
- Puppet::Parser::Functions.function("name").should be_false
+ expect(Puppet::Parser::Functions.function("name")).to be_falsey
end
it "should return its name if the function exists" do
Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| }
- Puppet::Parser::Functions.function("name").should == "function_name"
+ expect(Puppet::Parser::Functions.function("name")).to eq("function_name")
end
it "should try to autoload the function if it doesn't exist yet" do
Puppet::Parser::Functions.autoloader.expects(:load)
Puppet::Parser::Functions.function("name")
end
it "combines functions from the root with those from the current environment" do
Puppet.override(:current_environment => Puppet.lookup(:root_environment)) do
Puppet::Parser::Functions.newfunction("onlyroot", :type => :rvalue) do |args|
end
end
Puppet.override(:current_environment => Puppet::Node::Environment.create(:other, [])) do
Puppet::Parser::Functions.newfunction("other_env", :type => :rvalue) do |args|
end
expect(Puppet::Parser::Functions.function("onlyroot")).to eq("function_onlyroot")
expect(Puppet::Parser::Functions.function("other_env")).to eq("function_other_env")
end
- expect(Puppet::Parser::Functions.function("other_env")).to be_false
+ expect(Puppet::Parser::Functions.function("other_env")).to be_falsey
end
end
describe "when calling function to test arity" do
let(:function_module) { Puppet::Parser::Functions.environment_module(Puppet.lookup(:current_environment)) }
it "should raise an error if the function is called with too many arguments" do
Puppet::Parser::Functions.newfunction("name", :arity => 2) { |args| }
expect { callable_functions_from(function_module).function_name([1,2,3]) }.to raise_error ArgumentError
end
it "should raise an error if the function is called with too few arguments" do
Puppet::Parser::Functions.newfunction("name", :arity => 2) { |args| }
expect { callable_functions_from(function_module).function_name([1]) }.to raise_error ArgumentError
end
it "should not raise an error if the function is called with correct number of arguments" do
Puppet::Parser::Functions.newfunction("name", :arity => 2) { |args| }
expect { callable_functions_from(function_module).function_name([1,2]) }.to_not raise_error
end
it "should raise an error if the variable arg function is called with too few arguments" do
Puppet::Parser::Functions.newfunction("name", :arity => -3) { |args| }
expect { callable_functions_from(function_module).function_name([1]) }.to raise_error ArgumentError
end
it "should not raise an error if the variable arg function is called with correct number of arguments" do
Puppet::Parser::Functions.newfunction("name", :arity => -3) { |args| }
expect { callable_functions_from(function_module).function_name([1,2]) }.to_not raise_error
end
it "should not raise an error if the variable arg function is called with more number of arguments" do
Puppet::Parser::Functions.newfunction("name", :arity => -3) { |args| }
expect { callable_functions_from(function_module).function_name([1,2,3]) }.to_not raise_error
end
end
describe "::arity" do
it "returns the given arity of a function" do
Puppet::Parser::Functions.newfunction("name", :arity => 4) { |args| }
- Puppet::Parser::Functions.arity(:name).should == 4
+ expect(Puppet::Parser::Functions.arity(:name)).to eq(4)
end
it "returns -1 if no arity is given" do
Puppet::Parser::Functions.newfunction("name") { |args| }
- Puppet::Parser::Functions.arity(:name).should == -1
+ expect(Puppet::Parser::Functions.arity(:name)).to eq(-1)
end
end
end
diff --git a/spec/unit/parser/relationship_spec.rb b/spec/unit/parser/relationship_spec.rb
index 890b35e21..e068319ce 100755
--- a/spec/unit/parser/relationship_spec.rb
+++ b/spec/unit/parser/relationship_spec.rb
@@ -1,75 +1,75 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/parser/relationship'
describe Puppet::Parser::Relationship do
before do
@source = Puppet::Resource.new(:mytype, "source")
@target = Puppet::Resource.new(:mytype, "target")
@extra_resource = Puppet::Resource.new(:mytype, "extra")
@extra_resource2 = Puppet::Resource.new(:mytype, "extra2")
@dep = Puppet::Parser::Relationship.new(@source, @target, :relationship)
end
describe "when evaluating" do
before do
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource(@source)
@catalog.add_resource(@target)
@catalog.add_resource(@extra_resource)
@catalog.add_resource(@extra_resource2)
end
it "should fail if the source resource cannot be found" do
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource @target
- lambda { @dep.evaluate(@catalog) }.should raise_error(ArgumentError)
+ expect { @dep.evaluate(@catalog) }.to raise_error(ArgumentError)
end
it "should fail if the target resource cannot be found" do
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource @source
- lambda { @dep.evaluate(@catalog) }.should raise_error(ArgumentError)
+ expect { @dep.evaluate(@catalog) }.to raise_error(ArgumentError)
end
it "should add the target as a 'before' value if the type is 'relationship'" do
@dep.type = :relationship
@dep.evaluate(@catalog)
- @source[:before].should be_include("Mytype[target]")
+ expect(@source[:before]).to be_include("Mytype[target]")
end
it "should add the target as a 'notify' value if the type is 'subscription'" do
@dep.type = :subscription
@dep.evaluate(@catalog)
- @source[:notify].should be_include("Mytype[target]")
+ expect(@source[:notify]).to be_include("Mytype[target]")
end
it "should supplement rather than clobber existing relationship values" do
@source[:before] = "File[/bar]"
@dep.evaluate(@catalog)
# this test did not work before. It was appending the resources
# together as a string
- (@source[:before].class == Array).should be_true
- @source[:before].should be_include("Mytype[target]")
- @source[:before].should be_include("File[/bar]")
+ expect(@source[:before].class == Array).to be_truthy
+ expect(@source[:before]).to be_include("Mytype[target]")
+ expect(@source[:before]).to be_include("File[/bar]")
end
it "should supplement rather than clobber existing resource relationships" do
@source[:before] = @extra_resource
@dep.evaluate(@catalog)
- (@source[:before].class == Array).should be_true
- @source[:before].should be_include("Mytype[target]")
- @source[:before].should be_include(@extra_resource)
+ expect(@source[:before].class == Array).to be_truthy
+ expect(@source[:before]).to be_include("Mytype[target]")
+ expect(@source[:before]).to be_include(@extra_resource)
end
it "should supplement rather than clobber multiple existing resource relationships" do
@source[:before] = [@extra_resource, @extra_resource2]
@dep.evaluate(@catalog)
- (@source[:before].class == Array).should be_true
- @source[:before].should be_include("Mytype[target]")
- @source[:before].should be_include(@extra_resource)
- @source[:before].should be_include(@extra_resource2)
+ expect(@source[:before].class == Array).to be_truthy
+ expect(@source[:before]).to be_include("Mytype[target]")
+ expect(@source[:before]).to be_include(@extra_resource)
+ expect(@source[:before]).to be_include(@extra_resource2)
end
end
end
diff --git a/spec/unit/parser/resource_spec.rb b/spec/unit/parser/resource_spec.rb
index 97f19e21a..d4270dfb6 100755
--- a/spec/unit/parser/resource_spec.rb
+++ b/spec/unit/parser/resource_spec.rb
@@ -1,582 +1,582 @@
require 'spec_helper'
describe Puppet::Parser::Resource do
before do
environment = Puppet::Node::Environment.create(:testing, [])
@node = Puppet::Node.new("yaynode", :environment => environment)
@known_resource_types = environment.known_resource_types
@compiler = Puppet::Parser::Compiler.new(@node)
@source = newclass ""
@scope = @compiler.topscope
end
def mkresource(args = {})
args[:source] ||= @source
args[:scope] ||= @scope
params = args[:parameters] || {:one => "yay", :three => "rah"}
if args[:parameters] == :none
args.delete(:parameters)
elsif not args[:parameters].is_a? Array
args[:parameters] = paramify(args[:source], params)
end
Puppet::Parser::Resource.new("resource", "testing", args)
end
def param(name, value, source)
Puppet::Parser::Resource::Param.new(:name => name, :value => value, :source => source)
end
def paramify(source, hash)
hash.collect do |name, value|
Puppet::Parser::Resource::Param.new(
:name => name, :value => value, :source => source
)
end
end
def newclass(name)
@known_resource_types.add Puppet::Resource::Type.new(:hostclass, name)
end
def newdefine(name)
@known_resource_types.add Puppet::Resource::Type.new(:definition, name)
end
def newnode(name)
@known_resource_types.add Puppet::Resource::Type.new(:node, name)
end
it "should get its environment from its scope" do
scope = stub 'scope', :source => stub("source"), :namespaces => nil
scope.expects(:environment).returns("foo").at_least_once
- Puppet::Parser::Resource.new("file", "whatever", :scope => scope).environment.should == "foo"
+ expect(Puppet::Parser::Resource.new("file", "whatever", :scope => scope).environment).to eq("foo")
end
it "should use the resource type collection helper module" do
- Puppet::Parser::Resource.ancestors.should be_include(Puppet::Resource::TypeCollectionHelper)
+ expect(Puppet::Parser::Resource.ancestors).to be_include(Puppet::Resource::TypeCollectionHelper)
end
it "should use the scope's environment as its environment" do
@scope.expects(:environment).returns("myenv").at_least_once
- Puppet::Parser::Resource.new("file", "whatever", :scope => @scope).environment.should == "myenv"
+ expect(Puppet::Parser::Resource.new("file", "whatever", :scope => @scope).environment).to eq("myenv")
end
it "should be isomorphic if it is builtin and models an isomorphic type" do
Puppet::Type.type(:file).expects(:isomorphic?).returns(true)
- @resource = Puppet::Parser::Resource.new("file", "whatever", :scope => @scope, :source => @source).isomorphic?.should be_true
+ @resource = expect(Puppet::Parser::Resource.new("file", "whatever", :scope => @scope, :source => @source).isomorphic?).to be_truthy
end
it "should not be isomorphic if it is builtin and models a non-isomorphic type" do
Puppet::Type.type(:file).expects(:isomorphic?).returns(false)
- @resource = Puppet::Parser::Resource.new("file", "whatever", :scope => @scope, :source => @source).isomorphic?.should be_false
+ @resource = expect(Puppet::Parser::Resource.new("file", "whatever", :scope => @scope, :source => @source).isomorphic?).to be_falsey
end
it "should be isomorphic if it is not builtin" do
newdefine "whatever"
- @resource = Puppet::Parser::Resource.new("whatever", "whatever", :scope => @scope, :source => @source).isomorphic?.should be_true
+ @resource = expect(Puppet::Parser::Resource.new("whatever", "whatever", :scope => @scope, :source => @source).isomorphic?).to be_truthy
end
it "should have an array-indexing method for retrieving parameter values" do
@resource = mkresource
- @resource[:one].should == "yay"
+ expect(@resource[:one]).to eq("yay")
end
it "should use a Puppet::Resource for converting to a ral resource" do
trans = mock 'resource', :to_ral => "yay"
@resource = mkresource
@resource.expects(:copy_as_resource).returns trans
- @resource.to_ral.should == "yay"
+ expect(@resource.to_ral).to eq("yay")
end
it "should be able to use the indexing operator to access parameters" do
resource = Puppet::Parser::Resource.new("resource", "testing", :source => "source", :scope => @scope)
resource["foo"] = "bar"
- resource["foo"].should == "bar"
+ expect(resource["foo"]).to eq("bar")
end
it "should return the title when asked for a parameter named 'title'" do
- Puppet::Parser::Resource.new("resource", "testing", :source => @source, :scope => @scope)[:title].should == "testing"
+ expect(Puppet::Parser::Resource.new("resource", "testing", :source => @source, :scope => @scope)[:title]).to eq("testing")
end
describe "when initializing" do
before do
@arguments = {:scope => @scope}
end
it "should fail unless #{name.to_s} is specified" do
expect {
Puppet::Parser::Resource.new('file', '/my/file')
}.to raise_error(ArgumentError, /Resources require a hash as last argument/)
end
it "should set the reference correctly" do
res = Puppet::Parser::Resource.new("resource", "testing", @arguments)
- res.ref.should == "Resource[testing]"
+ expect(res.ref).to eq("Resource[testing]")
end
it "should be tagged with user tags" do
tags = [ "tag1", "tag2" ]
@arguments[:parameters] = [ param(:tag, tags , :source) ]
res = Puppet::Parser::Resource.new("resource", "testing", @arguments)
- res.should be_tagged("tag1")
- res.should be_tagged("tag2")
+ expect(res).to be_tagged("tag1")
+ expect(res).to be_tagged("tag2")
end
end
describe "when evaluating" do
before do
@catalog = Puppet::Resource::Catalog.new
source = stub('source')
source.stubs(:module_name)
@scope = Puppet::Parser::Scope.new(@compiler, :source => source)
@catalog.add_resource(Puppet::Parser::Resource.new("stage", :main, :scope => @scope))
end
it "should evaluate the associated AST definition" do
definition = newdefine "mydefine"
res = Puppet::Parser::Resource.new("mydefine", "whatever", :scope => @scope, :source => @source, :catalog => @catalog)
definition.expects(:evaluate_code).with(res)
res.evaluate
end
it "should evaluate the associated AST class" do
@class = newclass "myclass"
res = Puppet::Parser::Resource.new("class", "myclass", :scope => @scope, :source => @source, :catalog => @catalog)
@class.expects(:evaluate_code).with(res)
res.evaluate
end
it "should evaluate the associated AST node" do
nodedef = newnode("mynode")
res = Puppet::Parser::Resource.new("node", "mynode", :scope => @scope, :source => @source, :catalog => @catalog)
nodedef.expects(:evaluate_code).with(res)
res.evaluate
end
it "should add an edge to any specified stage for class resources" do
@compiler.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "foo", {})
other_stage = Puppet::Parser::Resource.new(:stage, "other", :scope => @scope, :catalog => @catalog)
@compiler.add_resource(@scope, other_stage)
resource = Puppet::Parser::Resource.new(:class, "foo", :scope => @scope, :catalog => @catalog)
resource[:stage] = 'other'
@compiler.add_resource(@scope, resource)
resource.evaluate
- @compiler.catalog.edge?(other_stage, resource).should be_true
+ expect(@compiler.catalog.edge?(other_stage, resource)).to be_truthy
end
it "should fail if an unknown stage is specified" do
@compiler.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "foo", {})
resource = Puppet::Parser::Resource.new(:class, "foo", :scope => @scope, :catalog => @catalog)
resource[:stage] = 'other'
expect { resource.evaluate }.to raise_error(ArgumentError, /Could not find stage other specified by/)
end
it "should add edges from the class resources to the parent's stage if no stage is specified" do
main = @compiler.catalog.resource(:stage, :main)
foo_stage = Puppet::Parser::Resource.new(:stage, :foo_stage, :scope => @scope, :catalog => @catalog)
@compiler.add_resource(@scope, foo_stage)
@compiler.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "foo", {})
resource = Puppet::Parser::Resource.new(:class, "foo", :scope => @scope, :catalog => @catalog)
resource[:stage] = 'foo_stage'
@compiler.add_resource(@scope, resource)
resource.evaluate
- @compiler.catalog.should be_edge(foo_stage, resource)
+ expect(@compiler.catalog).to be_edge(foo_stage, resource)
end
it "should allow edges to propagate multiple levels down the scope hierarchy" do
Puppet[:code] = <<-MANIFEST
stage { before: before => Stage[main] }
class alpha {
include beta
}
class beta {
include gamma
}
class gamma { }
class { alpha: stage => before }
MANIFEST
catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone')
# Stringify them to make for easier lookup
edges = catalog.edges.map {|e| [e.source.ref, e.target.ref]}
- edges.should include(["Stage[before]", "Class[Alpha]"])
- edges.should include(["Stage[before]", "Class[Beta]"])
- edges.should include(["Stage[before]", "Class[Gamma]"])
+ expect(edges).to include(["Stage[before]", "Class[Alpha]"])
+ expect(edges).to include(["Stage[before]", "Class[Beta]"])
+ expect(edges).to include(["Stage[before]", "Class[Gamma]"])
end
it "should use the specified stage even if the parent scope specifies one" do
Puppet[:code] = <<-MANIFEST
stage { before: before => Stage[main], }
stage { after: require => Stage[main], }
class alpha {
class { beta: stage => after }
}
class beta { }
class { alpha: stage => before }
MANIFEST
catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone')
edges = catalog.edges.map {|e| [e.source.ref, e.target.ref]}
- edges.should include(["Stage[before]", "Class[Alpha]"])
- edges.should include(["Stage[after]", "Class[Beta]"])
+ expect(edges).to include(["Stage[before]", "Class[Alpha]"])
+ expect(edges).to include(["Stage[after]", "Class[Beta]"])
end
it "should add edges from top-level class resources to the main stage if no stage is specified" do
main = @compiler.catalog.resource(:stage, :main)
@compiler.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "foo", {})
resource = Puppet::Parser::Resource.new(:class, "foo", :scope => @scope, :catalog => @catalog)
@compiler.add_resource(@scope, resource)
resource.evaluate
- @compiler.catalog.should be_edge(main, resource)
+ expect(@compiler.catalog).to be_edge(main, resource)
end
end
describe "when finishing" do
before do
@class = newclass "myclass"
@nodedef = newnode("mynode")
@resource = Puppet::Parser::Resource.new("file", "whatever", :scope => @scope, :source => @source)
end
it "should do nothing if it has already been finished" do
@resource.finish
@resource.expects(:add_defaults).never
@resource.finish
end
it "should add all defaults available from the scope" do
@resource.scope.expects(:lookupdefaults).with(@resource.type).returns(:owner => param(:owner, "default", @resource.source))
@resource.finish
- @resource[:owner].should == "default"
+ expect(@resource[:owner]).to eq("default")
end
it "should not replace existing parameters with defaults" do
@resource.set_parameter :owner, "oldvalue"
@resource.scope.expects(:lookupdefaults).with(@resource.type).returns(:owner => :replaced)
@resource.finish
- @resource[:owner].should == "oldvalue"
+ expect(@resource[:owner]).to eq("oldvalue")
end
it "should add a copy of each default, rather than the actual default parameter instance" do
newparam = param(:owner, "default", @resource.source)
other = newparam.dup
other.value = "other"
newparam.expects(:dup).returns(other)
@resource.scope.expects(:lookupdefaults).with(@resource.type).returns(:owner => newparam)
@resource.finish
- @resource[:owner].should == "other"
+ expect(@resource[:owner]).to eq("other")
end
end
describe "when being tagged" do
before do
@scope_resource = stub 'scope_resource', :tags => %w{srone srtwo}
@scope.stubs(:resource).returns @scope_resource
@resource = Puppet::Parser::Resource.new("file", "yay", :scope => @scope, :source => mock('source'))
end
it "should get tagged with the resource type" do
- @resource.tags.should be_include("file")
+ expect(@resource.tags).to be_include("file")
end
it "should get tagged with the title" do
- @resource.tags.should be_include("yay")
+ expect(@resource.tags).to be_include("yay")
end
it "should get tagged with each name in the title if the title is a qualified class name" do
resource = Puppet::Parser::Resource.new("file", "one::two", :scope => @scope, :source => mock('source'))
- resource.tags.should be_include("one")
- resource.tags.should be_include("two")
+ expect(resource.tags).to be_include("one")
+ expect(resource.tags).to be_include("two")
end
it "should get tagged with each name in the type if the type is a qualified class name" do
resource = Puppet::Parser::Resource.new("one::two", "whatever", :scope => @scope, :source => mock('source'))
- resource.tags.should be_include("one")
- resource.tags.should be_include("two")
+ expect(resource.tags).to be_include("one")
+ expect(resource.tags).to be_include("two")
end
it "should not get tagged with non-alphanumeric titles" do
resource = Puppet::Parser::Resource.new("file", "this is a test", :scope => @scope, :source => mock('source'))
- resource.tags.should_not be_include("this is a test")
+ expect(resource.tags).not_to be_include("this is a test")
end
it "should fail on tags containing '*' characters" do
expect { @resource.tag("bad*tag") }.to raise_error(Puppet::ParseError)
end
it "should fail on tags starting with '-' characters" do
expect { @resource.tag("-badtag") }.to raise_error(Puppet::ParseError)
end
it "should fail on tags containing ' ' characters" do
expect { @resource.tag("bad tag") }.to raise_error(Puppet::ParseError)
end
it "should allow alpha tags" do
expect { @resource.tag("good_tag") }.to_not raise_error
end
end
describe "when merging overrides" do
before do
@source = "source1"
@resource = mkresource :source => @source
@override = mkresource :source => @source
end
it "should fail when the override was not created by a parent class" do
@override.source = "source2"
@override.source.expects(:child_of?).with("source1").returns(false)
expect { @resource.merge(@override) }.to raise_error(Puppet::ParseError)
end
it "should succeed when the override was created in the current scope" do
@resource.source = "source3"
@override.source = @resource.source
@override.source.expects(:child_of?).with("source3").never
params = {:a => :b, :c => :d}
@override.expects(:parameters).returns(params)
@resource.expects(:override_parameter).with(:b)
@resource.expects(:override_parameter).with(:d)
@resource.merge(@override)
end
it "should succeed when a parent class created the override" do
@resource.source = "source3"
@override.source = "source4"
@override.source.expects(:child_of?).with("source3").returns(true)
params = {:a => :b, :c => :d}
@override.expects(:parameters).returns(params)
@resource.expects(:override_parameter).with(:b)
@resource.expects(:override_parameter).with(:d)
@resource.merge(@override)
end
it "should add new parameters when the parameter is not set" do
@source.stubs(:child_of?).returns true
@override.set_parameter(:testing, "value")
@resource.merge(@override)
- @resource[:testing].should == "value"
+ expect(@resource[:testing]).to eq("value")
end
it "should replace existing parameter values" do
@source.stubs(:child_of?).returns true
@resource.set_parameter(:testing, "old")
@override.set_parameter(:testing, "value")
@resource.merge(@override)
- @resource[:testing].should == "value"
+ expect(@resource[:testing]).to eq("value")
end
it "should add values to the parameter when the override was created with the '+>' syntax" do
@source.stubs(:child_of?).returns true
param = Puppet::Parser::Resource::Param.new(:name => :testing, :value => "testing", :source => @resource.source)
param.add = true
@override.set_parameter(param)
@resource.set_parameter(:testing, "other")
@resource.merge(@override)
- @resource[:testing].should == %w{other testing}
+ expect(@resource[:testing]).to eq(%w{other testing})
end
it "should not merge parameter values when multiple resources are overriden with '+>' at once " do
@resource_2 = mkresource :source => @source
@resource. set_parameter(:testing, "old_val_1")
@resource_2.set_parameter(:testing, "old_val_2")
@source.stubs(:child_of?).returns true
param = Puppet::Parser::Resource::Param.new(:name => :testing, :value => "new_val", :source => @resource.source)
param.add = true
@override.set_parameter(param)
@resource. merge(@override)
@resource_2.merge(@override)
- @resource [:testing].should == %w{old_val_1 new_val}
- @resource_2[:testing].should == %w{old_val_2 new_val}
+ expect(@resource [:testing]).to eq(%w{old_val_1 new_val})
+ expect(@resource_2[:testing]).to eq(%w{old_val_2 new_val})
end
it "should promote tag overrides to real tags" do
@source.stubs(:child_of?).returns true
param = Puppet::Parser::Resource::Param.new(:name => :tag, :value => "testing", :source => @resource.source)
@override.set_parameter(param)
@resource.merge(@override)
- @resource.tagged?("testing").should be_true
+ expect(@resource.tagged?("testing")).to be_truthy
end
end
it "should be able to be converted to a normal resource" do
@source = stub 'scope', :name => "myscope"
@resource = mkresource :source => @source
- @resource.should respond_to(:copy_as_resource)
+ expect(@resource).to respond_to(:copy_as_resource)
end
describe "when being converted to a resource" do
before do
@parser_resource = mkresource :scope => @scope, :parameters => {:foo => "bar", :fee => "fum"}
end
it "should create an instance of Puppet::Resource" do
- @parser_resource.copy_as_resource.should be_instance_of(Puppet::Resource)
+ expect(@parser_resource.copy_as_resource).to be_instance_of(Puppet::Resource)
end
it "should set the type correctly on the Puppet::Resource" do
- @parser_resource.copy_as_resource.type.should == @parser_resource.type
+ expect(@parser_resource.copy_as_resource.type).to eq(@parser_resource.type)
end
it "should set the title correctly on the Puppet::Resource" do
- @parser_resource.copy_as_resource.title.should == @parser_resource.title
+ expect(@parser_resource.copy_as_resource.title).to eq(@parser_resource.title)
end
it "should copy over all of the parameters" do
result = @parser_resource.copy_as_resource.to_hash
# The name will be in here, also.
- result[:foo].should == "bar"
- result[:fee].should == "fum"
+ expect(result[:foo]).to eq("bar")
+ expect(result[:fee]).to eq("fum")
end
it "should copy over the tags" do
@parser_resource.tag "foo"
@parser_resource.tag "bar"
- @parser_resource.copy_as_resource.tags.should == @parser_resource.tags
+ expect(@parser_resource.copy_as_resource.tags).to eq(@parser_resource.tags)
end
it "should copy over the line" do
@parser_resource.line = 40
- @parser_resource.copy_as_resource.line.should == 40
+ expect(@parser_resource.copy_as_resource.line).to eq(40)
end
it "should copy over the file" do
@parser_resource.file = "/my/file"
- @parser_resource.copy_as_resource.file.should == "/my/file"
+ expect(@parser_resource.copy_as_resource.file).to eq("/my/file")
end
it "should copy over the 'exported' value" do
@parser_resource.exported = true
- @parser_resource.copy_as_resource.exported.should be_true
+ expect(@parser_resource.copy_as_resource.exported).to be_truthy
end
it "should copy over the 'virtual' value" do
@parser_resource.virtual = true
- @parser_resource.copy_as_resource.virtual.should be_true
+ expect(@parser_resource.copy_as_resource.virtual).to be_truthy
end
it "should convert any parser resource references to Puppet::Resource instances" do
ref = Puppet::Resource.new("file", "/my/file")
@parser_resource = mkresource :source => @source, :parameters => {:foo => "bar", :fee => ref}
result = @parser_resource.copy_as_resource
- result[:fee].should == Puppet::Resource.new(:file, "/my/file")
+ expect(result[:fee]).to eq(Puppet::Resource.new(:file, "/my/file"))
end
it "should convert any parser resource references to Puppet::Resource instances even if they are in an array" do
ref = Puppet::Resource.new("file", "/my/file")
@parser_resource = mkresource :source => @source, :parameters => {:foo => "bar", :fee => ["a", ref]}
result = @parser_resource.copy_as_resource
- result[:fee].should == ["a", Puppet::Resource.new(:file, "/my/file")]
+ expect(result[:fee]).to eq(["a", Puppet::Resource.new(:file, "/my/file")])
end
it "should convert any parser resource references to Puppet::Resource instances even if they are in an array of array, and even deeper" do
ref1 = Puppet::Resource.new("file", "/my/file1")
ref2 = Puppet::Resource.new("file", "/my/file2")
@parser_resource = mkresource :source => @source, :parameters => {:foo => "bar", :fee => ["a", [ref1,ref2]]}
result = @parser_resource.copy_as_resource
- result[:fee].should == ["a", Puppet::Resource.new(:file, "/my/file1"), Puppet::Resource.new(:file, "/my/file2")]
+ expect(result[:fee]).to eq(["a", Puppet::Resource.new(:file, "/my/file1"), Puppet::Resource.new(:file, "/my/file2")])
end
it "should fail if the same param is declared twice" do
- lambda do
+ expect do
@parser_resource = mkresource :source => @source, :parameters => [
Puppet::Parser::Resource::Param.new(
:name => :foo, :value => "bar", :source => @source
),
Puppet::Parser::Resource::Param.new(
:name => :foo, :value => "baz", :source => @source
)
]
- end.should raise_error(Puppet::ParseError)
+ end.to raise_error(Puppet::ParseError)
end
end
describe "when validating" do
it "should check each parameter" do
resource = Puppet::Parser::Resource.new :foo, "bar", :scope => @scope, :source => stub("source")
resource[:one] = :two
resource[:three] = :four
resource.expects(:validate_parameter).with(:one)
resource.expects(:validate_parameter).with(:three)
resource.send(:validate)
end
it "should raise a parse error when there's a failure" do
resource = Puppet::Parser::Resource.new :foo, "bar", :scope => @scope, :source => stub("source")
resource[:one] = :two
resource.expects(:validate_parameter).with(:one).raises ArgumentError
expect { resource.send(:validate) }.to raise_error(Puppet::ParseError)
end
end
describe "when setting parameters" do
before do
@source = newclass "foobar"
@resource = Puppet::Parser::Resource.new :foo, "bar", :scope => @scope, :source => @source
end
it "should accept Param instances and add them to the parameter list" do
param = Puppet::Parser::Resource::Param.new :name => "foo", :value => "bar", :source => @source
@resource.set_parameter(param)
- @resource["foo"].should == "bar"
+ expect(@resource["foo"]).to eq("bar")
end
it "should allow parameters to be set to 'false'" do
@resource.set_parameter("myparam", false)
- @resource["myparam"].should be_false
+ expect(@resource["myparam"]).to be_falsey
end
it "should use its source when provided a parameter name and value" do
@resource.set_parameter("myparam", "myvalue")
- @resource["myparam"].should == "myvalue"
+ expect(@resource["myparam"]).to eq("myvalue")
end
end
# part of #629 -- the undef keyword. Make sure 'undef' params get skipped.
it "should not include 'undef' parameters when converting itself to a hash" do
resource = Puppet::Parser::Resource.new "file", "/tmp/testing", :source => mock("source"), :scope => mock("scope")
resource[:owner] = :undef
resource[:mode] = "755"
- resource.to_hash[:owner].should be_nil
+ expect(resource.to_hash[:owner]).to be_nil
end
end
diff --git a/spec/unit/parser/scope_spec.rb b/spec/unit/parser/scope_spec.rb
index 96b53f538..b9dd5409b 100755
--- a/spec/unit/parser/scope_spec.rb
+++ b/spec/unit/parser/scope_spec.rb
@@ -1,658 +1,658 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/compiler'
require 'puppet_spec/scope'
describe Puppet::Parser::Scope do
include PuppetSpec::Scope
before :each do
@scope = Puppet::Parser::Scope.new(
Puppet::Parser::Compiler.new(Puppet::Node.new("foo"))
)
@scope.source = Puppet::Resource::Type.new(:node, :foo)
@topscope = @scope.compiler.topscope
@scope.parent = @topscope
end
describe "create_test_scope_for_node" do
let(:node_name) { "node_name_foo" }
let(:scope) { create_test_scope_for_node(node_name) }
it "should be a kind of Scope" do
- scope.should be_a_kind_of(Puppet::Parser::Scope)
+ expect(scope).to be_a_kind_of(Puppet::Parser::Scope)
end
it "should set the source to a node resource" do
- scope.source.should be_a_kind_of(Puppet::Resource::Type)
+ expect(scope.source).to be_a_kind_of(Puppet::Resource::Type)
end
it "should have a compiler" do
- scope.compiler.should be_a_kind_of(Puppet::Parser::Compiler)
+ expect(scope.compiler).to be_a_kind_of(Puppet::Parser::Compiler)
end
it "should set the parent to the compiler topscope" do
- scope.parent.should be(scope.compiler.topscope)
+ expect(scope.parent).to be(scope.compiler.topscope)
end
end
it "should return a scope for use in a test harness" do
- create_test_scope_for_node("node_name_foo").should be_a_kind_of(Puppet::Parser::Scope)
+ expect(create_test_scope_for_node("node_name_foo")).to be_a_kind_of(Puppet::Parser::Scope)
end
it "should be able to retrieve class scopes by name" do
@scope.class_set "myname", "myscope"
- @scope.class_scope("myname").should == "myscope"
+ expect(@scope.class_scope("myname")).to eq("myscope")
end
it "should be able to retrieve class scopes by object" do
klass = mock 'ast_class'
klass.expects(:name).returns("myname")
@scope.class_set "myname", "myscope"
- @scope.class_scope(klass).should == "myscope"
+ expect(@scope.class_scope(klass)).to eq("myscope")
end
it "should be able to retrieve its parent module name from the source of its parent type" do
@topscope.source = Puppet::Resource::Type.new(:hostclass, :foo, :module_name => "foo")
- @scope.parent_module_name.should == "foo"
+ expect(@scope.parent_module_name).to eq("foo")
end
it "should return a nil parent module name if it has no parent" do
- @topscope.parent_module_name.should be_nil
+ expect(@topscope.parent_module_name).to be_nil
end
it "should return a nil parent module name if its parent has no source" do
- @scope.parent_module_name.should be_nil
+ expect(@scope.parent_module_name).to be_nil
end
it "should get its environment from its compiler" do
env = Puppet::Node::Environment.create(:testing, [])
compiler = stub 'compiler', :environment => env, :is_a? => true
scope = Puppet::Parser::Scope.new(compiler)
- scope.environment.should equal(env)
+ expect(scope.environment).to equal(env)
end
it "should fail if no compiler is supplied" do
expect {
Puppet::Parser::Scope.new
}.to raise_error(ArgumentError, /wrong number of arguments/)
end
it "should fail if something that isn't a compiler is supplied" do
expect {
Puppet::Parser::Scope.new(:compiler => true)
}.to raise_error(Puppet::DevError, /you must pass a compiler instance/)
end
it "should use the resource type collection helper to find its known resource types" do
- Puppet::Parser::Scope.ancestors.should include(Puppet::Resource::TypeCollectionHelper)
+ expect(Puppet::Parser::Scope.ancestors).to include(Puppet::Resource::TypeCollectionHelper)
end
describe "when custom functions are called" do
let(:env) { Puppet::Node::Environment.create(:testing, []) }
let(:compiler) { Puppet::Parser::Compiler.new(Puppet::Node.new('foo', :environment => env)) }
let(:scope) { Puppet::Parser::Scope.new(compiler) }
it "calls methods prefixed with function_ as custom functions" do
- scope.function_sprintf(["%b", 123]).should == "1111011"
+ expect(scope.function_sprintf(["%b", 123])).to eq("1111011")
end
it "raises an error when arguments are not passed in an Array" do
expect do
scope.function_sprintf("%b", 123)
end.to raise_error ArgumentError, /custom functions must be called with a single array that contains the arguments/
end
it "raises an error on subsequent calls when arguments are not passed in an Array" do
scope.function_sprintf(["first call"])
expect do
scope.function_sprintf("%b", 123)
end.to raise_error ArgumentError, /custom functions must be called with a single array that contains the arguments/
end
it "raises NoMethodError when the not prefixed" do
expect { scope.sprintf(["%b", 123]) }.to raise_error(NoMethodError)
end
it "raises NoMethodError when prefixed with function_ but it doesn't exist" do
expect { scope.function_fake_bs(['cows']) }.to raise_error(NoMethodError)
end
end
describe "when initializing" do
it "should extend itself with its environment's Functions module as well as the default" do
env = Puppet::Node::Environment.create(:myenv, [])
root = Puppet.lookup(:root_environment)
compiler = stub 'compiler', :environment => env, :is_a? => true
scope = Puppet::Parser::Scope.new(compiler)
- scope.singleton_class.ancestors.should be_include(Puppet::Parser::Functions.environment_module(env))
- scope.singleton_class.ancestors.should be_include(Puppet::Parser::Functions.environment_module(root))
+ expect(scope.singleton_class.ancestors).to be_include(Puppet::Parser::Functions.environment_module(env))
+ expect(scope.singleton_class.ancestors).to be_include(Puppet::Parser::Functions.environment_module(root))
end
it "should extend itself with the default Functions module if its environment is the default" do
root = Puppet.lookup(:root_environment)
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
scope = Puppet::Parser::Scope.new(compiler)
- scope.singleton_class.ancestors.should be_include(Puppet::Parser::Functions.environment_module(root))
+ expect(scope.singleton_class.ancestors).to be_include(Puppet::Parser::Functions.environment_module(root))
end
end
describe "when looking up a variable" do
it "should support :lookupvar and :setvar for backward compatibility" do
@scope.setvar("var", "yep")
- @scope.lookupvar("var").should == "yep"
+ expect(@scope.lookupvar("var")).to eq("yep")
end
it "should fail if invoked with a non-string name" do
expect { @scope[:foo] }.to raise_error(Puppet::ParseError, /Scope variable name .* not a string/)
expect { @scope[:foo] = 12 }.to raise_error(Puppet::ParseError, /Scope variable name .* not a string/)
end
it "should return nil for unset variables" do
- @scope["var"].should be_nil
+ expect(@scope["var"]).to be_nil
end
it "answers exist? with boolean false for non existing variables" do
expect(@scope.exist?("var")).to be(false)
end
it "answers exist? with boolean false for non existing variables" do
@scope["var"] = "yep"
expect(@scope.exist?("var")).to be(true)
end
it "should be able to look up values" do
@scope["var"] = "yep"
- @scope["var"].should == "yep"
+ expect(@scope["var"]).to eq("yep")
end
it "should be able to look up hashes" do
@scope["var"] = {"a" => "b"}
- @scope["var"].should == {"a" => "b"}
+ expect(@scope["var"]).to eq({"a" => "b"})
end
it "should be able to look up variables in parent scopes" do
@topscope["var"] = "parentval"
- @scope["var"].should == "parentval"
+ expect(@scope["var"]).to eq("parentval")
end
it "should prefer its own values to parent values" do
@topscope["var"] = "parentval"
@scope["var"] = "childval"
- @scope["var"].should == "childval"
+ expect(@scope["var"]).to eq("childval")
end
it "should be able to detect when variables are set" do
@scope["var"] = "childval"
- @scope.should be_include("var")
+ expect(@scope).to be_include("var")
end
it "does not allow changing a set value" do
@scope["var"] = "childval"
expect {
@scope["var"] = "change"
}.to raise_error(Puppet::Error, "Cannot reassign variable var")
end
it "should be able to detect when variables are not set" do
- @scope.should_not be_include("var")
+ expect(@scope).not_to be_include("var")
end
describe "and the variable is qualified" do
before :each do
@known_resource_types = @scope.known_resource_types
node = Puppet::Node.new('localhost')
@compiler = Puppet::Parser::Compiler.new(node)
end
def newclass(name)
@known_resource_types.add Puppet::Resource::Type.new(:hostclass, name)
end
def create_class_scope(name)
klass = newclass(name)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource(Puppet::Parser::Resource.new("stage", :main, :scope => Puppet::Parser::Scope.new(@compiler)))
Puppet::Parser::Resource.new("class", name, :scope => @scope, :source => mock('source'), :catalog => catalog).evaluate
@scope.class_scope(klass)
end
it "should be able to look up explicitly fully qualified variables from main" do
Puppet.expects(:deprecation_warning).never
other_scope = create_class_scope("")
other_scope["othervar"] = "otherval"
- @scope["::othervar"].should == "otherval"
+ expect(@scope["::othervar"]).to eq("otherval")
end
it "should be able to look up explicitly fully qualified variables from other scopes" do
Puppet.expects(:deprecation_warning).never
other_scope = create_class_scope("other")
other_scope["var"] = "otherval"
- @scope["::other::var"].should == "otherval"
+ expect(@scope["::other::var"]).to eq("otherval")
end
it "should be able to look up deeply qualified variables" do
Puppet.expects(:deprecation_warning).never
other_scope = create_class_scope("other::deep::klass")
other_scope["var"] = "otherval"
- @scope["other::deep::klass::var"].should == "otherval"
+ expect(@scope["other::deep::klass::var"]).to eq("otherval")
end
it "should return nil for qualified variables that cannot be found in other classes" do
other_scope = create_class_scope("other::deep::klass")
- @scope["other::deep::klass::var"].should be_nil
+ expect(@scope["other::deep::klass::var"]).to be_nil
end
it "should warn and return nil for qualified variables whose classes have not been evaluated" do
klass = newclass("other::deep::klass")
@scope.expects(:warning)
- @scope["other::deep::klass::var"].should be_nil
+ expect(@scope["other::deep::klass::var"]).to be_nil
end
it "should warn and return nil for qualified variables whose classes do not exist" do
@scope.expects(:warning)
- @scope["other::deep::klass::var"].should be_nil
+ expect(@scope["other::deep::klass::var"]).to be_nil
end
it "should return nil when asked for a non-string qualified variable from a class that does not exist" do
@scope.stubs(:warning)
- @scope["other::deep::klass::var"].should be_nil
+ expect(@scope["other::deep::klass::var"]).to be_nil
end
it "should return nil when asked for a non-string qualified variable from a class that has not been evaluated" do
@scope.stubs(:warning)
klass = newclass("other::deep::klass")
- @scope["other::deep::klass::var"].should be_nil
+ expect(@scope["other::deep::klass::var"]).to be_nil
end
end
context "and strict_variables is true" do
before(:each) do
Puppet[:strict_variables] = true
end
it "should throw a symbol when unknown variable is looked up" do
expect { @scope['john_doe'] }.to throw_symbol(:undefined_variable)
end
it "should throw a symbol when unknown qualified variable is looked up" do
expect { @scope['nowhere::john_doe'] }.to throw_symbol(:undefined_variable)
end
end
end
describe "when variables are set with append=true" do
it "should raise error if the variable is already defined in this scope" do
@scope.setvar("var", "1", :append => false)
expect {
@scope.setvar("var", "1", :append => true)
}.to raise_error(
Puppet::ParseError,
"Cannot append, variable var is defined in this scope"
)
end
it "should lookup current variable value" do
@scope.expects(:[]).with("var").returns("2")
@scope.setvar("var", "1", :append => true)
end
it "should store the concatenated string '42'" do
@topscope.setvar("var", "4", :append => false)
@scope.setvar("var", "2", :append => true)
- @scope["var"].should == "42"
+ expect(@scope["var"]).to eq("42")
end
it "should store the concatenated array [4,2]" do
@topscope.setvar("var", [4], :append => false)
@scope.setvar("var", [2], :append => true)
- @scope["var"].should == [4,2]
+ expect(@scope["var"]).to eq([4,2])
end
it "should store the merged hash {a => b, c => d}" do
@topscope.setvar("var", {"a" => "b"}, :append => false)
@scope.setvar("var", {"c" => "d"}, :append => true)
- @scope["var"].should == {"a" => "b", "c" => "d"}
+ expect(@scope["var"]).to eq({"a" => "b", "c" => "d"})
end
it "should raise an error when appending a hash with something other than another hash" do
@topscope.setvar("var", {"a" => "b"}, :append => false)
expect {
@scope.setvar("var", "not a hash", :append => true)
}.to raise_error(
ArgumentError,
"Trying to append to a hash with something which is not a hash is unsupported"
)
end
end
describe "when calling number?" do
it "should return nil if called with anything not a number" do
- Puppet::Parser::Scope.number?([2]).should be_nil
+ expect(Puppet::Parser::Scope.number?([2])).to be_nil
end
it "should return a Fixnum for a Fixnum" do
- Puppet::Parser::Scope.number?(2).should be_an_instance_of(Fixnum)
+ expect(Puppet::Parser::Scope.number?(2)).to be_an_instance_of(Fixnum)
end
it "should return a Float for a Float" do
- Puppet::Parser::Scope.number?(2.34).should be_an_instance_of(Float)
+ expect(Puppet::Parser::Scope.number?(2.34)).to be_an_instance_of(Float)
end
it "should return 234 for '234'" do
- Puppet::Parser::Scope.number?("234").should == 234
+ expect(Puppet::Parser::Scope.number?("234")).to eq(234)
end
it "should return nil for 'not a number'" do
- Puppet::Parser::Scope.number?("not a number").should be_nil
+ expect(Puppet::Parser::Scope.number?("not a number")).to be_nil
end
it "should return 23.4 for '23.4'" do
- Puppet::Parser::Scope.number?("23.4").should == 23.4
+ expect(Puppet::Parser::Scope.number?("23.4")).to eq(23.4)
end
it "should return 23.4e13 for '23.4e13'" do
- Puppet::Parser::Scope.number?("23.4e13").should == 23.4e13
+ expect(Puppet::Parser::Scope.number?("23.4e13")).to eq(23.4e13)
end
it "should understand negative numbers" do
- Puppet::Parser::Scope.number?("-234").should == -234
+ expect(Puppet::Parser::Scope.number?("-234")).to eq(-234)
end
it "should know how to convert exponential float numbers ala '23e13'" do
- Puppet::Parser::Scope.number?("23e13").should == 23e13
+ expect(Puppet::Parser::Scope.number?("23e13")).to eq(23e13)
end
it "should understand hexadecimal numbers" do
- Puppet::Parser::Scope.number?("0x234").should == 0x234
+ expect(Puppet::Parser::Scope.number?("0x234")).to eq(0x234)
end
it "should understand octal numbers" do
- Puppet::Parser::Scope.number?("0755").should == 0755
+ expect(Puppet::Parser::Scope.number?("0755")).to eq(0755)
end
it "should return nil on malformed integers" do
- Puppet::Parser::Scope.number?("0.24.5").should be_nil
+ expect(Puppet::Parser::Scope.number?("0.24.5")).to be_nil
end
it "should convert strings with leading 0 to integer if they are not octal" do
- Puppet::Parser::Scope.number?("0788").should == 788
+ expect(Puppet::Parser::Scope.number?("0788")).to eq(788)
end
it "should convert strings of negative integers" do
- Puppet::Parser::Scope.number?("-0788").should == -788
+ expect(Puppet::Parser::Scope.number?("-0788")).to eq(-788)
end
it "should return nil on malformed hexadecimal numbers" do
- Puppet::Parser::Scope.number?("0x89g").should be_nil
+ expect(Puppet::Parser::Scope.number?("0x89g")).to be_nil
end
end
describe "when using ephemeral variables" do
it "should store the variable value" do
# @scope.setvar("1", :value, :ephemeral => true)
@scope.set_match_data({1 => :value})
- @scope["1"].should == :value
+ expect(@scope["1"]).to eq(:value)
end
it "should remove the variable value when unset_ephemeral_var(:all) is called" do
# @scope.setvar("1", :value, :ephemeral => true)
@scope.set_match_data({1 => :value})
@scope.stubs(:parent).returns(nil)
@scope.unset_ephemeral_var(:all)
- @scope["1"].should be_nil
+ expect(@scope["1"]).to be_nil
end
it "should not remove classic variables when unset_ephemeral_var(:all) is called" do
@scope['myvar'] = :value1
@scope.set_match_data({1 => :value2})
@scope.stubs(:parent).returns(nil)
@scope.unset_ephemeral_var(:all)
- @scope["myvar"].should == :value1
+ expect(@scope["myvar"]).to eq(:value1)
end
it "should raise an error when setting numerical variable" do
expect {
@scope.setvar("1", :value3, :ephemeral => true)
}.to raise_error(Puppet::ParseError, /Cannot assign to a numeric match result variable/)
end
describe "with more than one level" do
it "should prefer latest ephemeral scopes" do
@scope.set_match_data({0 => :earliest})
@scope.new_ephemeral
@scope.set_match_data({0 => :latest})
- @scope["0"].should == :latest
+ expect(@scope["0"]).to eq(:latest)
end
it "should be able to report the current level" do
- @scope.ephemeral_level.should == 1
+ expect(@scope.ephemeral_level).to eq(1)
@scope.new_ephemeral
- @scope.ephemeral_level.should == 2
+ expect(@scope.ephemeral_level).to eq(2)
end
it "should not check presence of an ephemeral variable across multiple levels" do
# This test was testing that scope actuallys screwed up - making values from earlier matches show as if they
# where true for latest match - insanity !
@scope.new_ephemeral
@scope.set_match_data({1 => :value1})
@scope.new_ephemeral
@scope.set_match_data({0 => :value2})
@scope.new_ephemeral
- @scope.include?("1").should be_false
+ expect(@scope.include?("1")).to be_falsey
end
it "should return false when an ephemeral variable doesn't exist in any ephemeral scope" do
@scope.new_ephemeral
@scope.set_match_data({1 => :value1})
@scope.new_ephemeral
@scope.set_match_data({0 => :value2})
@scope.new_ephemeral
- @scope.include?("2").should be_false
+ expect(@scope.include?("2")).to be_falsey
end
it "should not get ephemeral values from earlier scope when not in later" do
@scope.set_match_data({1 => :value1})
@scope.new_ephemeral
@scope.set_match_data({0 => :value2})
- @scope.include?("1").should be_false
+ expect(@scope.include?("1")).to be_falsey
end
describe "when calling unset_ephemeral_var with a level" do
it "should remove ephemeral scopes up to this level" do
@scope.set_match_data({1 => :value1})
@scope.new_ephemeral
@scope.set_match_data({1 => :value2})
level = @scope.ephemeral_level()
@scope.new_ephemeral
@scope.set_match_data({1 => :value3})
@scope.unset_ephemeral_var(level)
- @scope["1"].should == :value2
+ expect(@scope["1"]).to eq(:value2)
end
end
end
end
context "when using ephemeral as local scope" do
it "should store all variables in local scope" do
@scope.new_ephemeral true
@scope.setvar("apple", :fruit)
- @scope["apple"].should == :fruit
+ expect(@scope["apple"]).to eq(:fruit)
end
it "should remove all local scope variables on unset" do
@scope.new_ephemeral true
@scope.setvar("apple", :fruit)
- @scope["apple"].should == :fruit
+ expect(@scope["apple"]).to eq(:fruit)
@scope.unset_ephemeral_var
- @scope["apple"].should == nil
+ expect(@scope["apple"]).to eq(nil)
end
it "should be created from a hash" do
@scope.ephemeral_from({ "apple" => :fruit, "strawberry" => :berry})
- @scope["apple"].should == :fruit
- @scope["strawberry"].should == :berry
+ expect(@scope["apple"]).to eq(:fruit)
+ expect(@scope["strawberry"]).to eq(:berry)
end
end
describe "when setting ephemeral vars from matches" do
before :each do
@match = stub 'match', :is_a? => true
@match.stubs(:[]).with(0).returns("this is a string")
@match.stubs(:captures).returns([])
@scope.stubs(:setvar)
end
it "should accept only MatchData" do
expect {
@scope.ephemeral_from("match")
}.to raise_error(ArgumentError, /Invalid regex match data/)
end
it "should set $0 with the full match" do
# This is an internal impl detail test
@scope.expects(:new_match_scope).with { |*arg| arg[0][0] == "this is a string" }
@scope.ephemeral_from(@match)
end
it "should set every capture as ephemeral var" do
# This is an internal impl detail test
@match.stubs(:[]).with(1).returns(:capture1)
@match.stubs(:[]).with(2).returns(:capture2)
@scope.expects(:new_match_scope).with { |*arg| arg[0][1] == :capture1 && arg[0][2] == :capture2 }
@scope.ephemeral_from(@match)
end
it "should shadow previous match variables" do
# This is an internal impl detail test
@match.stubs(:[]).with(1).returns(:capture1)
@match.stubs(:[]).with(2).returns(:capture2)
@match2 = stub 'match', :is_a? => true
@match2.stubs(:[]).with(1).returns(:capture2_1)
@match2.stubs(:[]).with(2).returns(nil)
@scope.ephemeral_from(@match)
@scope.ephemeral_from(@match2)
- @scope.lookupvar('2').should == nil
+ expect(@scope.lookupvar('2')).to eq(nil)
end
it "should create a new ephemeral level" do
level_before = @scope.ephemeral_level
@scope.ephemeral_from(@match)
expect(level_before < @scope.ephemeral_level)
end
end
describe "when managing defaults" do
it "should be able to set and lookup defaults" do
param = Puppet::Parser::Resource::Param.new(:name => :myparam, :value => "myvalue", :source => stub("source"))
@scope.define_settings(:mytype, param)
- @scope.lookupdefaults(:mytype).should == {:myparam => param}
+ expect(@scope.lookupdefaults(:mytype)).to eq({:myparam => param})
end
it "should fail if a default is already defined and a new default is being defined" do
param = Puppet::Parser::Resource::Param.new(:name => :myparam, :value => "myvalue", :source => stub("source"))
@scope.define_settings(:mytype, param)
expect {
@scope.define_settings(:mytype, param)
}.to raise_error(Puppet::ParseError, /Default already defined .* cannot redefine/)
end
it "should return multiple defaults at once" do
param1 = Puppet::Parser::Resource::Param.new(:name => :myparam, :value => "myvalue", :source => stub("source"))
@scope.define_settings(:mytype, param1)
param2 = Puppet::Parser::Resource::Param.new(:name => :other, :value => "myvalue", :source => stub("source"))
@scope.define_settings(:mytype, param2)
- @scope.lookupdefaults(:mytype).should == {:myparam => param1, :other => param2}
+ expect(@scope.lookupdefaults(:mytype)).to eq({:myparam => param1, :other => param2})
end
it "should look up defaults defined in parent scopes" do
param1 = Puppet::Parser::Resource::Param.new(:name => :myparam, :value => "myvalue", :source => stub("source"))
@scope.define_settings(:mytype, param1)
child_scope = @scope.newscope
param2 = Puppet::Parser::Resource::Param.new(:name => :other, :value => "myvalue", :source => stub("source"))
child_scope.define_settings(:mytype, param2)
- child_scope.lookupdefaults(:mytype).should == {:myparam => param1, :other => param2}
+ expect(child_scope.lookupdefaults(:mytype)).to eq({:myparam => param1, :other => param2})
end
end
context "#true?" do
{ "a string" => true,
"true" => true,
"false" => true,
true => true,
"" => false,
:undef => false,
nil => false
}.each do |input, output|
it "should treat #{input.inspect} as #{output}" do
- Puppet::Parser::Scope.true?(input).should == output
+ expect(Puppet::Parser::Scope.true?(input)).to eq(output)
end
end
end
context "when producing a hash of all variables (as used in templates)" do
it "should contain all defined variables in the scope" do
@scope.setvar("orange", :tangerine)
@scope.setvar("pear", :green)
- @scope.to_hash.should == {'orange' => :tangerine, 'pear' => :green }
+ expect(@scope.to_hash).to eq({'orange' => :tangerine, 'pear' => :green })
end
it "should contain variables in all local scopes (#21508)" do
@scope.new_ephemeral true
@scope.setvar("orange", :tangerine)
@scope.setvar("pear", :green)
@scope.new_ephemeral true
@scope.setvar("apple", :red)
- @scope.to_hash.should == {'orange' => :tangerine, 'pear' => :green, 'apple' => :red }
+ expect(@scope.to_hash).to eq({'orange' => :tangerine, 'pear' => :green, 'apple' => :red })
end
it "should contain all defined variables in the scope and all local scopes" do
@scope.setvar("orange", :tangerine)
@scope.setvar("pear", :green)
@scope.new_ephemeral true
@scope.setvar("apple", :red)
- @scope.to_hash.should == {'orange' => :tangerine, 'pear' => :green, 'apple' => :red }
+ expect(@scope.to_hash).to eq({'orange' => :tangerine, 'pear' => :green, 'apple' => :red })
end
it "should not contain varaibles in match scopes (non local emphemeral)" do
@scope.new_ephemeral true
@scope.setvar("orange", :tangerine)
@scope.setvar("pear", :green)
@scope.ephemeral_from(/(f)(o)(o)/.match('foo'))
- @scope.to_hash.should == {'orange' => :tangerine, 'pear' => :green }
+ expect(@scope.to_hash).to eq({'orange' => :tangerine, 'pear' => :green })
end
it "should delete values that are :undef in inner scope" do
@scope.new_ephemeral true
@scope.setvar("orange", :tangerine)
@scope.setvar("pear", :green)
@scope.new_ephemeral true
@scope.setvar("apple", :red)
@scope.setvar("orange", :undef)
- @scope.to_hash.should == {'pear' => :green, 'apple' => :red }
+ expect(@scope.to_hash).to eq({'pear' => :green, 'apple' => :red })
end
end
end
diff --git a/spec/unit/parser/templatewrapper_spec.rb b/spec/unit/parser/templatewrapper_spec.rb
index 38dcb7000..83985423b 100755
--- a/spec/unit/parser/templatewrapper_spec.rb
+++ b/spec/unit/parser/templatewrapper_spec.rb
@@ -1,101 +1,101 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/parser/templatewrapper'
describe Puppet::Parser::TemplateWrapper do
let(:known_resource_types) { Puppet::Resource::TypeCollection.new("env") }
let(:scope) do
compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("mynode"))
compiler.environment.stubs(:known_resource_types).returns known_resource_types
Puppet::Parser::Scope.new compiler
end
let(:tw) { Puppet::Parser::TemplateWrapper.new(scope) }
it "fails if a template cannot be found" do
Puppet::Parser::Files.expects(:find_template).returns nil
expect { tw.file = "fake_template" }.to raise_error(Puppet::ParseError)
end
it "stringifies as template[<filename>] for a file based template" do
Puppet::Parser::Files.stubs(:find_template).returns("/tmp/fake_template")
tw.file = "fake_template"
- tw.to_s.should eql("template[/tmp/fake_template]")
+ expect(tw.to_s).to eql("template[/tmp/fake_template]")
end
it "stringifies as template[inline] for a string-based template" do
- tw.to_s.should eql("template[inline]")
+ expect(tw.to_s).to eql("template[inline]")
end
it "reads and evaluates a file-based template" do
given_a_template_file("fake_template", "template contents")
tw.file = "fake_template"
- tw.result.should eql("template contents")
+ expect(tw.result).to eql("template contents")
end
it "provides access to the name of the template via #file" do
full_file_name = given_a_template_file("fake_template", "<%= file %>")
tw.file = "fake_template"
- tw.result.should == full_file_name
+ expect(tw.result).to eq(full_file_name)
end
it "evaluates a given string as a template" do
- tw.result("template contents").should eql("template contents")
+ expect(tw.result("template contents")).to eql("template contents")
end
it "provides the defined classes with #classes" do
catalog = mock 'catalog', :classes => ["class1", "class2"]
scope.expects(:catalog).returns( catalog )
- tw.classes.should == ["class1", "class2"]
+ expect(tw.classes).to eq(["class1", "class2"])
end
it "provides all the tags with #all_tags" do
catalog = mock 'catalog', :tags => ["tag1", "tag2"]
scope.expects(:catalog).returns( catalog )
- tw.all_tags.should == ["tag1","tag2"]
+ expect(tw.all_tags).to eq(["tag1","tag2"])
end
it "provides the tags defined in the current scope with #tags" do
scope.expects(:tags).returns( ["tag1", "tag2"] )
- tw.tags.should == ["tag1","tag2"]
+ expect(tw.tags).to eq(["tag1","tag2"])
end
it "raises error on access to removed in-scope variables via method calls" do
scope["in_scope_variable"] = "is good"
expect { tw.result("<%= in_scope_variable %>") }.to raise_error(/undefined local variable or method `in_scope_variable'/ )
end
it "reports that variable is available when it is in scope" do
scope["in_scope_variable"] = "is good"
- tw.result("<%= has_variable?('in_scope_variable') %>").should == "true"
+ expect(tw.result("<%= has_variable?('in_scope_variable') %>")).to eq("true")
end
it "reports that a variable is not available when it is not in scope" do
- tw.result("<%= has_variable?('not_in_scope_variable') %>").should == "false"
+ expect(tw.result("<%= has_variable?('not_in_scope_variable') %>")).to eq("false")
end
it "provides access to in-scope variables via instance variables" do
scope["one"] = "foo"
- tw.result("<%= @one %>").should == "foo"
+ expect(tw.result("<%= @one %>")).to eq("foo")
end
%w{! . ; :}.each do |badchar|
it "translates #{badchar} to _ in instance variables" do
scope["one#{badchar}"] = "foo"
- tw.result("<%= @one_ %>").should == "foo"
+ expect(tw.result("<%= @one_ %>")).to eq("foo")
end
end
def given_a_template_file(name, contents)
full_name = "/full/path/to/#{name}"
Puppet::Parser::Files.stubs(:find_template).
with(name, anything()).
returns(full_name)
File.stubs(:read).with(full_name).returns(contents)
full_name
end
end
diff --git a/spec/unit/parser/type_loader_spec.rb b/spec/unit/parser/type_loader_spec.rb
index d2de50548..06818297f 100755
--- a/spec/unit/parser/type_loader_spec.rb
+++ b/spec/unit/parser/type_loader_spec.rb
@@ -1,204 +1,204 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/parser/type_loader'
require 'puppet/parser/parser_factory'
require 'puppet_spec/modules'
require 'puppet_spec/files'
describe Puppet::Parser::TypeLoader do
include PuppetSpec::Modules
include PuppetSpec::Files
let(:empty_hostclass) { Puppet::Parser::AST::Hostclass.new('') }
let(:loader) { Puppet::Parser::TypeLoader.new(:myenv) }
let(:my_env) { Puppet::Node::Environment.create(:myenv, []) }
around do |example|
envs = Puppet::Environments::Static.new(my_env)
Puppet.override(:environments => envs) do
example.run
end
end
it "should support an environment" do
loader = Puppet::Parser::TypeLoader.new(:myenv)
- loader.environment.name.should == :myenv
+ expect(loader.environment.name).to eq(:myenv)
end
it "should delegate its known resource types to its environment" do
- loader.known_resource_types.should be_instance_of(Puppet::Resource::TypeCollection)
+ expect(loader.known_resource_types).to be_instance_of(Puppet::Resource::TypeCollection)
end
describe "when loading names from namespaces" do
it "should do nothing if the name to import is an empty string" do
- loader.try_load_fqname(:hostclass, "").should be_nil
+ expect(loader.try_load_fqname(:hostclass, "")).to be_nil
end
it "should attempt to import each generated name" do
loader.expects(:import_from_modules).with("foo/bar").returns([])
loader.expects(:import_from_modules).with("foo").returns([])
loader.try_load_fqname(:hostclass, "foo::bar")
end
it "should attempt to load each possible name going from most to least specific" do
path_order = sequence('path')
['foo/bar/baz', 'foo/bar', 'foo'].each do |path|
Puppet::Parser::Files.expects(:find_manifests_in_modules).with(path, anything).returns([nil, []]).in_sequence(path_order)
end
loader.try_load_fqname(:hostclass, 'foo::bar::baz')
end
end
describe "when importing" do
let(:stub_parser) { stub 'Parser', :file= => nil, :parse => empty_hostclass }
before(:each) do
Puppet::Parser::ParserFactory.stubs(:parser).with(anything).returns(stub_parser)
end
it "should find all manifests matching the file or pattern" do
Puppet::Parser::Files.expects(:find_manifests_in_modules).with("myfile", anything).returns ["modname", %w{one}]
loader.import("myfile", "/path")
end
it "should pass the environment when looking for files" do
Puppet::Parser::Files.expects(:find_manifests_in_modules).with(anything, loader.environment).returns ["modname", %w{one}]
loader.import("myfile", "/path")
end
it "should fail if no files are found" do
Puppet::Parser::Files.expects(:find_manifests_in_modules).returns [nil, []]
- lambda { loader.import("myfile", "/path") }.should raise_error(/No file\(s\) found for import/)
+ expect { loader.import("myfile", "/path") }.to raise_error(/No file\(s\) found for import/)
end
it "should parse each found file" do
Puppet::Parser::Files.expects(:find_manifests_in_modules).returns ["modname", [make_absolute("/one")]]
loader.expects(:parse_file).with(make_absolute("/one")).returns(Puppet::Parser::AST::Hostclass.new(''))
loader.import("myfile", "/path")
end
it "should not attempt to import files that have already been imported" do
loader = Puppet::Parser::TypeLoader.new(:myenv)
Puppet::Parser::Files.expects(:find_manifests_in_modules).twice.returns ["modname", %w{/one}]
- loader.import("myfile", "/path").should_not be_empty
+ expect(loader.import("myfile", "/path")).not_to be_empty
- loader.import("myfile", "/path").should be_empty
+ expect(loader.import("myfile", "/path")).to be_empty
end
end
describe "when importing all" do
let(:base) { tmpdir("base") }
let(:modulebase1) { File.join(base, "first") }
let(:modulebase2) { File.join(base, "second") }
let(:my_env) { Puppet::Node::Environment.create(:myenv, [modulebase1, modulebase2]) }
before do
# Create two module path directories
FileUtils.mkdir_p(modulebase1)
FileUtils.mkdir_p(modulebase2)
end
def mk_module(basedir, name)
PuppetSpec::Modules.create(name, basedir)
end
# We have to pass the base path so that we can
# write to modules that are in the second search path
def mk_manifests(base, mod, files)
files.collect do |file|
name = mod.name + "::" + file.gsub("/", "::")
path = File.join(base, mod.name, "manifests", file + ".pp")
FileUtils.mkdir_p(File.split(path)[0])
# write out the class
File.open(path, "w") { |f| f.print "class #{name} {}" }
name
end
end
it "should load all puppet manifests from all modules in the specified environment" do
module1 = mk_module(modulebase1, "one")
module2 = mk_module(modulebase2, "two")
mk_manifests(modulebase1, module1, %w{a b})
mk_manifests(modulebase2, module2, %w{c d})
loader.import_all
- loader.environment.known_resource_types.hostclass("one::a").should be_instance_of(Puppet::Resource::Type)
- loader.environment.known_resource_types.hostclass("one::b").should be_instance_of(Puppet::Resource::Type)
- loader.environment.known_resource_types.hostclass("two::c").should be_instance_of(Puppet::Resource::Type)
- loader.environment.known_resource_types.hostclass("two::d").should be_instance_of(Puppet::Resource::Type)
+ expect(loader.environment.known_resource_types.hostclass("one::a")).to be_instance_of(Puppet::Resource::Type)
+ expect(loader.environment.known_resource_types.hostclass("one::b")).to be_instance_of(Puppet::Resource::Type)
+ expect(loader.environment.known_resource_types.hostclass("two::c")).to be_instance_of(Puppet::Resource::Type)
+ expect(loader.environment.known_resource_types.hostclass("two::d")).to be_instance_of(Puppet::Resource::Type)
end
it "should not load manifests from duplicate modules later in the module path" do
module1 = mk_module(modulebase1, "one")
# duplicate
module2 = mk_module(modulebase2, "one")
mk_manifests(modulebase1, module1, %w{a})
mk_manifests(modulebase2, module2, %w{c})
loader.import_all
- loader.environment.known_resource_types.hostclass("one::c").should be_nil
+ expect(loader.environment.known_resource_types.hostclass("one::c")).to be_nil
end
it "should load manifests from subdirectories" do
module1 = mk_module(modulebase1, "one")
mk_manifests(modulebase1, module1, %w{a a/b a/b/c})
loader.import_all
- loader.environment.known_resource_types.hostclass("one::a::b").should be_instance_of(Puppet::Resource::Type)
- loader.environment.known_resource_types.hostclass("one::a::b::c").should be_instance_of(Puppet::Resource::Type)
+ expect(loader.environment.known_resource_types.hostclass("one::a::b")).to be_instance_of(Puppet::Resource::Type)
+ expect(loader.environment.known_resource_types.hostclass("one::a::b::c")).to be_instance_of(Puppet::Resource::Type)
end
it "should skip modules that don't have manifests" do
module1 = mk_module(modulebase1, "one")
module2 = mk_module(modulebase2, "two")
mk_manifests(modulebase2, module2, %w{c d})
loader.import_all
- loader.environment.known_resource_types.hostclass("one::a").should be_nil
- loader.environment.known_resource_types.hostclass("two::c").should be_instance_of(Puppet::Resource::Type)
- loader.environment.known_resource_types.hostclass("two::d").should be_instance_of(Puppet::Resource::Type)
+ expect(loader.environment.known_resource_types.hostclass("one::a")).to be_nil
+ expect(loader.environment.known_resource_types.hostclass("two::c")).to be_instance_of(Puppet::Resource::Type)
+ expect(loader.environment.known_resource_types.hostclass("two::d")).to be_instance_of(Puppet::Resource::Type)
end
end
describe "when parsing a file" do
it "requests a new parser instance for each file" do
parser = stub 'Parser', :file= => nil, :parse => empty_hostclass
Puppet::Parser::ParserFactory.expects(:parser).twice.returns(parser)
loader.parse_file("/my/file")
loader.parse_file("/my/other_file")
end
it "assigns the parser its file and then parses" do
parser = mock 'parser'
Puppet::Parser::ParserFactory.expects(:parser).returns(parser)
parser.expects(:file=).with("/my/file")
parser.expects(:parse).returns(empty_hostclass)
loader.parse_file("/my/file")
end
end
it "should be able to add classes to the current resource type collection" do
file = tmpfile("simple_file.pp")
File.open(file, "w") { |f| f.puts "class foo {}" }
loader.import(File.basename(file), File.dirname(file))
- loader.known_resource_types.hostclass("foo").should be_instance_of(Puppet::Resource::Type)
+ expect(loader.known_resource_types.hostclass("foo")).to be_instance_of(Puppet::Resource::Type)
end
end
diff --git a/spec/unit/pops/adaptable_spec.rb b/spec/unit/pops/adaptable_spec.rb
index 544a6c54f..d4529b900 100644
--- a/spec/unit/pops/adaptable_spec.rb
+++ b/spec/unit/pops/adaptable_spec.rb
@@ -1,141 +1,141 @@
#! /usr/bin/env ruby
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)
- a.class.should == ValueAdapter
+ 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)
- b.value.should == 10
+ expect(b.value).to eq(10)
end
it "should return the correct adapter if there are several" do
d = Duck.new
other = OtherAdapter.adapt(d)
a = ValueAdapter.adapt(d)
a.value = 10
b = ValueAdapter.adapt(d)
- b.value.should == 10
+ expect(b.value).to eq(10)
end
it "should allow specialization to override creating" do
d = Duck.new
a = OtherAdapter.adapt(d)
- a.value.should == "I am calling you Daffy."
+ 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)
- a.value.should == "I am calling you Daffy."
+ expect(a.value).to eq("I am calling you Daffy.")
a.value = "Something different"
- a.value.should == "Something different"
+ expect(a.value).to eq("Something different")
b = OtherAdapter.adapt(d)
- b.value.should == "Something different"
+ expect(b.value).to eq("Something different")
b = OtherAdapter.adapt_new(d)
- b.value.should == "I am calling you Daffy."
+ 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)
- a.should == nil
+ expect(a).to eq(nil)
end
it "should return same adapter from get after adapt" do
d = Duck.new
a = OtherAdapter.get(d)
- a.should == nil
+ expect(a).to eq(nil)
a = OtherAdapter.adapt(d)
- a.value.should == "I am calling you Daffy."
+ expect(a.value).to eq("I am calling you Daffy.")
b = OtherAdapter.get(d)
- b.value.should == "I am calling you Daffy."
- a.should == b
+ 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)
- a.should == nil
+ expect(a).to eq(nil)
a = Farm::FarmAdapter.adapt(d)
a.value = 10
b = Farm::FarmAdapter.get(d)
- b.value.should == 10
+ expect(b.value).to eq(10)
end
it "should be able to clear the adapter" do
d = Duck.new
a = OtherAdapter.adapt(d)
- a.value.should == "I am calling you Daffy."
+ expect(a.value).to eq("I am calling you Daffy.")
# The adapter cleared should be returned
- OtherAdapter.clear(d).value.should == "I am calling you Daffy."
- OtherAdapter.get(d).should == nil
+ 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
- a.value.should == "Donald"
+ 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
- a.value.should == "Donald, the Duck"
+ 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
- a.value.should == "Donald"
+ 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
- a.value.should == "Donald, the Duck"
+ expect(a.value).to eq("Donald, the Duck")
end
end
end
diff --git a/spec/unit/pops/binder/bindings_checker_spec.rb b/spec/unit/pops/binder/bindings_checker_spec.rb
index 9d8630de2..982e3b420 100644
--- a/spec/unit/pops/binder/bindings_checker_spec.rb
+++ b/spec/unit/pops/binder/bindings_checker_spec.rb
@@ -1,155 +1,155 @@
require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/pops'
describe 'The bindings checker' do
include PuppetSpec::Pops
Issues = Puppet::Pops::Binder::BinderIssues
Bindings = Puppet::Pops::Binder::Bindings
TypeFactory = Puppet::Pops::Types::TypeFactory
let (:acceptor) { Puppet::Pops::Validation::Acceptor.new() }
let (:binding) { Bindings::Binding.new() }
let (:ok_binding) {
b = Bindings::Binding.new()
b.producer = Bindings::ConstantProducerDescriptor.new()
b.producer.value = 'some value'
b.type = TypeFactory.string()
b
}
def validate(binding)
Puppet::Pops::Binder::BindingsValidatorFactory.new().validator(acceptor).validate(binding)
end
def bindings(*args)
b = Bindings::Bindings.new()
b.bindings = args
b
end
def named_bindings(name, *args)
b = Bindings::NamedBindings.new()
b.name = name
b.bindings = args
b
end
def layer(name, *bindings)
l = Bindings::NamedLayer.new()
l.name = name
l.bindings = bindings
l
end
def layered_bindings(*layers)
b = Bindings::LayeredBindings.new()
b.layers = layers
b
end
def array_multibinding()
b = Bindings::Multibinding.new()
b.producer = Bindings::ArrayMultibindProducerDescriptor.new()
b.type = TypeFactory.array_of_data()
b
end
def bad_array_multibinding()
b = array_multibinding()
b.type = TypeFactory.hash_of_data() # intentionally wrong!
b
end
def hash_multibinding()
b = Bindings::Multibinding.new()
b.producer = Bindings::HashMultibindProducerDescriptor.new()
b.type = TypeFactory.hash_of_data()
b
end
def bad_hash_multibinding()
b = hash_multibinding()
b.type = TypeFactory.array_of_data() # intentionally wrong!
b
end
it 'should complain about missing producer and type' do
validate(binding())
- acceptor.should have_issue(Issues::MISSING_PRODUCER)
- acceptor.should have_issue(Issues::MISSING_TYPE)
+ expect(acceptor).to have_issue(Issues::MISSING_PRODUCER)
+ expect(acceptor).to have_issue(Issues::MISSING_TYPE)
end
context 'when checking array multibinding' do
it 'should complain about non array producers' do
validate(bad_array_multibinding())
- acceptor.should have_issue(Issues::MULTIBIND_INCOMPATIBLE_TYPE)
+ expect(acceptor).to have_issue(Issues::MULTIBIND_INCOMPATIBLE_TYPE)
end
end
context 'when checking hash multibinding' do
it 'should complain about non hash producers' do
validate(bad_hash_multibinding())
- acceptor.should have_issue(Issues::MULTIBIND_INCOMPATIBLE_TYPE)
+ expect(acceptor).to have_issue(Issues::MULTIBIND_INCOMPATIBLE_TYPE)
end
end
context 'when checking bindings' do
it 'should not accept zero bindings' do
validate(bindings())
- acceptor.should have_issue(Issues::MISSING_BINDINGS)
+ expect(acceptor).to have_issue(Issues::MISSING_BINDINGS)
end
it 'should accept non-zero bindings' do
validate(bindings(ok_binding))
- acceptor.errors_or_warnings?.should() == false
+ expect(acceptor.errors_or_warnings?).to eq(false)
end
it 'should check contained bindings' do
validate(bindings(bad_array_multibinding()))
- acceptor.should have_issue(Issues::MULTIBIND_INCOMPATIBLE_TYPE)
+ expect(acceptor).to have_issue(Issues::MULTIBIND_INCOMPATIBLE_TYPE)
end
end
context 'when checking named bindings' do
it 'should accept named bindings' do
validate(named_bindings('garfield', ok_binding))
- acceptor.errors_or_warnings?.should() == false
+ expect(acceptor.errors_or_warnings?).to eq(false)
end
it 'should not accept unnamed bindings' do
validate(named_bindings(nil, ok_binding))
- acceptor.should have_issue(Issues::MISSING_BINDINGS_NAME)
+ expect(acceptor).to have_issue(Issues::MISSING_BINDINGS_NAME)
end
it 'should do generic bindings check' do
validate(named_bindings('garfield'))
- acceptor.should have_issue(Issues::MISSING_BINDINGS)
+ expect(acceptor).to have_issue(Issues::MISSING_BINDINGS)
end
end
context 'when checking layered bindings' do
it 'should not accept zero layers' do
validate(layered_bindings())
- acceptor.should have_issue(Issues::MISSING_LAYERS)
+ expect(acceptor).to have_issue(Issues::MISSING_LAYERS)
end
it 'should accept non-zero layers' do
validate(layered_bindings(layer('foo', named_bindings('bar', ok_binding))))
- acceptor.errors_or_warnings?.should() == false
+ expect(acceptor.errors_or_warnings?).to eq(false)
end
it 'should not accept unnamed layers' do
validate(layered_bindings(layer(nil, named_bindings('bar', ok_binding))))
- acceptor.should have_issue(Issues::MISSING_LAYER_NAME)
+ expect(acceptor).to have_issue(Issues::MISSING_LAYER_NAME)
end
it 'should accept layers without bindings' do
validate(layered_bindings(layer('foo')))
- acceptor.should_not have_issue(Issues::MISSING_BINDINGS_IN_LAYER)
+ expect(acceptor).not_to have_issue(Issues::MISSING_BINDINGS_IN_LAYER)
end
end
end
diff --git a/spec/unit/pops/binder/bindings_validator_factory_spec.rb b/spec/unit/pops/binder/bindings_validator_factory_spec.rb
index c90da799c..1bf05750f 100644
--- a/spec/unit/pops/binder/bindings_validator_factory_spec.rb
+++ b/spec/unit/pops/binder/bindings_validator_factory_spec.rb
@@ -1,18 +1,18 @@
require 'spec_helper'
require 'puppet/pops'
describe 'The bindings validator factory' do
let(:factory) { Puppet::Pops::Binder::BindingsValidatorFactory.new() }
it 'should instantiate a BindingsValidatorFactory' do
- factory.class.should == Puppet::Pops::Binder::BindingsValidatorFactory
+ expect(factory.class).to eq(Puppet::Pops::Binder::BindingsValidatorFactory)
end
it 'should produce label_provider of class BindingsLabelProvider' do
- factory.label_provider.class.should == Puppet::Pops::Binder::BindingsLabelProvider
+ expect(factory.label_provider.class).to eq(Puppet::Pops::Binder::BindingsLabelProvider)
end
it 'should produce validator of class BindingsChecker' do
- factory.validator(Puppet::Pops::Validation::Acceptor.new()).class.should == Puppet::Pops::Binder::BindingsChecker
+ expect(factory.validator(Puppet::Pops::Validation::Acceptor.new()).class).to eq(Puppet::Pops::Binder::BindingsChecker)
end
end
diff --git a/spec/unit/pops/binder/injector_spec.rb b/spec/unit/pops/binder/injector_spec.rb
index 7feeb4192..be92f7292 100644
--- a/spec/unit/pops/binder/injector_spec.rb
+++ b/spec/unit/pops/binder/injector_spec.rb
@@ -1,786 +1,786 @@
require 'spec_helper'
require 'puppet/pops'
module InjectorSpecModule
def injector(binder)
Puppet::Pops::Binder::Injector.new(binder)
end
def factory
Puppet::Pops::Binder::BindingsFactory
end
def test_layer_with_empty_bindings
factory.named_layer('test-layer', factory.named_bindings('test').model)
end
def test_layer_with_bindings(*bindings)
factory.named_layer('test-layer', *bindings)
end
def null_scope()
nil
end
def type_calculator
Puppet::Pops::Types::TypeCalculator
end
def type_factory
Puppet::Pops::Types::TypeFactory
end
# Returns a binder
#
def configured_binder
b = Puppet::Pops::Binder::Binder.new()
b
end
class TestDuck
end
class Daffy < TestDuck
end
class AngryDuck < TestDuck
# Supports assisted inject, returning a Donald duck as the default impl of Duck
def self.inject(injector, scope, binding, *args)
Donald.new()
end
end
class Donald < AngryDuck
end
class ArneAnka < AngryDuck
attr_reader :label
def initialize()
@label = 'A Swedish angry cartoon duck'
end
end
class ScroogeMcDuck < TestDuck
attr_reader :fortune
# Supports assisted inject, returning an ScroogeMcDuck with 1$ fortune or first arg in args
# Note that when injected (via instance producer, or implict assisted inject, the inject method
# always wins.
def self.inject(injector, scope, binding, *args)
self.new(args[0].nil? ? 1 : args[0])
end
def initialize(fortune)
@fortune = fortune
end
end
class NamedDuck < TestDuck
attr_reader :name
def initialize(name)
@name = name
end
end
# Test custom producer that on each produce returns a duck that is twice as rich as its predecessor
class ScroogeProducer < Puppet::Pops::Binder::Producers::Producer
attr_reader :next_capital
def initialize
@next_capital = 100
end
def produce(scope)
ScroogeMcDuck.new(@next_capital *= 2)
end
end
end
describe 'Injector' do
include InjectorSpecModule
let(:bindings) { factory.named_bindings('test') }
let(:scope) { null_scope()}
let(:binder) { Puppet::Pops::Binder::Binder }
let(:lbinder) do
binder.new(layered_bindings)
end
def duck_type
# create distinct instances
type_factory.ruby(InjectorSpecModule::TestDuck)
end
let(:layered_bindings) { factory.layered_bindings(test_layer_with_bindings(bindings.model)) }
context 'When created' do
it 'should not raise an error if binder is configured' do
expect { injector(lbinder) }.to_not raise_error
end
it 'should create an empty injector given an empty binder' do
expect { binder.new(layered_bindings) }.to_not raise_exception
end
it "should be possible to reference the TypeCalculator" do
- injector(lbinder).type_calculator.is_a?(Puppet::Pops::Types::TypeCalculator).should == true
+ expect(injector(lbinder).type_calculator.is_a?(Puppet::Pops::Types::TypeCalculator)).to eq(true)
end
it "should be possible to reference the KeyFactory" do
- injector(lbinder).key_factory.is_a?(Puppet::Pops::Binder::KeyFactory).should == true
+ expect(injector(lbinder).key_factory.is_a?(Puppet::Pops::Binder::KeyFactory)).to eq(true)
end
it "can be created using a model" do
bindings.bind.name('a_string').to('42')
injector = Puppet::Pops::Binder::Injector.create_from_model(layered_bindings)
- injector.lookup(scope, 'a_string').should == '42'
+ expect(injector.lookup(scope, 'a_string')).to eq('42')
end
it 'can be created using a block' do
injector = Puppet::Pops::Binder::Injector.create('test') do
bind.name('a_string').to('42')
end
- injector.lookup(scope, 'a_string').should == '42'
+ expect(injector.lookup(scope, 'a_string')).to eq('42')
end
it 'can be created using a hash' do
injector = Puppet::Pops::Binder::Injector.create_from_hash('test', 'a_string' => '42')
- injector.lookup(scope, 'a_string').should == '42'
+ expect(injector.lookup(scope, 'a_string')).to eq('42')
end
it 'can be created using an overriding injector with block' do
injector = Puppet::Pops::Binder::Injector.create('test') do
bind.name('a_string').to('42')
end
injector2 = injector.override('override') do
bind.name('a_string').to('43')
end
- injector.lookup(scope, 'a_string').should == '42'
- injector2.lookup(scope, 'a_string').should == '43'
+ expect(injector.lookup(scope, 'a_string')).to eq('42')
+ expect(injector2.lookup(scope, 'a_string')).to eq('43')
end
it 'can be created using an overriding injector with hash' do
injector = Puppet::Pops::Binder::Injector.create_from_hash('test', 'a_string' => '42')
injector2 = injector.override_with_hash('override', 'a_string' => '43')
- injector.lookup(scope, 'a_string').should == '42'
- injector2.lookup(scope, 'a_string').should == '43'
+ expect(injector.lookup(scope, 'a_string')).to eq('42')
+ expect(injector2.lookup(scope, 'a_string')).to eq('43')
end
it "can be created using an overriding injector with a model" do
injector = Puppet::Pops::Binder::Injector.create_from_hash('test', 'a_string' => '42')
bindings.bind.name('a_string').to('43')
injector2 = injector.override_with_model(layered_bindings)
- injector.lookup(scope, 'a_string').should == '42'
- injector2.lookup(scope, 'a_string').should == '43'
+ expect(injector.lookup(scope, 'a_string')).to eq('42')
+ expect(injector2.lookup(scope, 'a_string')).to eq('43')
end
end
context "When looking up objects" do
it 'lookup(scope, name) finds bound object of type Data with given name' do
bindings.bind().name('a_string').to('42')
- injector(lbinder).lookup(scope, 'a_string').should == '42'
+ expect(injector(lbinder).lookup(scope, 'a_string')).to eq('42')
end
context 'a block transforming the result can be given' do
it 'that transform a found value given scope and value' do
bindings.bind().name('a_string').to('42')
- injector(lbinder).lookup(scope, 'a_string') {|zcope, val| val + '42' }.should == '4242'
+ expect(injector(lbinder).lookup(scope, 'a_string') {|zcope, val| val + '42' }).to eq('4242')
end
it 'that transform a found value given only value' do
bindings.bind().name('a_string').to('42')
- injector(lbinder).lookup(scope, 'a_string') {|val| val + '42' }.should == '4242'
+ expect(injector(lbinder).lookup(scope, 'a_string') {|val| val + '42' }).to eq('4242')
end
it 'that produces a default value when entry is missing' do
bindings.bind().name('a_string').to('42')
- injector(lbinder).lookup(scope, 'a_non_existing_string') {|val| val ? (raise Error, "Should not happen") : '4242' }.should == '4242'
+ expect(injector(lbinder).lookup(scope, 'a_non_existing_string') {|val| val ? (raise Error, "Should not happen") : '4242' }).to eq('4242')
end
end
context "and class is not bound" do
it "assisted inject kicks in for classes with zero args constructor" do
duck_type = type_factory.ruby(InjectorSpecModule::Daffy)
injector = injector(lbinder)
- injector.lookup(scope, duck_type).is_a?(InjectorSpecModule::Daffy).should == true
- injector.lookup_producer(scope, duck_type).produce(scope).is_a?(InjectorSpecModule::Daffy).should == true
+ expect(injector.lookup(scope, duck_type).is_a?(InjectorSpecModule::Daffy)).to eq(true)
+ expect(injector.lookup_producer(scope, duck_type).produce(scope).is_a?(InjectorSpecModule::Daffy)).to eq(true)
end
it "assisted inject produces same instance on lookup but not on lookup producer" do
duck_type = type_factory.ruby(InjectorSpecModule::Daffy)
injector = injector(lbinder)
d1 = injector.lookup(scope, duck_type)
d2 = injector.lookup(scope, duck_type)
- d1.equal?(d2).should == true
+ expect(d1.equal?(d2)).to eq(true)
d1 = injector.lookup_producer(scope, duck_type).produce(scope)
d2 = injector.lookup_producer(scope, duck_type).produce(scope)
- d1.equal?(d2).should == false
+ expect(d1.equal?(d2)).to eq(false)
end
it "assisted inject kicks in for classes with a class inject method" do
duck_type = type_factory.ruby(InjectorSpecModule::ScroogeMcDuck)
injector = injector(lbinder)
# Do not pass any arguments, the ScroogeMcDuck :inject method should pick 1 by default
# This tests zero args passed
- injector.lookup(scope, duck_type).fortune.should == 1
- injector.lookup_producer(scope, duck_type).produce(scope).fortune.should == 1
+ expect(injector.lookup(scope, duck_type).fortune).to eq(1)
+ expect(injector.lookup_producer(scope, duck_type).produce(scope).fortune).to eq(1)
end
it "assisted inject selects the inject method if it exists over a zero args constructor" do
injector = injector(lbinder)
duck_type = type_factory.ruby(InjectorSpecModule::AngryDuck)
- injector.lookup(scope, duck_type).is_a?(InjectorSpecModule::Donald).should == true
- injector.lookup_producer(scope, duck_type).produce(scope).is_a?(InjectorSpecModule::Donald).should == true
+ expect(injector.lookup(scope, duck_type).is_a?(InjectorSpecModule::Donald)).to eq(true)
+ expect(injector.lookup_producer(scope, duck_type).produce(scope).is_a?(InjectorSpecModule::Donald)).to eq(true)
end
it "assisted inject selects the zero args constructor if injector is from a superclass" do
injector = injector(lbinder)
duck_type = type_factory.ruby(InjectorSpecModule::ArneAnka)
- injector.lookup(scope, duck_type).is_a?(InjectorSpecModule::ArneAnka).should == true
- injector.lookup_producer(scope, duck_type).produce(scope).is_a?(InjectorSpecModule::ArneAnka).should == true
+ expect(injector.lookup(scope, duck_type).is_a?(InjectorSpecModule::ArneAnka)).to eq(true)
+ expect(injector.lookup_producer(scope, duck_type).produce(scope).is_a?(InjectorSpecModule::ArneAnka)).to eq(true)
end
end
context "and multiple layers are in use" do
it "a higher layer shadows anything in a lower layer" do
bindings1 = factory.named_bindings('test1')
bindings1.bind().name('a_string').to('bad stuff')
lower_layer = factory.named_layer('lower-layer', bindings1.model)
bindings2 = factory.named_bindings('test2')
bindings2.bind().name('a_string').to('good stuff')
higher_layer = factory.named_layer('higher-layer', bindings2.model)
injector = injector(binder.new(factory.layered_bindings(higher_layer, lower_layer)))
- injector.lookup(scope,'a_string').should == 'good stuff'
+ expect(injector.lookup(scope,'a_string')).to eq('good stuff')
end
it "a higher layer may not shadow a lower layer binding that is final" do
bindings1 = factory.named_bindings('test1')
bindings1.bind().final.name('a_string').to('required stuff')
lower_layer = factory.named_layer('lower-layer', bindings1.model)
bindings2 = factory.named_bindings('test2')
bindings2.bind().name('a_string').to('contraband')
higher_layer = factory.named_layer('higher-layer', bindings2.model)
expect {
injector = injector(binder.new(factory.layered_bindings(higher_layer, lower_layer)))
}.to raise_error(/Override of final binding not allowed/)
end
end
context "and dealing with Data types" do
let(:lbinder) { binder.new(layered_bindings) }
it "should treat all data as same type w.r.t. key" do
bindings.bind().name('a_string').to('42')
bindings.bind().name('an_int').to(43)
bindings.bind().name('a_float').to(3.14)
bindings.bind().name('a_boolean').to(true)
bindings.bind().name('an_array').to([1,2,3])
bindings.bind().name('a_hash').to({'a'=>1,'b'=>2,'c'=>3})
injector = injector(lbinder)
- injector.lookup(scope,'a_string').should == '42'
- injector.lookup(scope,'an_int').should == 43
- injector.lookup(scope,'a_float').should == 3.14
- injector.lookup(scope,'a_boolean').should == true
- injector.lookup(scope,'an_array').should == [1,2,3]
- injector.lookup(scope,'a_hash').should == {'a'=>1,'b'=>2,'c'=>3}
+ expect(injector.lookup(scope,'a_string')).to eq('42')
+ expect(injector.lookup(scope,'an_int')).to eq(43)
+ expect(injector.lookup(scope,'a_float')).to eq(3.14)
+ expect(injector.lookup(scope,'a_boolean')).to eq(true)
+ expect(injector.lookup(scope,'an_array')).to eq([1,2,3])
+ expect(injector.lookup(scope,'a_hash')).to eq({'a'=>1,'b'=>2,'c'=>3})
end
it "should provide type-safe lookup of given type/name" do
bindings.bind().string().name('a_string').to('42')
bindings.bind().integer().name('an_int').to(43)
bindings.bind().float().name('a_float').to(3.14)
bindings.bind().boolean().name('a_boolean').to(true)
bindings.bind().array_of_data().name('an_array').to([1,2,3])
bindings.bind().hash_of_data().name('a_hash').to({'a'=>1,'b'=>2,'c'=>3})
injector = injector(lbinder)
# Check lookup using implied Data type
- injector.lookup(scope,'a_string').should == '42'
- injector.lookup(scope,'an_int').should == 43
- injector.lookup(scope,'a_float').should == 3.14
- injector.lookup(scope,'a_boolean').should == true
- injector.lookup(scope,'an_array').should == [1,2,3]
- injector.lookup(scope,'a_hash').should == {'a'=>1,'b'=>2,'c'=>3}
+ expect(injector.lookup(scope,'a_string')).to eq('42')
+ expect(injector.lookup(scope,'an_int')).to eq(43)
+ expect(injector.lookup(scope,'a_float')).to eq(3.14)
+ expect(injector.lookup(scope,'a_boolean')).to eq(true)
+ expect(injector.lookup(scope,'an_array')).to eq([1,2,3])
+ expect(injector.lookup(scope,'a_hash')).to eq({'a'=>1,'b'=>2,'c'=>3})
# Check lookup using expected type
- injector.lookup(scope,type_factory.string(), 'a_string').should == '42'
- injector.lookup(scope,type_factory.integer(), 'an_int').should == 43
- injector.lookup(scope,type_factory.float(),'a_float').should == 3.14
- injector.lookup(scope,type_factory.boolean(),'a_boolean').should == true
- injector.lookup(scope,type_factory.array_of_data(),'an_array').should == [1,2,3]
- injector.lookup(scope,type_factory.hash_of_data(),'a_hash').should == {'a'=>1,'b'=>2,'c'=>3}
+ expect(injector.lookup(scope,type_factory.string(), 'a_string')).to eq('42')
+ expect(injector.lookup(scope,type_factory.integer(), 'an_int')).to eq(43)
+ expect(injector.lookup(scope,type_factory.float(),'a_float')).to eq(3.14)
+ expect(injector.lookup(scope,type_factory.boolean(),'a_boolean')).to eq(true)
+ expect(injector.lookup(scope,type_factory.array_of_data(),'an_array')).to eq([1,2,3])
+ expect(injector.lookup(scope,type_factory.hash_of_data(),'a_hash')).to eq({'a'=>1,'b'=>2,'c'=>3})
# Check lookup using wrong type
expect { injector.lookup(scope,type_factory.integer(), 'a_string')}.to raise_error(/Type error/)
expect { injector.lookup(scope,type_factory.string(), 'an_int')}.to raise_error(/Type error/)
expect { injector.lookup(scope,type_factory.string(),'a_float')}.to raise_error(/Type error/)
expect { injector.lookup(scope,type_factory.string(),'a_boolean')}.to raise_error(/Type error/)
expect { injector.lookup(scope,type_factory.string(),'an_array')}.to raise_error(/Type error/)
expect { injector.lookup(scope,type_factory.string(),'a_hash')}.to raise_error(/Type error/)
end
end
end
context "When looking up producer" do
it 'the value is produced by calling produce(scope)' do
bindings.bind().name('a_string').to('42')
- injector(lbinder).lookup_producer(scope, 'a_string').produce(scope).should == '42'
+ expect(injector(lbinder).lookup_producer(scope, 'a_string').produce(scope)).to eq('42')
end
context 'a block transforming the result can be given' do
it 'that transform a found value given scope and producer' do
bindings.bind().name('a_string').to('42')
- injector(lbinder).lookup_producer(scope, 'a_string') {|zcope, p| p.produce(zcope) + '42' }.should == '4242'
+ expect(injector(lbinder).lookup_producer(scope, 'a_string') {|zcope, p| p.produce(zcope) + '42' }).to eq('4242')
end
it 'that transform a found value given only producer' do
bindings.bind().name('a_string').to('42')
- injector(lbinder).lookup_producer(scope, 'a_string') {|p| p.produce(scope) + '42' }.should == '4242'
+ expect(injector(lbinder).lookup_producer(scope, 'a_string') {|p| p.produce(scope) + '42' }).to eq('4242')
end
it 'that can produce a default value when entry is not found' do
bindings.bind().name('a_string').to('42')
- injector(lbinder).lookup_producer(scope, 'a_non_existing_string') {|p| p ? (raise Error,"Should not happen") : '4242' }.should == '4242'
+ expect(injector(lbinder).lookup_producer(scope, 'a_non_existing_string') {|p| p ? (raise Error,"Should not happen") : '4242' }).to eq('4242')
end
end
end
context "When dealing with singleton vs. non singleton" do
it "should produce the same instance when producer is a singleton" do
bindings.bind().name('a_string').to('42')
injector = injector(lbinder)
a = injector.lookup(scope, 'a_string')
b = injector.lookup(scope, 'a_string')
- a.equal?(b).should == true
+ expect(a.equal?(b)).to eq(true)
end
it "should produce different instances when producer is a non singleton producer" do
bindings.bind().name('a_string').to_series_of('42')
injector = injector(lbinder)
a = injector.lookup(scope, 'a_string')
b = injector.lookup(scope, 'a_string')
- a.should == '42'
- b.should == '42'
- a.equal?(b).should == false
+ expect(a).to eq('42')
+ expect(b).to eq('42')
+ expect(a.equal?(b)).to eq(false)
end
end
context "When using the lookup producer" do
it "should lookup again to produce a value" do
bindings.bind().name('a_string').to_lookup_of('another_string')
bindings.bind().name('another_string').to('hello')
- injector(lbinder).lookup(scope, 'a_string').should == 'hello'
+ expect(injector(lbinder).lookup(scope, 'a_string')).to eq('hello')
end
it "should produce nil if looked up key does not exist" do
bindings.bind().name('a_string').to_lookup_of('non_existing')
- injector(lbinder).lookup(scope, 'a_string').should == nil
+ expect(injector(lbinder).lookup(scope, 'a_string')).to eq(nil)
end
it "should report an error if lookup loop is detected" do
bindings.bind().name('a_string').to_lookup_of('a_string')
expect { injector(lbinder).lookup(scope, 'a_string') }.to raise_error(/Lookup loop/)
end
end
context "When using the hash lookup producer" do
it "should lookup a key in looked up hash" do
data_hash = type_factory.hash_of_data()
bindings.bind().name('a_string').to_hash_lookup_of(data_hash, 'a_hash', 'huey')
bindings.bind().name('a_hash').to({'huey' => 'red', 'dewey' => 'blue', 'louie' => 'green'})
- injector(lbinder).lookup(scope, 'a_string').should == 'red'
+ expect(injector(lbinder).lookup(scope, 'a_string')).to eq('red')
end
it "should produce nil if looked up entry does not exist" do
data_hash = type_factory.hash_of_data()
bindings.bind().name('a_string').to_hash_lookup_of(data_hash, 'non_existing_entry', 'huey')
bindings.bind().name('a_hash').to({'huey' => 'red', 'dewey' => 'blue', 'louie' => 'green'})
- injector(lbinder).lookup(scope, 'a_string').should == nil
+ expect(injector(lbinder).lookup(scope, 'a_string')).to eq(nil)
end
end
context "When using the first found producer" do
it "should lookup until it finds a value, but not further" do
bindings.bind().name('a_string').to_first_found('b_string', 'c_string', 'g_string')
bindings.bind().name('c_string').to('hello')
bindings.bind().name('g_string').to('Oh, mrs. Smith...')
- injector(lbinder).lookup(scope, 'a_string').should == 'hello'
+ expect(injector(lbinder).lookup(scope, 'a_string')).to eq('hello')
end
it "should lookup until it finds a value using mix of type and name, but not further" do
bindings.bind().name('a_string').to_first_found('b_string', [type_factory.string, 'c_string'], 'g_string')
bindings.bind().name('c_string').to('hello')
bindings.bind().name('g_string').to('Oh, mrs. Smith...')
- injector(lbinder).lookup(scope, 'a_string').should == 'hello'
+ expect(injector(lbinder).lookup(scope, 'a_string')).to eq('hello')
end
end
context "When producing instances" do
it "should lookup an instance of a class without arguments" do
bindings.bind().type(duck_type).name('the_duck').to(InjectorSpecModule::Daffy)
- injector(lbinder).lookup(scope, duck_type, 'the_duck').is_a?(InjectorSpecModule::Daffy).should == true
+ expect(injector(lbinder).lookup(scope, duck_type, 'the_duck').is_a?(InjectorSpecModule::Daffy)).to eq(true)
end
it "should lookup an instance of a class with arguments" do
bindings.bind().type(duck_type).name('the_duck').to(InjectorSpecModule::ScroogeMcDuck, 1234)
injector = injector(lbinder)
the_duck = injector.lookup(scope, duck_type, 'the_duck')
- the_duck.is_a?(InjectorSpecModule::ScroogeMcDuck).should == true
- the_duck.fortune.should == 1234
+ expect(the_duck.is_a?(InjectorSpecModule::ScroogeMcDuck)).to eq(true)
+ expect(the_duck.fortune).to eq(1234)
end
it "singleton producer should not be recreated between lookups" do
bindings.bind().type(duck_type).name('the_duck').to_producer(InjectorSpecModule::ScroogeProducer)
injector = injector(lbinder)
the_duck = injector.lookup(scope, duck_type, 'the_duck')
- the_duck.is_a?(InjectorSpecModule::ScroogeMcDuck).should == true
- the_duck.fortune.should == 200
+ expect(the_duck.is_a?(InjectorSpecModule::ScroogeMcDuck)).to eq(true)
+ expect(the_duck.fortune).to eq(200)
# singleton, do it again to get next value in series - it is the producer that is a singleton
# not the produced value
the_duck = injector.lookup(scope, duck_type, 'the_duck')
- the_duck.is_a?(InjectorSpecModule::ScroogeMcDuck).should == true
- the_duck.fortune.should == 400
+ expect(the_duck.is_a?(InjectorSpecModule::ScroogeMcDuck)).to eq(true)
+ expect(the_duck.fortune).to eq(400)
duck_producer = injector.lookup_producer(scope, duck_type, 'the_duck')
- duck_producer.produce(scope).fortune.should == 800
+ expect(duck_producer.produce(scope).fortune).to eq(800)
end
it "series of producers should recreate producer on each lookup and lookup_producer" do
bindings.bind().type(duck_type).name('the_duck').to_producer_series(InjectorSpecModule::ScroogeProducer)
injector = injector(lbinder)
duck_producer = injector.lookup_producer(scope, duck_type, 'the_duck')
- duck_producer.produce(scope).fortune().should == 200
- duck_producer.produce(scope).fortune().should == 400
+ expect(duck_producer.produce(scope).fortune()).to eq(200)
+ expect(duck_producer.produce(scope).fortune()).to eq(400)
# series, each lookup gets a new producer (initialized to produce 200)
duck_producer = injector.lookup_producer(scope, duck_type, 'the_duck')
- duck_producer.produce(scope).fortune().should == 200
- duck_producer.produce(scope).fortune().should == 400
+ expect(duck_producer.produce(scope).fortune()).to eq(200)
+ expect(duck_producer.produce(scope).fortune()).to eq(400)
- injector.lookup(scope, duck_type, 'the_duck').fortune().should == 200
- injector.lookup(scope, duck_type, 'the_duck').fortune().should == 200
+ expect(injector.lookup(scope, duck_type, 'the_duck').fortune()).to eq(200)
+ expect(injector.lookup(scope, duck_type, 'the_duck').fortune()).to eq(200)
end
end
context "When working with multibind" do
context "of hash kind" do
it "a multibind produces contributed items keyed by their bound key-name" do
hash_of_duck = type_factory.hash_of(duck_type)
multibind_id = "ducks"
bindings.multibind(multibind_id).type(hash_of_duck).name('donalds_nephews')
bindings.bind.in_multibind(multibind_id).type(duck_type).name('nephew1').to(InjectorSpecModule::NamedDuck, 'Huey')
bindings.bind.in_multibind(multibind_id).type(duck_type).name('nephew2').to(InjectorSpecModule::NamedDuck, 'Dewey')
bindings.bind.in_multibind(multibind_id).type(duck_type).name('nephew3').to(InjectorSpecModule::NamedDuck, 'Louie')
injector = injector(lbinder)
the_ducks = injector.lookup(scope, hash_of_duck, "donalds_nephews")
- the_ducks.size.should == 3
- the_ducks['nephew1'].name.should == 'Huey'
- the_ducks['nephew2'].name.should == 'Dewey'
- the_ducks['nephew3'].name.should == 'Louie'
+ expect(the_ducks.size).to eq(3)
+ expect(the_ducks['nephew1'].name).to eq('Huey')
+ expect(the_ducks['nephew2'].name).to eq('Dewey')
+ expect(the_ducks['nephew3'].name).to eq('Louie')
end
it "is an error to not bind contribution with a name" do
hash_of_duck = type_factory.hash_of(duck_type)
multibind_id = "ducks"
bindings.multibind(multibind_id).type(hash_of_duck).name('donalds_nephews')
# missing name
bindings.bind.in_multibind(multibind_id).type(duck_type).to(InjectorSpecModule::NamedDuck, 'Huey')
bindings.bind.in_multibind(multibind_id).type(duck_type).to(InjectorSpecModule::NamedDuck, 'Dewey')
expect {
the_ducks = injector(lbinder).lookup(scope, hash_of_duck, "donalds_nephews")
}.to raise_error(/must have a name/)
end
it "is an error to bind with duplicate key when using default (priority) conflict resolution" do
hash_of_duck = type_factory.hash_of(duck_type)
multibind_id = "ducks"
bindings.multibind(multibind_id).type(hash_of_duck).name('donalds_nephews')
# missing name
bindings.bind.in_multibind(multibind_id).type(duck_type).name('foo').to(InjectorSpecModule::NamedDuck, 'Huey')
bindings.bind.in_multibind(multibind_id).type(duck_type).name('foo').to(InjectorSpecModule::NamedDuck, 'Dewey')
expect {
the_ducks = injector(lbinder).lookup(scope, hash_of_duck, "donalds_nephews")
}.to raise_error(/Duplicate key/)
end
it "is not an error to bind with duplicate key when using (ignore) conflict resolution" do
hash_of_duck = type_factory.hash_of(duck_type)
multibind_id = "ducks"
bindings.multibind(multibind_id).type(hash_of_duck).name('donalds_nephews').producer_options(:conflict_resolution => :ignore)
bindings.bind.in_multibind(multibind_id).type(duck_type).name('foo').to(InjectorSpecModule::NamedDuck, 'Huey')
bindings.bind.in_multibind(multibind_id).type(duck_type).name('foo').to(InjectorSpecModule::NamedDuck, 'Dewey')
expect {
the_ducks = injector(lbinder).lookup(scope, hash_of_duck, "donalds_nephews")
}.to_not raise_error
end
it "should produce detailed type error message" do
hash_of_integer = type_factory.hash_of(type_factory.integer())
multibind_id = "ints"
mb = bindings.multibind(multibind_id).type(hash_of_integer).name('donalds_family')
bindings.bind.in_multibind(multibind_id).name('nephew').to('Huey')
expect { ducks = injector(lbinder).lookup(scope, 'donalds_family')
}.to raise_error(%r{expected: Integer, got: String})
end
it "should be possible to combine hash multibind contributions with append on conflict" do
# This case uses a multibind of individual strings, but combines them
# into an array bound to a hash key
# (There are other ways to do this - e.g. have the multibind lookup a multibind
# of array type to which nephews are contributed).
#
hash_of_data = type_factory.hash_of_data()
multibind_id = "ducks"
mb = bindings.multibind(multibind_id).type(hash_of_data).name('donalds_family')
mb.producer_options(:conflict_resolution => :append)
bindings.bind.in_multibind(multibind_id).name('nephews').to('Huey')
bindings.bind.in_multibind(multibind_id).name('nephews').to('Dewey')
bindings.bind.in_multibind(multibind_id).name('nephews').to('Louie')
bindings.bind.in_multibind(multibind_id).name('uncles').to('Scrooge McDuck')
bindings.bind.in_multibind(multibind_id).name('uncles').to('Ludwig Von Drake')
ducks = injector(lbinder).lookup(scope, 'donalds_family')
- ducks['nephews'].should == ['Huey', 'Dewey', 'Louie']
- ducks['uncles'].should == ['Scrooge McDuck', 'Ludwig Von Drake']
+ expect(ducks['nephews']).to eq(['Huey', 'Dewey', 'Louie'])
+ expect(ducks['uncles']).to eq(['Scrooge McDuck', 'Ludwig Von Drake'])
end
it "should be possible to combine hash multibind contributions with append, flat, and uniq, on conflict" do
# This case uses a multibind of individual strings, but combines them
# into an array bound to a hash key
# (There are other ways to do this - e.g. have the multibind lookup a multibind
# of array type to which nephews are contributed).
#
hash_of_data = type_factory.hash_of_data()
multibind_id = "ducks"
mb = bindings.multibind(multibind_id).type(hash_of_data).name('donalds_family')
mb.producer_options(:conflict_resolution => :append, :flatten => true, :uniq => true)
bindings.bind.in_multibind(multibind_id).name('nephews').to('Huey')
bindings.bind.in_multibind(multibind_id).name('nephews').to('Huey')
bindings.bind.in_multibind(multibind_id).name('nephews').to('Dewey')
bindings.bind.in_multibind(multibind_id).name('nephews').to(['Huey', ['Louie'], 'Dewey'])
bindings.bind.in_multibind(multibind_id).name('uncles').to('Scrooge McDuck')
bindings.bind.in_multibind(multibind_id).name('uncles').to('Ludwig Von Drake')
ducks = injector(lbinder).lookup(scope, 'donalds_family')
- ducks['nephews'].should == ['Huey', 'Dewey', 'Louie']
- ducks['uncles'].should == ['Scrooge McDuck', 'Ludwig Von Drake']
+ expect(ducks['nephews']).to eq(['Huey', 'Dewey', 'Louie'])
+ expect(ducks['uncles']).to eq(['Scrooge McDuck', 'Ludwig Von Drake'])
end
it "should fail attempts to append, perform uniq or flatten on type incompatible multibind hash" do
hash_of_integer = type_factory.hash_of(type_factory.integer())
ids = ["ducks1", "ducks2", "ducks3"]
mb = bindings.multibind(ids[0]).type(hash_of_integer.copy).name('broken_family0')
mb.producer_options(:conflict_resolution => :append)
mb = bindings.multibind(ids[1]).type(hash_of_integer.copy).name('broken_family1')
mb.producer_options(:flatten => :true)
mb = bindings.multibind(ids[2]).type(hash_of_integer.copy).name('broken_family2')
mb.producer_options(:uniq => :true)
injector = injector(binder.new(factory.layered_bindings(test_layer_with_bindings(bindings.model))))
expect { injector.lookup(scope, 'broken_family0')}.to raise_error(/:conflict_resolution => :append/)
expect { injector.lookup(scope, 'broken_family1')}.to raise_error(/:flatten/)
expect { injector.lookup(scope, 'broken_family2')}.to raise_error(/:uniq/)
end
it "a higher priority contribution is selected when resolution is :priority" do
hash_of_duck = type_factory.hash_of(duck_type)
multibind_id = "ducks"
bindings.multibind(multibind_id).type(hash_of_duck).name('donalds_nephews')
mb1 = bindings.bind.in_multibind(multibind_id)
pending 'priority based on layers not added, and priority on category removed'
mb1.type(duck_type).name('nephew').to(InjectorSpecModule::NamedDuck, 'Huey')
mb2 = bindings.bind.in_multibind(multibind_id)
mb2.type(duck_type).name('nephew').to(InjectorSpecModule::NamedDuck, 'Dewey')
binder.define_layers(layered_bindings)
- injector(binder).lookup(scope, hash_of_duck, "donalds_nephews")['nephew'].name.should == 'Huey'
+ expect(injector(binder).lookup(scope, hash_of_duck, "donalds_nephews")['nephew'].name).to eq('Huey')
end
it "a higher priority contribution wins when resolution is :merge" do
# THIS TEST MAY DEPEND ON HASH ORDER SINCE PRIORITY BASED ON CATEGORY IS REMOVED
hash_of_data = type_factory.hash_of_data()
multibind_id = "hashed_ducks"
bindings.multibind(multibind_id).type(hash_of_data).name('donalds_nephews').producer_options(:conflict_resolution => :merge)
mb1 = bindings.bind.in_multibind(multibind_id)
mb1.name('nephew').to({'name' => 'Huey', 'is' => 'winner'})
mb2 = bindings.bind.in_multibind(multibind_id)
mb2.name('nephew').to({'name' => 'Dewey', 'is' => 'looser', 'has' => 'cap'})
the_ducks = injector(binder.new(layered_bindings)).lookup(scope, "donalds_nephews");
- the_ducks['nephew']['name'].should == 'Huey'
- the_ducks['nephew']['is'].should == 'winner'
- the_ducks['nephew']['has'].should == 'cap'
+ expect(the_ducks['nephew']['name']).to eq('Huey')
+ expect(the_ducks['nephew']['is']).to eq('winner')
+ expect(the_ducks['nephew']['has']).to eq('cap')
end
end
context "of array kind" do
it "an array multibind produces contributed items, names are allowed but ignored" do
array_of_duck = type_factory.array_of(duck_type)
multibind_id = "ducks"
bindings.multibind(multibind_id).type(array_of_duck).name('donalds_nephews')
# one with name (ignored, expect no error)
bindings.bind.in_multibind(multibind_id).type(duck_type).name('nephew1').to(InjectorSpecModule::NamedDuck, 'Huey')
# two without name
bindings.bind.in_multibind(multibind_id).type(duck_type).to(InjectorSpecModule::NamedDuck, 'Dewey')
bindings.bind.in_multibind(multibind_id).type(duck_type).to(InjectorSpecModule::NamedDuck, 'Louie')
the_ducks = injector(lbinder).lookup(scope, array_of_duck, "donalds_nephews")
- the_ducks.size.should == 3
- the_ducks.collect {|d| d.name }.sort.should == ['Dewey', 'Huey', 'Louie']
+ expect(the_ducks.size).to eq(3)
+ expect(the_ducks.collect {|d| d.name }.sort).to eq(['Dewey', 'Huey', 'Louie'])
end
it "should be able to make result contain only unique entries" do
# This case uses a multibind of individual strings, and combines them
# into an array of unique values
#
array_of_data = type_factory.array_of_data()
multibind_id = "ducks"
mb = bindings.multibind(multibind_id).type(array_of_data).name('donalds_family')
# turn off priority on named to not trigger conflict as all additions have the same precedence
# (could have used the default for unnamed and add unnamed entries).
mb.producer_options(:priority_on_named => false, :uniq => true)
bindings.bind.in_multibind(multibind_id).name('nephews').to('Huey')
bindings.bind.in_multibind(multibind_id).name('nephews').to('Dewey')
bindings.bind.in_multibind(multibind_id).name('nephews').to('Dewey') # duplicate
bindings.bind.in_multibind(multibind_id).name('nephews').to('Louie')
bindings.bind.in_multibind(multibind_id).name('nephews').to('Louie') # duplicate
bindings.bind.in_multibind(multibind_id).name('nephews').to('Louie') # duplicate
ducks = injector(lbinder).lookup(scope, 'donalds_family')
- ducks.should == ['Huey', 'Dewey', 'Louie']
+ expect(ducks).to eq(['Huey', 'Dewey', 'Louie'])
end
it "should be able to contribute elements and arrays of elements and flatten 1 level" do
# This case uses a multibind of individual strings and arrays, and combines them
# into an array of flattened
#
array_of_string = type_factory.array_of(type_factory.string())
multibind_id = "ducks"
mb = bindings.multibind(multibind_id).type(array_of_string).name('donalds_family')
# flatten one level
mb.producer_options(:flatten => 1)
bindings.bind.in_multibind(multibind_id).to('Huey')
bindings.bind.in_multibind(multibind_id).to('Dewey')
bindings.bind.in_multibind(multibind_id).to('Louie') # duplicate
bindings.bind.in_multibind(multibind_id).to(['Huey', 'Dewey', 'Louie'])
ducks = injector(lbinder).lookup(scope, 'donalds_family')
- ducks.should == ['Huey', 'Dewey', 'Louie', 'Huey', 'Dewey', 'Louie']
+ expect(ducks).to eq(['Huey', 'Dewey', 'Louie', 'Huey', 'Dewey', 'Louie'])
end
it "should produce detailed type error message" do
array_of_integer = type_factory.array_of(type_factory.integer())
multibind_id = "ints"
mb = bindings.multibind(multibind_id).type(array_of_integer).name('donalds_family')
bindings.bind.in_multibind(multibind_id).to('Huey')
expect { ducks = injector(lbinder).lookup(scope, 'donalds_family')
}.to raise_error(%r{expected: Integer, or Array\[Integer\], got: String})
end
end
context "When using multibind in multibind" do
it "a hash multibind can be contributed to another" do
hash_of_data = type_factory.hash_of_data()
mb1_id = 'data1'
mb2_id = 'data2'
top = bindings.multibind(mb1_id).type(hash_of_data).name("top")
detail = bindings.multibind(mb2_id).type(hash_of_data).name("detail").in_multibind(mb1_id)
bindings.bind.in_multibind(mb1_id).name('a').to(10)
bindings.bind.in_multibind(mb1_id).name('b').to(20)
bindings.bind.in_multibind(mb2_id).name('a').to(30)
bindings.bind.in_multibind(mb2_id).name('b').to(40)
expect( injector(lbinder).lookup(scope, "top") ).to eql({'detail' => {'a' => 30, 'b' => 40}, 'a' => 10, 'b' => 20})
end
end
context "When looking up entries requiring evaluation" do
let(:node) { Puppet::Node.new('localhost') }
let(:compiler) { Puppet::Parser::Compiler.new(node)}
let(:scope) { Puppet::Parser::Scope.new(compiler) }
let(:parser) { Puppet::Pops::Parser::Parser.new() }
it "should be possible to lookup a concatenated string" do
scope['duck'] = 'Donald Fauntleroy Duck'
expr = parser.parse_string('"Hello $duck"').current()
bindings.bind.name('the_duck').to(expr)
- injector(lbinder).lookup(scope, 'the_duck').should == 'Hello Donald Fauntleroy Duck'
+ expect(injector(lbinder).lookup(scope, 'the_duck')).to eq('Hello Donald Fauntleroy Duck')
end
it "should be possible to post process lookup with a puppet lambda" do
model = parser.parse_string('fake() |$value| {$value + 1 }').current
bindings.bind.name('an_int').to(42).producer_options( :transformer => model.body.lambda)
- injector(lbinder).lookup(scope, 'an_int').should == 43
+ expect(injector(lbinder).lookup(scope, 'an_int')).to eq(43)
end
it "should be possible to post process lookup with a ruby proc" do
transformer = lambda {|value| value + 1 }
bindings.bind.name('an_int').to(42).producer_options( :transformer => transformer)
- injector(lbinder).lookup(scope, 'an_int').should == 43
+ expect(injector(lbinder).lookup(scope, 'an_int')).to eq(43)
end
end
end
context "When there are problems with configuration" do
let(:lbinder) { binder.new(layered_bindings) }
it "reports error for surfacing abstract bindings" do
bindings.bind.abstract.name('an_int')
expect{injector(lbinder).lookup(scope, 'an_int') }.to raise_error(/The abstract binding .* was not overridden/)
end
it "does not report error for abstract binding that is ovrridden" do
bindings.bind.abstract.name('an_int')
bindings.bind.override.name('an_int').to(142)
expect{ injector(lbinder).lookup(scope, 'an_int') }.to_not raise_error
end
it "reports error for overriding binding that does not override" do
bindings.bind.override.name('an_int').to(42)
expect{injector(lbinder).lookup(scope, 'an_int') }.to raise_error(/Binding with unresolved 'override' detected/)
end
it "reports error for binding without producer" do
bindings.bind.name('an_int')
expect{injector(lbinder).lookup(scope, 'an_int') }.to raise_error(/Binding without producer/)
end
end
end
\ No newline at end of file
diff --git a/spec/unit/pops/containment_spec.rb b/spec/unit/pops/containment_spec.rb
index b992ed9d1..bbddea33e 100644
--- a/spec/unit/pops/containment_spec.rb
+++ b/spec/unit/pops/containment_spec.rb
@@ -1,26 +1,26 @@
require 'spec_helper'
require 'puppet/pops'
require File.join(File.dirname(__FILE__), 'factory_rspec_helper')
describe Puppet::Pops::Containment do
include FactoryRspecHelper
it "Should return an Enumerable if eAllContents is called without arguments" do
- (literal(1) + literal(2)).current.eAllContents.is_a?(Enumerable).should == true
+ expect((literal(1) + literal(2)).current.eAllContents.is_a?(Enumerable)).to eq(true)
end
it "Should return all content" do
# Note the top object is not included (an ArithmeticOperation with + operator)
- (literal(1) + literal(2) + literal(3)).current.eAllContents.collect {|x| x}.size.should == 4
+ expect((literal(1) + literal(2) + literal(3)).current.eAllContents.collect {|x| x}.size).to eq(4)
end
it "Should return containing feature" do
left = literal(1)
right = literal(2)
op = left + right
#pending "eContainingFeature does not work on _uni containments in RGen < 0.6.1"
- left.current.eContainingFeature.should == :left_expr
- right.current.eContainingFeature.should == :right_expr
+ expect(left.current.eContainingFeature).to eq(:left_expr)
+ expect(right.current.eContainingFeature).to eq(:right_expr)
end
end
diff --git a/spec/unit/pops/evaluator/access_ops_spec.rb b/spec/unit/pops/evaluator/access_ops_spec.rb
index 8eb696d47..f5c912aae 100644
--- a/spec/unit/pops/evaluator/access_ops_spec.rb
+++ b/spec/unit/pops/evaluator/access_ops_spec.rb
@@ -1,441 +1,441 @@
#! /usr/bin/env ruby
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/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
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')[1])).to eql('b')
end
it 'can get the last character using the key -1 in []' do
expect(evaluate(literal('abc')[-1])).to eql('c')
end
it 'can get a substring by giving two keys' do
expect(evaluate(literal('abcd')[1,2])).to eql('bc')
# flattens keys
expect(evaluate(literal('abcd')[[1,2]])).to eql('bc')
end
it 'produces empty string for a substring out of range' do
expect(evaluate(literal('abc')[100])).to eql('')
end
it 'raises an error if arity is wrong for []' do
expect{evaluate(literal('abc')[])}.to raise_error(/String supports \[\] with one or two arguments\. Got 0/)
expect{evaluate(literal('abc')[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])[1].current.is_a?(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])[1])).to eql(2)
end
it 'can get the last element using the key -1 in []' do
expect(evaluate(literal([1,2,3])[-1])).to eql(3)
end
it 'can get a slice of elements using two keys' do
expect(evaluate(literal([1,2,3,4])[1,2])).to eql([2,3])
# flattens keys
expect(evaluate(literal([1,2,3,4])[[1,2]])).to eql([2,3])
end
it 'produces nil for a missing entry' do
expect(evaluate(literal([1,2,3])[100])).to eql(nil)
end
it 'raises an error if arity is wrong for []' do
expect{evaluate(literal([1,2,3,4])[])}.to raise_error(/Array supports \[\] with one or two arguments\. Got 0/)
expect{evaluate(literal([1,2,3,4])[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})['b'])).to eql(2)
end
it 'can lookup an array' do
expect(evaluate(literal({[1]=>10,[2]=>20})[[2]])).to eql(20)
end
it 'produces nil for a missing key' do
expect(evaluate(literal({'a'=>1,'b'=>2,'c'=>3})['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})['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})['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})['x', 'y'])).to eql([])
end
it 'raises an error if arity is wrong for []' do
expect{evaluate(literal({'a'=>1,'b'=>2,'c'=>3})[])}.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')[1, 3]
expect(evaluate(expr)).to eql(range(1,3))
# arguments are flattened
expr = fqr('Integer')[[1, 3]]
expect(evaluate(expr)).to eql(range(1,3))
end
it 'produces an Integer[1]' do
expr = fqr('Integer')[1]
expect(evaluate(expr)).to eql(range(1,1))
end
it 'produces an Integer[from, <from]' do
expr = fqr('Integer')[1,0]
expect(evaluate(expr)).to eql(range(1,0))
end
it 'produces an error for Integer[] if there are more than 2 keys' do
expr = fqr('Integer')[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')[1, 3]
expect(evaluate(expr)).to eql(float_range(1.0,3.0))
# arguments are flattened
expr = fqr('Float')[[1, 3]]
expect(evaluate(expr)).to eql(float_range(1.0,3.0))
end
it 'produces a Float[1.0]' do
expr = fqr('Float')[1.0]
expect(evaluate(expr)).to eql(float_range(1.0,1.0))
end
it 'produces a Float[1]' do
expr = fqr('Float')[1]
expect(evaluate(expr)).to eql(float_range(1.0,1.0))
end
it 'produces a Float[from, <from]' do
expr = fqr('Float')[1.0,0.0]
expect(evaluate(expr)).to eql(float_range(1.0,0.0))
end
it 'produces an error for Float[] if there are more than 2 keys' do
expr = fqr('Float')[1,2,3]
expect { evaluate(expr)}.to raise_error(/with one or two arguments/)
end
# Hash Type
#
it 'produces a Hash[Scalar,String] from the expression Hash[Scalar, String]' do
expr = fqr('Hash')[fqr('Scalar'), fqr('String')]
expect(evaluate(expr)).to be_the_type(types.hash_of(types.string, types.scalar))
# arguments are flattened
expr = fqr('Hash')[[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')[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')[fqr('Integer'), fqr('Array')][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')['String']
expect { evaluate(expr)}.to raise_error(/Hash-Type\[\] arguments must be types/)
end
# Array Type
#
it 'produces an Array[String] from the expression Array[String]' do
expr = fqr('Array')[fqr('String')]
expect(evaluate(expr)).to be_the_type(types.array_of(types.string))
# arguments are flattened
expr = fqr('Array')[[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')[fqr('Integer')][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')[fqr('String'), 1]
expected_t = types.array_of(String)
types.constrain_size(expected_t, 1, :default)
expect(evaluate(expr)).to be_the_type(expected_t)
expr = fqr('Array')[fqr('String'), 1, 2]
expected_t = types.array_of(String)
types.constrain_size(expected_t, 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')['String']
expect { evaluate(expr)}.to raise_error(/Array-Type\[\] arguments must be types/)
end
# Tuple Type
#
it 'produces a Tuple[String] from the expression Tuple[String]' do
expr = fqr('Tuple')[fqr('String')]
expect(evaluate(expr)).to be_the_type(types.tuple(String))
# arguments are flattened
expr = fqr('Tuple')[[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')['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')[fqr('String'), 1]
expected_t = types.tuple(String)
types.constrain_size(expected_t, 1, :default)
expect(evaluate(expr)).to be_the_type(expected_t)
expr = fqr('Tuple')[fqr('String'), 1, 2]
expected_t = types.tuple(String)
types.constrain_size(expected_t, 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')['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')['foo']
expect(evaluate(regexp_expr)).to eql(Puppet::Pops::Types::TypeFactory.regexp('foo'))
# arguments are flattened
regexp_expr = fqr('Regexp')[['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')[fqn('apache')]
expect(evaluate(expr)).to be_the_type(types.host_class('apache'))
expr = fqr('Class')[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')[[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')[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')[[]]
expect(evaluate(expr)).to be_eql([])
expr = fqr('Class')[[nil]]
expect(evaluate(expr)).to be_eql([])
end
it 'raises error if access is to no keys' do
expr = fqr('Class')[fqn('apache')][]
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')[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')['::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')['fail-whale']
expect { evaluate(expr) }.to raise_error(/Illegal name/)
end
it 'downcases capitalized class names' do
expr = fqr('Class')['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')[]
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')[literal([[],[]])]
expect(evaluate(expr)).to be_eql([])
end
# Resource
it 'produces a specific resource type from Resource[type]' do
expr = fqr('Resource')[fqr('File')]
expect(evaluate(expr)).to be_the_type(types.resource('File'))
expr = fqr('Resource')[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')[[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')[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')[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')[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')[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')[]
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')[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')[]
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')[literal([[],[]])]
expect(evaluate(expr)).to be_eql([])
end
it 'gives an error if resource is not found' do
expr = fqr('File')[fqn('x')][fqn('y')]
expect {evaluate(expr)}.to raise_error(/Resource not found: File\['x'\]/)
end
# Type Type
#
it 'creates a Type instance when applied to a Type' do
type_expr = fqr('Type')[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')[[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')['ruby','String']
tf = Puppet::Pops::Types::TypeFactory
expect(evaluate(type_expr)).to eql(tf.ruby_type('String'))
# arguments are flattened
type_expr = fqr('Runtime')[['ruby', 'String']]
expect(evaluate(type_expr)).to eql(tf.ruby_type('String'))
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_for_should do |actual|
+ failure_message do |actual|
"expected #{type.to_s}, but was #{actual.to_s}"
end
end
end
diff --git a/spec/unit/pops/evaluator/arithmetic_ops_spec.rb b/spec/unit/pops/evaluator/arithmetic_ops_spec.rb
index 40e5d4844..d209c0318 100644
--- a/spec/unit/pops/evaluator/arithmetic_ops_spec.rb
+++ b/spec/unit/pops/evaluator/arithmetic_ops_spec.rb
@@ -1,77 +1,77 @@
#! /usr/bin/env ruby
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 arithmetic" do
context "on Integers" do
- it "2 + 2 == 4" do; evaluate(literal(2) + literal(2)).should == 4 ; end
- it "7 - 3 == 4" do; evaluate(literal(7) - literal(3)).should == 4 ; end
- it "6 * 3 == 18" do; evaluate(literal(6) * literal(3)).should == 18; end
- it "6 / 3 == 2" do; evaluate(literal(6) / literal(3)).should == 2 ; end
- it "6 % 3 == 0" do; evaluate(literal(6) % literal(3)).should == 0 ; end
- it "10 % 3 == 1" do; evaluate(literal(10) % literal(3)).should == 1; end
- it "-(6/3) == -2" do; evaluate(minus(literal(6) / literal(3))).should == -2 ; end
- it "-6/3 == -2" do; evaluate(minus(literal(6)) / literal(3)).should == -2 ; end
- it "8 >> 1 == 4" do; evaluate(literal(8) >> literal(1)).should == 4 ; end
- it "8 << 1 == 16" do; evaluate(literal(8) << literal(1)).should == 16; end
- it "8 >> -1 == 16" do; evaluate(literal(8) >> literal(-1)).should == 16 ; end
- it "8 << -1 == 4" do; evaluate(literal(8) << literal(-1)).should == 4; end
+ 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
context "on Floats" do
- it "2.2 + 2.2 == 4.4" do; evaluate(literal(2.2) + literal(2.2)).should == 4.4 ; end
- it "7.7 - 3.3 == 4.4" do; evaluate(literal(7.7) - literal(3.3)).should == 4.4 ; end
- it "6.1 * 3.1 == 18.91" do; evaluate(literal(6.1) * literal(3.1)).should == 18.91; end
- it "6.6 / 3.3 == 2.0" do; evaluate(literal(6.6) / literal(3.3)).should == 2.0 ; end
- it "-(6.0/3.0) == -2.0" do; evaluate(minus(literal(6.0) / literal(3.0))).should == -2.0; end
- it "-6.0/3.0 == -2.0" do; evaluate(minus(literal(6.0)) / literal(3.0)).should == -2.0; end
+ 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
it "'2' + '2' == 4" do
- evaluate(literal('2') + literal('2')).should == 4
+ expect(evaluate(literal('2') + literal('2'))).to eq(4)
end
it "'2.2' + '2.2' == 4.4" do
- evaluate(literal('2.2') + literal('2.2')).should == 4.4
+ expect(evaluate(literal('2.2') + literal('2.2'))).to eq(4.4)
end
it "'0xF7' + '0x8' == 0xFF" do
- evaluate(literal('0xF7') + literal('0x8')).should == 0xFF
+ expect(evaluate(literal('0xF7') + literal('0x8'))).to eq(0xFF)
end
it "'0367' + '010' == 0xFF" do
- evaluate(literal('0367') + literal('010')).should == 0xFF
+ 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
- evaluate(literal('012.3') + literal('010')).should == 20.3
+ expect(evaluate(literal('012.3') + literal('010'))).to eq(20.3)
end
end
end
end
diff --git a/spec/unit/pops/evaluator/basic_expressions_spec.rb b/spec/unit/pops/evaluator/basic_expressions_spec.rb
index 6ee46ac1a..5dd34210d 100644
--- a/spec/unit/pops/evaluator/basic_expressions_spec.rb
+++ b/spec/unit/pops/evaluator/basic_expressions_spec.rb
@@ -1,103 +1,103 @@
#! /usr/bin/env ruby
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
- evaluate(literal(1)).should == 1
- evaluate(literal(3.14)).should == 3.14
+ expect(evaluate(literal(1))).to eq(1)
+ expect(evaluate(literal(3.14))).to eq(3.14)
end
it 'should evaluate strings to string' do
- evaluate(literal('banana')).should == 'banana'
+ expect(evaluate(literal('banana'))).to eq('banana')
end
it 'should evaluate booleans to booleans' do
- evaluate(literal(false)).should == false
- evaluate(literal(true)).should == true
+ expect(evaluate(literal(false))).to eq(false)
+ expect(evaluate(literal(true))).to eq(true)
end
it 'should evaluate names to strings' do
- evaluate(fqn('banana')).should == 'banana'
+ expect(evaluate(fqn('banana'))).to eq('banana')
end
it 'should evaluator types to types' do
array_type = Puppet::Pops::Types::PArrayType.new()
array_type.element_type = Puppet::Pops::Types::PDataType.new()
- evaluate(fqr('Array')).should == array_type
+ 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
- evaluate(literal([1,2,3])).should == [1,2,3]
+ expect(evaluate(literal([1,2,3]))).to eq([1,2,3])
end
it "[...[...[]]] should create nested arrays without trouble" do
- evaluate(literal([1,[2.0, 2.1, [2.2]],[3.0, 3.1]])).should == [1,[2.0, 2.1, [2.2]],[3.0, 3.1]]
+ 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)]);
- Puppet::Pops::Model::ModelTreeDumper.new.dump(x).should == "([] (+ 2 2))"
- evaluate(x)[0].should == 4
+ 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
- evaluate(literal([1,2,3]) == literal([1,2,3])).should == true;
+ expect(evaluate(literal([1,2,3]) == literal([1,2,3]))).to eq(true);
end
it "[1,2,3] != [2,3,4] == true" do
- evaluate(literal([1,2,3]).ne(literal([2,3,4]))).should == true;
+ expect(evaluate(literal([1,2,3]).ne(literal([2,3,4])))).to eq(true);
end
it "[1, 2, 3][2] == 3" do
- evaluate(literal([1,2,3])[2]).should == 3
+ 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
- evaluate(literal({'a'=>1,'b'=>2})).should == {'a'=>1,'b'=>2}
+ expect(evaluate(literal({'a'=>1,'b'=>2}))).to eq({'a'=>1,'b'=>2})
end
it "{...{...{}}} should create nested hashes without trouble" do
- evaluate(literal({'a'=>1,'b'=>{'x'=>2.1,'y'=>2.2}})).should == {'a'=>1,'b'=>{'x'=>2.1,'y'=>2.2}}
+ 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
- evaluate(literal({'a'=> literal(2) + literal(2)}))['a'].should == 4
+ expect(evaluate(literal({'a'=> literal(2) + literal(2)}))['a']).to eq(4)
end
it "{'a'=> 1, 'b'=>2} == {'a'=> 1, 'b'=>2} == true" do
- evaluate(literal({'a'=> 1, 'b'=>2}) == literal({'a'=> 1, 'b'=>2})).should == true;
+ expect(evaluate(literal({'a'=> 1, 'b'=>2}) == literal({'a'=> 1, 'b'=>2}))).to eq(true);
end
it "{'a'=> 1, 'b'=>2} != {'x'=> 1, 'y'=>3} == true" do
- evaluate(literal({'a'=> 1, 'b'=>2}).ne(literal({'x'=> 1, 'y'=>3}))).should == true;
+ 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
- evaluate(literal({:a => 1, :b => 2})[:b]).should == 2
+ expect(evaluate(literal({:a => 1, :b => 2})[:b])).to eq(2)
end
end
context 'When the evaluator evaluates a Block' do
it 'an empty block evaluates to nil' do
- evaluate(block()).should == nil
+ expect(evaluate(block())).to eq(nil)
end
it 'a block evaluates to its last expression' do
- evaluate(block(literal(1), literal(2))).should == 2
+ expect(evaluate(block(literal(1), literal(2)))).to eq(2)
end
end
end
diff --git a/spec/unit/pops/evaluator/comparison_ops_spec.rb b/spec/unit/pops/evaluator/comparison_ops_spec.rb
index f06bb9dee..ee79e91af 100644
--- a/spec/unit/pops/evaluator/comparison_ops_spec.rb
+++ b/spec/unit/pops/evaluator/comparison_ops_spec.rb
@@ -1,265 +1,265 @@
#! /usr/bin/env ruby
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; evaluate(literal('a') == literal('a')).should == true ; end
- it "'a' == 'b' == false" do; evaluate(literal('a') == literal('b')).should == false ; end
- it "'a' != 'a' == false" do; evaluate(literal('a').ne(literal('a'))).should == false ; end
- it "'a' != 'b' == true" do; evaluate(literal('a').ne(literal('b'))).should == true ; end
+ it "'a' == 'a' == true" do; expect(evaluate(literal('a') == literal('a'))).to eq(true) ; 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').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; evaluate(literal('a') < literal('b')).should == true ; end
- it "'a' < 'a' == false" do; evaluate(literal('a') < literal('a')).should == false ; end
- it "'b' < 'a' == false" do; evaluate(literal('b') < literal('a')).should == false ; 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; evaluate(literal('a') <= literal('b')).should == true ; end
- it "'a' <= 'a' == true" do; evaluate(literal('a') <= literal('a')).should == true ; end
- it "'b' <= 'a' == false" do; evaluate(literal('b') <= literal('a')).should == 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; evaluate(literal('a') > literal('b')).should == false ; end
- it "'a' > 'a' == false" do; evaluate(literal('a') > literal('a')).should == false ; end
- it "'b' > 'a' == true" do; evaluate(literal('b') > literal('a')).should == true ; 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; evaluate(literal('a') >= literal('b')).should == false ; end
- it "'a' >= 'a' == true" do; evaluate(literal('a') >= literal('a')).should == true ; end
- it "'b' >= 'a' == true" do; evaluate(literal('b') >= literal('a')).should == 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; evaluate(literal('a') == literal('A')).should == true ; end
- it "'a' != 'A' == false" do; evaluate(literal('a').ne(literal('A'))).should == false ; end
- it "'a' > 'A' == false" do; evaluate(literal('a') > literal('A')).should == false ; end
- it "'a' >= 'A' == true" do; evaluate(literal('a') >= literal('A')).should == true ; end
- it "'A' < 'a' == false" do; evaluate(literal('A') < literal('a')).should == false ; end
- it "'A' <= 'a' == true" do; evaluate(literal('A') <= literal('a')).should == true ; 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').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; evaluate(literal(1) == literal(1)).should == true ; end
- it "1 == 2 == false" do; evaluate(literal(1) == literal(2)).should == false ; end
- it "1 != 1 == false" do; evaluate(literal(1).ne(literal(1))).should == false ; end
- it "1 != 2 == true" do; evaluate(literal(1).ne(literal(2))).should == true ; end
-
- it "1 < 2 == true" do; evaluate(literal(1) < literal(2)).should == true ; end
- it "1 < 1 == false" do; evaluate(literal(1) < literal(1)).should == false ; end
- it "2 < 1 == false" do; evaluate(literal(2) < literal(1)).should == false ; end
-
- it "1 <= 2 == true" do; evaluate(literal(1) <= literal(2)).should == true ; end
- it "1 <= 1 == true" do; evaluate(literal(1) <= literal(1)).should == true ; end
- it "2 <= 1 == false" do; evaluate(literal(2) <= literal(1)).should == false ; end
-
- it "1 > 2 == false" do; evaluate(literal(1) > literal(2)).should == false ; end
- it "1 > 1 == false" do; evaluate(literal(1) > literal(1)).should == false ; end
- it "2 > 1 == true" do; evaluate(literal(2) > literal(1)).should == true ; end
-
- it "1 >= 2 == false" do; evaluate(literal(1) >= literal(2)).should == false ; end
- it "1 >= 1 == true" do; evaluate(literal(1) >= literal(1)).should == true ; end
- it "2 >= 1 == true" do; evaluate(literal(2) >= literal(1)).should == true ; end
+ it "1 == 1 == true" do; expect(evaluate(literal(1) == literal(1))).to eq(true) ; 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).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; evaluate(literal(1) == literal(1.0)).should == true ; end
- it "1 < 1.1 == true" do; evaluate(literal(1) < literal(1.1)).should == true ; end
- it "1.0 == 1 == true" do; evaluate(literal(1.0) == literal(1)).should == true ; end
- it "1.0 < 2 == true" do; evaluate(literal(1.0) < literal(2)).should == true ; end
- it "'1.0' < 'a' == true" do; evaluate(literal('1.0') < literal('a')).should == true ; end
- it "'1.0' < '' == true" do; evaluate(literal('1.0') < literal('')).should == false ; end
- it "'1.0' < ' ' == true" do; evaluate(literal('1.0') < literal(' ')).should == false ; end
- it "'a' > '1.0' == true" do; evaluate(literal('a') > literal('1.0')).should == true ; end
+ it "1 == 1.0 == true" do; expect(evaluate(literal(1) == 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) == 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
end
context "of regular expressions" do
- it "/.*/ == /.*/ == true" do; evaluate(literal(/.*/) == literal(/.*/)).should == true ; end
- it "/.*/ != /a.*/ == true" do; evaluate(literal(/.*/).ne(literal(/a.*/))).should == true ; end
+ it "/.*/ == /.*/ == true" do; expect(evaluate(literal(/.*/) == 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; evaluate(literal(true) == literal(true)).should == true ; end;
- it "false == false == true" do; evaluate(literal(false) == literal(false)).should == true ; end;
- it "true == false != true" do; evaluate(literal(true) == literal(false)).should == false ; end;
- it "false == '' == false" do; evaluate(literal(false) == literal('')).should == false ; end;
- it "undef == '' == false" do; evaluate(literal(:undef) == literal('')).should == false ; end;
- it "undef == undef == true" do; evaluate(literal(:undef) == literal(:undef)).should == true ; end;
- it "nil == undef == true" do; evaluate(literal(nil) == literal(:undef)).should == true ; end;
+ it "true == true == true" do; expect(evaluate(literal(true) == literal(true))).to eq(true) ; end;
+ it "false == false == true" do; expect(evaluate(literal(false) == literal(false))).to eq(true) ; end;
+ it "true == false != true" do; expect(evaluate(literal(true) == literal(false))).to eq(false) ; end;
+ it "false == '' == false" do; expect(evaluate(literal(false) == literal(''))).to eq(false) ; end;
+ it "undef == '' == false" do; expect(evaluate(literal(:undef) == literal(''))).to eq(false) ; end;
+ it "undef == undef == true" do; expect(evaluate(literal(:undef) == literal(:undef))).to eq(true) ; end;
+ it "nil == undef == true" do; expect(evaluate(literal(nil) == literal(:undef))).to eq(true) ; end;
end
context "of collections" do
it "[1,2,3] == [1,2,3] == true" do
- evaluate(literal([1,2,3]) == literal([1,2,3])).should == true
- evaluate(literal([1,2,3]).ne(literal([1,2,3]))).should == false
- evaluate(literal([1,2,4]) == literal([1,2,3])).should == false
- evaluate(literal([1,2,4]).ne(literal([1,2,3]))).should == true
+ expect(evaluate(literal([1,2,3]) == 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]) == 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
- evaluate(literal({'a'=>1, 'b'=>2}) == literal({'a'=>1, 'b'=>2})).should == true
- evaluate(literal({'a'=>1, 'b'=>2}).ne(literal({'a'=>1, 'b'=>2}))).should == false
- evaluate(literal({'a'=>1, 'b'=>2}) == literal({'x'=>1, 'b'=>2})).should == false
- evaluate(literal({'a'=>1, 'b'=>2}).ne(literal({'x'=>1, 'b'=>2}))).should == true
+ expect(evaluate(literal({'a'=>1, 'b'=>2}) == 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}) == 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; evaluate(literal('a') =~ literal(/.*/)).should == true ; end
- it "'a' =~ '.*' == true" do; evaluate(literal('a') =~ literal(".*")).should == true ; end
- it "'a' !~ /b.*/ == true" do; evaluate(literal('a').mne(literal(/b.*/))).should == true ; end
- it "'a' !~ 'b.*' == true" do; evaluate(literal('a').mne(literal("b.*"))).should == true ; end
+ 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
- evaluate(literal('a') =~ fqr('Pattern')[literal(".*")]).should == true
+ expect(evaluate(literal('a') =~ fqr('Pattern')[literal(".*")])).to eq(true)
end
it "$a = Pattern['.*']; 'a' =~ $a == true" do
expr = block(var('a').set(fqr('Pattern')['foo']), literal('foo') =~ var('a'))
- evaluate(expr).should == true
+ 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
- evaluate(literal(1).in(literal([1,2,3]))).should == true
- evaluate(literal(4).in(literal([1,2,3]))).should == false
+ 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
- evaluate(literal('a').in(literal({'x'=>1, 'a'=>2, 'y'=> 3}))).should == true
- evaluate(literal('z').in(literal({'x'=>1, 'a'=>2, 'y'=> 3}))).should == false
+ 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
- evaluate(literal('ana').in(literal('bananas'))).should == true
- evaluate(literal('xxx').in(literal('bananas'))).should == false
+ 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
- evaluate(literal(/ana/).in(literal('bananas'))).should == true
- evaluate(literal(/xxx/).in(literal('bananas'))).should == false
+ 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
- evaluate(literal('ANA').in(literal('bananas'))).should == true
- evaluate(literal('ana').in(literal('BANANAS'))).should == true
- evaluate(literal('xxx').in(literal('BANANAS'))).should == false
+ 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
- evaluate(literal([2,3]).in(literal([1,[2,3],4]))).should == true
- evaluate(literal([2,4]).in(literal([1,[2,3],4]))).should == false
+ 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
- evaluate(literal(['a','b']).in(literal(['A',['A','B'],'C']))).should == true
- evaluate(literal(['x','y']).in(literal(['A',['A','B'],'C']))).should == false
+ 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
- evaluate(literal('a').in(literal({'a' => 10, 'b' => 20}))).should == true
- evaluate(literal('x').in(literal({'a' => 10, 'b' => 20}))).should == false
+ 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
- evaluate(literal('A').in(literal({'a' => 10, 'b' => 20}))).should == true
- evaluate(literal('X').in(literal({'a' => 10, 'b' => 20}))).should == false
+ 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
- evaluate(literal(/xxx/).in(literal({'abcxxxabc' => 10, 'xyz' => 20}))).should == true
- evaluate(literal(/yyy/).in(literal({'abcxxxabc' => 10, 'xyz' => 20}))).should == false
+ 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
- evaluate(literal(15).in(literal([1,0xf,2]))).should == true
+ expect(evaluate(literal(15).in(literal([1,0xf,2])))).to eq(true)
end
it "should not find numbers as strings" do
- evaluate(literal(15).in(literal([1, '0xf',2]))).should == false
- evaluate(literal('15').in(literal([1, 0xf,2]))).should == false
+ 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
- evaluate(literal(15).in(literal([1, '115', 2]))).should == false
- evaluate(literal(1).in(literal([11, 111, 2]))).should == false
- evaluate(literal('1').in(literal([11, 111, 2]))).should == false
+ 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
- evaluate(fqr('Array')[fqr('Integer')].in(literal(['a', [1,2,3], 'b']))).should == true
- evaluate(fqr('Array')[fqr('Integer')].in(literal(['a', [1,2,'not integer'], 'b']))).should == false
+ expect(evaluate(fqr('Array')[fqr('Integer')].in(literal(['a', [1,2,3], 'b'])))).to eq(true)
+ expect(evaluate(fqr('Array')[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
- evaluate(fqr('Integer').in(literal({1 => 'a', 'a' => 'b'}))).should == true
- evaluate(fqr('Integer').in(literal({'a' => 'a', 'a' => 'b'}))).should == false
+ expect(evaluate(fqr('Integer').in(literal({1 => 'a', 'a' => 'b'})))).to eq(true)
+ expect(evaluate(fqr('Integer').in(literal({'a' => 'a', 'a' => 'b'})))).to eq(false)
end
end
end
diff --git a/spec/unit/pops/evaluator/conditionals_spec.rb b/spec/unit/pops/evaluator/conditionals_spec.rb
index 020734a5d..287511f71 100644
--- a/spec/unit/pops/evaluator/conditionals_spec.rb
+++ b/spec/unit/pops/evaluator/conditionals_spec.rb
@@ -1,190 +1,190 @@
#! /usr/bin/env ruby
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
- dump(IF(literal(true), literal(2), literal(5))).should == unindent(<<-TEXT
+ 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
- evaluate(IF(literal(true), literal(5))).should == 5
+ expect(evaluate(IF(literal(true), literal(5)))).to eq(5)
end
it 'if false {5} == nil' do
- evaluate(IF(literal(false), literal(5))).should == nil
+ expect(evaluate(IF(literal(false), literal(5)))).to eq(nil)
end
it 'if false {2} else {5} == 5' do
- evaluate(IF(literal(false), literal(2), literal(5))).should == 5
+ expect(evaluate(IF(literal(false), literal(2), literal(5)))).to eq(5)
end
it 'if false {2} elsif true {5} == 5' do
- evaluate(IF(literal(false), literal(2), IF(literal(true), literal(5)))).should == 5
+ 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
- evaluate(IF(literal(false), literal(2), IF(literal(false), literal(5)))).should == nil
+ 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
- dump(UNLESS(literal(true), literal(2), literal(5))).should == unindent(<<-TEXT
+ 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
- evaluate(UNLESS(literal(false), literal(5))).should == 5
+ expect(evaluate(UNLESS(literal(false), literal(5)))).to eq(5)
end
it 'unless true {5} == nil' do
- evaluate(UNLESS(literal(true), literal(5))).should == nil
+ expect(evaluate(UNLESS(literal(true), literal(5)))).to eq(nil)
end
it 'unless true {2} else {5} == 5' do
- evaluate(UNLESS(literal(true), literal(2), literal(5))).should == 5
+ 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
- evaluate(UNLESS(literal(true), literal(2), IF(literal(true), literal(5)))).should == 5
+ 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
- evaluate(UNLESS(literal(true), literal(2), IF(literal(false), literal(5)))).should == nil
+ 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
- dump(CASE(literal(2),
+ expect(dump(CASE(literal(2),
WHEN(literal(1), literal('wat')),
WHEN([literal(2), literal(3)], literal('w00t'))
- )).should == unindent(<<-TEXT
+ ))).to eq unindent(<<-TEXT
(case 2
(when (1) (then 'wat'))
(when (2 3) (then 'w00t')))
TEXT
)
- dump(CASE(literal(2),
+ expect(dump(CASE(literal(2),
WHEN(literal(1), literal('wat')),
WHEN([literal(2), literal(3)], literal('w00t'))
- ).default(literal(4))).should == unindent(<<-TEXT
+ ).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
- evaluate(CASE(literal(1), WHEN(literal(1), literal('w00t')))).should == 'w00t'
+ expect(evaluate(CASE(literal(1), WHEN(literal(1), literal('w00t'))))).to eq('w00t')
end
it "case 2 { 1,2,3 : { 'w00t'} } == 'w00t'" do
- evaluate(CASE(literal(2), WHEN([literal(1), literal(2), literal(3)], literal('w00t')))).should == 'w00t'
+ 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
- evaluate(CASE(literal(2),
+ expect(evaluate(CASE(literal(2),
WHEN([literal(1), literal(3)], literal('wat')),
- WHEN(literal(2), literal('w00t')))).should == 'w00t'
+ WHEN(literal(2), literal('w00t'))))).to eq('w00t')
end
it "case 2 { 1,3 : {'wat'} 5: { 'wat'} default: {'w00t'}} == 'w00t'" do
- evaluate(CASE(literal(2),
+ expect(evaluate(CASE(literal(2),
WHEN([literal(1), literal(3)], literal('wat')),
WHEN(literal(5), literal('wat'))).default(literal('w00t'))
- ).should == 'w00t'
+ )).to eq('w00t')
end
it "case 2 { 1,3 : {'wat'} 5: { 'wat'} } == nil" do
- evaluate(CASE(literal(2),
+ expect(evaluate(CASE(literal(2),
WHEN([literal(1), literal(3)], literal('wat')),
WHEN(literal(5), literal('wat')))
- ).should == nil
+ )).to eq(nil)
end
it "case 'banana' { 1,3 : {'wat'} /.*ana.*/: { 'w00t'} } == w00t" do
- evaluate(CASE(literal('banana'),
+ expect(evaluate(CASE(literal('banana'),
WHEN([literal(1), literal(3)], literal('wat')),
WHEN(literal(/.*ana.*/), literal('w00t')))
- ).should == 'w00t'
+ )).to eq('w00t')
end
context "with regular expressions" do
it "should set numeric variables from the match" do
- evaluate(CASE(literal('banana'),
+ expect(evaluate(CASE(literal('banana'),
WHEN([literal(1), literal(3)], literal('wat')),
WHEN(literal(/.*(ana).*/), var(1)))
- ).should == 'ana'
+ )).to eq('ana')
end
end
end
context "select expressions" do
it 'should output the expected result when dumped' do
- dump(literal(2).select(
+ expect(dump(literal(2).select(
MAP(literal(1), literal('wat')),
MAP(literal(2), literal('w00t'))
- )).should == "(? 2 (1 => 'wat') (2 => 'w00t'))"
+ ))).to eq("(? 2 (1 => 'wat') (2 => 'w00t'))")
end
it "1 ? {1 => 'w00t'} == 'w00t'" do
- evaluate(literal(1).select(MAP(literal(1), literal('w00t')))).should == 'w00t'
+ expect(evaluate(literal(1).select(MAP(literal(1), literal('w00t'))))).to eq('w00t')
end
it "2 ? {1 => 'wat', 2 => 'w00t'} == 'w00t'" do
- evaluate(literal(2).select(
+ expect(evaluate(literal(2).select(
MAP(literal(1), literal('wat')),
MAP(literal(2), literal('w00t'))
- )).should == 'w00t'
+ ))).to eq('w00t')
end
it "3 ? {1 => 'wat', 2 => 'wat', default => 'w00t'} == 'w00t'" do
- evaluate(literal(3).select(
+ expect(evaluate(literal(3).select(
MAP(literal(1), literal('wat')),
MAP(literal(2), literal('wat')),
MAP(literal(:default), literal('w00t'))
- )).should == 'w00t'
+ ))).to eq('w00t')
end
it "3 ? {1 => 'wat', default => 'w00t', 3 => 'wat'} == 'w00t'" do
- evaluate(literal(3).select(
+ expect(evaluate(literal(3).select(
MAP(literal(1), literal('wat')),
MAP(literal(:default), literal('w00t')),
MAP(literal(2), literal('wat'))
- )).should == 'w00t'
+ ))).to eq('w00t')
end
it "should set numerical variables from match" do
- evaluate(literal('banana').select(
+ expect(evaluate(literal('banana').select(
MAP(literal(1), literal('wat')),
MAP(literal(/.*(ana).*/), var(1))
- )).should == 'ana'
+ ))).to eq('ana')
end
end
end
end
diff --git a/spec/unit/pops/evaluator/evaluating_parser_spec.rb b/spec/unit/pops/evaluator/evaluating_parser_spec.rb
index 5fd44e5ca..389555ad4 100644
--- a/spec/unit/pops/evaluator/evaluating_parser_spec.rb
+++ b/spec/unit/pops/evaluator/evaluating_parser_spec.rb
@@ -1,1323 +1,1323 @@
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
# 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
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_data(),
"/.*/" => /.*/
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
- parser.evaluate_string(scope, source, __FILE__).should == result
+ expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
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" => [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
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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,
"[1,2,3] =~ Array[Integer[1,10]]" => true,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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,
"ANA in bananas" => false, # ANA is a type, not a String
"String[1] in bananas" => false, # Philosophically true though :-)
"'ANA' in bananas" => true,
"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
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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
- parser.evaluate_string(scope, source, __FILE__).should == result
+ expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
'Any' => ['Data', 'Scalar', 'Numeric', 'Integer', 'Float', 'Boolean', 'String', 'Pattern', 'Collection',
'Array', 'Hash', 'CatalogEntry', 'Resource', 'Class', 'Undef', 'File', 'NotYetKnownResourceType'],
# Note, Data > Collection is false (so not included)
'Data' => ['Scalar', 'Numeric', 'Integer', 'Float', 'Boolean', 'String', 'Pattern', 'Array', 'Hash',],
'Scalar' => ['Numeric', 'Integer', 'Float', 'Boolean', 'String', 'Pattern'],
'Numeric' => ['Integer', 'Float'],
'CatalogEntry' => ['Class', 'Resource', 'File', 'NotYetKnownResourceType'],
'Integer[1,10]' => ['Integer[2,3]'],
}.each do |general, specials|
specials.each do |special |
it "should compute that #{general} > #{special}" do
- parser.evaluate_string(scope, "#{general} > #{special}", __FILE__).should == true
+ expect(parser.evaluate_string(scope, "#{general} > #{special}", __FILE__)).to eq(true)
end
it "should compute that #{special} < #{general}" do
- parser.evaluate_string(scope, "#{special} < #{general}", __FILE__).should == true
+ expect(parser.evaluate_string(scope, "#{special} < #{general}", __FILE__)).to eq(true)
end
it "should compute that #{general} != #{special}" do
- parser.evaluate_string(scope, "#{special} != #{general}", __FILE__).should == true
+ 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
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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
{
"'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
- parser.evaluate_string(scope, source, __FILE__).should == result
+ expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
"'0888' + '010'" => :error,
"'0xWTF' + '010'" => :error,
"'0x12.3' + '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,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
- parser.evaluate_string(scope, source, __FILE__).should == result
+ expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
"[a,b,c] = [1,2,3]" => /attempt to assign to 'an Array Expression'/,
"[a,b,c] = {b=>2,c=>3,a=>1}" => /attempt to assign to 'an Array Expression'/,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to error with #{result}" do
expect { parser.evaluate_string(scope, source, __FILE__)}.to raise_error(Puppet::ParseError, result)
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,
"$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
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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',
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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',
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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
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
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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
- parser.evaluate_string(scope, source, __FILE__).should == result
+ 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.constrain_size(types.array_of(types.integer),1, :default),
"Array[Integer,1,2]" => types.constrain_size(types.array_of(types.integer),1, 2),
"Array[Integer,Integer[1,2]]" => types.constrain_size(types.array_of(types.integer),1, 2),
"Array[Integer,Integer[1]]" => types.constrain_size(types.array_of(types.integer),1, :default),
"Hash[Integer,Integer]" => types.hash_of(types.integer, types.integer),
"Hash[Integer,Integer,1]" => types.constrain_size(types.hash_of(types.integer, types.integer),1, :default),
"Hash[Integer,Integer,1,2]" => types.constrain_size(types.hash_of(types.integer, types.integer),1, 2),
"Hash[Integer,Integer,Integer[1,2]]" => types.constrain_size(types.hash_of(types.integer, types.integer),1, 2),
"Hash[Integer,Integer,Integer[1]]" => types.constrain_size(types.hash_of(types.integer, types.integer),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.constrain_size(types.string,1, 2),
"String[Integer[1,2]]" => types.constrain_size(types.string,1, 2),
"String[Integer[1]]" => types.constrain_size(types.string,1, :default),
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
- parser.evaluate_string(scope, source, __FILE__).should == result
+ expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
# LHS where [] not supported, and missing key(s)
{
"Array[]" => :error,
"'abc'[]" => :error,
"Resource[]" => :error,
"File[]" => :error,
"String[]" => :error,
"1[]" => :error,
"3.14[]" => :error,
"/.*/[]" => :error,
"$a=[1] $a[]" => :error,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect { parser.evaluate_string(scope, source, __FILE__)}.to raise_error(/Syntax error/)
end
end
# Errors when wrong number/type of keys are used
{
"Array[0]" => 'Array-Type[] arguments must be types. Got Fixnum',
"Hash[0]" => 'Hash-Type[] arguments must be types. Got Fixnum',
"Hash[Integer, 0]" => 'Hash-Type[] arguments must be types. Got Fixnum',
"Array[Integer,1,2,3]" => 'Array-Type[] accepts 1 to 3 arguments. Got 4',
"Array[Integer,String]" => "A Type's size constraint arguments must be a single Integer type, or 1-2 integers (or default). Got a String-Type",
"Hash[Integer,String, 1,2,3]" => 'Hash-Type[] accepts 2 to 4 arguments. Got 5',
"'abc'[x]" => "The value 'x' cannot be converted to Numeric",
"'abc'[1.0]" => "A String[] cannot use Float where Integer is expected",
"'abc'[1,2,3]" => "String supports [] with one or two arguments. Got 3",
"Resource[0]" => 'First argument to Resource[] must be a resource type or a String. Got Integer',
"Resource[a, 0]" => 'Error creating type specialization of a Resource-Type, Cannot use Integer where a resource title String is expected',
"File[0]" => 'Error creating type specialization of a File-Type, Cannot use Integer where a resource title String is expected',
"String[a]" => "A Type's size constraint arguments must be a single Integer type, or 1-2 integers (or default). Got a String",
"Pattern[0]" => 'Error creating type specialization of a Pattern-Type, Cannot use Integer where String or Regexp or Pattern-Type or Regexp-Type is expected',
"Regexp[0]" => 'Error creating type specialization of a Regexp-Type, Cannot use Integer where String or Regexp is expected',
"Regexp[a,b]" => 'A Regexp-Type[] accepts 1 argument. Got 2',
"true[0]" => "Operator '[]' is not applicable to a Boolean",
"1[0]" => "Operator '[]' is not applicable to an Integer",
"3.14[0]" => "Operator '[]' is not applicable to a Float",
"/.*/[0]" => "Operator '[]' is not applicable to a Regexp",
"[1][a]" => "The value 'a' cannot be converted to Numeric",
"[1][0.0]" => "An Array[] cannot use Float where Integer is expected",
"[1]['0.0']" => "An Array[] cannot use Float where Integer is expected",
"[1,2][1, 0.0]" => "An Array[] cannot use Float where Integer is expected",
"[1,2][1.0, -1]" => "An Array[] cannot use Float where Integer is expected",
"[1,2][1, -1.0]" => "An Array[] cannot use Float where Integer is expected",
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect { parser.evaluate_string(scope, source, __FILE__)}.to raise_error(Regexp.new(Regexp.quote(result)))
end
end
context "on catalog types" do
it "[n] gets resource parameter [n]" do
source = "notify { 'hello': message=>'yo'} Notify[hello][message]"
- parser.evaluate_string(scope, source, __FILE__).should == 'yo'
+ expect(parser.evaluate_string(scope, source, __FILE__)).to eq('yo')
end
it "[n] gets class parameter [n]" do
source = "class wonka($produces='chocolate'){ }
include wonka
Class[wonka][produces]"
# This is more complicated since it needs to run like 3.x and do an import_ast
adapted_parser = Puppet::Parser::E4ParserAdapter.new
adapted_parser.file = __FILE__
ast = adapted_parser.parse(source)
Puppet.override({:global_scope => scope,
:environments => Puppet::Environments::Static.new(@node.environment)
}, "gets class parameter test") do
scope.known_resource_types.import_ast(ast, '')
- ast.code.safeevaluate(scope).should == 'chocolate'
+ expect(ast.code.safeevaluate(scope)).to eq('chocolate')
end
end
# Resource default and override expressions and resource parameter access with []
{
# Properties
"notify { id: message=>explicit} Notify[id][message]" => "explicit",
"Notify { message=>by_default} notify {foo:} Notify[foo][message]" => "by_default",
"notify {foo:} Notify[foo]{message =>by_override} Notify[foo][message]" => "by_override",
# Parameters
"notify { id: withpath=>explicit} Notify[id][withpath]" => "explicit",
"Notify { withpath=>by_default } notify { foo: } Notify[foo][withpath]" => "by_default",
"notify {foo:}
Notify[foo]{withpath=>by_override}
Notify[foo][withpath]" => "by_override",
# Metaparameters
"notify { foo: tag => evoe} Notify[foo][tag]" => "evoe",
# Does not produce the defaults for tag parameter (title, type or names of scopes)
"notify { foo: } Notify[foo][tag]" => nil,
# But a default may be specified on the type
"Notify { tag=>by_default } notify { foo: } Notify[foo][tag]" => "by_default",
"Notify { tag=>by_default }
notify { foo: }
Notify[foo]{ tag=>by_override }
Notify[foo][tag]" => "by_override",
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
- parser.evaluate_string(scope, source, __FILE__).should == result
+ expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
# Virtual and realized resource default and overridden resource parameter access with []
{
# Properties
"@notify { id: message=>explicit } Notify[id][message]" => "explicit",
"@notify { id: message=>explicit }
realize Notify[id]
Notify[id][message]" => "explicit",
"Notify { message=>by_default } @notify { id: } Notify[id][message]" => "by_default",
"Notify { message=>by_default }
@notify { id: tag=>thisone }
Notify <| tag == thisone |>;
Notify[id][message]" => "by_default",
"@notify { id: } Notify[id]{message=>by_override} Notify[id][message]" => "by_override",
# Parameters
"@notify { id: withpath=>explicit } Notify[id][withpath]" => "explicit",
"Notify { withpath=>by_default }
@notify { id: }
Notify[id][withpath]" => "by_default",
"@notify { id: }
realize Notify[id]
Notify[id]{withpath=>by_override}
Notify[id][withpath]" => "by_override",
# Metaparameters
"@notify { id: tag=>explicit } Notify[id][tag]" => "explicit",
}.each do |source, result|
it "parses and evaluates virtual and realized resources in the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
# Exported resource attributes
{
"@@notify { id: message=>explicit } Notify[id][message]" => "explicit",
"@@notify { id: message=>explicit, tag=>thisone }
Notify <<| tag == thisone |>>
Notify[id][message]" => "explicit",
}.each do |source, result|
it "parses and evaluates exported resources in the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
# Resource default and override expressions and resource parameter access error conditions
{
"notify { xid: message=>explicit} Notify[id][message]" => /Resource not found/,
"notify { id: message=>explicit} Notify[id][mustard]" => /does not have a parameter called 'mustard'/,
# NOTE: these meta-esque parameters are not recognized as such
"notify { id: message=>explicit} Notify[id][title]" => /does not have a parameter called 'title'/,
"notify { id: message=>explicit} Notify[id]['type']" => /does not have a parameter called 'type'/,
"notify { id: message=>explicit } Notify[id]{message=>override}" => /'message' is already set on Notify\[id\]/
}.each do |source, result|
it "should parse '#{source}' and raise error matching #{result}" do
expect { parser.evaluate_string(scope, source, __FILE__)}.to raise_error(result)
end
end
context 'with errors' do
{ "Class['fail-whale']" => /Illegal name/,
"Class[0]" => /An Integer cannot be used where a String is expected/,
"Class[/.*/]" => /A Regexp cannot be used where a String is expected/,
"Class[4.1415]" => /A Float cannot be used where a String is expected/,
"Class[Integer]" => /An Integer-Type cannot be used where a String is expected/,
"Class[File['tmp']]" => /A File\['tmp'\] Resource-Reference cannot be used where a String is expected/,
}.each do | source, error_pattern|
it "an error is flagged for '#{source}'" do
expect { parser.evaluate_string(scope, source, __FILE__)}.to raise_error(error_pattern)
end
end
end
end
# end [] operations
end
context "When the evaluator performs boolean operations" do
{
"true and true" => true,
"false and true" => false,
"true and false" => false,
"false and false" => false,
"true or true" => true,
"false or true" => true,
"true or false" => true,
"false or false" => false,
"! true" => false,
"!! true" => true,
"!! false" => false,
"! 'x'" => false,
"! ''" => false,
"! undef" => true,
"! [a]" => false,
"! []" => false,
"! {a=>1}" => false,
"! {}" => false,
"true and false and '0xwtf' + 1" => false,
"false or true or '0xwtf' + 1" => true,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
- parser.evaluate_string(scope, source, __FILE__).should == result
+ expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
"false || false || '0xwtf' + 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 evaluator performs operations on literal undef" do
it "computes non existing hash lookup as undef" do
- parser.evaluate_string(scope, "{a => 1}[b] == undef", __FILE__).should == true
- parser.evaluate_string(scope, "undef == {a => 1}[b]", __FILE__).should == true
+ expect(parser.evaluate_string(scope, "{a => 1}[b] == undef", __FILE__)).to eq(true)
+ expect(parser.evaluate_string(scope, "undef == {a => 1}[b]", __FILE__)).to eq(true)
end
end
context "When evaluator performs calls" do
let(:populate) do
parser.evaluate_string(scope, "$a = 10 $b = [1,2,3]")
end
{
'sprintf( "x%iy", $a )' => "x10y",
# unfolds
'sprintf( *["x%iy", $a] )' => "x10y",
'"x%iy".sprintf( $a )' => "x10y",
'$b.reduce |$memo,$x| { $memo + $x }' => 6,
'reduce($b) |$memo,$x| { $memo + $x }' => 6,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
populate
- parser.evaluate_string(scope, source, __FILE__).should == result
+ expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
'"value is ${a*2} yo"' => :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
it "provides location information on error in unparenthesized call logic" do
expect{parser.evaluate_string(scope, "include non_existing_class", __FILE__)}.to raise_error(Puppet::ParseError, /line 1\:1/)
end
it 'defaults can be given in a lambda and used only when arg is missing' do
env_loader = @compiler.loaders.public_environment_loader
fc = Puppet::Functions.create_function(:test) do
dispatch :test do
param 'Integer', :count
required_block_param
end
def test(count, block)
block.call(*[].fill(10, 0, count))
end
end
the_func = fc.new({}, env_loader)
env_loader.add_entry(:function, 'test', the_func, __FILE__)
expect(parser.evaluate_string(scope, "test(1) |$x, $y=20| { $x + $y}")).to eql(30)
expect(parser.evaluate_string(scope, "test(2) |$x, $y=20| { $x + $y}")).to eql(20)
end
it 'a given undef does not select the default value' do
env_loader = @compiler.loaders.public_environment_loader
fc = Puppet::Functions.create_function(:test) do
dispatch :test do
param 'Any', :lambda_arg
required_block_param
end
def test(lambda_arg, block)
block.call(lambda_arg)
end
end
the_func = fc.new({}, env_loader)
env_loader.add_entry(:function, 'test', the_func, __FILE__)
expect(parser.evaluate_string(scope, "test(undef) |$x=20| { $x == undef}")).to eql(true)
end
it 'a given undef is given as nil' do
env_loader = @compiler.loaders.public_environment_loader
fc = Puppet::Functions.create_function(:assert_no_undef) do
dispatch :assert_no_undef do
param 'Any', :x
end
def assert_no_undef(x)
case x
when Array
return unless x.include?(:undef)
when Hash
return unless x.keys.include?(:undef) || x.values.include?(:undef)
else
return unless x == :undef
end
raise "contains :undef"
end
end
the_func = fc.new({}, env_loader)
env_loader.add_entry(:function, 'assert_no_undef', the_func, __FILE__)
expect{parser.evaluate_string(scope, "assert_no_undef(undef)")}.to_not raise_error()
expect{parser.evaluate_string(scope, "assert_no_undef([undef])")}.to_not raise_error()
expect{parser.evaluate_string(scope, "assert_no_undef({undef => 1})")}.to_not raise_error()
expect{parser.evaluate_string(scope, "assert_no_undef({1 => undef})")}.to_not raise_error()
end
context 'using the 3x function api' do
it 'can call a 3x function' do
Puppet::Parser::Functions.newfunction("bazinga", :type => :rvalue) { |args| args[0] }
- parser.evaluate_string(scope, "bazinga(42)", __FILE__).should == 42
+ expect(parser.evaluate_string(scope, "bazinga(42)", __FILE__)).to eq(42)
end
it 'maps :undef to empty string' do
Puppet::Parser::Functions.newfunction("bazinga", :type => :rvalue) { |args| args[0] }
- parser.evaluate_string(scope, "$a = {} bazinga($a[nope])", __FILE__).should == ''
- parser.evaluate_string(scope, "bazinga(undef)", __FILE__).should == ''
+ expect(parser.evaluate_string(scope, "$a = {} bazinga($a[nope])", __FILE__)).to eq('')
+ expect(parser.evaluate_string(scope, "bazinga(undef)", __FILE__)).to eq('')
end
it 'does not map :undef to empty string in arrays' do
Puppet::Parser::Functions.newfunction("bazinga", :type => :rvalue) { |args| args[0][0] }
- parser.evaluate_string(scope, "$a = {} $b = [$a[nope]] bazinga($b)", __FILE__).should == :undef
- parser.evaluate_string(scope, "bazinga([undef])", __FILE__).should == :undef
+ expect(parser.evaluate_string(scope, "$a = {} $b = [$a[nope]] bazinga($b)", __FILE__)).to eq(:undef)
+ expect(parser.evaluate_string(scope, "bazinga([undef])", __FILE__)).to eq(:undef)
end
it 'does not map :undef to empty string in hashes' do
Puppet::Parser::Functions.newfunction("bazinga", :type => :rvalue) { |args| args[0]['a'] }
- parser.evaluate_string(scope, "$a = {} $b = {a => $a[nope]} bazinga($b)", __FILE__).should == :undef
- parser.evaluate_string(scope, "bazinga({a => undef})", __FILE__).should == :undef
+ expect(parser.evaluate_string(scope, "$a = {} $b = {a => $a[nope]} bazinga($b)", __FILE__)).to eq(:undef)
+ expect(parser.evaluate_string(scope, "bazinga({a => undef})", __FILE__)).to eq(:undef)
end
end
end
context "When evaluator performs string interpolation" do
let(:populate) do
parser.evaluate_string(scope, "$a = 10 $b = [1,2,3]")
end
{
'"value is $a yo"' => "value is 10 yo",
'"value is \$a yo"' => "value is $a yo",
'"value is ${a} yo"' => "value is 10 yo",
'"value is \${a} yo"' => "value is ${a} yo",
'"value is ${$a} yo"' => "value is 10 yo",
'"value is ${$a*2} yo"' => "value is 20 yo",
'"value is ${sprintf("x%iy",$a)} yo"' => "value is x10y yo",
'"value is ${"x%iy".sprintf($a)} yo"' => "value is x10y yo",
'"value is ${[1,2,3]} yo"' => "value is [1, 2, 3] yo",
'"value is ${/.*/} yo"' => "value is /.*/ yo",
'$x = undef "value is $x yo"' => "value is yo",
'$x = default "value is $x yo"' => "value is default yo",
'$x = Array[Integer] "value is $x yo"' => "value is Array[Integer] yo",
'"value is ${Array[Integer]} yo"' => "value is Array[Integer] yo",
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
populate
- parser.evaluate_string(scope, source, __FILE__).should == result
+ expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
it "should parse and evaluate an interpolation of a hash" do
source = '"value is ${{a=>1,b=>2}} yo"'
# This test requires testing against two options because a hash to string
# produces a result that is unordered
hashstr = {'a' => 1, 'b' => 2}.to_s
alt_results = ["value is {a => 1, b => 2} yo", "value is {b => 2, a => 1} yo" ]
populate
parse_result = parser.evaluate_string(scope, source, __FILE__)
- alt_results.include?(parse_result).should == true
+ expect(alt_results.include?(parse_result)).to eq(true)
end
it 'should accept a variable with leading underscore when used directly' do
source = '$_x = 10; "$_x"'
expect(parser.evaluate_string(scope, source, __FILE__)).to eql('10')
end
it 'should accept a variable with leading underscore when used as an expression' do
source = '$_x = 10; "${_x}"'
expect(parser.evaluate_string(scope, source, __FILE__)).to eql('10')
end
{
'"value is ${a*2} yo"' => :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 evaluating variables" do
context "that are non existing an error is raised for" do
it "unqualified variable" do
expect { parser.evaluate_string(scope, "$quantum_gravity", __FILE__) }.to raise_error(/Unknown variable/)
end
it "qualified variable" do
expect { parser.evaluate_string(scope, "$quantum_gravity::graviton", __FILE__) }.to raise_error(/Unknown variable/)
end
end
it "a lex error should be raised for '$foo::::bar'" do
expect { parser.evaluate_string(scope, "$foo::::bar") }.to raise_error(Puppet::LexError, /Illegal fully qualified name at line 1:7/)
end
{ '$a = $0' => nil,
'$a = $1' => nil,
}.each do |source, value|
it "it is ok to reference numeric unassigned variables '#{source}'" do
- parser.evaluate_string(scope, source, __FILE__).should == value
+ expect(parser.evaluate_string(scope, source, __FILE__)).to eq(value)
end
end
{ '$00 = 0' => /must be a decimal value/,
'$0xf = 0' => /must be a decimal value/,
'$0777 = 0' => /must be a decimal value/,
'$123a = 0' => /must be a decimal value/,
}.each do |source, error_pattern|
it "should raise an error for '#{source}'" do
expect { parser.evaluate_string(scope, source, __FILE__) }.to raise_error(error_pattern)
end
end
context "an initial underscore in the last segment of a var name is allowed" do
{ '$_a = 1' => 1,
'$__a = 1' => 1,
}.each do |source, value|
it "as in this example '#{source}'" do
- parser.evaluate_string(scope, source, __FILE__).should == value
+ expect(parser.evaluate_string(scope, source, __FILE__)).to eq(value)
end
end
end
end
context "When evaluating relationships" do
it 'should form a relation with File[a] -> File[b]' do
source = "File[a] -> File[b]"
parser.evaluate_string(scope, source, __FILE__)
- scope.compiler.should have_relationship(['File', 'a', '->', 'File', 'b'])
+ expect(scope.compiler).to have_relationship(['File', 'a', '->', 'File', 'b'])
end
it 'should form a relation with resource -> resource' do
source = "notify{a:} -> notify{b:}"
parser.evaluate_string(scope, source, __FILE__)
- scope.compiler.should have_relationship(['Notify', 'a', '->', 'Notify', 'b'])
+ expect(scope.compiler).to have_relationship(['Notify', 'a', '->', 'Notify', 'b'])
end
it 'should form a relation with [File[a], File[b]] -> [File[x], File[y]]' do
source = "[File[a], File[b]] -> [File[x], File[y]]"
parser.evaluate_string(scope, source, __FILE__)
- scope.compiler.should have_relationship(['File', 'a', '->', 'File', 'x'])
- scope.compiler.should have_relationship(['File', 'b', '->', 'File', 'x'])
- scope.compiler.should have_relationship(['File', 'a', '->', 'File', 'y'])
- scope.compiler.should have_relationship(['File', 'b', '->', 'File', 'y'])
+ expect(scope.compiler).to have_relationship(['File', 'a', '->', 'File', 'x'])
+ expect(scope.compiler).to have_relationship(['File', 'b', '->', 'File', 'x'])
+ expect(scope.compiler).to have_relationship(['File', 'a', '->', 'File', 'y'])
+ expect(scope.compiler).to have_relationship(['File', 'b', '->', 'File', 'y'])
end
it 'should tolerate (eliminate) duplicates in operands' do
source = "[File[a], File[a]] -> File[x]"
parser.evaluate_string(scope, source, __FILE__)
- scope.compiler.should have_relationship(['File', 'a', '->', 'File', 'x'])
- scope.compiler.relationships.size.should == 1
+ expect(scope.compiler).to have_relationship(['File', 'a', '->', 'File', 'x'])
+ expect(scope.compiler.relationships.size).to eq(1)
end
it 'should form a relation with <-' do
source = "File[a] <- File[b]"
parser.evaluate_string(scope, source, __FILE__)
- scope.compiler.should have_relationship(['File', 'b', '->', 'File', 'a'])
+ expect(scope.compiler).to have_relationship(['File', 'b', '->', 'File', 'a'])
end
it 'should form a relation with <-' do
source = "File[a] <~ File[b]"
parser.evaluate_string(scope, source, __FILE__)
- scope.compiler.should have_relationship(['File', 'b', '~>', 'File', 'a'])
+ expect(scope.compiler).to have_relationship(['File', 'b', '~>', 'File', 'a'])
end
end
context "When evaluating heredoc" do
it "evaluates plain heredoc" do
src = "@(END)\nThis is\nheredoc text\nEND\n"
- parser.evaluate_string(scope, src).should == "This is\nheredoc text\n"
+ expect(parser.evaluate_string(scope, src)).to eq("This is\nheredoc text\n")
end
it "parses heredoc with margin" do
src = [
"@(END)",
" This is",
" heredoc text",
" | END",
""
].join("\n")
- parser.evaluate_string(scope, src).should == "This is\nheredoc text\n"
+ expect(parser.evaluate_string(scope, src)).to eq("This is\nheredoc text\n")
end
it "parses heredoc with margin and right newline trim" do
src = [
"@(END)",
" This is",
" heredoc text",
" |- END",
""
].join("\n")
- parser.evaluate_string(scope, src).should == "This is\nheredoc text"
+ expect(parser.evaluate_string(scope, src)).to eq("This is\nheredoc text")
end
it "parses escape specification" do
src = <<-CODE
@(END/t)
Tex\\tt\\n
|- END
CODE
- parser.evaluate_string(scope, src).should == "Tex\tt\\n"
+ expect(parser.evaluate_string(scope, src)).to eq("Tex\tt\\n")
end
it "parses syntax checked specification" do
src = <<-CODE
@(END:json)
["foo", "bar"]
|- END
CODE
- parser.evaluate_string(scope, src).should == '["foo", "bar"]'
+ expect(parser.evaluate_string(scope, src)).to eq('["foo", "bar"]')
end
it "parses syntax checked specification with error and reports it" do
src = <<-CODE
@(END:json)
['foo', "bar"]
|- END
CODE
expect { parser.evaluate_string(scope, src)}.to raise_error(/Cannot parse invalid JSON string/)
end
it "parses interpolated heredoc expression" do
src = <<-CODE
$name = 'Fjodor'
@("END")
Hello $name
|- END
CODE
- parser.evaluate_string(scope, src).should == "Hello Fjodor"
+ expect(parser.evaluate_string(scope, src)).to eq("Hello Fjodor")
end
end
context "Handles Deprecations and Discontinuations" do
it 'of import statements' do
source = "\nimport foo"
# Error references position 5 at the opening '{'
# Set file to nil to make it easier to match with line number (no file name in output)
expect { parser.evaluate_string(scope, source) }.to raise_error(/'import' has been discontinued.*line 2:1/)
end
end
context "Detailed Error messages are reported" do
it 'for illegal type references' do
source = '1+1 { "title": }'
# Error references position 5 at the opening '{'
# Set file to nil to make it easier to match with line number (no file name in output)
expect { parser.evaluate_string(scope, source) }.to raise_error(
/Illegal Resource Type expression, expected result to be a type name, or untitled Resource.*line 1:2/)
end
it 'for non r-value producing <| |>' do
expect { parser.parse_string("$a = File <| |>", nil) }.to raise_error(/A Virtual Query does not produce a value at line 1:6/)
end
it 'for non r-value producing <<| |>>' do
expect { parser.parse_string("$a = File <<| |>>", nil) }.to raise_error(/An Exported Query does not produce a value at line 1:6/)
end
it 'for non r-value producing define' do
Puppet.expects(:err).with("Invalid use of expression. A 'define' expression does not produce a value at line 1:6")
Puppet.expects(:err).with("Classes, definitions, and nodes may only appear at toplevel or inside other classes at line 1:6")
expect { parser.parse_string("$a = define foo { }", nil) }.to raise_error(/2 errors/)
end
it 'for non r-value producing class' do
Puppet.expects(:err).with("Invalid use of expression. A Host Class Definition does not produce a value at line 1:6")
Puppet.expects(:err).with("Classes, definitions, and nodes may only appear at toplevel or inside other classes at line 1:6")
expect { parser.parse_string("$a = class foo { }", nil) }.to raise_error(/2 errors/)
end
it 'for unclosed quote with indication of start position of string' do
source = <<-SOURCE.gsub(/^ {6}/,'')
$a = "xx
yyy
SOURCE
# first char after opening " reported as being in error.
expect { parser.parse_string(source) }.to raise_error(/Unclosed quote after '"' followed by 'xx\\nyy\.\.\.' at line 1:7/)
end
it 'for multiple errors with a summary exception' do
Puppet.expects(:err).with("Invalid use of expression. A Node Definition does not produce a value at line 1:6")
Puppet.expects(:err).with("Classes, definitions, and nodes may only appear at toplevel or inside other classes at line 1:6")
expect { parser.parse_string("$a = node x { }",nil) }.to raise_error(/2 errors/)
end
it 'for a bad hostname' do
expect {
parser.parse_string("node 'macbook+owned+by+name' { }", nil)
}.to raise_error(/The hostname 'macbook\+owned\+by\+name' contains illegal characters.*at line 1:6/)
end
it 'for a hostname with interpolation' do
source = <<-SOURCE.gsub(/^ {6}/,'')
$name = 'fred'
node "macbook-owned-by$name" { }
SOURCE
expect {
parser.parse_string(source, nil)
}.to raise_error(/An interpolated expression is not allowed in a hostname of a node at line 2:23/)
end
end
context 'does not leak variables' do
it 'local variables are gone when lambda ends' do
source = <<-SOURCE
[1,2,3].each |$x| { $y = $x}
$a = $y
SOURCE
expect do
parser.evaluate_string(scope, source)
end.to raise_error(/Unknown variable: 'y'/)
end
it 'lambda parameters are gone when lambda ends' do
source = <<-SOURCE
[1,2,3].each |$x| { $y = $x}
$a = $x
SOURCE
expect do
parser.evaluate_string(scope, source)
end.to raise_error(/Unknown variable: 'x'/)
end
it 'does not leak match variables' do
source = <<-SOURCE
if 'xyz' =~ /(x)(y)(z)/ { notice $2 }
case 'abc' {
/(a)(b)(c)/ : { $x = $2 }
}
"-$x-$2-"
SOURCE
expect(parser.evaluate_string(scope, source)).to eq('-b--')
end
end
matcher :have_relationship do |expected|
calc = Puppet::Pops::Types::TypeCalculator.new
match do |compiler|
op_name = {'->' => :relationship, '~>' => :subscription}
compiler.relationships.any? do | relation |
relation.source.type == expected[0] &&
relation.source.title == expected[1] &&
relation.type == op_name[expected[2]] &&
relation.target.type == expected[3] &&
relation.target.title == expected[4]
end
end
- failure_message_for_should do |actual|
+ failure_message do |actual|
"Relationship #{expected[0]}[#{expected[1]}] #{expected[2]} #{expected[3]}[#{expected[4]}] but was unknown to compiler"
end
end
end
diff --git a/spec/unit/pops/evaluator/logical_ops_spec.rb b/spec/unit/pops/evaluator/logical_ops_spec.rb
index d6a179e03..868dffd29 100644
--- a/spec/unit/pops/evaluator/logical_ops_spec.rb
+++ b/spec/unit/pops/evaluator/logical_ops_spec.rb
@@ -1,90 +1,90 @@
#! /usr/bin/env ruby
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
- evaluate(literal(true).and(literal(true))).should == true
+ expect(evaluate(literal(true).and(literal(true)))).to eq(true)
end
it "false && true == false" do
- evaluate(literal(false).and(literal(true))).should == false
+ expect(evaluate(literal(false).and(literal(true)))).to eq(false)
end
it "true && false == false" do
- evaluate(literal(true).and(literal(false))).should == false
+ expect(evaluate(literal(true).and(literal(false)))).to eq(false)
end
it "false && false == false" do
- evaluate(literal(false).and(literal(false))).should == false
+ expect(evaluate(literal(false).and(literal(false)))).to eq(false)
end
end
context "using operator OR" do
it "true || true == true" do
- evaluate(literal(true).or(literal(true))).should == true
+ expect(evaluate(literal(true).or(literal(true)))).to eq(true)
end
it "false || true == true" do
- evaluate(literal(false).or(literal(true))).should == true
+ expect(evaluate(literal(false).or(literal(true)))).to eq(true)
end
it "true || false == true" do
- evaluate(literal(true).or(literal(false))).should == true
+ expect(evaluate(literal(true).or(literal(false)))).to eq(true)
end
it "false || false == false" do
- evaluate(literal(false).or(literal(false))).should == false
+ expect(evaluate(literal(false).or(literal(false)))).to eq(false)
end
end
context "using operator NOT" do
it "!false == true" do
- evaluate(literal(false).not()).should == true
+ expect(evaluate(literal(false).not())).to eq(true)
end
it "!true == false" do
- evaluate(literal(true).not()).should == false
+ expect(evaluate(literal(true).not())).to eq(false)
end
end
context "on values requiring boxing to Boolean" do
it "'x' == true" do
- evaluate(literal('x').not()).should == false
+ expect(evaluate(literal('x').not())).to eq(false)
end
it "'' == true" do
- evaluate(literal('').not()).should == false
+ expect(evaluate(literal('').not())).to eq(false)
end
it ":undef == false" do
- evaluate(literal(:undef).not()).should == true
+ 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
- evaluate(literal(false).and(literal('0xwtf') + literal(1)).and(literal(true))).should == false
+ 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
- evaluate(literal(true).or(literal('0xwtf') + literal(1)).or(literal(false))).should == true
+ 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
diff --git a/spec/unit/pops/evaluator/string_interpolation_spec.rb b/spec/unit/pops/evaluator/string_interpolation_spec.rb
index 49f674588..3031fd6c7 100644
--- a/spec/unit/pops/evaluator/string_interpolation_spec.rb
+++ b/spec/unit/pops/evaluator/string_interpolation_spec.rb
@@ -1,44 +1,44 @@
#! /usr/bin/env ruby
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(10), string('value is ', text(fqn('a')), ' yo'))
- evaluate(a_block).should == "value is 10 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(10), string('value is ', text(var(fqn('a'))), ' yo'))
- evaluate(a_block).should == "value is 10 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(10), string('value is ', var(fqn('a')), ' yo'))
- evaluate(a_block).should == "value is 10 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(5), string('value is ', text(var(fqn('a')) * 2) , ' yo'))
- evaluate(a_block).should == "value is 10 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(5), string('value is ', var(fqn('a')) * 2 , ' yo'))
- evaluate(a_block).should == "value is 10 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
diff --git a/spec/unit/pops/evaluator/variables_spec.rb b/spec/unit/pops/evaluator/variables_spec.rb
index 6c1e9f821..b12bad468 100644
--- a/spec/unit/pops/evaluator/variables_spec.rb
+++ b/spec/unit/pops/evaluator/variables_spec.rb
@@ -1,89 +1,89 @@
#! /usr/bin/env ruby
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
- evaluate_l(block( var('a').set(literal(2)+literal(2)), var('a'))).should == 4
+ 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'))
- evaluate_l(top_scope_block, local_scope_block).should == 6
+ 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')
- evaluate_l(top_scope_block, local_scope_block, top_scope_again).should == 4
+ 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'))
- evaluate_l(top_scope_block).should == 4
+ 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(var('::a')+literal(2)), var('::a'))
- evaluate_l(top_scope_block, local_scope_block).should == 6
+ 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(10), var('a').set(20))) }.to raise_error(/Cannot reassign variable a/)
end
context "access to numeric variables" do
it "without a match" do
- evaluate_l(block(literal(2) + literal(2),
- [var(0), var(1), var(2), var(3)])).should == [nil, nil, nil, nil]
+ 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
- evaluate_l(block(literal('abc') =~ literal(/(a)(b)(c)/),
- [var(0), var(1), var(2), var(3)])).should == ['abc', 'a', 'b', 'c']
+ 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
- evaluate_l(block(literal('abc') =~ literal(/(x)(y)(z)/),
- [var(0), var(1), var(2), var(3)])).should == [nil, nil, nil, nil]
+ 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
- evaluate_l(block(
+ expect(evaluate_l(block(
literal('abc') =~ literal(/(a)(b)(c)/),
literal('abc') =~ literal(/(x)(y)(z)/),
- [var(0), var(1), var(2), var(3)])).should == ['abc', 'a', 'b', 'c']
+ [var(0), var(1), var(2), var(3)]))).to eq(['abc', 'a', 'b', 'c'])
end
it "a new match completely shadows previous match" do
- evaluate_l(block(
+ expect(evaluate_l(block(
literal('abc') =~ literal(/(a)(b)(c)/),
literal('abc') =~ literal(/(a)bc/),
- [var(0), var(1), var(2), var(3)])).should == ['abc', 'a', nil, nil]
+ [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
- evaluate_l(block(literal('abc') =~ literal(/(a)(b)(c)/),
- [var(0), var(1), var(2), var(3), var(4)])).should == ['abc', 'a', 'b', 'c', nil]
+ 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
diff --git a/spec/unit/pops/factory_rspec_helper.rb b/spec/unit/pops/factory_rspec_helper.rb
index b11f6ee87..9c2635ebc 100644
--- a/spec/unit/pops/factory_rspec_helper.rb
+++ b/spec/unit/pops/factory_rspec_helper.rb
@@ -1,77 +1,69 @@
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 text(x)
Puppet::Pops::Model::Factory.text(x)
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 respond_to? method
- if Puppet::Pops::Model::Factory.respond_to? method
- true
- else
- super
- end
- 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
diff --git a/spec/unit/pops/factory_spec.rb b/spec/unit/pops/factory_spec.rb
index 779a0630d..64cb30209 100644
--- a/spec/unit/pops/factory_spec.rb
+++ b/spec/unit/pops/factory_spec.rb
@@ -1,306 +1,306 @@
#! /usr/bin/env ruby
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
- var('a').current.class.should == Puppet::Pops::Model::VariableExpression
+ expect(var('a').current.class).to eq(Puppet::Pops::Model::VariableExpression)
end
it "tests #fqn should create a QualifiedName" do
- fqn('a').current.class.should == Puppet::Pops::Model::QualifiedName
+ expect(fqn('a').current.class).to eq(Puppet::Pops::Model::QualifiedName)
end
it "tests #QNAME should create a QualifiedName" do
- QNAME('a').current.class.should == Puppet::Pops::Model::QualifiedName
+ expect(QNAME('a').current.class).to eq(Puppet::Pops::Model::QualifiedName)
end
it "tests #QREF should create a QualifiedReference" do
- QREF('a').current.class.should == Puppet::Pops::Model::QualifiedReference
+ expect(QREF('a').current.class).to eq(Puppet::Pops::Model::QualifiedReference)
end
it "tests #block should create a BlockExpression" do
- block().current.is_a?(Puppet::Pops::Model::BlockExpression).should == true
+ expect(block().current.is_a?(Puppet::Pops::Model::BlockExpression)).to eq(true)
end
it "should create a literal undef on :undef" do
- literal(:undef).current.class.should == Puppet::Pops::Model::LiteralUndef
+ expect(literal(:undef).current.class).to eq(Puppet::Pops::Model::LiteralUndef)
end
it "should create a literal default on :default" do
- literal(:default).current.class.should == Puppet::Pops::Model::LiteralDefault
+ expect(literal(:default).current.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
- block_or_expression(literal(1) + literal(2)).current.is_a?(Puppet::Pops::Model::ArithmeticExpression).should == true
+ expect(block_or_expression(literal(1) + literal(2)).current.is_a?(Puppet::Pops::Model::ArithmeticExpression)).to eq(true)
end
it "Multiple expressions should produce a block expression" do
built = block_or_expression(literal(1) + literal(2), literal(2) + literal(3)).current
- built.is_a?(Puppet::Pops::Model::BlockExpression).should == true
- built.statements.size.should == 2
+ expect(built.is_a?(Puppet::Pops::Model::BlockExpression)).to eq(true)
+ expect(built.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, []).current
- built.is_a?(Puppet::Pops::Model::CallNamedFunctionExpression).should == true
- built.rval_required.should == true
+ 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, []).current
- built.is_a?(Puppet::Pops::Model::CallNamedFunctionExpression).should == true
- built.functor_expr.is_a?(Puppet::Pops::Model::QualifiedName).should == true
- built.functor_expr.value.should == "foo"
- built.rval_required.should == false
- built.arguments.size.should == 0
+ 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)]).current
- built.is_a?(Puppet::Pops::Model::CallNamedFunctionExpression).should == true
- built.functor_expr.is_a?(Puppet::Pops::Model::QualifiedName).should == true
- built.functor_expr.value.should == "foo"
- built.rval_required.should == false
- built.arguments.size.should == 1
- built.arguments[0].is_a?(Puppet::Pops::Model::ArithmeticExpression).should == true
+ 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)]).current
- built.is_a?(Puppet::Pops::Model::CallNamedFunctionExpression).should == true
- built.functor_expr.is_a?(Puppet::Pops::Model::QualifiedName).should == true
- built.functor_expr.value.should == "foo"
- built.rval_required.should == false
- built.arguments.size.should == 2
- built.arguments[0].is_a?(Puppet::Pops::Model::ArithmeticExpression).should == true
- built.arguments[1].is_a?(Puppet::Pops::Model::ArithmeticExpression).should == true
+ 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", :'=>', 'x').current
built.is_a?(Puppet::Pops::Model::AttributeOperation)
- built.operator.should == :'=>'
- built.attribute_name.should == "aname"
- built.value_expr.is_a?(Puppet::Pops::Model::LiteralString).should == true
+ 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", :'+>', 'x').current
built.is_a?(Puppet::Pops::Model::AttributeOperation)
- built.operator.should == :'+>'
- built.attribute_name.should == "aname"
- built.value_expr.is_a?(Puppet::Pops::Model::LiteralString).should == true
+ 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("title", [ATTRIBUTE_OP('aname', :'=>', 'x')]).current
- built.is_a?(Puppet::Pops::Model::ResourceBody).should == true
- built.title.is_a?(Puppet::Pops::Model::LiteralString).should == true
- built.operations.size.should == 1
- built.operations[0].class.should == Puppet::Pops::Model::AttributeOperation
- built.operations[0].attribute_name.should == 'aname'
+ 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("rtype", bodies).current
- built.class.should == Puppet::Pops::Model::ResourceExpression
- built.bodies.size.should == 0
+ 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('title', [])
built = RESOURCE("rtype", bodies).current
- built.class.should == Puppet::Pops::Model::ResourceExpression
- built.bodies.size.should == 1
- built.bodies[0].title.value.should == 'title'
+ 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('title', []) << RESOURCE_BODY('title2', [])
built = RESOURCE("rtype", bodies).current
- built.class.should == Puppet::Pops::Model::ResourceExpression
- built.bodies.size.should == 2
- built.bodies[0].title.value.should == 'title'
- built.bodies[1].title.value.should == 'title2'
+ 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
built = literal(true).current
- built.class.should == Puppet::Pops::Model::LiteralBoolean
- built.value.should == true
+ expect(built.class).to eq(Puppet::Pops::Model::LiteralBoolean)
+ expect(built.value).to eq(true)
built = literal(false).current
- built.class.should == Puppet::Pops::Model::LiteralBoolean
- built.value.should == false
+ expect(built.class).to eq(Puppet::Pops::Model::LiteralBoolean)
+ expect(built.value).to eq(false)
end
end
context "When processing COLLECT" do
it "should produce a virtual query" do
built = VIRTUAL_QUERY(fqn('a') == literal(1)).current
- built.class.should == Puppet::Pops::Model::VirtualQuery
- built.expr.class.should == Puppet::Pops::Model::ComparisonExpression
- built.expr.operator.should == :'=='
+ expect(built.class).to eq(Puppet::Pops::Model::VirtualQuery)
+ expect(built.expr.class).to eq(Puppet::Pops::Model::ComparisonExpression)
+ expect(built.expr.operator).to eq(:'==')
end
it "should produce an export query" do
built = EXPORTED_QUERY(fqn('a') == literal(1)).current
- built.class.should == Puppet::Pops::Model::ExportedQuery
- built.expr.class.should == Puppet::Pops::Model::ComparisonExpression
- built.expr.operator.should == :'=='
+ expect(built.class).to eq(Puppet::Pops::Model::ExportedQuery)
+ expect(built.expr.class).to eq(Puppet::Pops::Model::ComparisonExpression)
+ expect(built.expr.operator).to eq(:'==')
end
it "should produce a collect expression" do
q = VIRTUAL_QUERY(fqn('a') == literal(1))
built = COLLECT(literal('t'), q, [ATTRIBUTE_OP('name', :'=>', 3)]).current
- built.class.should == Puppet::Pops::Model::CollectExpression
- built.operations.size.should == 1
+ 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') == literal(1))
built = COLLECT(literal('t'), q, []).current
- built.class.should == Puppet::Pops::Model::CollectExpression
- built.operations.size.should == 0
+ 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
built = string('blah blah').current
- built.class.should == Puppet::Pops::Model::ConcatenatedString
+ expect(built.class).to eq(Puppet::Pops::Model::ConcatenatedString)
built.segments.size == 1
- built.segments[0].class.should == Puppet::Pops::Model::LiteralString
- built.segments[0].value.should == "blah blah"
+ expect(built.segments[0].class).to eq(Puppet::Pops::Model::LiteralString)
+ expect(built.segments[0].value).to eq("blah blah")
end
it "should handle one expression in the middle" do
built = string('blah blah', TEXT(literal(1)+literal(2)), 'blah blah').current
- built.class.should == Puppet::Pops::Model::ConcatenatedString
+ expect(built.class).to eq(Puppet::Pops::Model::ConcatenatedString)
built.segments.size == 3
- built.segments[0].class.should == Puppet::Pops::Model::LiteralString
- built.segments[0].value.should == "blah blah"
- built.segments[1].class.should == Puppet::Pops::Model::TextExpression
- built.segments[1].expr.class.should == Puppet::Pops::Model::ArithmeticExpression
- built.segments[2].class.should == Puppet::Pops::Model::LiteralString
- built.segments[2].value.should == "blah blah"
+ expect(built.segments[0].class).to eq(Puppet::Pops::Model::LiteralString)
+ expect(built.segments[0].value).to eq("blah blah")
+ expect(built.segments[1].class).to eq(Puppet::Pops::Model::TextExpression)
+ expect(built.segments[1].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression)
+ expect(built.segments[2].class).to eq(Puppet::Pops::Model::LiteralString)
+ expect(built.segments[2].value).to eq("blah blah")
end
it "should handle one expression at the end" do
built = string('blah blah', TEXT(literal(1)+literal(2))).current
- built.class.should == Puppet::Pops::Model::ConcatenatedString
+ expect(built.class).to eq(Puppet::Pops::Model::ConcatenatedString)
built.segments.size == 2
- built.segments[0].class.should == Puppet::Pops::Model::LiteralString
- built.segments[0].value.should == "blah blah"
- built.segments[1].class.should == Puppet::Pops::Model::TextExpression
- built.segments[1].expr.class.should == Puppet::Pops::Model::ArithmeticExpression
+ expect(built.segments[0].class).to eq(Puppet::Pops::Model::LiteralString)
+ expect(built.segments[0].value).to eq("blah blah")
+ expect(built.segments[1].class).to eq(Puppet::Pops::Model::TextExpression)
+ expect(built.segments[1].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression)
end
it "should handle only one expression" do
built = string(TEXT(literal(1)+literal(2))).current
- built.class.should == Puppet::Pops::Model::ConcatenatedString
+ expect(built.class).to eq(Puppet::Pops::Model::ConcatenatedString)
built.segments.size == 1
- built.segments[0].class.should == Puppet::Pops::Model::TextExpression
- built.segments[0].expr.class.should == Puppet::Pops::Model::ArithmeticExpression
+ expect(built.segments[0].class).to eq(Puppet::Pops::Model::TextExpression)
+ expect(built.segments[0].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression)
end
it "should handle several expressions" do
built = string(TEXT(literal(1)+literal(2)), TEXT(literal(1)+literal(2))).current
- built.class.should == Puppet::Pops::Model::ConcatenatedString
+ expect(built.class).to eq(Puppet::Pops::Model::ConcatenatedString)
built.segments.size == 2
- built.segments[0].class.should == Puppet::Pops::Model::TextExpression
- built.segments[0].expr.class.should == Puppet::Pops::Model::ArithmeticExpression
- built.segments[1].class.should == Puppet::Pops::Model::TextExpression
- built.segments[1].expr.class.should == Puppet::Pops::Model::ArithmeticExpression
+ expect(built.segments[0].class).to eq(Puppet::Pops::Model::TextExpression)
+ expect(built.segments[0].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression)
+ expect(built.segments[1].class).to eq(Puppet::Pops::Model::TextExpression)
+ expect(built.segments[1].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression)
end
it "should handle no expression" do
built = string().current
- built.class.should == Puppet::Pops::Model::ConcatenatedString
+ expect(built.class).to eq(Puppet::Pops::Model::ConcatenatedString)
built.segments.size == 0
end
end
context "When processing UNLESS" do
it "should create an UNLESS expression with then part" do
built = UNLESS(true, literal(1), nil).current
- built.class.should == Puppet::Pops::Model::UnlessExpression
- built.test.class.should == Puppet::Pops::Model::LiteralBoolean
- built.then_expr.class.should == Puppet::Pops::Model::LiteralInteger
- built.else_expr.class.should == Puppet::Pops::Model::Nop
+ 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(true, literal(1), literal(2)).current
- built.class.should == Puppet::Pops::Model::UnlessExpression
- built.test.class.should == Puppet::Pops::Model::LiteralBoolean
- built.then_expr.class.should == Puppet::Pops::Model::LiteralInteger
- built.else_expr.class.should == Puppet::Pops::Model::LiteralInteger
+ 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(true, literal(1), nil).current
- built.class.should == Puppet::Pops::Model::IfExpression
- built.test.class.should == Puppet::Pops::Model::LiteralBoolean
- built.then_expr.class.should == Puppet::Pops::Model::LiteralInteger
- built.else_expr.class.should == Puppet::Pops::Model::Nop
+ 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(true, literal(1), literal(2)).current
- built.class.should == Puppet::Pops::Model::IfExpression
- built.test.class.should == Puppet::Pops::Model::LiteralBoolean
- built.then_expr.class.should == Puppet::Pops::Model::LiteralInteger
- built.else_expr.class.should == Puppet::Pops::Model::LiteralInteger
+ 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
diff --git a/spec/unit/pops/issues_spec.rb b/spec/unit/pops/issues_spec.rb
index 82dce1b44..823462d0e 100644
--- a/spec/unit/pops/issues_spec.rb
+++ b/spec/unit/pops/issues_spec.rb
@@ -1,196 +1,196 @@
#! /usr/bin/env ruby
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
- x.class.should == Puppet::Pops::Issues::Issue
- x.issue_code.should == :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
- x.format(:name => 'Boo-Hoo',
+ expect(x.format(:name => 'Boo-Hoo',
:label => Puppet::Pops::Model::ModelLabelProvider.new,
:semantic => "dummy"
- ).should == "A String may not have a name containing a hyphen. The name 'Boo-Hoo' is not legal"
+ )).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
- x.format().should == "Classes, definitions, and nodes may only appear at toplevel or inside other classes"
+ 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)
stub("positioned_#{number}", :line => number, :pos => number)
end
def diagnostic(severity, number)
Puppet::Pops::Validation::Diagnostic.new(
severity,
Puppet::Pops::Issues::Issue.new(number) { "#{severity}#{number}" },
"#{severity}file",
fake_positioned(number))
end
def warning(number)
diagnostic(:warning, number)
end
def deprecation(number)
diagnostic(:deprecation, number)
end
def error(number)
diagnostic(:error, number)
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
Puppet.expects(:warning).twice.with(regexp_matches(/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
Puppet.expects(:warning).never
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
Puppet.expects(:warning).once.with(regexp_matches(/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
Puppet.expects(:warning).twice.with(regexp_matches(/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
Puppet.expects(:warning).once.with(regexp_matches(/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'
Puppet.expects(:warning).once.with(regexp_matches(/warning1/))
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) )
Puppet.expects(:err).never
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) )
Puppet.expects(:err).never
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) )
Puppet.expects(:err).never
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
Puppet.expects(:err).never
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) )
Puppet.expects(:err).times(3).with(regexp_matches(/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
Puppet.expects(:err).times(2).with(regexp_matches(/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
Puppet.expects(:err).times(3).with(regexp_matches(/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'
Puppet.expects(:err).times(2).with(regexp_matches(/error1|error2/))
expect do
Puppet::Pops::IssueReporter.assert_and_report(acceptor, { })
end.to raise_error(Puppet::ParseError, /Giving up/)
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
Puppet.expects(:warning).twice.with(regexp_matches(/warning1|deprecation1/))
Puppet.expects(:err).times(2).with(regexp_matches(/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
diff --git a/spec/unit/pops/label_provider_spec.rb b/spec/unit/pops/label_provider_spec.rb
index 3e822669a..da5348e46 100644
--- a/spec/unit/pops/label_provider_spec.rb
+++ b/spec/unit/pops/label_provider_spec.rb
@@ -1,42 +1,42 @@
require 'spec_helper'
require 'puppet/pops'
describe Puppet::Pops::LabelProvider do
let(:labeler) { Puppet::Pops::LabelProvider.new }
it "prefixes words that start with a vowel with an 'an'" do
- labeler.a_an('owl').should == 'an owl'
+ expect(labeler.a_an('owl')).to eq('an owl')
end
it "prefixes words that start with a consonant with an 'a'" do
- labeler.a_an('bear').should == 'a bear'
+ expect(labeler.a_an('bear')).to eq('a bear')
end
it "prefixes non-word characters with an 'a'" do
- labeler.a_an('[] expression').should == 'a [] expression'
+ expect(labeler.a_an('[] expression')).to eq('a [] expression')
end
it "ignores a single quote leading the word" do
- labeler.a_an("'owl'").should == "an 'owl'"
+ expect(labeler.a_an("'owl'")).to eq("an 'owl'")
end
it "ignores a double quote leading the word" do
- labeler.a_an('"owl"').should == 'an "owl"'
+ expect(labeler.a_an('"owl"')).to eq('an "owl"')
end
it "capitalizes the indefinite article for a word when requested" do
- labeler.a_an_uc('owl').should == 'An owl'
+ 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
diff --git a/spec/unit/pops/loaders/loaders_spec.rb b/spec/unit/pops/loaders/loaders_spec.rb
index 831236698..76958c714 100644
--- a/spec/unit/pops/loaders/loaders_spec.rb
+++ b/spec/unit/pops/loaders/loaders_spec.rb
@@ -1,125 +1,125 @@
require 'spec_helper'
require 'puppet_spec/files'
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_true
+ 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::Loader::TypedName.new(:function, '::foo::bar')
- expect(tn.frozen?).to be_true
+ 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_true
+ expect(tn.qualified).to be_truthy
end
end
describe 'loaders' do
include PuppetSpec::Files
let(:module_without_metadata) { File.join(config_dir('wo_metadata_module'), 'modules') }
let(:module_with_metadata) { File.join(config_dir('single_module'), 'modules') }
let(:dependent_modules_with_metadata) { config_dir('dependent_modules_with_metadata') }
let(:empty_test_env) { environment_for() }
# Loaders caches the puppet_system_loader, must reset between tests
before(:each) { Puppet::Pops::Loaders.clear() }
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 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:*test*')")
expect(loaders.private_environment_loader()).to be_a(Puppet::Pops::Loader::DependencyLoader)
expect(loaders.private_environment_loader().to_s).to eql("(DependencyLoader 'environment' [])")
end
it 'can load a function using a qualified or unqualified name from a module with metadata' 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 'can load a function with a qualified name from module without metadata' 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 'cannot load an unqualified function from a module without metadata' 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 'makes all other modules visible to a module without metadata' 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
it 'makes dependent modules visible to a module with metadata' do
env = environment_for(dependent_modules_with_metadata)
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
it 'can load a function more than once from modules' do
env = environment_for(dependent_modules_with_metadata)
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
def environment_for(*module_paths)
Puppet::Node::Environment.create(:'*test*', module_paths, '')
end
def typed_name(type, name)
Puppet::Pops::Loader::Loader::TypedName.new(type, name)
end
def config_dir(config_name)
my_fixture(config_name)
end
end
diff --git a/spec/unit/pops/model/model_spec.rb b/spec/unit/pops/model/model_spec.rb
index 3c1b22e3e..2d2290575 100644
--- a/spec/unit/pops/model/model_spec.rb
+++ b/spec/unit/pops/model/model_spec.rb
@@ -1,37 +1,37 @@
#! /usr/bin/env ruby
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
- nop.class.should == Puppet::Pops::Model::Nop
+ 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)
- x.is_a?(Factory).should == true
+ expect(x.is_a?(Factory)).to eq(true)
current = x.current
- current.is_a?(Model::ArithmeticExpression).should == true
- current.operator.should == :'+'
- current.left_expr.class.should == Model::LiteralInteger
- current.right_expr.class.should == Model::LiteralInteger
- current.left_expr.value.should == 10
- current.right_expr.value.should == 20
+ expect(current.is_a?(Model::ArithmeticExpression)).to eq(true)
+ expect(current.operator).to eq(:'+')
+ expect(current.left_expr.class).to eq(Model::LiteralInteger)
+ expect(current.right_expr.class).to eq(Model::LiteralInteger)
+ expect(current.left_expr.value).to eq(10)
+ expect(current.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)
- Puppet::Pops::Model::ModelTreeDumper.new.dump(x.current).should == "(+ 10 20)"
+ expect(Puppet::Pops::Model::ModelTreeDumper.new.dump(x.current)).to eq("(+ 10 20)")
end
it "builder should apply precedence" do
x = Factory.literal(2) * Factory.literal(10) + Factory.literal(20)
- Puppet::Pops::Model::ModelTreeDumper.new.dump(x.current).should == "(+ (* 2 10) 20)"
+ expect(Puppet::Pops::Model::ModelTreeDumper.new.dump(x.current)).to eq("(+ (* 2 10) 20)")
end
end
diff --git a/spec/unit/pops/parser/epp_parser_spec.rb b/spec/unit/pops/parser/epp_parser_spec.rb
index fb32b9ba4..44ff10a5e 100644
--- a/spec/unit/pops/parser/epp_parser_spec.rb
+++ b/spec/unit/pops/parser/epp_parser_spec.rb
@@ -1,115 +1,115 @@
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()
- parser.class.should == Puppet::Pops::Parser::EppParser
+ 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...").current
- model.class.should == Puppet::Pops::Model::Program
- model.body.class.should == Puppet::Pops::Model::LambdaExpression
- model.body.body.class.should == Puppet::Pops::Model::EppExpression
+ 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
- dump(parse("Hello World")).should == [
+ expect(dump(parse("Hello World"))).to eq([
"(lambda (epp (block",
" (render-s 'Hello World')",
- ")))"].join("\n")
+ ")))"].join("\n"))
end
it "template parameters" do
- dump(parse("<%|$x|%>Hello World")).should == [
+ expect(dump(parse("<%|$x|%>Hello World"))).to eq([
"(lambda (parameters x) (epp (block",
" (render-s 'Hello World')",
- ")))"].join("\n")
+ ")))"].join("\n"))
end
it "template parameters with default" do
- dump(parse("<%|$x='cigar'|%>Hello World")).should == [
+ expect(dump(parse("<%|$x='cigar'|%>Hello World"))).to eq([
"(lambda (parameters (= x 'cigar')) (epp (block",
" (render-s 'Hello World')",
- ")))"].join("\n")
+ ")))"].join("\n"))
end
it "template parameters with and without default" do
- dump(parse("<%|$x='cigar', $y|%>Hello World")).should == [
+ expect(dump(parse("<%|$x='cigar', $y|%>Hello World"))).to eq([
"(lambda (parameters (= x 'cigar') y) (epp (block",
" (render-s 'Hello World')",
- ")))"].join("\n")
+ ")))"].join("\n"))
end
it "template parameters + additional setup" do
- dump(parse("<%|$x| $y = 10 %>Hello World")).should == [
+ expect(dump(parse("<%|$x| $y = 10 %>Hello World"))).to eq([
"(lambda (parameters x) (epp (block",
" (= $y 10)",
" (render-s 'Hello World')",
- ")))"].join("\n")
+ ")))"].join("\n"))
end
it "comments" do
- dump(parse("<%#($x='cigar', $y)%>Hello World")).should == [
+ expect(dump(parse("<%#($x='cigar', $y)%>Hello World"))).to eq([
"(lambda (epp (block",
" (render-s 'Hello World')",
")))"
- ].join("\n")
+ ].join("\n"))
end
it "verbatim epp tags" do
- dump(parse("<%% contemplating %%>Hello World")).should == [
+ expect(dump(parse("<%% contemplating %%>Hello World"))).to eq([
"(lambda (epp (block",
" (render-s '<% contemplating %>Hello World')",
")))"
- ].join("\n")
+ ].join("\n"))
end
it "expressions" do
- dump(parse("We all live in <%= 3.14 - 2.14 %> world")).should == [
+ 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")
+ ].join("\n"))
end
end
end
diff --git a/spec/unit/pops/parser/evaluating_parser_spec.rb b/spec/unit/pops/parser/evaluating_parser_spec.rb
index 7645b9bc2..6664d20d2 100644
--- a/spec/unit/pops/parser/evaluating_parser_spec.rb
+++ b/spec/unit/pops/parser/evaluating_parser_spec.rb
@@ -1,89 +1,89 @@
require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/pops'
require 'puppet_spec/scope'
describe 'The Evaluating Parser' do
include PuppetSpec::Pops
include PuppetSpec::Scope
let(:acceptor) { Puppet::Pops::Validation::Acceptor.new() }
let(:scope) { s = create_test_scope_for_node(node); s }
let(:node) { 'node.example.com' }
def quote(x)
Puppet::Pops::Parser::EvaluatingParser.quote(x)
end
def evaluator()
Puppet::Pops::Parser::EvaluatingParser.new()
end
def evaluate(s)
evaluator.evaluate(scope, quote(s))
end
def test(x)
- evaluator.evaluate_string(scope, quote(x)).should == x
+ expect(evaluator.evaluate_string(scope, quote(x))).to eq(x)
end
def test_interpolate(x, y)
scope['a'] = 'expansion'
- evaluator.evaluate_string(scope, quote(x)).should == y
+ expect(evaluator.evaluate_string(scope, quote(x))).to eq(y)
end
context 'when evaluating' do
it 'should produce an empty string with no change' do
test('')
end
it 'should produce a normal string with no change' do
test('A normal string')
end
it 'should produce a string with newlines with no change' do
test("A\nnormal\nstring")
end
it 'should produce a string with escaped newlines with no change' do
test("A\\nnormal\\nstring")
end
it 'should produce a string containing quotes without change' do
test('This " should remain untouched')
end
it 'should produce a string containing escaped quotes without change' do
test('This \" should remain untouched')
end
it 'should expand ${a} variables' do
test_interpolate('This ${a} was expanded', 'This expansion was expanded')
end
it 'should expand quoted ${a} variables' do
test_interpolate('This "${a}" was expanded', 'This "expansion" was expanded')
end
it 'should not expand escaped ${a}' do
test_interpolate('This \${a} was not expanded', 'This ${a} was not expanded')
end
it 'should expand $a variables' do
test_interpolate('This $a was expanded', 'This expansion was expanded')
end
it 'should expand quoted $a variables' do
test_interpolate('This "$a" was expanded', 'This "expansion" was expanded')
end
it 'should not expand escaped $a' do
test_interpolate('This \$a was not expanded', 'This $a was not expanded')
end
it 'should produce an single space from a \s' do
test_interpolate("\\s", ' ')
end
end
end
diff --git a/spec/unit/pops/parser/lexer2_spec.rb b/spec/unit/pops/parser/lexer2_spec.rb
index f6f3be12c..11ad574ae 100644
--- a/spec/unit/pops/parser/lexer2_spec.rb
+++ b/spec/unit/pops/parser/lexer2_spec.rb
@@ -1,475 +1,475 @@
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
tokens = lexer.fullscan[0..-2]
end
def epp_tokens_scanned_from(s)
lexer = Puppet::Pops::Parser::Lexer2.new
lexer.string = s
tokens = lexer.fullscan_epp[0..-2]
end
end
describe 'Lexer2' do
include EgrammarLexer2Spec
{
:LISTSTART => '[',
:RBRACK => ']',
:LBRACE => '{',
:RBRACE => '}',
:LPAREN => '(',
: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
- tokens_scanned_from(string).should match_tokens2(name)
+ expect(tokens_scanned_from(string)).to match_tokens2(name)
end
end
it "should lex [ in position after non whitespace as LBRACK" do
- tokens_scanned_from("a[").should match_tokens2(:NAME, :LBRACK)
+ 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,
}.each do |string, name|
it "should lex a keyword from '#{string}'" do
- tokens_scanned_from(string).should match_tokens2(name)
+ expect(tokens_scanned_from(string)).to match_tokens2(name)
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
- tokens_scanned_from(string).should match_tokens2([:CLASSREF, string])
+ 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
- tokens_scanned_from(string).should match_tokens2([:NAME, string])
+ 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
- tokens_scanned_from(string).should match_tokens2([:WORD, string])
+ 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 bad NAME" do
expect {
tokens_scanned_from(string)
}.to raise_error(/Illegal fully qualified name/)
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
- tokens_scanned_from(source).should match_tokens2(*expected)
+ 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
- tokens_scanned_from(string).should match_tokens2([:BOOLEAN, value])
+ 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
- tokens_scanned_from(string).should match_tokens2([:NUMBER, string])
+ 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
- tokens_scanned_from(string).should match_tokens2([:NUMBER, value])
+ 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
- tokens_scanned_from(string).should match_tokens2([:NUMBER, string])
+ 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
- tokens_scanned_from(string).should match_tokens2([:NUMBER, string])
+ 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
- tokens_scanned_from(string).should match_tokens2([:NUMBER, string])
+ 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
- tokens_scanned_from(source).should match_tokens2([:STRING, expected])
+ 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
- tokens_scanned_from(source).should match_tokens2([:STRING, value, {:line => 1, :pos=>1, :length=> length}])
+ 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
- tokens_scanned_from(source).should match_tokens2([:STRING, expected])
+ 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 }]],
}.each do |source, expected|
it "should lex an interpolated variable 'x' from #{source}" do
- tokens_scanned_from(source).should match_tokens2(*expected)
+ 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
- tokens_scanned_from(source).should match_tokens2([:STRING, expected])
+ expect(tokens_scanned_from(source)).to match_tokens2([:STRING, expected])
end
end
it "differentiates between foo[x] and foo [x] (whitespace)" do
- tokens_scanned_from("$a[1]").should match_tokens2(:VARIABLE, :LBRACK, :NUMBER, :RBRACK)
- tokens_scanned_from("$a [1]").should match_tokens2(:VARIABLE, :LISTSTART, :NUMBER, :RBRACK)
- tokens_scanned_from("a[1]").should match_tokens2(:NAME, :LBRACK, :NUMBER, :RBRACK)
- tokens_scanned_from("a [1]").should match_tokens2(:NAME, :LISTSTART, :NUMBER, :RBRACK)
- tokens_scanned_from(" if \n\r\t\nif if ").should match_tokens2(:IF, :IF, :IF)
+ 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)
+ expect(tokens_scanned_from(" if \n\r\t\nif if ")).to match_tokens2(:IF, :IF, :IF)
end
it "skips whitepsace" do
- tokens_scanned_from(" if if if ").should match_tokens2(:IF, :IF, :IF)
- tokens_scanned_from(" if \n\r\t\nif if ").should match_tokens2(:IF, :IF, :IF)
+ 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)
end
it "skips single line comments" do
- tokens_scanned_from("if # comment\nif").should match_tokens2(:IF, :IF)
+ 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
- tokens_scanned_from(source).should match_tokens2(:IF, :IF)
+ expect(tokens_scanned_from(source)).to match_tokens2(:IF, :IF)
end
end
{ "=~" => [:MATCH, "=~ /./"],
"!~" => [:NOMATCH, "!~ /./"],
"," => [:COMMA, ", /./"],
"(" => [:LPAREN, "( /./"],
"[" => [:LISTSTART, "[ /./"],
"[" => [[:NAME, :LBRACK], "a[ /./"],
"[" => [[:NAME, :LISTSTART], "a [ /./"],
"{" => [:LBRACE, "{ /./"],
"+" => [:PLUS, "+ /./"],
"-" => [:MINUS, "- /./"],
"*" => [:TIMES, "* /./"],
";" => [:SEMIC, "; /./"],
}.each do |token, entry|
it "should lex regexp after '#{token}'" do
expected = [entry[0], :REGEX].flatten
- tokens_scanned_from(entry[1]).should match_tokens2(*expected)
+ expect(tokens_scanned_from(entry[1])).to match_tokens2(*expected)
end
end
it "should lex a simple expression" do
- tokens_scanned_from('1 + 1').should match_tokens2([:NUMBER, '1'], :PLUS, [:NUMBER, '1'])
+ 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]],
'"a$a"' => ['"a$a" /./', [:DQPRE, :VARIABLE, :DQPOST, :DIV, :DOT, :DIV]],
}.each do |token, entry|
it "should not lex regexp after '#{token}'" do
- tokens_scanned_from(entry[ 0 ]).should match_tokens2(*entry[ 1 ])
+ expect(tokens_scanned_from(entry[ 0 ])).to match_tokens2(*entry[ 1 ])
end
end
it 'should lex assignment' do
- tokens_scanned_from("$a = 10").should match_tokens2([:VARIABLE, "a"], :EQUALS, [:NUMBER, '10'])
+ 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
- tokens_scanned_from(" /./").should match_tokens2(:REGEX)
+ expect(tokens_scanned_from(" /./")).to match_tokens2(:REGEX)
end
it "should lex regexp right of div" do
- tokens_scanned_from("1 / /./").should match_tokens2(:NUMBER, :DIV, :REGEX)
+ expect(tokens_scanned_from("1 / /./")).to match_tokens2(:NUMBER, :DIV, :REGEX)
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
- tokens_scanned_from(code).should match_tokens2([:HEREDOC, 'syntax'], :SUBLOCATE, [:STRING, "Tex\tt\\n"])
+ 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
- tokens_scanned_from(code).should match_tokens2(
+ expect(tokens_scanned_from(code)).to match_tokens2(
[:HEREDOC, 'syntax'],
:SUBLOCATE,
[:DQPRE, "Tex\tt\\n"],
[:VARIABLE, "var"],
[:DQPOST, " After"]
)
end
end
context 'when dealing with multi byte characters' do
it 'should support unicode characters' do
code = <<-CODE
"x\\u2713y"
CODE
# >= Ruby 1.9.3 reports \u
- tokens_scanned_from(code).should match_tokens2([:STRING, "x\u2713y"])
+ expect(tokens_scanned_from(code)).to match_tokens2([:STRING, "x\u2713y"])
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"
- tokens_scanned_from(code).should match_tokens2(
+ 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
- epp_tokens_scanned_from(code).should match_tokens2(:EPP_START, [:RENDER_STRING, " This is just text\n"])
+ 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
- epp_tokens_scanned_from(code).should match_tokens2(
+ 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
- epp_tokens_scanned_from(code).should match_tokens2(
+ 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
- epp_tokens_scanned_from(code).should match_tokens2(
+ 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 leading space in tail text' do
code = <<-CODE
This is <% $x=10 -%>
just text
CODE
- epp_tokens_scanned_from(code).should match_tokens2(
+ 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
This is <% $x=10 -%>
<%# This is an epp comment -%>
just text
CODE
- epp_tokens_scanned_from(code).should match_tokens2(
+ 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 escape epp tags' do
code = <<-CODE
This is <% $x=10 -%>
<%% this is escaped epp %%>
CODE
- epp_tokens_scanned_from(code).should match_tokens2(
+ 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
end
end
diff --git a/spec/unit/pops/parser/parse_basic_expressions_spec.rb b/spec/unit/pops/parser/parse_basic_expressions_spec.rb
index f2c84615e..20b7267bb 100644
--- a/spec/unit/pops/parser/parse_basic_expressions_spec.rb
+++ b/spec/unit/pops/parser/parse_basic_expressions_spec.rb
@@ -1,288 +1,288 @@
#! /usr/bin/env ruby
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 basic expressions" do
include ParserRspecHelper
context "When the parser parses arithmetic" do
context "with Integers" do
- it "$a = 2 + 2" do; dump(parse("$a = 2 + 2")).should == "(= $a (+ 2 2))" ; end
- it "$a = 7 - 3" do; dump(parse("$a = 7 - 3")).should == "(= $a (- 7 3))" ; end
- it "$a = 6 * 3" do; dump(parse("$a = 6 * 3")).should == "(= $a (* 6 3))" ; end
- it "$a = 6 / 3" do; dump(parse("$a = 6 / 3")).should == "(= $a (/ 6 3))" ; end
- it "$a = 6 % 3" do; dump(parse("$a = 6 % 3")).should == "(= $a (% 6 3))" ; end
- it "$a = -(6/3)" do; dump(parse("$a = -(6/3)")).should == "(= $a (- (/ 6 3)))" ; end
- it "$a = -6/3" do; dump(parse("$a = -6/3")).should == "(= $a (/ (- 6) 3))" ; end
- it "$a = 8 >> 1 " do; dump(parse("$a = 8 >> 1")).should == "(= $a (>> 8 1))" ; end
- it "$a = 8 << 1 " do; dump(parse("$a = 8 << 1")).should == "(= $a (<< 8 1))" ; end
+ it "$a = 2 + 2" do; expect(dump(parse("$a = 2 + 2"))).to eq("(= $a (+ 2 2))") ; end
+ it "$a = 7 - 3" do; expect(dump(parse("$a = 7 - 3"))).to eq("(= $a (- 7 3))") ; end
+ it "$a = 6 * 3" do; expect(dump(parse("$a = 6 * 3"))).to eq("(= $a (* 6 3))") ; end
+ it "$a = 6 / 3" do; expect(dump(parse("$a = 6 / 3"))).to eq("(= $a (/ 6 3))") ; end
+ it "$a = 6 % 3" do; expect(dump(parse("$a = 6 % 3"))).to eq("(= $a (% 6 3))") ; end
+ it "$a = -(6/3)" do; expect(dump(parse("$a = -(6/3)"))).to eq("(= $a (- (/ 6 3)))") ; end
+ it "$a = -6/3" do; expect(dump(parse("$a = -6/3"))).to eq("(= $a (/ (- 6) 3))") ; end
+ it "$a = 8 >> 1 " do; expect(dump(parse("$a = 8 >> 1"))).to eq("(= $a (>> 8 1))") ; end
+ it "$a = 8 << 1 " do; expect(dump(parse("$a = 8 << 1"))).to eq("(= $a (<< 8 1))") ; end
end
context "with Floats" do
- it "$a = 2.2 + 2.2" do; dump(parse("$a = 2.2 + 2.2")).should == "(= $a (+ 2.2 2.2))" ; end
- it "$a = 7.7 - 3.3" do; dump(parse("$a = 7.7 - 3.3")).should == "(= $a (- 7.7 3.3))" ; end
- it "$a = 6.1 * 3.1" do; dump(parse("$a = 6.1 - 3.1")).should == "(= $a (- 6.1 3.1))" ; end
- it "$a = 6.6 / 3.3" do; dump(parse("$a = 6.6 / 3.3")).should == "(= $a (/ 6.6 3.3))" ; end
- it "$a = -(6.0/3.0)" do; dump(parse("$a = -(6.0/3.0)")).should == "(= $a (- (/ 6.0 3.0)))" ; end
- it "$a = -6.0/3.0" do; dump(parse("$a = -6.0/3.0")).should == "(= $a (/ (- 6.0) 3.0))" ; end
- it "$a = 3.14 << 2" do; dump(parse("$a = 3.14 << 2")).should == "(= $a (<< 3.14 2))" ; end
- it "$a = 3.14 >> 2" do; dump(parse("$a = 3.14 >> 2")).should == "(= $a (>> 3.14 2))" ; end
+ it "$a = 2.2 + 2.2" do; expect(dump(parse("$a = 2.2 + 2.2"))).to eq("(= $a (+ 2.2 2.2))") ; end
+ it "$a = 7.7 - 3.3" do; expect(dump(parse("$a = 7.7 - 3.3"))).to eq("(= $a (- 7.7 3.3))") ; end
+ it "$a = 6.1 * 3.1" do; expect(dump(parse("$a = 6.1 - 3.1"))).to eq("(= $a (- 6.1 3.1))") ; end
+ it "$a = 6.6 / 3.3" do; expect(dump(parse("$a = 6.6 / 3.3"))).to eq("(= $a (/ 6.6 3.3))") ; end
+ it "$a = -(6.0/3.0)" do; expect(dump(parse("$a = -(6.0/3.0)"))).to eq("(= $a (- (/ 6.0 3.0)))") ; end
+ it "$a = -6.0/3.0" do; expect(dump(parse("$a = -6.0/3.0"))).to eq("(= $a (/ (- 6.0) 3.0))") ; end
+ it "$a = 3.14 << 2" do; expect(dump(parse("$a = 3.14 << 2"))).to eq("(= $a (<< 3.14 2))") ; end
+ it "$a = 3.14 >> 2" do; expect(dump(parse("$a = 3.14 >> 2"))).to eq("(= $a (>> 3.14 2))") ; end
end
context "with hex and octal Integer values" do
- it "$a = 0xAB + 0xCD" do; dump(parse("$a = 0xAB + 0xCD")).should == "(= $a (+ 0xAB 0xCD))" ; end
- it "$a = 0777 - 0333" do; dump(parse("$a = 0777 - 0333")).should == "(= $a (- 0777 0333))" ; end
+ it "$a = 0xAB + 0xCD" do; expect(dump(parse("$a = 0xAB + 0xCD"))).to eq("(= $a (+ 0xAB 0xCD))") ; end
+ it "$a = 0777 - 0333" do; expect(dump(parse("$a = 0777 - 0333"))).to eq("(= $a (- 0777 0333))") ; end
end
context "with strings requiring boxing to Numeric" do
# Test that numbers in string form does not turn into numbers
- it "$a = '2' + '2'" do; dump(parse("$a = '2' + '2'")).should == "(= $a (+ '2' '2'))" ; end
- it "$a = '2.2' + '0.2'" do; dump(parse("$a = '2.2' + '0.2'")).should == "(= $a (+ '2.2' '0.2'))" ; end
- it "$a = '0xab' + '0xcd'" do; dump(parse("$a = '0xab' + '0xcd'")).should == "(= $a (+ '0xab' '0xcd'))" ; end
- it "$a = '0777' + '0333'" do; dump(parse("$a = '0777' + '0333'")).should == "(= $a (+ '0777' '0333'))" ; end
+ it "$a = '2' + '2'" do; expect(dump(parse("$a = '2' + '2'"))).to eq("(= $a (+ '2' '2'))") ; end
+ it "$a = '2.2' + '0.2'" do; expect(dump(parse("$a = '2.2' + '0.2'"))).to eq("(= $a (+ '2.2' '0.2'))") ; end
+ it "$a = '0xab' + '0xcd'" do; expect(dump(parse("$a = '0xab' + '0xcd'"))).to eq("(= $a (+ '0xab' '0xcd'))") ; end
+ it "$a = '0777' + '0333'" do; expect(dump(parse("$a = '0777' + '0333'"))).to eq("(= $a (+ '0777' '0333'))") ; end
end
context "precedence should be correct" do
- it "$a = 1 + 2 * 3" do; dump(parse("$a = 1 + 2 * 3")).should == "(= $a (+ 1 (* 2 3)))"; end
- it "$a = 1 + 2 % 3" do; dump(parse("$a = 1 + 2 % 3")).should == "(= $a (+ 1 (% 2 3)))"; end
- it "$a = 1 + 2 / 3" do; dump(parse("$a = 1 + 2 / 3")).should == "(= $a (+ 1 (/ 2 3)))"; end
- it "$a = 1 + 2 << 3" do; dump(parse("$a = 1 + 2 << 3")).should == "(= $a (<< (+ 1 2) 3))"; end
- it "$a = 1 + 2 >> 3" do; dump(parse("$a = 1 + 2 >> 3")).should == "(= $a (>> (+ 1 2) 3))"; end
+ it "$a = 1 + 2 * 3" do; expect(dump(parse("$a = 1 + 2 * 3"))).to eq("(= $a (+ 1 (* 2 3)))"); end
+ it "$a = 1 + 2 % 3" do; expect(dump(parse("$a = 1 + 2 % 3"))).to eq("(= $a (+ 1 (% 2 3)))"); end
+ it "$a = 1 + 2 / 3" do; expect(dump(parse("$a = 1 + 2 / 3"))).to eq("(= $a (+ 1 (/ 2 3)))"); end
+ it "$a = 1 + 2 << 3" do; expect(dump(parse("$a = 1 + 2 << 3"))).to eq("(= $a (<< (+ 1 2) 3))"); end
+ it "$a = 1 + 2 >> 3" do; expect(dump(parse("$a = 1 + 2 >> 3"))).to eq("(= $a (>> (+ 1 2) 3))"); end
end
context "parentheses alter precedence" do
- it "$a = (1 + 2) * 3" do; dump(parse("$a = (1 + 2) * 3")).should == "(= $a (* (+ 1 2) 3))"; end
- it "$a = (1 + 2) / 3" do; dump(parse("$a = (1 + 2) / 3")).should == "(= $a (/ (+ 1 2) 3))"; end
+ it "$a = (1 + 2) * 3" do; expect(dump(parse("$a = (1 + 2) * 3"))).to eq("(= $a (* (+ 1 2) 3))"); end
+ it "$a = (1 + 2) / 3" do; expect(dump(parse("$a = (1 + 2) / 3"))).to eq("(= $a (/ (+ 1 2) 3))"); end
end
end
context "When the evaluator performs boolean operations" do
context "using operators AND OR NOT" do
- it "$a = true and true" do; dump(parse("$a = true and true")).should == "(= $a (&& true true))"; end
- it "$a = true or true" do; dump(parse("$a = true or true")).should == "(= $a (|| true true))" ; end
- it "$a = !true" do; dump(parse("$a = !true")).should == "(= $a (! true))" ; end
+ it "$a = true and true" do; expect(dump(parse("$a = true and true"))).to eq("(= $a (&& true true))"); end
+ it "$a = true or true" do; expect(dump(parse("$a = true or true"))).to eq("(= $a (|| true true))") ; end
+ it "$a = !true" do; expect(dump(parse("$a = !true"))).to eq("(= $a (! true))") ; end
end
context "precedence should be correct" do
it "$a = false or true and true" do
- dump(parse("$a = false or true and true")).should == "(= $a (|| false (&& true true)))"
+ expect(dump(parse("$a = false or true and true"))).to eq("(= $a (|| false (&& true true)))")
end
it "$a = (false or true) and true" do
- dump(parse("$a = (false or true) and true")).should == "(= $a (&& (|| false true) true))"
+ expect(dump(parse("$a = (false or true) and true"))).to eq("(= $a (&& (|| false true) true))")
end
it "$a = !true or true and true" do
- dump(parse("$a = !false or true and true")).should == "(= $a (|| (! false) (&& true true)))"
+ expect(dump(parse("$a = !false or true and true"))).to eq("(= $a (|| (! false) (&& true true)))")
end
end
# Possibly change to check of literal expressions
context "on values requiring boxing to Boolean" do
it "'x' == true" do
- dump(parse("! 'x'")).should == "(! 'x')"
+ expect(dump(parse("! 'x'"))).to eq("(! 'x')")
end
it "'' == false" do
- dump(parse("! ''")).should == "(! '')"
+ expect(dump(parse("! ''"))).to eq("(! '')")
end
it ":undef == false" do
- dump(parse("! undef")).should == "(! :undef)"
+ expect(dump(parse("! undef"))).to eq("(! :undef)")
end
end
end
context "When parsing comparisons" do
context "of string values" do
- it "$a = 'a' == 'a'" do; dump(parse("$a = 'a' == 'a'")).should == "(= $a (== 'a' 'a'))" ; end
- it "$a = 'a' != 'a'" do; dump(parse("$a = 'a' != 'a'")).should == "(= $a (!= 'a' 'a'))" ; end
- it "$a = 'a' < 'b'" do; dump(parse("$a = 'a' < 'b'")).should == "(= $a (< 'a' 'b'))" ; end
- it "$a = 'a' > 'b'" do; dump(parse("$a = 'a' > 'b'")).should == "(= $a (> 'a' 'b'))" ; end
- it "$a = 'a' <= 'b'" do; dump(parse("$a = 'a' <= 'b'")).should == "(= $a (<= 'a' 'b'))" ; end
- it "$a = 'a' >= 'b'" do; dump(parse("$a = 'a' >= 'b'")).should == "(= $a (>= 'a' 'b'))" ; end
+ it "$a = 'a' == 'a'" do; expect(dump(parse("$a = 'a' == 'a'"))).to eq("(= $a (== 'a' 'a'))") ; end
+ it "$a = 'a' != 'a'" do; expect(dump(parse("$a = 'a' != 'a'"))).to eq("(= $a (!= 'a' 'a'))") ; end
+ it "$a = 'a' < 'b'" do; expect(dump(parse("$a = 'a' < 'b'"))).to eq("(= $a (< 'a' 'b'))") ; end
+ it "$a = 'a' > 'b'" do; expect(dump(parse("$a = 'a' > 'b'"))).to eq("(= $a (> 'a' 'b'))") ; end
+ it "$a = 'a' <= 'b'" do; expect(dump(parse("$a = 'a' <= 'b'"))).to eq("(= $a (<= 'a' 'b'))") ; end
+ it "$a = 'a' >= 'b'" do; expect(dump(parse("$a = 'a' >= 'b'"))).to eq("(= $a (>= 'a' 'b'))") ; end
end
context "of integer values" do
- it "$a = 1 == 1" do; dump(parse("$a = 1 == 1")).should == "(= $a (== 1 1))" ; end
- it "$a = 1 != 1" do; dump(parse("$a = 1 != 1")).should == "(= $a (!= 1 1))" ; end
- it "$a = 1 < 2" do; dump(parse("$a = 1 < 2")).should == "(= $a (< 1 2))" ; end
- it "$a = 1 > 2" do; dump(parse("$a = 1 > 2")).should == "(= $a (> 1 2))" ; end
- it "$a = 1 <= 2" do; dump(parse("$a = 1 <= 2")).should == "(= $a (<= 1 2))" ; end
- it "$a = 1 >= 2" do; dump(parse("$a = 1 >= 2")).should == "(= $a (>= 1 2))" ; end
+ it "$a = 1 == 1" do; expect(dump(parse("$a = 1 == 1"))).to eq("(= $a (== 1 1))") ; end
+ it "$a = 1 != 1" do; expect(dump(parse("$a = 1 != 1"))).to eq("(= $a (!= 1 1))") ; end
+ it "$a = 1 < 2" do; expect(dump(parse("$a = 1 < 2"))).to eq("(= $a (< 1 2))") ; end
+ it "$a = 1 > 2" do; expect(dump(parse("$a = 1 > 2"))).to eq("(= $a (> 1 2))") ; end
+ it "$a = 1 <= 2" do; expect(dump(parse("$a = 1 <= 2"))).to eq("(= $a (<= 1 2))") ; end
+ it "$a = 1 >= 2" do; expect(dump(parse("$a = 1 >= 2"))).to eq("(= $a (>= 1 2))") ; end
end
context "of regular expressions (parse errors)" do
# Not supported in concrete syntax
it "$a = /.*/ == /.*/" do
- dump(parse("$a = /.*/ == /.*/")).should == "(= $a (== /.*/ /.*/))"
+ expect(dump(parse("$a = /.*/ == /.*/"))).to eq("(= $a (== /.*/ /.*/))")
end
it "$a = /.*/ != /a.*/" do
- dump(parse("$a = /.*/ != /.*/")).should == "(= $a (!= /.*/ /.*/))"
+ expect(dump(parse("$a = /.*/ != /.*/"))).to eq("(= $a (!= /.*/ /.*/))")
end
end
end
context "When parsing Regular Expression matching" do
- it "$a = 'a' =~ /.*/" do; dump(parse("$a = 'a' =~ /.*/")).should == "(= $a (=~ 'a' /.*/))" ; end
- it "$a = 'a' =~ '.*'" do; dump(parse("$a = 'a' =~ '.*'")).should == "(= $a (=~ 'a' '.*'))" ; end
- it "$a = 'a' !~ /b.*/" do; dump(parse("$a = 'a' !~ /b.*/")).should == "(= $a (!~ 'a' /b.*/))" ; end
- it "$a = 'a' !~ 'b.*'" do; dump(parse("$a = 'a' !~ 'b.*'")).should == "(= $a (!~ 'a' 'b.*'))" ; end
+ it "$a = 'a' =~ /.*/" do; expect(dump(parse("$a = 'a' =~ /.*/"))).to eq("(= $a (=~ 'a' /.*/))") ; end
+ it "$a = 'a' =~ '.*'" do; expect(dump(parse("$a = 'a' =~ '.*'"))).to eq("(= $a (=~ 'a' '.*'))") ; end
+ it "$a = 'a' !~ /b.*/" do; expect(dump(parse("$a = 'a' !~ /b.*/"))).to eq("(= $a (!~ 'a' /b.*/))") ; end
+ it "$a = 'a' !~ 'b.*'" do; expect(dump(parse("$a = 'a' !~ 'b.*'"))).to eq("(= $a (!~ 'a' 'b.*'))") ; end
end
context "When parsing unfold" do
- it "$a = *[1,2]" do; dump(parse("$a = *[1,2]")).should == "(= $a (unfold ([] 1 2)))" ; end
- it "$a = *1" do; dump(parse("$a = *1")).should == "(= $a (unfold 1))" ; end
+ it "$a = *[1,2]" do; expect(dump(parse("$a = *[1,2]"))).to eq("(= $a (unfold ([] 1 2)))") ; end
+ it "$a = *1" do; expect(dump(parse("$a = *1"))).to eq("(= $a (unfold 1))") ; end
end
context "When parsing Lists" do
it "$a = []" do
- dump(parse("$a = []")).should == "(= $a ([]))"
+ expect(dump(parse("$a = []"))).to eq("(= $a ([]))")
end
it "$a = [1]" do
- dump(parse("$a = [1]")).should == "(= $a ([] 1))"
+ expect(dump(parse("$a = [1]"))).to eq("(= $a ([] 1))")
end
it "$a = [1,2,3]" do
- dump(parse("$a = [1,2,3]")).should == "(= $a ([] 1 2 3))"
+ expect(dump(parse("$a = [1,2,3]"))).to eq("(= $a ([] 1 2 3))")
end
it "[...[...[]]] should create nested arrays without trouble" do
- dump(parse("$a = [1,[2.0, 2.1, [2.2]],[3.0, 3.1]]")).should == "(= $a ([] 1 ([] 2.0 2.1 ([] 2.2)) ([] 3.0 3.1)))"
+ expect(dump(parse("$a = [1,[2.0, 2.1, [2.2]],[3.0, 3.1]]"))).to eq("(= $a ([] 1 ([] 2.0 2.1 ([] 2.2)) ([] 3.0 3.1)))")
end
it "$a = [2 + 2]" do
- dump(parse("$a = [2+2]")).should == "(= $a ([] (+ 2 2)))"
+ expect(dump(parse("$a = [2+2]"))).to eq("(= $a ([] (+ 2 2)))")
end
it "$a [1,2,3] == [1,2,3]" do
- dump(parse("$a = [1,2,3] == [1,2,3]")).should == "(= $a (== ([] 1 2 3) ([] 1 2 3)))"
+ expect(dump(parse("$a = [1,2,3] == [1,2,3]"))).to eq("(= $a (== ([] 1 2 3) ([] 1 2 3)))")
end
it "calculates the text length of an empty array" do
expect(parse("[]").current.body.length).to eq(2)
expect(parse("[ ]").current.body.length).to eq(3)
end
end
context "When parsing indexed access" do
it "$a = $b[2]" do
- dump(parse("$a = $b[2]")).should == "(= $a (slice $b 2))"
+ expect(dump(parse("$a = $b[2]"))).to eq("(= $a (slice $b 2))")
end
it "$a = [1, 2, 3][2]" do
- dump(parse("$a = [1,2,3][2]")).should == "(= $a (slice ([] 1 2 3) 2))"
+ expect(dump(parse("$a = [1,2,3][2]"))).to eq("(= $a (slice ([] 1 2 3) 2))")
end
it "$a = {'a' => 1, 'b' => 2}['b']" do
- dump(parse("$a = {'a'=>1,'b' =>2}[b]")).should == "(= $a (slice ({} ('a' 1) ('b' 2)) b))"
+ expect(dump(parse("$a = {'a'=>1,'b' =>2}[b]"))).to eq("(= $a (slice ({} ('a' 1) ('b' 2)) b))")
end
end
context "When parsing assignments" do
it "Should allow simple assignment" do
- dump(parse("$a = 10")).should == "(= $a 10)"
+ expect(dump(parse("$a = 10"))).to eq("(= $a 10)")
end
it "Should allow append assignment" do
- dump(parse("$a += 10")).should == "(+= $a 10)"
+ expect(dump(parse("$a += 10"))).to eq("(+= $a 10)")
end
it "Should allow without assignment" do
- dump(parse("$a -= 10")).should == "(-= $a 10)"
+ expect(dump(parse("$a -= 10"))).to eq("(-= $a 10)")
end
it "Should allow chained assignment" do
- dump(parse("$a = $b = 10")).should == "(= $a (= $b 10))"
+ expect(dump(parse("$a = $b = 10"))).to eq("(= $a (= $b 10))")
end
it "Should allow chained assignment with expressions" do
- dump(parse("$a = 1 + ($b = 10)")).should == "(= $a (+ 1 (= $b 10)))"
+ expect(dump(parse("$a = 1 + ($b = 10)"))).to eq("(= $a (+ 1 (= $b 10)))")
end
end
context "When parsing Hashes" do
it "should create a Hash when evaluating a LiteralHash" do
- dump(parse("$a = {'a'=>1,'b'=>2}")).should == "(= $a ({} ('a' 1) ('b' 2)))"
+ expect(dump(parse("$a = {'a'=>1,'b'=>2}"))).to eq("(= $a ({} ('a' 1) ('b' 2)))")
end
it "$a = {...{...{}}} should create nested hashes without trouble" do
- dump(parse("$a = {'a'=>1,'b'=>{'x'=>2.1,'y'=>2.2}}")).should == "(= $a ({} ('a' 1) ('b' ({} ('x' 2.1) ('y' 2.2)))))"
+ expect(dump(parse("$a = {'a'=>1,'b'=>{'x'=>2.1,'y'=>2.2}}"))).to eq("(= $a ({} ('a' 1) ('b' ({} ('x' 2.1) ('y' 2.2)))))")
end
it "$a = {'a'=> 2 + 2} should evaluate values in entries" do
- dump(parse("$a = {'a'=>2+2}")).should == "(= $a ({} ('a' (+ 2 2))))"
+ expect(dump(parse("$a = {'a'=>2+2}"))).to eq("(= $a ({} ('a' (+ 2 2))))")
end
it "$a = {'a'=> 1, 'b'=>2} == {'a'=> 1, 'b'=>2}" do
- dump(parse("$a = {'a'=>1,'b'=>2} == {'a'=>1,'b'=>2}")).should == "(= $a (== ({} ('a' 1) ('b' 2)) ({} ('a' 1) ('b' 2))))"
+ expect(dump(parse("$a = {'a'=>1,'b'=>2} == {'a'=>1,'b'=>2}"))).to eq("(= $a (== ({} ('a' 1) ('b' 2)) ({} ('a' 1) ('b' 2))))")
end
it "$a = {'a'=> 1, 'b'=>2} != {'x'=> 1, 'y'=>3}" do
- dump(parse("$a = {'a'=>1,'b'=>2} != {'a'=>1,'b'=>2}")).should == "(= $a (!= ({} ('a' 1) ('b' 2)) ({} ('a' 1) ('b' 2))))"
+ expect(dump(parse("$a = {'a'=>1,'b'=>2} != {'a'=>1,'b'=>2}"))).to eq("(= $a (!= ({} ('a' 1) ('b' 2)) ({} ('a' 1) ('b' 2))))")
end
it "calculates the text length of an empty hash" do
expect(parse("{}").current.body.length).to eq(2)
expect(parse("{ }").current.body.length).to eq(3)
end
end
context "When parsing the 'in' operator" do
it "with integer in a list" do
- dump(parse("$a = 1 in [1,2,3]")).should == "(= $a (in 1 ([] 1 2 3)))"
+ expect(dump(parse("$a = 1 in [1,2,3]"))).to eq("(= $a (in 1 ([] 1 2 3)))")
end
it "with string key in a hash" do
- dump(parse("$a = 'a' in {'x'=>1, 'a'=>2, 'y'=> 3}")).should == "(= $a (in 'a' ({} ('x' 1) ('a' 2) ('y' 3))))"
+ expect(dump(parse("$a = 'a' in {'x'=>1, 'a'=>2, 'y'=> 3}"))).to eq("(= $a (in 'a' ({} ('x' 1) ('a' 2) ('y' 3))))")
end
it "with substrings of a string" do
- dump(parse("$a = 'ana' in 'bananas'")).should == "(= $a (in 'ana' 'bananas'))"
+ expect(dump(parse("$a = 'ana' in 'bananas'"))).to eq("(= $a (in 'ana' 'bananas'))")
end
it "with sublist in a list" do
- dump(parse("$a = [2,3] in [1,2,3]")).should == "(= $a (in ([] 2 3) ([] 1 2 3)))"
+ expect(dump(parse("$a = [2,3] in [1,2,3]"))).to eq("(= $a (in ([] 2 3) ([] 1 2 3)))")
end
end
context "When parsing string interpolation" do
it "should interpolate a bare word as a variable name, \"${var}\"" do
- dump(parse("$a = \"$var\"")).should == "(= $a (cat '' (str $var) ''))"
+ expect(dump(parse("$a = \"$var\""))).to eq("(= $a (cat '' (str $var) ''))")
end
it "should interpolate a variable in a text expression, \"${$var}\"" do
- dump(parse("$a = \"${$var}\"")).should == "(= $a (cat '' (str $var) ''))"
+ expect(dump(parse("$a = \"${$var}\""))).to eq("(= $a (cat '' (str $var) ''))")
end
it "should interpolate a variable, \"yo${var}yo\"" do
- dump(parse("$a = \"yo${var}yo\"")).should == "(= $a (cat 'yo' (str $var) 'yo'))"
+ expect(dump(parse("$a = \"yo${var}yo\""))).to eq("(= $a (cat 'yo' (str $var) 'yo'))")
end
it "should interpolate any expression in a text expression, \"${$var*2}\"" do
- dump(parse("$a = \"yo${$var+2}yo\"")).should == "(= $a (cat 'yo' (str (+ $var 2)) 'yo'))"
+ expect(dump(parse("$a = \"yo${$var+2}yo\""))).to eq("(= $a (cat 'yo' (str (+ $var 2)) 'yo'))")
end
it "should not interpolate names as variable in expression, \"${notvar*2}\"" do
- dump(parse("$a = \"yo${notvar+2}yo\"")).should == "(= $a (cat 'yo' (str (+ notvar 2)) 'yo'))"
+ expect(dump(parse("$a = \"yo${notvar+2}yo\""))).to eq("(= $a (cat 'yo' (str (+ notvar 2)) 'yo'))")
end
it "should interpolate name as variable in access expression, \"${var[0]}\"" do
- dump(parse("$a = \"yo${var[0]}yo\"")).should == "(= $a (cat 'yo' (str (slice $var 0)) 'yo'))"
+ expect(dump(parse("$a = \"yo${var[0]}yo\""))).to eq("(= $a (cat 'yo' (str (slice $var 0)) 'yo'))")
end
it "should interpolate name as variable in method call, \"${var.foo}\"" do
- dump(parse("$a = \"yo${$var.foo}yo\"")).should == "(= $a (cat 'yo' (str (call-method (. $var foo))) 'yo'))"
+ expect(dump(parse("$a = \"yo${$var.foo}yo\""))).to eq("(= $a (cat 'yo' (str (call-method (. $var foo))) 'yo'))")
end
it "should interpolate name as variable in method call, \"${var.foo}\"" do
- dump(parse("$a = \"yo${var.foo}yo\"")).should == "(= $a (cat 'yo' (str (call-method (. $var foo))) 'yo'))"
- dump(parse("$a = \"yo${var.foo.bar}yo\"")).should == "(= $a (cat 'yo' (str (call-method (. (call-method (. $var foo)) bar))) 'yo'))"
+ expect(dump(parse("$a = \"yo${var.foo}yo\""))).to eq("(= $a (cat 'yo' (str (call-method (. $var foo))) 'yo'))")
+ expect(dump(parse("$a = \"yo${var.foo.bar}yo\""))).to eq("(= $a (cat 'yo' (str (call-method (. (call-method (. $var foo)) bar))) 'yo'))")
end
end
end
diff --git a/spec/unit/pops/parser/parse_calls_spec.rb b/spec/unit/pops/parser/parse_calls_spec.rb
index 6f75eabc8..5e84142e2 100644
--- a/spec/unit/pops/parser/parse_calls_spec.rb
+++ b/spec/unit/pops/parser/parse_calls_spec.rb
@@ -1,119 +1,119 @@
#! /usr/bin/env ruby
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 function calls" do
include ParserRspecHelper
context "When parsing calls as statements" do
context "in top level scope" do
it "foo()" do
- dump(parse("foo()")).should == "(invoke foo)"
+ expect(dump(parse("foo()"))).to eq("(invoke foo)")
end
it "notice bar" do
- dump(parse("notice bar")).should == "(invoke notice bar)"
+ expect(dump(parse("notice bar"))).to eq("(invoke notice bar)")
end
it "notice(bar)" do
- dump(parse("notice bar")).should == "(invoke notice bar)"
+ expect(dump(parse("notice bar"))).to eq("(invoke notice bar)")
end
it "foo(bar)" do
- dump(parse("foo(bar)")).should == "(invoke foo bar)"
+ expect(dump(parse("foo(bar)"))).to eq("(invoke foo bar)")
end
it "foo(bar,)" do
- dump(parse("foo(bar,)")).should == "(invoke foo bar)"
+ expect(dump(parse("foo(bar,)"))).to eq("(invoke foo bar)")
end
it "foo(bar, fum,)" do
- dump(parse("foo(bar,fum,)")).should == "(invoke foo bar fum)"
+ expect(dump(parse("foo(bar,fum,)"))).to eq("(invoke foo bar fum)")
end
it "notice fqdn_rand(30)" do
- dump(parse("notice fqdn_rand(30)")).should == '(invoke notice (call fqdn_rand 30))'
+ expect(dump(parse("notice fqdn_rand(30)"))).to eq('(invoke notice (call fqdn_rand 30))')
end
end
context "in nested scopes" do
it "if true { foo() }" do
- dump(parse("if true {foo()}")).should == "(if true\n (then (invoke foo)))"
+ expect(dump(parse("if true {foo()}"))).to eq("(if true\n (then (invoke foo)))")
end
it "if true { notice bar}" do
- dump(parse("if true {notice bar}")).should == "(if true\n (then (invoke notice bar)))"
+ expect(dump(parse("if true {notice bar}"))).to eq("(if true\n (then (invoke notice bar)))")
end
end
end
context "When parsing calls as expressions" do
it "$a = foo()" do
- dump(parse("$a = foo()")).should == "(= $a (call foo))"
+ expect(dump(parse("$a = foo()"))).to eq("(= $a (call foo))")
end
it "$a = foo(bar)" do
- dump(parse("$a = foo()")).should == "(= $a (call foo))"
+ expect(dump(parse("$a = foo()"))).to eq("(= $a (call foo))")
end
# For egrammar where a bare word can be a "statement"
it "$a = foo bar # illegal, must have parentheses" do
- dump(parse("$a = foo bar")).should == "(block\n (= $a foo)\n bar\n)"
+ expect(dump(parse("$a = foo bar"))).to eq("(block\n (= $a foo)\n bar\n)")
end
context "in nested scopes" do
it "if true { $a = foo() }" do
- dump(parse("if true { $a = foo()}")).should == "(if true\n (then (= $a (call foo))))"
+ expect(dump(parse("if true { $a = foo()}"))).to eq("(if true\n (then (= $a (call foo))))")
end
it "if true { $a= foo(bar)}" do
- dump(parse("if true {$a = foo(bar)}")).should == "(if true\n (then (= $a (call foo bar))))"
+ expect(dump(parse("if true {$a = foo(bar)}"))).to eq("(if true\n (then (= $a (call foo bar))))")
end
end
end
context "When parsing method calls" do
it "$a.foo" do
- dump(parse("$a.foo")).should == "(call-method (. $a foo))"
+ expect(dump(parse("$a.foo"))).to eq("(call-method (. $a foo))")
end
it "$a.foo || { }" do
- dump(parse("$a.foo || { }")).should == "(call-method (. $a foo) (lambda ()))"
+ expect(dump(parse("$a.foo || { }"))).to eq("(call-method (. $a foo) (lambda ()))")
end
it "$a.foo |$x| { }" do
- dump(parse("$a.foo |$x|{ }")).should == "(call-method (. $a foo) (lambda (parameters x) ()))"
+ expect(dump(parse("$a.foo |$x|{ }"))).to eq("(call-method (. $a foo) (lambda (parameters x) ()))")
end
it "$a.foo |$x|{ }" do
- dump(parse("$a.foo |$x|{ $b = $x}")).should == [
+ expect(dump(parse("$a.foo |$x|{ $b = $x}"))).to eq([
"(call-method (. $a foo) (lambda (parameters x) (block",
" (= $b $x)",
")))"
- ].join("\n")
+ ].join("\n"))
end
end
context "When parsing an illegal argument list" do
it "raises an error if argument list is not for a call" do
expect do
parse("$a = 10, 3")
end.to raise_error(/illegal comma/)
end
it "raises an error if argument list is for a potential call not allowed without parentheses" do
expect do
parse("foo 10, 3")
end.to raise_error(/attempt to pass argument list to the function 'foo' which cannot be called without parentheses/)
end
it "does no raise an error for an argument list to an allowed call" do
expect do
parse("notice 10, 3")
end.to_not raise_error()
end
end
end
diff --git a/spec/unit/pops/parser/parse_conditionals_spec.rb b/spec/unit/pops/parser/parse_conditionals_spec.rb
index 591b20e97..fe74c693b 100644
--- a/spec/unit/pops/parser/parse_conditionals_spec.rb
+++ b/spec/unit/pops/parser/parse_conditionals_spec.rb
@@ -1,157 +1,173 @@
#! /usr/bin/env ruby
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 conditionals" do
include ParserRspecHelper
context "When parsing if statements" do
it "if true { $a = 10 }" do
- dump(parse("if true { $a = 10 }")).should == "(if true\n (then (= $a 10)))"
+ expect(dump(parse("if true { $a = 10 }"))).to eq("(if true\n (then (= $a 10)))")
end
it "if true { $a = 10 } else {$a = 20}" do
- dump(parse("if true { $a = 10 } else {$a = 20}")).should ==
+ expect(dump(parse("if true { $a = 10 } else {$a = 20}"))).to eq(
["(if true",
" (then (= $a 10))",
" (else (= $a 20)))"].join("\n")
+ )
end
it "if true { $a = 10 } elsif false { $a = 15} else {$a = 20}" do
- dump(parse("if true { $a = 10 } elsif false { $a = 15} else {$a = 20}")).should ==
+ expect(dump(parse("if true { $a = 10 } elsif false { $a = 15} else {$a = 20}"))).to eq(
["(if true",
" (then (= $a 10))",
" (else (if false",
" (then (= $a 15))",
" (else (= $a 20)))))"].join("\n")
+ )
end
it "if true { $a = 10 $b = 10 } else {$a = 20}" do
- dump(parse("if true { $a = 10 $b = 20} else {$a = 20}")).should == [
+ expect(dump(parse("if true { $a = 10 $b = 20} else {$a = 20}"))).to eq([
"(if true",
" (then (block",
" (= $a 10)",
" (= $b 20)",
" ))",
" (else (= $a 20)))"
- ].join("\n")
+ ].join("\n"))
end
it "allows a parenthesized conditional expression" do
- dump(parse("if (true) { 10 }")).should == "(if true\n (then 10))"
+ expect(dump(parse("if (true) { 10 }"))).to eq("(if true\n (then 10))")
end
it "allows a parenthesized elsif conditional expression" do
- dump(parse("if true { 10 } elsif (false) { 20 }")).should ==
+ expect(dump(parse("if true { 10 } elsif (false) { 20 }"))).to eq(
["(if true",
" (then 10)",
" (else (if false",
" (then 20))))"].join("\n")
+ )
end
end
context "When parsing unless statements" do
it "unless true { $a = 10 }" do
- dump(parse("unless true { $a = 10 }")).should == "(unless true\n (then (= $a 10)))"
+ expect(dump(parse("unless true { $a = 10 }"))).to eq("(unless true\n (then (= $a 10)))")
end
it "unless true { $a = 10 } else {$a = 20}" do
- dump(parse("unless true { $a = 10 } else {$a = 20}")).should ==
+ expect(dump(parse("unless true { $a = 10 } else {$a = 20}"))).to eq(
["(unless true",
" (then (= $a 10))",
" (else (= $a 20)))"].join("\n")
+ )
end
it "allows a parenthesized conditional expression" do
- dump(parse("unless (true) { 10 }")).should == "(unless true\n (then 10))"
+ expect(dump(parse("unless (true) { 10 }"))).to eq("(unless true\n (then 10))")
end
it "unless true { $a = 10 } elsif false { $a = 15} else {$a = 20} # is illegal" do
expect { parse("unless true { $a = 10 } elsif false { $a = 15} else {$a = 20}")}.to raise_error(Puppet::ParseError)
end
end
context "When parsing selector expressions" do
it "$a = $b ? banana => fruit " do
- dump(parse("$a = $b ? banana => fruit")).should ==
+ expect(dump(parse("$a = $b ? banana => fruit"))).to eq(
"(= $a (? $b (banana => fruit)))"
+ )
end
it "$a = $b ? { banana => fruit}" do
- dump(parse("$a = $b ? { banana => fruit }")).should ==
+ expect(dump(parse("$a = $b ? { banana => fruit }"))).to eq(
"(= $a (? $b (banana => fruit)))"
+ )
end
it "does not fail on a trailing blank line" do
- dump(parse("$a = $b ? { banana => fruit }\n\n")).should ==
+ expect(dump(parse("$a = $b ? { banana => fruit }\n\n"))).to eq(
"(= $a (? $b (banana => fruit)))"
+ )
end
it "$a = $b ? { banana => fruit, grape => berry }" do
- dump(parse("$a = $b ? {banana => fruit, grape => berry}")).should ==
+ expect(dump(parse("$a = $b ? {banana => fruit, grape => berry}"))).to eq(
"(= $a (? $b (banana => fruit) (grape => berry)))"
+ )
end
it "$a = $b ? { banana => fruit, grape => berry, default => wat }" do
- dump(parse("$a = $b ? {banana => fruit, grape => berry, default => wat}")).should ==
+ expect(dump(parse("$a = $b ? {banana => fruit, grape => berry, default => wat}"))).to eq(
"(= $a (? $b (banana => fruit) (grape => berry) (:default => wat)))"
+ )
end
it "$a = $b ? { default => wat, banana => fruit, grape => berry, }" do
- dump(parse("$a = $b ? {default => wat, banana => fruit, grape => berry}")).should ==
+ expect(dump(parse("$a = $b ? {default => wat, banana => fruit, grape => berry}"))).to eq(
"(= $a (? $b (:default => wat) (banana => fruit) (grape => berry)))"
+ )
end
end
context "When parsing case statements" do
it "case $a { a : {}}" do
- dump(parse("case $a { a : {}}")).should ==
+ expect(dump(parse("case $a { a : {}}"))).to eq(
["(case $a",
" (when (a) (then ())))"
].join("\n")
+ )
end
it "allows a parenthesized value expression" do
- dump(parse("case ($a) { a : {}}")).should ==
+ expect(dump(parse("case ($a) { a : {}}"))).to eq(
["(case $a",
" (when (a) (then ())))"
].join("\n")
+ )
end
it "case $a { /.*/ : {}}" do
- dump(parse("case $a { /.*/ : {}}")).should ==
+ expect(dump(parse("case $a { /.*/ : {}}"))).to eq(
["(case $a",
" (when (/.*/) (then ())))"
].join("\n")
+ )
end
it "case $a { a, b : {}}" do
- dump(parse("case $a { a, b : {}}")).should ==
+ expect(dump(parse("case $a { a, b : {}}"))).to eq(
["(case $a",
" (when (a b) (then ())))"
].join("\n")
+ )
end
it "case $a { a, b : {} default : {}}" do
- dump(parse("case $a { a, b : {} default : {}}")).should ==
+ expect(dump(parse("case $a { a, b : {} default : {}}"))).to eq(
["(case $a",
" (when (a b) (then ()))",
" (when (:default) (then ())))"
].join("\n")
+ )
end
it "case $a { a : {$b = 10 $c = 20}}" do
- dump(parse("case $a { a : {$b = 10 $c = 20}}")).should ==
+ expect(dump(parse("case $a { a : {$b = 10 $c = 20}}"))).to eq(
["(case $a",
" (when (a) (then (block",
" (= $b 10)",
" (= $c 20)",
" ))))"
].join("\n")
+ )
end
end
end
diff --git a/spec/unit/pops/parser/parse_containers_spec.rb b/spec/unit/pops/parser/parse_containers_spec.rb
index a05c5975d..5bb0a8d83 100644
--- a/spec/unit/pops/parser/parse_containers_spec.rb
+++ b/spec/unit/pops/parser/parse_containers_spec.rb
@@ -1,261 +1,261 @@
#! /usr/bin/env ruby
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 containers" do
include ParserRspecHelper
context "When parsing file scope" do
it "$a = 10 $b = 20" do
- dump(parse("$a = 10 $b = 20")).should == [
+ expect(dump(parse("$a = 10 $b = 20"))).to eq([
"(block",
" (= $a 10)",
" (= $b 20)",
")"
- ].join("\n")
+ ].join("\n"))
end
it "$a = 10" do
- dump(parse("$a = 10")).should == "(= $a 10)"
+ expect(dump(parse("$a = 10"))).to eq("(= $a 10)")
end
end
context "When parsing class" do
it "class foo {}" do
- dump(parse("class foo {}")).should == "(class foo ())"
+ expect(dump(parse("class foo {}"))).to eq("(class foo ())")
end
it "class foo { class bar {} }" do
- dump(parse("class foo { class bar {}}")).should == [
+ expect(dump(parse("class foo { class bar {}}"))).to eq([
"(class foo (block",
" (class foo::bar ())",
"))"
- ].join("\n")
+ ].join("\n"))
end
it "class foo::bar {}" do
- dump(parse("class foo::bar {}")).should == "(class foo::bar ())"
+ expect(dump(parse("class foo::bar {}"))).to eq("(class foo::bar ())")
end
it "class foo inherits bar {}" do
- dump(parse("class foo inherits bar {}")).should == "(class foo (inherits bar) ())"
+ expect(dump(parse("class foo inherits bar {}"))).to eq("(class foo (inherits bar) ())")
end
it "class foo($a) {}" do
- dump(parse("class foo($a) {}")).should == "(class foo (parameters a) ())"
+ expect(dump(parse("class foo($a) {}"))).to eq("(class foo (parameters a) ())")
end
it "class foo($a, $b) {}" do
- dump(parse("class foo($a, $b) {}")).should == "(class foo (parameters a b) ())"
+ expect(dump(parse("class foo($a, $b) {}"))).to eq("(class foo (parameters a b) ())")
end
it "class foo($a, $b=10) {}" do
- dump(parse("class foo($a, $b=10) {}")).should == "(class foo (parameters a (= b 10)) ())"
+ expect(dump(parse("class foo($a, $b=10) {}"))).to eq("(class foo (parameters a (= b 10)) ())")
end
it "class foo($a, $b) inherits belgo::bar {}" do
- dump(parse("class foo($a, $b) inherits belgo::bar{}")).should == "(class foo (inherits belgo::bar) (parameters a b) ())"
+ expect(dump(parse("class foo($a, $b) inherits belgo::bar{}"))).to eq("(class foo (inherits belgo::bar) (parameters a b) ())")
end
it "class foo {$a = 10 $b = 20}" do
- dump(parse("class foo {$a = 10 $b = 20}")).should == [
+ expect(dump(parse("class foo {$a = 10 $b = 20}"))).to eq([
"(class foo (block",
" (= $a 10)",
" (= $b 20)",
"))"
- ].join("\n")
+ ].join("\n"))
end
context "it should handle '3x weirdness'" do
it "class class {} # a class named 'class'" do
# Not as much weird as confusing that it is possible to name a class 'class'. Can have
# a very confusing effect when resolving relative names, getting the global hardwired "Class"
# instead of some foo::class etc.
# This is allowed in 3.x.
expect {
- dump(parse("class class {}")).should == "(class class ())"
+ expect(dump(parse("class class {}"))).to eq("(class class ())")
}.to raise_error(/not a valid classname/)
end
it "class default {} # a class named 'default'" do
# The weirdness here is that a class can inherit 'default' but not declare a class called default.
# (It will work with relative names i.e. foo::default though). The whole idea with keywords as
# names is flawed to begin with - it generally just a very bad idea.
- expect { dump(parse("class default {}")).should == "(class default ())" }.to raise_error(Puppet::ParseError)
+ expect { expect(dump(parse("class default {}"))).to eq("(class default ())") }.to raise_error(Puppet::ParseError)
end
it "class foo::default {} # a nested name 'default'" do
- dump(parse("class foo::default {}")).should == "(class foo::default ())"
+ expect(dump(parse("class foo::default {}"))).to eq("(class foo::default ())")
end
it "class class inherits default {} # inherits default", :broken => true do
expect {
- dump(parse("class class inherits default {}")).should == "(class class (inherits default) ())"
+ expect(dump(parse("class class inherits default {}"))).to eq("(class class (inherits default) ())")
}.to raise_error(/not a valid classname/)
end
it "class class inherits default {} # inherits default" do
# TODO: See previous test marked as :broken=>true, it is actually this test (result) that is wacky,
# this because a class is named at parse time (since class evaluation is lazy, the model must have the
# full class name for nested classes - only, it gets this wrong when a class is named "class" - or at least
# I think it is wrong.)
#
expect {
- dump(parse("class class inherits default {}")).should == "(class class::class (inherits default) ())"
+ expect(dump(parse("class class inherits default {}"))).to eq("(class class::class (inherits default) ())")
}.to raise_error(/not a valid classname/)
end
it "class foo inherits class" do
expect {
- dump(parse("class foo inherits class {}")).should == "(class foo (inherits class) ())"
+ expect(dump(parse("class foo inherits class {}"))).to eq("(class foo (inherits class) ())")
}.to raise_error(/not a valid classname/)
end
end
context 'it should allow keywords as attribute names' do
['and', 'case', 'class', 'default', 'define', 'else', 'elsif', 'if', 'in', 'inherits', 'node', 'or',
'undef', 'unless', 'type', 'attr', 'function', 'private'].each do |keyword|
it "such as #{keyword}" do
expect {parse("class x ($#{keyword}){} class { x: #{keyword} => 1 }")}.to_not raise_error
end
end
end
end
context "When the parser parses define" do
it "define foo {}" do
- dump(parse("define foo {}")).should == "(define foo ())"
+ expect(dump(parse("define foo {}"))).to eq("(define foo ())")
end
it "class foo { define bar {}}" do
- dump(parse("class foo {define bar {}}")).should == [
+ expect(dump(parse("class foo {define bar {}}"))).to eq([
"(class foo (block",
" (define foo::bar ())",
"))"
- ].join("\n")
+ ].join("\n"))
end
it "define foo { define bar {}}" do
# This is illegal, but handled as part of validation
- dump(parse("define foo { define bar {}}")).should == [
+ expect(dump(parse("define foo { define bar {}}"))).to eq([
"(define foo (block",
" (define bar ())",
"))"
- ].join("\n")
+ ].join("\n"))
end
it "define foo::bar {}" do
- dump(parse("define foo::bar {}")).should == "(define foo::bar ())"
+ expect(dump(parse("define foo::bar {}"))).to eq("(define foo::bar ())")
end
it "define foo($a) {}" do
- dump(parse("define foo($a) {}")).should == "(define foo (parameters a) ())"
+ expect(dump(parse("define foo($a) {}"))).to eq("(define foo (parameters a) ())")
end
it "define foo($a, $b) {}" do
- dump(parse("define foo($a, $b) {}")).should == "(define foo (parameters a b) ())"
+ expect(dump(parse("define foo($a, $b) {}"))).to eq("(define foo (parameters a b) ())")
end
it "define foo($a, $b=10) {}" do
- dump(parse("define foo($a, $b=10) {}")).should == "(define foo (parameters a (= b 10)) ())"
+ expect(dump(parse("define foo($a, $b=10) {}"))).to eq("(define foo (parameters a (= b 10)) ())")
end
it "define foo {$a = 10 $b = 20}" do
- dump(parse("define foo {$a = 10 $b = 20}")).should == [
+ expect(dump(parse("define foo {$a = 10 $b = 20}"))).to eq([
"(define foo (block",
" (= $a 10)",
" (= $b 20)",
"))"
- ].join("\n")
+ ].join("\n"))
end
context "it should handle '3x weirdness'" do
it "define class {} # a define named 'class'" do
# This is weird because Class already exists, and instantiating this define will probably not
# work
expect {
- dump(parse("define class {}")).should == "(define class ())"
+ expect(dump(parse("define class {}"))).to eq("(define class ())")
}.to raise_error(/not a valid classname/)
end
it "define default {} # a define named 'default'" do
# Check unwanted ability to define 'default'.
# The expression below is not allowed (which is good).
#
- expect { dump(parse("define default {}")).should == "(define default ())"}.to raise_error(Puppet::ParseError)
+ expect { expect(dump(parse("define default {}"))).to eq("(define default ())")}.to raise_error(Puppet::ParseError)
end
end
context 'it should allow keywords as attribute names' do
['and', 'case', 'class', 'default', 'define', 'else', 'elsif', 'if', 'in', 'inherits', 'node', 'or',
'undef', 'unless', 'type', 'attr', 'function', 'private'].each do |keyword|
it "such as #{keyword}" do
expect {parse("define x ($#{keyword}){} x { y: #{keyword} => 1 }")}.to_not raise_error
end
end
end
end
context "When parsing node" do
it "node foo {}" do
- dump(parse("node foo {}")).should == "(node (matches 'foo') ())"
+ expect(dump(parse("node foo {}"))).to eq("(node (matches 'foo') ())")
end
it "node foo, {} # trailing comma" do
- dump(parse("node foo, {}")).should == "(node (matches 'foo') ())"
+ expect(dump(parse("node foo, {}"))).to eq("(node (matches 'foo') ())")
end
it "node kermit.example.com {}" do
- dump(parse("node kermit.example.com {}")).should == "(node (matches 'kermit.example.com') ())"
+ expect(dump(parse("node kermit.example.com {}"))).to eq("(node (matches 'kermit.example.com') ())")
end
it "node kermit . example . com {}" do
- dump(parse("node kermit . example . com {}")).should == "(node (matches 'kermit.example.com') ())"
+ expect(dump(parse("node kermit . example . com {}"))).to eq("(node (matches 'kermit.example.com') ())")
end
it "node foo, x::bar, default {}" do
- dump(parse("node foo, x::bar, default {}")).should == "(node (matches 'foo' 'x::bar' :default) ())"
+ expect(dump(parse("node foo, x::bar, default {}"))).to eq("(node (matches 'foo' 'x::bar' :default) ())")
end
it "node 'foo' {}" do
- dump(parse("node 'foo' {}")).should == "(node (matches 'foo') ())"
+ expect(dump(parse("node 'foo' {}"))).to eq("(node (matches 'foo') ())")
end
it "node foo inherits x::bar {}" do
- dump(parse("node foo inherits x::bar {}")).should == "(node (matches 'foo') (parent 'x::bar') ())"
+ expect(dump(parse("node foo inherits x::bar {}"))).to eq("(node (matches 'foo') (parent 'x::bar') ())")
end
it "node foo inherits 'bar' {}" do
- dump(parse("node foo inherits 'bar' {}")).should == "(node (matches 'foo') (parent 'bar') ())"
+ expect(dump(parse("node foo inherits 'bar' {}"))).to eq("(node (matches 'foo') (parent 'bar') ())")
end
it "node foo inherits default {}" do
- dump(parse("node foo inherits default {}")).should == "(node (matches 'foo') (parent :default) ())"
+ expect(dump(parse("node foo inherits default {}"))).to eq("(node (matches 'foo') (parent :default) ())")
end
it "node /web.*/ {}" do
- dump(parse("node /web.*/ {}")).should == "(node (matches /web.*/) ())"
+ expect(dump(parse("node /web.*/ {}"))).to eq("(node (matches /web.*/) ())")
end
it "node /web.*/, /do\.wop.*/, and.so.on {}" do
- dump(parse("node /web.*/, /do\.wop.*/, 'and.so.on' {}")).should == "(node (matches /web.*/ /do\.wop.*/ 'and.so.on') ())"
+ expect(dump(parse("node /web.*/, /do\.wop.*/, 'and.so.on' {}"))).to eq("(node (matches /web.*/ /do\.wop.*/ 'and.so.on') ())")
end
it "node wat inherits /apache.*/ {}" do
- dump(parse("node wat inherits /apache.*/ {}")).should == "(node (matches 'wat') (parent /apache.*/) ())"
+ expect(dump(parse("node wat inherits /apache.*/ {}"))).to eq("(node (matches 'wat') (parent /apache.*/) ())")
end
it "node foo inherits bar {$a = 10 $b = 20}" do
- dump(parse("node foo inherits bar {$a = 10 $b = 20}")).should == [
+ expect(dump(parse("node foo inherits bar {$a = 10 $b = 20}"))).to eq([
"(node (matches 'foo') (parent 'bar') (block",
" (= $a 10)",
" (= $b 20)",
"))"
- ].join("\n")
+ ].join("\n"))
end
end
end
diff --git a/spec/unit/pops/parser/parse_heredoc_spec.rb b/spec/unit/pops/parser/parse_heredoc_spec.rb
index 38d0158f3..045d85c9f 100644
--- a/spec/unit/pops/parser/parse_heredoc_spec.rb
+++ b/spec/unit/pops/parser/parse_heredoc_spec.rb
@@ -1,117 +1,117 @@
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
- dump(parse("@(END)\nThis is\nheredoc text\nEND\n")).should == [
+ expect(dump(parse("@(END)\nThis is\nheredoc text\nEND\n"))).to eq([
"(@()",
" (sublocated 'This is\nheredoc text\n')",
")"
- ].join("\n")
+ ].join("\n"))
end
it "parses heredoc with margin" do
src = [
"@(END)",
" This is",
" heredoc text",
" | END",
""
].join("\n")
- dump(parse(src)).should == [
+ expect(dump(parse(src))).to eq([
"(@()",
" (sublocated 'This is\nheredoc text\n')",
")"
- ].join("\n")
+ ].join("\n"))
end
it "parses heredoc with margin and right newline trim" do
src = [
"@(END)",
" This is",
" heredoc text",
" |- END",
""
].join("\n")
- dump(parse(src)).should == [
+ expect(dump(parse(src))).to eq([
"(@()",
" (sublocated 'This is\nheredoc text')",
")"
- ].join("\n")
+ ].join("\n"))
end
it "parses syntax and escape specification" do
src = <<-CODE
@(END:syntax/t)
Tex\\tt\\n
|- END
CODE
- dump(parse(src)).should == [
+ expect(dump(parse(src))).to eq([
"(@(syntax)",
" (sublocated 'Tex\tt\\n')",
")"
- ].join("\n")
+ ].join("\n"))
end
it "parses interpolated heredoc expression" do
src = <<-CODE
@("END")
Hello $name
|- END
CODE
- dump(parse(src)).should == [
+ expect(dump(parse(src))).to eq([
"(@()",
" (sublocated (cat 'Hello ' (str $name) ''))",
")"
- ].join("\n")
+ ].join("\n"))
end
it "parses with escaped newlines without preceding whitespace" do
src = <<-CODE
@(END/L)
First Line\\
Second Line
|- END
CODE
parse(src)
- dump(parse(src)).should == [
+ expect(dump(parse(src))).to eq([
"(@()",
" (sublocated 'First Line Second Line')",
")"
- ].join("\n")
+ ].join("\n"))
end
it "parses with escaped newlines with proper margin" do
src = <<-CODE
@(END/L)
First Line\\
Second Line
|- END
CODE
parse(src)
- dump(parse(src)).should == [
+ expect(dump(parse(src))).to eq([
"(@()",
" (sublocated ' First Line Second Line')",
")"
- ].join("\n")
+ ].join("\n"))
end
it "parses interpolated heredoc expression with false start on $" do
src = <<-CODE
@("END")
Hello $name$%a
|- END
CODE
- dump(parse(src)).should == [
+ expect(dump(parse(src))).to eq([
"(@()",
" (sublocated (cat 'Hello ' (str $name) '$%a'))",
")"
- ].join("\n")
+ ].join("\n"))
end
end
diff --git a/spec/unit/pops/parser/parse_resource_spec.rb b/spec/unit/pops/parser/parse_resource_spec.rb
index cf7e7cb01..b19b305fc 100644
--- a/spec/unit/pops/parser/parse_resource_spec.rb
+++ b/spec/unit/pops/parser/parse_resource_spec.rb
@@ -1,324 +1,329 @@
#! /usr/bin/env ruby
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 resource declarations" do
include ParserRspecHelper
context "When parsing regular resource" do
["File", "file"].each do |word|
it "#{word} { 'title': }" do
- dump(parse("#{word} { 'title': }")).should == [
+ expect(dump(parse("#{word} { 'title': }"))).to eq([
"(resource file",
" ('title'))"
- ].join("\n")
+ ].join("\n"))
end
it "#{word} { 'title': path => '/somewhere', mode => '0777'}" do
- dump(parse("#{word} { 'title': path => '/somewhere', mode => '0777'}")).should == [
+ expect(dump(parse("#{word} { 'title': path => '/somewhere', mode => '0777'}"))).to eq([
"(resource file",
" ('title'",
" (path => '/somewhere')",
" (mode => '0777')))"
- ].join("\n")
+ ].join("\n"))
end
it "#{word} { 'title': path => '/somewhere', }" do
- dump(parse("#{word} { 'title': path => '/somewhere', }")).should == [
+ expect(dump(parse("#{word} { 'title': path => '/somewhere', }"))).to eq([
"(resource file",
" ('title'",
" (path => '/somewhere')))"
- ].join("\n")
+ ].join("\n"))
end
it "#{word} { 'title': , }" do
- dump(parse("#{word} { 'title': , }")).should == [
+ expect(dump(parse("#{word} { 'title': , }"))).to eq([
"(resource file",
" ('title'))"
- ].join("\n")
+ ].join("\n"))
end
it "#{word} { 'title': ; }" do
- dump(parse("#{word} { 'title': ; }")).should == [
+ expect(dump(parse("#{word} { 'title': ; }"))).to eq([
"(resource file",
" ('title'))"
- ].join("\n")
+ ].join("\n"))
end
it "#{word} { 'title': ; 'other_title': }" do
- dump(parse("#{word} { 'title': ; 'other_title': }")).should == [
+ expect(dump(parse("#{word} { 'title': ; 'other_title': }"))).to eq([
"(resource file",
" ('title')",
" ('other_title'))"
- ].join("\n")
+ ].join("\n"))
end
# PUP-2898, trailing ';'
it "#{word} { 'title': ; 'other_title': ; }" do
- dump(parse("#{word} { 'title': ; 'other_title': ; }")).should == [
+ expect(dump(parse("#{word} { 'title': ; 'other_title': ; }"))).to eq([
"(resource file",
" ('title')",
" ('other_title'))"
- ].join("\n")
+ ].join("\n"))
end
it "#{word} { 'title1': path => 'x'; 'title2': path => 'y'}" do
- dump(parse("#{word} { 'title1': path => 'x'; 'title2': path => 'y'}")).should == [
+ expect(dump(parse("#{word} { 'title1': path => 'x'; 'title2': path => 'y'}"))).to eq([
"(resource file",
" ('title1'",
" (path => 'x'))",
" ('title2'",
" (path => 'y')))",
- ].join("\n")
+ ].join("\n"))
end
it "#{word} { title: * => {mode => '0777'} }" do
- dump(parse("#{word} { title: * => {mode => '0777'}}")).should == [
+ expect(dump(parse("#{word} { title: * => {mode => '0777'}}"))).to eq([
"(resource file",
" (title",
" (* => ({} (mode '0777')))))"
- ].join("\n")
+ ].join("\n"))
end
end
end
context "When parsing (type based) resource defaults" do
it "File { }" do
- dump(parse("File { }")).should == "(resource-defaults file)"
+ expect(dump(parse("File { }"))).to eq("(resource-defaults file)")
end
it "File { mode => '0777' }" do
- dump(parse("File { mode => '0777'}")).should == [
+ expect(dump(parse("File { mode => '0777'}"))).to eq([
"(resource-defaults file",
" (mode => '0777'))"
- ].join("\n")
+ ].join("\n"))
end
it "File { * => {mode => '0777'} } (even if validated to be illegal)" do
- dump(parse("File { * => {mode => '0777'}}")).should == [
+ expect(dump(parse("File { * => {mode => '0777'}}"))).to eq([
"(resource-defaults file",
" (* => ({} (mode '0777'))))"
- ].join("\n")
+ ].join("\n"))
end
end
context "When parsing resource override" do
it "File['x'] { }" do
- dump(parse("File['x'] { }")).should == "(override (slice file 'x'))"
+ expect(dump(parse("File['x'] { }"))).to eq("(override (slice file 'x'))")
end
it "File['x'] { x => 1 }" do
- dump(parse("File['x'] { x => 1}")).should == [
+ expect(dump(parse("File['x'] { x => 1}"))).to eq([
"(override (slice file 'x')",
" (x => 1))"
- ].join("\n")
+ ].join("\n"))
end
it "File['x', 'y'] { x => 1 }" do
- dump(parse("File['x', 'y'] { x => 1}")).should == [
+ expect(dump(parse("File['x', 'y'] { x => 1}"))).to eq([
"(override (slice file ('x' 'y'))",
" (x => 1))"
- ].join("\n")
+ ].join("\n"))
end
it "File['x'] { x => 1, y => 2 }" do
- dump(parse("File['x'] { x => 1, y=> 2}")).should == [
+ expect(dump(parse("File['x'] { x => 1, y=> 2}"))).to eq([
"(override (slice file 'x')",
" (x => 1)",
" (y => 2))"
- ].join("\n")
+ ].join("\n"))
end
it "File['x'] { x +> 1 }" do
- dump(parse("File['x'] { x +> 1}")).should == [
+ expect(dump(parse("File['x'] { x +> 1}"))).to eq([
"(override (slice file 'x')",
" (x +> 1))"
- ].join("\n")
+ ].join("\n"))
end
it "File['x'] { * => {mode => '0777'} } (even if validated to be illegal)" do
- dump(parse("File['x'] { * => {mode => '0777'}}")).should == [
+ expect(dump(parse("File['x'] { * => {mode => '0777'}}"))).to eq([
"(override (slice file 'x')",
" (* => ({} (mode '0777'))))"
- ].join("\n")
+ ].join("\n"))
end
end
context "When parsing virtual and exported resources" do
it "parses exported @@file { 'title': }" do
- dump(parse("@@file { 'title': }")).should == "(exported-resource file\n ('title'))"
+ expect(dump(parse("@@file { 'title': }"))).to eq("(exported-resource file\n ('title'))")
end
it "parses virtual @file { 'title': }" do
- dump(parse("@file { 'title': }")).should == "(virtual-resource file\n ('title'))"
+ expect(dump(parse("@file { 'title': }"))).to eq("(virtual-resource file\n ('title'))")
end
it "nothing before the title colon is a syntax error" do
expect do
parse("@file {: mode => '0777' }")
end.to raise_error(/Syntax error/)
end
it "raises error for user error; not a resource" do
# The expression results in VIRTUAL, CALL FUNCTION('file', HASH) since the resource body has
# no title.
expect do
parse("@file { mode => '0777' }")
end.to raise_error(/Virtual \(@\) can only be applied to a Resource Expression/)
end
it "parses global defaults with @ (even if validated to be illegal)" do
- dump(parse("@File { mode => '0777' }")).should == [
+ expect(dump(parse("@File { mode => '0777' }"))).to eq([
"(virtual-resource-defaults file",
" (mode => '0777'))"
- ].join("\n")
+ ].join("\n"))
end
it "parses global defaults with @@ (even if validated to be illegal)" do
- dump(parse("@@File { mode => '0777' }")).should == [
+ expect(dump(parse("@@File { mode => '0777' }"))).to eq([
"(exported-resource-defaults file",
" (mode => '0777'))"
- ].join("\n")
+ ].join("\n"))
end
it "parses override with @ (even if validated to be illegal)" do
- dump(parse("@File[foo] { mode => '0777' }")).should == [
+ expect(dump(parse("@File[foo] { mode => '0777' }"))).to eq([
"(virtual-override (slice file foo)",
" (mode => '0777'))"
- ].join("\n")
+ ].join("\n"))
end
it "parses override combined with @@ (even if validated to be illegal)" do
- dump(parse("@@File[foo] { mode => '0777' }")).should == [
+ expect(dump(parse("@@File[foo] { mode => '0777' }"))).to eq([
"(exported-override (slice file foo)",
" (mode => '0777'))"
- ].join("\n")
+ ].join("\n"))
end
end
context "When parsing class resource" do
it "class { 'cname': }" do
- dump(parse("class { 'cname': }")).should == [
+ expect(dump(parse("class { 'cname': }"))).to eq([
"(resource class",
" ('cname'))"
- ].join("\n")
+ ].join("\n"))
end
it "@class { 'cname': }" do
- dump(parse("@class { 'cname': }")).should == [
+ expect(dump(parse("@class { 'cname': }"))).to eq([
"(virtual-resource class",
" ('cname'))"
- ].join("\n")
+ ].join("\n"))
end
it "@@class { 'cname': }" do
- dump(parse("@@class { 'cname': }")).should == [
+ expect(dump(parse("@@class { 'cname': }"))).to eq([
"(exported-resource class",
" ('cname'))"
- ].join("\n")
+ ].join("\n"))
end
it "class { 'cname': x => 1, y => 2}" do
- dump(parse("class { 'cname': x => 1, y => 2}")).should == [
+ expect(dump(parse("class { 'cname': x => 1, y => 2}"))).to eq([
"(resource class",
" ('cname'",
" (x => 1)",
" (y => 2)))"
- ].join("\n")
+ ].join("\n"))
end
it "class { 'cname1': x => 1; 'cname2': y => 2}" do
- dump(parse("class { 'cname1': x => 1; 'cname2': y => 2}")).should == [
+ expect(dump(parse("class { 'cname1': x => 1; 'cname2': y => 2}"))).to eq([
"(resource class",
" ('cname1'",
" (x => 1))",
" ('cname2'",
" (y => 2)))",
- ].join("\n")
+ ].join("\n"))
end
end
context "reported issues in 3.x" do
it "should not screw up on brackets in title of resource #19632" do
- dump(parse('notify { "thisisa[bug]": }')).should == [
+ expect(dump(parse('notify { "thisisa[bug]": }'))).to eq([
"(resource notify",
" ('thisisa[bug]'))",
- ].join("\n")
+ ].join("\n"))
end
end
context "When parsing Relationships" do
it "File[a] -> File[b]" do
- dump(parse("File[a] -> File[b]")).should == "(-> (slice file a) (slice file b))"
+ expect(dump(parse("File[a] -> File[b]"))).to eq("(-> (slice file a) (slice file b))")
end
it "File[a] <- File[b]" do
- dump(parse("File[a] <- File[b]")).should == "(<- (slice file a) (slice file b))"
+ expect(dump(parse("File[a] <- File[b]"))).to eq("(<- (slice file a) (slice file b))")
end
it "File[a] ~> File[b]" do
- dump(parse("File[a] ~> File[b]")).should == "(~> (slice file a) (slice file b))"
+ expect(dump(parse("File[a] ~> File[b]"))).to eq("(~> (slice file a) (slice file b))")
end
it "File[a] <~ File[b]" do
- dump(parse("File[a] <~ File[b]")).should == "(<~ (slice file a) (slice file b))"
+ expect(dump(parse("File[a] <~ File[b]"))).to eq("(<~ (slice file a) (slice file b))")
end
it "Should chain relationships" do
- dump(parse("a -> b -> c")).should ==
+ expect(dump(parse("a -> b -> c"))).to eq(
"(-> (-> a b) c)"
+ )
end
it "Should chain relationships" do
- dump(parse("File[a] -> File[b] ~> File[c] <- File[d] <~ File[e]")).should ==
+ expect(dump(parse("File[a] -> File[b] ~> File[c] <- File[d] <~ File[e]"))).to eq(
"(<~ (<- (~> (-> (slice file a) (slice file b)) (slice file c)) (slice file d)) (slice file e))"
+ )
end
it "should create relationships between collects" do
- dump(parse("File <| mode == 0644 |> -> File <| mode == 0755 |>")).should ==
+ expect(dump(parse("File <| mode == 0644 |> -> File <| mode == 0755 |>"))).to eq(
"(-> (collect file\n (<| |> (== mode 0644))) (collect file\n (<| |> (== mode 0755))))"
+ )
end
end
context "When parsing collection" do
context "of virtual resources" do
it "File <| |>" do
- dump(parse("File <| |>")).should == "(collect file\n (<| |>))"
+ expect(dump(parse("File <| |>"))).to eq("(collect file\n (<| |>))")
end
end
context "of exported resources" do
it "File <<| |>>" do
- dump(parse("File <<| |>>")).should == "(collect file\n (<<| |>>))"
+ expect(dump(parse("File <<| |>>"))).to eq("(collect file\n (<<| |>>))")
end
end
context "queries are parsed with correct precedence" do
it "File <| tag == 'foo' |>" do
- dump(parse("File <| tag == 'foo' |>")).should == "(collect file\n (<| |> (== tag 'foo')))"
+ expect(dump(parse("File <| tag == 'foo' |>"))).to eq("(collect file\n (<| |> (== tag 'foo')))")
end
it "File <| tag == 'foo' and mode != '0777' |>" do
- dump(parse("File <| tag == 'foo' and mode != '0777' |>")).should == "(collect file\n (<| |> (&& (== tag 'foo') (!= mode '0777'))))"
+ expect(dump(parse("File <| tag == 'foo' and mode != '0777' |>"))).to eq("(collect file\n (<| |> (&& (== tag 'foo') (!= mode '0777'))))")
end
it "File <| tag == 'foo' or mode != '0777' |>" do
- dump(parse("File <| tag == 'foo' or mode != '0777' |>")).should == "(collect file\n (<| |> (|| (== tag 'foo') (!= mode '0777'))))"
+ expect(dump(parse("File <| tag == 'foo' or mode != '0777' |>"))).to eq("(collect file\n (<| |> (|| (== tag 'foo') (!= mode '0777'))))")
end
it "File <| tag == 'foo' or tag == 'bar' and mode != '0777' |>" do
- dump(parse("File <| tag == 'foo' or tag == 'bar' and mode != '0777' |>")).should ==
+ expect(dump(parse("File <| tag == 'foo' or tag == 'bar' and mode != '0777' |>"))).to eq(
"(collect file\n (<| |> (|| (== tag 'foo') (&& (== tag 'bar') (!= mode '0777')))))"
+ )
end
it "File <| (tag == 'foo' or tag == 'bar') and mode != '0777' |>" do
- dump(parse("File <| (tag == 'foo' or tag == 'bar') and mode != '0777' |>")).should ==
+ expect(dump(parse("File <| (tag == 'foo' or tag == 'bar') and mode != '0777' |>"))).to eq(
"(collect file\n (<| |> (&& (|| (== tag 'foo') (== tag 'bar')) (!= mode '0777'))))"
+ )
end
end
end
end
diff --git a/spec/unit/pops/parser/parser_spec.rb b/spec/unit/pops/parser/parser_spec.rb
index dcbe1fbdc..5bf480a42 100644
--- a/spec/unit/pops/parser/parser_spec.rb
+++ b/spec/unit/pops/parser/parser_spec.rb
@@ -1,47 +1,47 @@
require 'spec_helper'
require 'puppet/pops'
describe Puppet::Pops::Parser::Parser do
it "should instantiate a parser" do
parser = Puppet::Pops::Parser::Parser.new()
- parser.class.should == Puppet::Pops::Parser::Parser
+ expect(parser.class).to eq(Puppet::Pops::Parser::Parser)
end
it "should parse a code string and return a model" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("$a = 10").current
- model.class.should == Puppet::Pops::Model::Program
- model.body.class.should == Puppet::Pops::Model::AssignmentExpression
+ expect(model.class).to eq(Puppet::Pops::Model::Program)
+ expect(model.body.class).to eq(Puppet::Pops::Model::AssignmentExpression)
end
it "should accept empty input and return a model" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("").current
- model.class.should == Puppet::Pops::Model::Program
- model.body.class.should == Puppet::Pops::Model::Nop
+ expect(model.class).to eq(Puppet::Pops::Model::Program)
+ expect(model.body.class).to eq(Puppet::Pops::Model::Nop)
end
it "should accept empty input containing only comments and report location at end of input" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("# comment\n").current
- model.class.should == Puppet::Pops::Model::Program
- model.body.class.should == Puppet::Pops::Model::Nop
+ expect(model.class).to eq(Puppet::Pops::Model::Program)
+ expect(model.body.class).to eq(Puppet::Pops::Model::Nop)
adapter = Puppet::Pops::Adapters::SourcePosAdapter.adapt(model.body)
expect(adapter.offset).to eq(10)
expect(adapter.length).to eq(0)
end
it "should raise an error with position information when error is raised from within parser" do
parser = Puppet::Pops::Parser::Parser.new()
the_error = nil
begin
parser.parse_string("File [1] { }", 'fakefile.pp')
rescue Puppet::ParseError => e
the_error = e
end
expect(the_error).to be_a(Puppet::ParseError)
expect(the_error.file).to eq('fakefile.pp')
expect(the_error.line).to eq(1)
expect(the_error.pos).to eq(6)
end
end
diff --git a/spec/unit/pops/parser/rgen_sanitycheck_spec.rb b/spec/unit/pops/parser/rgen_sanitycheck_spec.rb
index cfbdf7d99..377c98230 100644
--- a/spec/unit/pops/parser/rgen_sanitycheck_spec.rb
+++ b/spec/unit/pops/parser/rgen_sanitycheck_spec.rb
@@ -1,23 +1,23 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/pops'
require 'rgen/array_extensions'
describe "RGen extensions to core classes" do
it "should be possible to create an empty hash after having required the files above" do
# If this fails, it means the rgen addition to Array is not monkey patched as it
# should (it will return an array instead of fail in a method_missing), and thus
# screw up Hash's check if it can do "to_hash' or not.
#
Hash[[]]
end
it "should be possible to automatically stringify a nested, empty array during join" do
# When this fails it means that rgen has incorrectly implemented
# method_missing on array and is returning an array for to_str instead of
# failing as is expected allowing stringification to occur
- [[]].join(":").should == ""
- ["1", []].join(":").should == "1:"
+ expect([[]].join(":")).to eq("")
+ expect(["1", []].join(":")).to eq("1:")
end
end
diff --git a/spec/unit/pops/types/type_calculator_spec.rb b/spec/unit/pops/types/type_calculator_spec.rb
index b1dd286de..19c17f46c 100644
--- a/spec/unit/pops/types/type_calculator_spec.rb
+++ b/spec/unit/pops/types/type_calculator_spec.rb
@@ -1,1877 +1,1877 @@
require 'spec_helper'
require 'puppet/pops'
describe 'The type calculator' do
let(:calculator) { Puppet::Pops::Types::TypeCalculator.new() }
def range_t(from, to)
t = Puppet::Pops::Types::PIntegerType.new
t.from = from
t.to = to
t
end
def constrained_t(t, from, to)
Puppet::Pops::Types::TypeFactory.constrain_size(t, from, to)
end
def pattern_t(*patterns)
Puppet::Pops::Types::TypeFactory.pattern(*patterns)
end
def regexp_t(pattern)
Puppet::Pops::Types::TypeFactory.regexp(pattern)
end
def string_t(*strings)
Puppet::Pops::Types::TypeFactory.string(*strings)
end
def callable_t(*params)
Puppet::Pops::Types::TypeFactory.callable(*params)
end
def all_callables_t(*params)
Puppet::Pops::Types::TypeFactory.all_callables()
end
def with_block_t(callable_t, *params)
Puppet::Pops::Types::TypeFactory.with_block(callable_t, *params)
end
def with_optional_block_t(callable_t, *params)
Puppet::Pops::Types::TypeFactory.with_optional_block(callable_t, *params)
end
def enum_t(*strings)
Puppet::Pops::Types::TypeFactory.enum(*strings)
end
def variant_t(*types)
Puppet::Pops::Types::TypeFactory.variant(*types)
end
def integer_t()
Puppet::Pops::Types::TypeFactory.integer()
end
def array_t(t)
Puppet::Pops::Types::TypeFactory.array_of(t)
end
def hash_t(k,v)
Puppet::Pops::Types::TypeFactory.hash_of(v, k)
end
def data_t()
Puppet::Pops::Types::TypeFactory.data()
end
def factory()
Puppet::Pops::Types::TypeFactory
end
def collection_t()
Puppet::Pops::Types::TypeFactory.collection()
end
def tuple_t(*types)
Puppet::Pops::Types::TypeFactory.tuple(*types)
end
def struct_t(type_hash)
Puppet::Pops::Types::TypeFactory.struct(type_hash)
end
def object_t
Puppet::Pops::Types::TypeFactory.any()
end
def unit_t
# Cannot be created via factory, the type is private to the type system
Puppet::Pops::Types::PUnitType.new
end
def types
Puppet::Pops::Types
end
shared_context "types_setup" do
# Do not include the special type Unit in this list
def all_types
[ Puppet::Pops::Types::PAnyType,
Puppet::Pops::Types::PNilType,
Puppet::Pops::Types::PDataType,
Puppet::Pops::Types::PScalarType,
Puppet::Pops::Types::PStringType,
Puppet::Pops::Types::PNumericType,
Puppet::Pops::Types::PIntegerType,
Puppet::Pops::Types::PFloatType,
Puppet::Pops::Types::PRegexpType,
Puppet::Pops::Types::PBooleanType,
Puppet::Pops::Types::PCollectionType,
Puppet::Pops::Types::PArrayType,
Puppet::Pops::Types::PHashType,
Puppet::Pops::Types::PRuntimeType,
Puppet::Pops::Types::PHostClassType,
Puppet::Pops::Types::PResourceType,
Puppet::Pops::Types::PPatternType,
Puppet::Pops::Types::PEnumType,
Puppet::Pops::Types::PVariantType,
Puppet::Pops::Types::PStructType,
Puppet::Pops::Types::PTupleType,
Puppet::Pops::Types::PCallableType,
Puppet::Pops::Types::PType,
Puppet::Pops::Types::POptionalType,
Puppet::Pops::Types::PDefaultType,
]
end
def scalar_types
# PVariantType is also scalar, if its types are all Scalar
[
Puppet::Pops::Types::PScalarType,
Puppet::Pops::Types::PStringType,
Puppet::Pops::Types::PNumericType,
Puppet::Pops::Types::PIntegerType,
Puppet::Pops::Types::PFloatType,
Puppet::Pops::Types::PRegexpType,
Puppet::Pops::Types::PBooleanType,
Puppet::Pops::Types::PPatternType,
Puppet::Pops::Types::PEnumType,
]
end
def numeric_types
# PVariantType is also numeric, if its types are all numeric
[
Puppet::Pops::Types::PNumericType,
Puppet::Pops::Types::PIntegerType,
Puppet::Pops::Types::PFloatType,
]
end
def string_types
# PVariantType is also string type, if its types are all compatible
[
Puppet::Pops::Types::PStringType,
Puppet::Pops::Types::PPatternType,
Puppet::Pops::Types::PEnumType,
]
end
def collection_types
# PVariantType is also string type, if its types are all compatible
[
Puppet::Pops::Types::PCollectionType,
Puppet::Pops::Types::PHashType,
Puppet::Pops::Types::PArrayType,
Puppet::Pops::Types::PStructType,
Puppet::Pops::Types::PTupleType,
]
end
def data_compatible_types
result = scalar_types
result << Puppet::Pops::Types::PDataType
result << array_t(types::PDataType.new)
result << types::TypeFactory.hash_of_data
result << Puppet::Pops::Types::PNilType
tmp = tuple_t(types::PDataType.new)
result << (tmp)
tmp.size_type = range_t(0, nil)
result
end
def type_from_class(c)
c.is_a?(Class) ? c.new : c
end
end
context 'when inferring ruby' do
it 'fixnum translates to PIntegerType' do
- calculator.infer(1).class.should == Puppet::Pops::Types::PIntegerType
+ expect(calculator.infer(1).class).to eq(Puppet::Pops::Types::PIntegerType)
end
it 'large fixnum (or bignum depending on architecture) translates to PIntegerType' do
- calculator.infer(2**33).class.should == Puppet::Pops::Types::PIntegerType
+ expect(calculator.infer(2**33).class).to eq(Puppet::Pops::Types::PIntegerType)
end
it 'float translates to PFloatType' do
- calculator.infer(1.3).class.should == Puppet::Pops::Types::PFloatType
+ expect(calculator.infer(1.3).class).to eq(Puppet::Pops::Types::PFloatType)
end
it 'string translates to PStringType' do
- calculator.infer('foo').class.should == Puppet::Pops::Types::PStringType
+ expect(calculator.infer('foo').class).to eq(Puppet::Pops::Types::PStringType)
end
it 'inferred string type knows the string value' do
t = calculator.infer('foo')
- t.class.should == Puppet::Pops::Types::PStringType
- t.values.should == ['foo']
+ expect(t.class).to eq(Puppet::Pops::Types::PStringType)
+ expect(t.values).to eq(['foo'])
end
it 'boolean true translates to PBooleanType' do
- calculator.infer(true).class.should == Puppet::Pops::Types::PBooleanType
+ expect(calculator.infer(true).class).to eq(Puppet::Pops::Types::PBooleanType)
end
it 'boolean false translates to PBooleanType' do
- calculator.infer(false).class.should == Puppet::Pops::Types::PBooleanType
+ expect(calculator.infer(false).class).to eq(Puppet::Pops::Types::PBooleanType)
end
it 'regexp translates to PRegexpType' do
- calculator.infer(/^a regular expression$/).class.should == Puppet::Pops::Types::PRegexpType
+ expect(calculator.infer(/^a regular expression$/).class).to eq(Puppet::Pops::Types::PRegexpType)
end
it 'nil translates to PNilType' do
- calculator.infer(nil).class.should == Puppet::Pops::Types::PNilType
+ expect(calculator.infer(nil).class).to eq(Puppet::Pops::Types::PNilType)
end
it ':undef translates to PRuntimeType' do
- calculator.infer(:undef).class.should == Puppet::Pops::Types::PRuntimeType
+ expect(calculator.infer(:undef).class).to eq(Puppet::Pops::Types::PRuntimeType)
end
it 'an instance of class Foo translates to PRuntimeType[ruby, Foo]' do
class Foo
end
t = calculator.infer(Foo.new)
- t.class.should == Puppet::Pops::Types::PRuntimeType
- t.runtime.should == :ruby
- t.runtime_type_name.should == 'Foo'
+ expect(t.class).to eq(Puppet::Pops::Types::PRuntimeType)
+ expect(t.runtime).to eq(:ruby)
+ expect(t.runtime_type_name).to eq('Foo')
end
context 'array' do
it 'translates to PArrayType' do
- calculator.infer([1,2]).class.should == Puppet::Pops::Types::PArrayType
+ expect(calculator.infer([1,2]).class).to eq(Puppet::Pops::Types::PArrayType)
end
it 'with fixnum values translates to PArrayType[PIntegerType]' do
- calculator.infer([1,2]).element_type.class.should == Puppet::Pops::Types::PIntegerType
+ expect(calculator.infer([1,2]).element_type.class).to eq(Puppet::Pops::Types::PIntegerType)
end
it 'with 32 and 64 bit integer values translates to PArrayType[PIntegerType]' do
- calculator.infer([1,2**33]).element_type.class.should == Puppet::Pops::Types::PIntegerType
+ expect(calculator.infer([1,2**33]).element_type.class).to eq(Puppet::Pops::Types::PIntegerType)
end
it 'Range of integer values are computed' do
t = calculator.infer([-3,0,42]).element_type
- t.class.should == Puppet::Pops::Types::PIntegerType
- t.from.should == -3
- t.to.should == 42
+ expect(t.class).to eq(Puppet::Pops::Types::PIntegerType)
+ expect(t.from).to eq(-3)
+ expect(t.to).to eq(42)
end
it "Compound string values are computed" do
t = calculator.infer(['a','b', 'c']).element_type
- t.class.should == Puppet::Pops::Types::PStringType
- t.values.should == ['a', 'b', 'c']
+ expect(t.class).to eq(Puppet::Pops::Types::PStringType)
+ expect(t.values).to eq(['a', 'b', 'c'])
end
it 'with fixnum and float values translates to PArrayType[PNumericType]' do
- calculator.infer([1,2.0]).element_type.class.should == Puppet::Pops::Types::PNumericType
+ expect(calculator.infer([1,2.0]).element_type.class).to eq(Puppet::Pops::Types::PNumericType)
end
it 'with fixnum and string values translates to PArrayType[PScalarType]' do
- calculator.infer([1,'two']).element_type.class.should == Puppet::Pops::Types::PScalarType
+ expect(calculator.infer([1,'two']).element_type.class).to eq(Puppet::Pops::Types::PScalarType)
end
it 'with float and string values translates to PArrayType[PScalarType]' do
- calculator.infer([1.0,'two']).element_type.class.should == Puppet::Pops::Types::PScalarType
+ expect(calculator.infer([1.0,'two']).element_type.class).to eq(Puppet::Pops::Types::PScalarType)
end
it 'with fixnum, float, and string values translates to PArrayType[PScalarType]' do
- calculator.infer([1, 2.0,'two']).element_type.class.should == Puppet::Pops::Types::PScalarType
+ expect(calculator.infer([1, 2.0,'two']).element_type.class).to eq(Puppet::Pops::Types::PScalarType)
end
it 'with fixnum and regexp values translates to PArrayType[PScalarType]' do
- calculator.infer([1, /two/]).element_type.class.should == Puppet::Pops::Types::PScalarType
+ expect(calculator.infer([1, /two/]).element_type.class).to eq(Puppet::Pops::Types::PScalarType)
end
it 'with string and regexp values translates to PArrayType[PScalarType]' do
- calculator.infer(['one', /two/]).element_type.class.should == Puppet::Pops::Types::PScalarType
+ expect(calculator.infer(['one', /two/]).element_type.class).to eq(Puppet::Pops::Types::PScalarType)
end
it 'with string and symbol values translates to PArrayType[PAnyType]' do
- calculator.infer(['one', :two]).element_type.class.should == Puppet::Pops::Types::PAnyType
+ expect(calculator.infer(['one', :two]).element_type.class).to eq(Puppet::Pops::Types::PAnyType)
end
it 'with fixnum and nil values translates to PArrayType[PIntegerType]' do
- calculator.infer([1, nil]).element_type.class.should == Puppet::Pops::Types::PIntegerType
+ expect(calculator.infer([1, nil]).element_type.class).to eq(Puppet::Pops::Types::PIntegerType)
end
it 'with arrays of string values translates to PArrayType[PArrayType[PStringType]]' do
et = calculator.infer([['first' 'array'], ['second','array']])
- et.class.should == Puppet::Pops::Types::PArrayType
+ expect(et.class).to eq(Puppet::Pops::Types::PArrayType)
et = et.element_type
- et.class.should == Puppet::Pops::Types::PArrayType
+ expect(et.class).to eq(Puppet::Pops::Types::PArrayType)
et = et.element_type
- et.class.should == Puppet::Pops::Types::PStringType
+ expect(et.class).to eq(Puppet::Pops::Types::PStringType)
end
it 'with array of string values and array of fixnums translates to PArrayType[PArrayType[PScalarType]]' do
et = calculator.infer([['first' 'array'], [1,2]])
- et.class.should == Puppet::Pops::Types::PArrayType
+ expect(et.class).to eq(Puppet::Pops::Types::PArrayType)
et = et.element_type
- et.class.should == Puppet::Pops::Types::PArrayType
+ expect(et.class).to eq(Puppet::Pops::Types::PArrayType)
et = et.element_type
- et.class.should == Puppet::Pops::Types::PScalarType
+ expect(et.class).to eq(Puppet::Pops::Types::PScalarType)
end
it 'with hashes of string values translates to PArrayType[PHashType[PStringType]]' do
et = calculator.infer([{:first => 'first', :second => 'second' }, {:first => 'first', :second => 'second' }])
- et.class.should == Puppet::Pops::Types::PArrayType
+ expect(et.class).to eq(Puppet::Pops::Types::PArrayType)
et = et.element_type
- et.class.should == Puppet::Pops::Types::PHashType
+ expect(et.class).to eq(Puppet::Pops::Types::PHashType)
et = et.element_type
- et.class.should == Puppet::Pops::Types::PStringType
+ expect(et.class).to eq(Puppet::Pops::Types::PStringType)
end
it 'with hash of string values and hash of fixnums translates to PArrayType[PHashType[PScalarType]]' do
et = calculator.infer([{:first => 'first', :second => 'second' }, {:first => 1, :second => 2 }])
- et.class.should == Puppet::Pops::Types::PArrayType
+ expect(et.class).to eq(Puppet::Pops::Types::PArrayType)
et = et.element_type
- et.class.should == Puppet::Pops::Types::PHashType
+ expect(et.class).to eq(Puppet::Pops::Types::PHashType)
et = et.element_type
- et.class.should == Puppet::Pops::Types::PScalarType
+ expect(et.class).to eq(Puppet::Pops::Types::PScalarType)
end
end
context 'hash' do
it 'translates to PHashType' do
- calculator.infer({:first => 1, :second => 2}).class.should == Puppet::Pops::Types::PHashType
+ expect(calculator.infer({:first => 1, :second => 2}).class).to eq(Puppet::Pops::Types::PHashType)
end
it 'with symbolic keys translates to PHashType[PRuntimeType[ruby, Symbol], value]' do
k = calculator.infer({:first => 1, :second => 2}).key_type
- k.class.should == Puppet::Pops::Types::PRuntimeType
- k.runtime.should == :ruby
- k.runtime_type_name.should == 'Symbol'
+ expect(k.class).to eq(Puppet::Pops::Types::PRuntimeType)
+ expect(k.runtime).to eq(:ruby)
+ expect(k.runtime_type_name).to eq('Symbol')
end
it 'with string keys translates to PHashType[PStringType, value]' do
- calculator.infer({'first' => 1, 'second' => 2}).key_type.class.should == Puppet::Pops::Types::PStringType
+ expect(calculator.infer({'first' => 1, 'second' => 2}).key_type.class).to eq(Puppet::Pops::Types::PStringType)
end
it 'with fixnum values translates to PHashType[key, PIntegerType]' do
- calculator.infer({:first => 1, :second => 2}).element_type.class.should == Puppet::Pops::Types::PIntegerType
+ expect(calculator.infer({:first => 1, :second => 2}).element_type.class).to eq(Puppet::Pops::Types::PIntegerType)
end
end
end
context 'patterns' do
it "constructs a PPatternType" do
t = pattern_t('a(b)c')
- t.class.should == Puppet::Pops::Types::PPatternType
- t.patterns.size.should == 1
- t.patterns[0].class.should == Puppet::Pops::Types::PRegexpType
- t.patterns[0].pattern.should == 'a(b)c'
- t.patterns[0].regexp.match('abc')[1].should == 'b'
+ expect(t.class).to eq(Puppet::Pops::Types::PPatternType)
+ expect(t.patterns.size).to eq(1)
+ expect(t.patterns[0].class).to eq(Puppet::Pops::Types::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 PStringType with multiple strings" do
t = string_t('a', 'b', 'c', 'abc')
- t.values.should == ['a', 'b', 'c', 'abc']
+ expect(t.values).to eq(['a', 'b', 'c', 'abc'])
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 = Puppet::Pops::Types::PResourceType.new()
r1.type_name = 'File'
r2 = Puppet::Pops::Types::PResourceType.new()
r2.type_name = 'File'
- calculator.string(calculator.common_type(r1, r2)).should == "File"
+ expect(calculator.string(calculator.common_type(r1, r2))).to eq("File")
r2 = Puppet::Pops::Types::PResourceType.new()
r2.type_name = 'File'
r2.title = '/tmp/foo'
- calculator.string(calculator.common_type(r1, r2)).should == "File"
+ expect(calculator.string(calculator.common_type(r1, r2))).to eq("File")
r1 = Puppet::Pops::Types::PResourceType.new()
r1.type_name = 'File'
r1.title = '/tmp/foo'
- calculator.string(calculator.common_type(r1, r2)).should == "File['/tmp/foo']"
+ expect(calculator.string(calculator.common_type(r1, r2))).to eq("File['/tmp/foo']")
r1 = Puppet::Pops::Types::PResourceType.new()
r1.type_name = 'File'
r1.title = '/tmp/bar'
- calculator.string(calculator.common_type(r1, r2)).should == "File"
+ expect(calculator.string(calculator.common_type(r1, r2))).to eq("File")
r2 = Puppet::Pops::Types::PResourceType.new()
r2.type_name = 'Package'
r2.title = 'apache'
- calculator.string(calculator.common_type(r1, r2)).should == "Resource"
+ expect(calculator.string(calculator.common_type(r1, r2))).to eq("Resource")
end
it 'computes given hostclass type commonality' do
r1 = Puppet::Pops::Types::PHostClassType.new()
r1.class_name = 'foo'
r2 = Puppet::Pops::Types::PHostClassType.new()
r2.class_name = 'foo'
- calculator.string(calculator.common_type(r1, r2)).should == "Class[foo]"
+ expect(calculator.string(calculator.common_type(r1, r2))).to eq("Class[foo]")
r2 = Puppet::Pops::Types::PHostClassType.new()
r2.class_name = 'bar'
- calculator.string(calculator.common_type(r1, r2)).should == "Class"
+ expect(calculator.string(calculator.common_type(r1, r2))).to eq("Class")
r2 = Puppet::Pops::Types::PHostClassType.new()
- calculator.string(calculator.common_type(r1, r2)).should == "Class"
+ expect(calculator.string(calculator.common_type(r1, r2))).to eq("Class")
r1 = Puppet::Pops::Types::PHostClassType.new()
- calculator.string(calculator.common_type(r1, r2)).should == "Class"
+ expect(calculator.string(calculator.common_type(r1, r2))).to eq("Class")
end
it 'computes pattern commonality' do
t1 = pattern_t('abc')
t2 = pattern_t('xyz')
common_t = calculator.common_type(t1,t2)
- common_t.class.should == Puppet::Pops::Types::PPatternType
- common_t.patterns.map { |pr| pr.pattern }.should == ['abc', 'xyz']
- calculator.string(common_t).should == "Pattern[/abc/, /xyz/]"
+ expect(common_t.class).to eq(Puppet::Pops::Types::PPatternType)
+ expect(common_t.patterns.map { |pr| pr.pattern }).to eq(['abc', 'xyz'])
+ expect(calculator.string(common_t)).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)
- common_t.should == enum_t('a', 'b', 'c', 'x', 'y', 'z')
+ 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 = enum_t('a')
v_b = variant_t(b_t1)
common_t = calculator.common_type(v_a, v_b)
- common_t.class.should == Puppet::Pops::Types::PVariantType
- Set.new(common_t.types).should == Set.new([a_t1, a_t2, b_t1])
+ expect(common_t.class).to eq(Puppet::Pops::Types::PVariantType)
+ expect(Set.new(common_t.types)).to eq(Set.new([a_t1, a_t2, b_t1]))
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 = enum_t('a')
v_b = variant_t(b_t1)
common_t = calculator.common_type(v_a, v_b)
- common_t.class.should == Puppet::Pops::Types::PVariantType
- Set.new(common_t.types).should == Set.new([a_t1, a_t2])
+ expect(common_t.class).to eq(Puppet::Pops::Types::PVariantType)
+ expect(Set.new(common_t.types)).to eq(Set.new([a_t1, a_t2]))
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(Puppet::Pops::Types::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 = Puppet::Pops::Types::PScalarType.new
t2 = callable_t(scalar_t)
common_t = calculator.common_type(t1, t2)
expect(common_t.class).to be(Puppet::Pops::Types::PCallableType)
expect(common_t.param_types.class).to be(Puppet::Pops::Types::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
t1 = with_block_t(callable_t(String), String)
t2 = with_block_t(callable_t(String), Integer)
common_t = calculator.common_type(t1, t2)
expect(common_t.class).to be(Puppet::Pops::Types::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
t1 = with_block_t(callable_t(String), String)
scalar_t = Puppet::Pops::Types::PScalarType.new
t2 = with_block_t(callable_t(String), scalar_t)
common_t = calculator.common_type(t1, t2)
expect(common_t.param_types.class).to be(Puppet::Pops::Types::PTupleType)
expect(common_t.block_type).to eql(callable_t(scalar_t))
end
end
end
context 'computes assignability' do
include_context "types_setup"
context 'for Unit, such that' do
it 'all types are assignable to Unit' do
t = Puppet::Pops::Types::PUnitType.new()
- all_types.each { |t2| t2.new.should be_assignable_to(t) }
+ all_types.each { |t2| expect(t2.new).to be_assignable_to(t) }
end
it 'Unit is assignable to all other types' do
t = Puppet::Pops::Types::PUnitType.new()
- all_types.each { |t2| t.should be_assignable_to(t2.new) }
+ all_types.each { |t2| expect(t).to be_assignable_to(t2.new) }
end
it 'Unit is assignable to Unit' do
t = Puppet::Pops::Types::PUnitType.new()
t2 = Puppet::Pops::Types::PUnitType.new()
- t.should be_assignable_to(t2)
+ expect(t).to be_assignable_to(t2)
end
end
context "for Any, such that" do
it 'all types are assignable to Any' do
t = Puppet::Pops::Types::PAnyType.new()
- all_types.each { |t2| t2.new.should be_assignable_to(t) }
+ all_types.each { |t2| expect(t2.new).to be_assignable_to(t) }
end
it 'Any is not assignable to anything but Any' do
tested_types = all_types() - [Puppet::Pops::Types::PAnyType]
t = Puppet::Pops::Types::PAnyType.new()
- tested_types.each { |t2| t.should_not be_assignable_to(t2.new) }
+ tested_types.each { |t2| expect(t).not_to be_assignable_to(t2.new) }
end
end
context "for Data, such that" do
it 'all scalars + array and hash are assignable to Data' do
t = Puppet::Pops::Types::PDataType.new()
data_compatible_types.each { |t2|
- type_from_class(t2).should be_assignable_to(t)
+ expect(type_from_class(t2)).to be_assignable_to(t)
}
end
it 'a Variant of scalar, hash, or array is assignable to Data' do
t = Puppet::Pops::Types::PDataType.new()
- data_compatible_types.each { |t2| variant_t(type_from_class(t2)).should be_assignable_to(t) }
+ data_compatible_types.each { |t2| expect(variant_t(type_from_class(t2))).to be_assignable_to(t) }
end
it 'Data is not assignable to any of its subtypes' do
t = Puppet::Pops::Types::PDataType.new()
types_to_test = data_compatible_types- [Puppet::Pops::Types::PDataType]
- types_to_test.each {|t2| t.should_not be_assignable_to(type_from_class(t2)) }
+ types_to_test.each {|t2| expect(t).not_to be_assignable_to(type_from_class(t2)) }
end
it 'Data is not assignable to a Variant of Data subtype' do
t = Puppet::Pops::Types::PDataType.new()
types_to_test = data_compatible_types- [Puppet::Pops::Types::PDataType]
- types_to_test.each { |t2| t.should_not be_assignable_to(variant_t(type_from_class(t2))) }
+ types_to_test.each { |t2| expect(t).not_to be_assignable_to(variant_t(type_from_class(t2))) }
end
it 'Data is not assignable to any disjunct type' do
tested_types = all_types - [Puppet::Pops::Types::PAnyType, Puppet::Pops::Types::PDataType] - scalar_types
t = Puppet::Pops::Types::PDataType.new()
- tested_types.each {|t2| t.should_not be_assignable_to(t2.new) }
+ tested_types.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
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))
- v.should be_assignable_to(integer_t)
- v.should be_assignable_to(range_t(10, 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
- v.should be_assignable_to(variant_t(range_t(10, 20), range_t(30, 40)))
+ 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
- v.should be_assignable_to(variant_t(range_t(10, 13), range_t(14, 40)))
+ expect(v).to be_assignable_to(variant_t(range_t(10, 13), range_t(14, 40)))
# not acceptable
- v.should_not be_assignable_to(range_t(0, 4))
- v.should_not be_assignable_to(string_t)
+ expect(v).not_to be_assignable_to(range_t(0, 4))
+ expect(v).not_to be_assignable_to(string_t)
end
end
context "for Scalar, such that" do
it "all scalars are assignable to Scalar" do
t = Puppet::Pops::Types::PScalarType.new()
- scalar_types.each {|t2| t2.new.should be_assignable_to(t) }
+ scalar_types.each {|t2| expect(t2.new).to be_assignable_to(t) }
end
it 'Scalar is not assignable to any of its subtypes' do
t = Puppet::Pops::Types::PScalarType.new()
types_to_test = scalar_types - [Puppet::Pops::Types::PScalarType]
- types_to_test.each {|t2| t.should_not be_assignable_to(t2.new) }
+ types_to_test.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
it 'Scalar is not assignable to any disjunct type' do
tested_types = all_types - [Puppet::Pops::Types::PAnyType, Puppet::Pops::Types::PDataType] - scalar_types
t = Puppet::Pops::Types::PScalarType.new()
- tested_types.each {|t2| t.should_not be_assignable_to(t2.new) }
+ tested_types.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
end
context "for Numeric, such that" do
it "all numerics are assignable to Numeric" do
t = Puppet::Pops::Types::PNumericType.new()
- numeric_types.each {|t2| t2.new.should be_assignable_to(t) }
+ numeric_types.each {|t2| expect(t2.new).to be_assignable_to(t) }
end
it 'Numeric is not assignable to any of its subtypes' do
t = Puppet::Pops::Types::PNumericType.new()
types_to_test = numeric_types - [Puppet::Pops::Types::PNumericType]
- types_to_test.each {|t2| t.should_not be_assignable_to(t2.new) }
+ types_to_test.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
it 'Numeric is not assignable to any disjunct type' do
tested_types = all_types - [
Puppet::Pops::Types::PAnyType,
Puppet::Pops::Types::PDataType,
Puppet::Pops::Types::PScalarType,
] - numeric_types
t = Puppet::Pops::Types::PNumericType.new()
- tested_types.each {|t2| t.should_not be_assignable_to(t2.new) }
+ tested_types.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
end
context "for Collection, such that" do
it "all collections are assignable to Collection" do
t = Puppet::Pops::Types::PCollectionType.new()
- collection_types.each {|t2| t2.new.should be_assignable_to(t) }
+ collection_types.each {|t2| expect(t2.new).to be_assignable_to(t) }
end
it 'Collection is not assignable to any of its subtypes' do
t = Puppet::Pops::Types::PCollectionType.new()
types_to_test = collection_types - [Puppet::Pops::Types::PCollectionType]
- types_to_test.each {|t2| t.should_not be_assignable_to(t2.new) }
+ types_to_test.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
it 'Collection is not assignable to any disjunct type' do
tested_types = all_types - [Puppet::Pops::Types::PAnyType] - collection_types
t = Puppet::Pops::Types::PCollectionType.new()
- tested_types.each {|t2| t.should_not be_assignable_to(t2.new) }
+ tested_types.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
end
context "for Array, such that" do
it "Array is not assignable to non Array based Collection type" do
t = Puppet::Pops::Types::PArrayType.new()
tested_types = collection_types - [
Puppet::Pops::Types::PCollectionType,
Puppet::Pops::Types::PArrayType,
Puppet::Pops::Types::PTupleType]
- tested_types.each {|t2| t.should_not be_assignable_to(t2.new) }
+ tested_types.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
it 'Array is not assignable to any disjunct type' do
tested_types = all_types - [
Puppet::Pops::Types::PAnyType,
Puppet::Pops::Types::PDataType] - collection_types
t = Puppet::Pops::Types::PArrayType.new()
- tested_types.each {|t2| t.should_not be_assignable_to(t2.new) }
+ tested_types.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
end
context "for Hash, such that" do
it "Hash is not assignable to any other Collection type" do
t = Puppet::Pops::Types::PHashType.new()
tested_types = collection_types - [
Puppet::Pops::Types::PCollectionType,
Puppet::Pops::Types::PStructType,
Puppet::Pops::Types::PHashType]
- tested_types.each {|t2| t.should_not be_assignable_to(t2.new) }
+ tested_types.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
it 'Hash is not assignable to any disjunct type' do
tested_types = all_types - [
Puppet::Pops::Types::PAnyType,
Puppet::Pops::Types::PDataType] - collection_types
t = Puppet::Pops::Types::PHashType.new()
- tested_types.each {|t2| t.should_not be_assignable_to(t2.new) }
+ tested_types.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
end
context "for Tuple, such that" do
it "Tuple is not assignable to any other non Array based Collection type" do
t = Puppet::Pops::Types::PTupleType.new()
tested_types = collection_types - [
Puppet::Pops::Types::PCollectionType,
Puppet::Pops::Types::PTupleType,
Puppet::Pops::Types::PArrayType]
- tested_types.each {|t2| t.should_not be_assignable_to(t2.new) }
+ tested_types.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
it 'Tuple is not assignable to any disjunct type' do
tested_types = all_types - [
Puppet::Pops::Types::PAnyType,
Puppet::Pops::Types::PDataType] - collection_types
t = Puppet::Pops::Types::PTupleType.new()
- tested_types.each {|t2| t.should_not be_assignable_to(t2.new) }
+ tested_types.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
end
context "for Struct, such that" do
it "Struct is not assignable to any other non Hashed based Collection type" do
t = Puppet::Pops::Types::PStructType.new()
tested_types = collection_types - [
Puppet::Pops::Types::PCollectionType,
Puppet::Pops::Types::PStructType,
Puppet::Pops::Types::PHashType]
- tested_types.each {|t2| t.should_not be_assignable_to(t2.new) }
+ tested_types.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
it 'Struct is not assignable to any disjunct type' do
tested_types = all_types - [
Puppet::Pops::Types::PAnyType,
Puppet::Pops::Types::PDataType] - collection_types
t = Puppet::Pops::Types::PStructType.new()
- tested_types.each {|t2| t.should_not be_assignable_to(t2.new) }
+ tested_types.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
end
context "for Callable, such that" do
it "Callable is not assignable to any disjunct type" do
t = Puppet::Pops::Types::PCallableType.new()
tested_types = all_types - [
Puppet::Pops::Types::PCallableType,
Puppet::Pops::Types::PAnyType]
- tested_types.each {|t2| t.should_not be_assignable_to(t2.new) }
+ tested_types.each {|t2| expect(t).not_to be_assignable_to(t2.new) }
end
end
it 'should recognize mapped ruby types' do
{ Integer => Puppet::Pops::Types::PIntegerType.new,
Fixnum => Puppet::Pops::Types::PIntegerType.new,
Bignum => Puppet::Pops::Types::PIntegerType.new,
Float => Puppet::Pops::Types::PFloatType.new,
Numeric => Puppet::Pops::Types::PNumericType.new,
NilClass => Puppet::Pops::Types::PNilType.new,
TrueClass => Puppet::Pops::Types::PBooleanType.new,
FalseClass => Puppet::Pops::Types::PBooleanType.new,
String => Puppet::Pops::Types::PStringType.new,
Regexp => Puppet::Pops::Types::PRegexpType.new,
Regexp => Puppet::Pops::Types::PRegexpType.new,
Array => Puppet::Pops::Types::TypeFactory.array_of_data(),
Hash => Puppet::Pops::Types::TypeFactory.hash_of_data()
}.each do |ruby_type, puppet_type |
- ruby_type.should be_assignable_to(puppet_type)
+ expect(ruby_type).to be_assignable_to(puppet_type)
end
end
context 'when dealing with integer ranges' do
it 'should accept an equal range' do
- calculator.assignable?(range_t(2,5), range_t(2,5)).should == true
+ expect(calculator.assignable?(range_t(2,5), range_t(2,5))).to eq(true)
end
it 'should accept an equal reverse range' do
- calculator.assignable?(range_t(2,5), range_t(5,2)).should == true
+ expect(calculator.assignable?(range_t(2,5), range_t(5,2))).to eq(true)
end
it 'should accept a narrower range' do
- calculator.assignable?(range_t(2,10), range_t(3,5)).should == true
+ expect(calculator.assignable?(range_t(2,10), range_t(3,5))).to eq(true)
end
it 'should accept a narrower reverse range' do
- calculator.assignable?(range_t(2,10), range_t(5,3)).should == true
+ expect(calculator.assignable?(range_t(2,10), range_t(5,3))).to eq(true)
end
it 'should reject a wider range' do
- calculator.assignable?(range_t(3,5), range_t(2,10)).should == false
+ expect(calculator.assignable?(range_t(3,5), range_t(2,10))).to eq(false)
end
it 'should reject a wider reverse range' do
- calculator.assignable?(range_t(3,5), range_t(10,2)).should == false
+ expect(calculator.assignable?(range_t(3,5), range_t(10,2))).to eq(false)
end
it 'should reject a partially overlapping range' do
- calculator.assignable?(range_t(3,5), range_t(2,4)).should == false
- calculator.assignable?(range_t(3,5), range_t(4,6)).should == false
+ expect(calculator.assignable?(range_t(3,5), range_t(2,4))).to eq(false)
+ expect(calculator.assignable?(range_t(3,5), range_t(4,6))).to eq(false)
end
it 'should reject a partially overlapping reverse range' do
- calculator.assignable?(range_t(3,5), range_t(4,2)).should == false
- calculator.assignable?(range_t(3,5), range_t(6,4)).should == false
+ expect(calculator.assignable?(range_t(3,5), range_t(4,2))).to eq(false)
+ expect(calculator.assignable?(range_t(3,5), range_t(6,4))).to eq(false)
end
end
context 'when dealing with patterns' do
it 'should accept a string matching a pattern' do
p_t = pattern_t('abc')
p_s = string_t('XabcY')
- calculator.assignable?(p_t, p_s).should == true
+ expect(calculator.assignable?(p_t, p_s)).to eq(true)
end
it 'should accept a regexp matching a pattern' do
p_t = pattern_t(/abc/)
p_s = string_t('XabcY')
- calculator.assignable?(p_t, p_s).should == true
+ expect(calculator.assignable?(p_t, p_s)).to eq(true)
end
it 'should accept a pattern matching a pattern' do
p_t = pattern_t(pattern_t('abc'))
p_s = string_t('XabcY')
- calculator.assignable?(p_t, p_s).should == true
+ expect(calculator.assignable?(p_t, p_s)).to eq(true)
end
it 'should accept a regexp matching a pattern' do
p_t = pattern_t(regexp_t('abc'))
p_s = string_t('XabcY')
- calculator.assignable?(p_t, p_s).should == true
+ expect(calculator.assignable?(p_t, p_s)).to eq(true)
end
it 'should accept a string matching all patterns' do
p_t = pattern_t('abc', 'ab', 'c')
p_s = string_t('XabcY')
- calculator.assignable?(p_t, p_s).should == true
+ expect(calculator.assignable?(p_t, p_s)).to eq(true)
end
it 'should accept multiple strings if they all match any patterns' do
p_t = pattern_t('X', 'Y', 'abc')
p_s = string_t('Xa', 'aY', 'abc')
- calculator.assignable?(p_t, p_s).should == true
+ expect(calculator.assignable?(p_t, p_s)).to eq(true)
end
it 'should reject a string not matching any patterns' do
p_t = pattern_t('abc', 'ab', 'c')
p_s = string_t('XqqqY')
- calculator.assignable?(p_t, p_s).should == false
+ expect(calculator.assignable?(p_t, p_s)).to eq(false)
end
it 'should reject multiple strings if not all match any patterns' do
p_t = pattern_t('abc', 'ab', 'c', 'q')
p_s = string_t('X', 'Y', 'Z')
- calculator.assignable?(p_t, p_s).should == false
+ expect(calculator.assignable?(p_t, p_s)).to eq(false)
end
it 'should accept enum matching patterns as instanceof' do
enum = enum_t('XS', 'S', 'M', 'L' 'XL', 'XXL')
pattern = pattern_t('S', 'M', 'L')
- calculator.assignable?(pattern, enum).should == true
+ expect(calculator.assignable?(pattern, enum)).to eq(true)
end
it 'pattern should accept a variant where all variants are acceptable' do
pattern = pattern_t(/^\w+$/)
- calculator.assignable?(pattern, variant_t(string_t('a'), string_t('b'))).should == true
+ expect(calculator.assignable?(pattern, variant_t(string_t('a'), string_t('b')))).to eq(true)
end
it 'pattern representing all patterns should accept any pattern' do
- calculator.assignable?(pattern_t(), pattern_t('a')).should == true
- calculator.assignable?(pattern_t(), pattern_t()).should == true
+ expect(calculator.assignable?(pattern_t(), pattern_t('a'))).to eq(true)
+ expect(calculator.assignable?(pattern_t(), pattern_t())).to eq(true)
end
it 'pattern representing all patterns should accept any enum' do
- calculator.assignable?(pattern_t(), enum_t('a')).should == true
- calculator.assignable?(pattern_t(), enum_t()).should == true
+ expect(calculator.assignable?(pattern_t(), enum_t('a'))).to eq(true)
+ expect(calculator.assignable?(pattern_t(), enum_t())).to eq(true)
end
it 'pattern representing all patterns should accept any string' do
- calculator.assignable?(pattern_t(), string_t('a')).should == true
- calculator.assignable?(pattern_t(), string_t()).should == true
+ expect(calculator.assignable?(pattern_t(), string_t('a'))).to eq(true)
+ expect(calculator.assignable?(pattern_t(), string_t())).to eq(true)
end
end
context 'when dealing with enums' do
it 'should accept a string with matching content' do
- calculator.assignable?(enum_t('a', 'b'), string_t('a')).should == true
- calculator.assignable?(enum_t('a', 'b'), string_t('b')).should == true
- calculator.assignable?(enum_t('a', 'b'), string_t('c')).should == false
+ expect(calculator.assignable?(enum_t('a', 'b'), string_t('a'))).to eq(true)
+ expect(calculator.assignable?(enum_t('a', 'b'), string_t('b'))).to eq(true)
+ expect(calculator.assignable?(enum_t('a', 'b'), string_t('c'))).to eq(false)
end
it 'should accept an enum with matching enum' do
- calculator.assignable?(enum_t('a', 'b'), enum_t('a', 'b')).should == true
- calculator.assignable?(enum_t('a', 'b'), enum_t('a')).should == true
- calculator.assignable?(enum_t('a', 'b'), enum_t('c')).should == false
+ expect(calculator.assignable?(enum_t('a', 'b'), enum_t('a', 'b'))).to eq(true)
+ expect(calculator.assignable?(enum_t('a', 'b'), enum_t('a'))).to eq(true)
+ expect(calculator.assignable?(enum_t('a', 'b'), enum_t('c'))).to eq(false)
end
it 'non parameterized enum accepts any other enum but not the reverse' do
- calculator.assignable?(enum_t(), enum_t('a')).should == true
- calculator.assignable?(enum_t('a'), enum_t()).should == false
+ expect(calculator.assignable?(enum_t(), enum_t('a'))).to eq(true)
+ expect(calculator.assignable?(enum_t('a'), enum_t())).to eq(false)
end
it 'enum should accept a variant where all variants are acceptable' do
enum = enum_t('a', 'b')
- calculator.assignable?(enum, variant_t(string_t('a'), string_t('b'))).should == true
+ expect(calculator.assignable?(enum, variant_t(string_t('a'), string_t('b')))).to eq(true)
end
end
context 'when dealing with string and enum combinations' do
it 'should accept assigning any enum to unrestricted string' do
- calculator.assignable?(string_t(), enum_t('blue')).should == true
- calculator.assignable?(string_t(), enum_t('blue', 'red')).should == true
+ expect(calculator.assignable?(string_t(), enum_t('blue'))).to eq(true)
+ expect(calculator.assignable?(string_t(), enum_t('blue', 'red'))).to eq(true)
end
it 'should not accept assigning longer enum value to size restricted string' do
- calculator.assignable?(constrained_t(string_t(),2,2), enum_t('a','blue')).should == false
+ expect(calculator.assignable?(constrained_t(string_t(),2,2), enum_t('a','blue'))).to eq(false)
end
it 'should accept assigning any string to empty enum' do
- calculator.assignable?(enum_t(), string_t()).should == true
+ expect(calculator.assignable?(enum_t(), string_t())).to eq(true)
end
it 'should accept assigning empty enum to any string' do
- calculator.assignable?(string_t(), enum_t()).should == true
+ expect(calculator.assignable?(string_t(), enum_t())).to eq(true)
end
it 'should not accept assigning empty enum to size constrained string' do
- calculator.assignable?(constrained_t(string_t(),2,2), enum_t()).should == false
+ expect(calculator.assignable?(constrained_t(string_t(),2,2), enum_t())).to eq(false)
end
end
context 'when dealing with string/pattern/enum combinations' do
it 'any string is equal to any enum is equal to any pattern' do
- calculator.assignable?(string_t(), enum_t()).should == true
- calculator.assignable?(string_t(), pattern_t()).should == true
- calculator.assignable?(enum_t(), string_t()).should == true
- calculator.assignable?(enum_t(), pattern_t()).should == true
- calculator.assignable?(pattern_t(), string_t()).should == true
- calculator.assignable?(pattern_t(), enum_t()).should == true
+ expect(calculator.assignable?(string_t(), enum_t())).to eq(true)
+ expect(calculator.assignable?(string_t(), pattern_t())).to eq(true)
+ expect(calculator.assignable?(enum_t(), string_t())).to eq(true)
+ expect(calculator.assignable?(enum_t(), pattern_t())).to eq(true)
+ expect(calculator.assignable?(pattern_t(), string_t())).to eq(true)
+ expect(calculator.assignable?(pattern_t(), enum_t())).to eq(true)
end
end
context 'when dealing with tuples' do
it 'matches empty tuples' do
tuple1 = tuple_t()
tuple2 = tuple_t()
- calculator.assignable?(tuple1, tuple2).should == true
- calculator.assignable?(tuple2, tuple1).should == true
+ expect(calculator.assignable?(tuple1, tuple2)).to eq(true)
+ expect(calculator.assignable?(tuple2, tuple1)).to eq(true)
end
it 'accepts an empty tuple as assignable to a tuple with a min size of 0' do
tuple1 = tuple_t(Object)
factory.constrain_size(tuple1, 0, :default)
tuple2 = tuple_t()
- calculator.assignable?(tuple1, tuple2).should == true
- calculator.assignable?(tuple2, tuple1).should == false
+ expect(calculator.assignable?(tuple1, tuple2)).to eq(true)
+ expect(calculator.assignable?(tuple2, tuple1)).to eq(false)
end
it 'should accept matching tuples' do
tuple1 = tuple_t(1,2)
tuple2 = tuple_t(Integer,Integer)
- calculator.assignable?(tuple1, tuple2).should == true
- calculator.assignable?(tuple2, tuple1).should == true
+ expect(calculator.assignable?(tuple1, tuple2)).to eq(true)
+ expect(calculator.assignable?(tuple2, tuple1)).to eq(true)
end
it 'should accept matching tuples where one is more general than the other' do
tuple1 = tuple_t(1,2)
tuple2 = tuple_t(Numeric,Numeric)
- calculator.assignable?(tuple1, tuple2).should == false
- calculator.assignable?(tuple2, tuple1).should == true
+ expect(calculator.assignable?(tuple1, tuple2)).to eq(false)
+ expect(calculator.assignable?(tuple2, tuple1)).to eq(true)
end
it 'should accept ranged tuples' do
tuple1 = tuple_t(1)
factory.constrain_size(tuple1, 5, 5)
tuple2 = tuple_t(Integer,Integer, Integer, Integer, Integer)
- calculator.assignable?(tuple1, tuple2).should == true
- calculator.assignable?(tuple2, tuple1).should == true
+ expect(calculator.assignable?(tuple1, tuple2)).to eq(true)
+ expect(calculator.assignable?(tuple2, tuple1)).to eq(true)
end
it 'should reject ranged tuples when ranges does not match' do
tuple1 = tuple_t(1)
factory.constrain_size(tuple1, 4, 5)
tuple2 = tuple_t(Integer,Integer, Integer, Integer, Integer)
- calculator.assignable?(tuple1, tuple2).should == true
- calculator.assignable?(tuple2, tuple1).should == false
+ expect(calculator.assignable?(tuple1, tuple2)).to eq(true)
+ expect(calculator.assignable?(tuple2, tuple1)).to eq(false)
end
it 'should reject ranged tuples when ranges does not match (using infinite upper bound)' do
tuple1 = tuple_t(1)
factory.constrain_size(tuple1, 4, :default)
tuple2 = tuple_t(Integer,Integer, Integer, Integer, Integer)
- calculator.assignable?(tuple1, tuple2).should == true
- calculator.assignable?(tuple2, tuple1).should == false
+ expect(calculator.assignable?(tuple1, tuple2)).to eq(true)
+ expect(calculator.assignable?(tuple2, tuple1)).to eq(false)
end
it 'should accept matching tuples with optional entries by repeating last' do
tuple1 = tuple_t(1,2)
factory.constrain_size(tuple1, 0, :default)
tuple2 = tuple_t(Numeric,Numeric)
factory.constrain_size(tuple2, 0, :default)
- calculator.assignable?(tuple1, tuple2).should == false
- calculator.assignable?(tuple2, tuple1).should == true
+ expect(calculator.assignable?(tuple1, tuple2)).to eq(false)
+ expect(calculator.assignable?(tuple2, tuple1)).to eq(true)
end
it 'should accept matching tuples with optional entries' do
tuple1 = tuple_t(Integer, Integer, String)
factory.constrain_size(tuple1, 1, 3)
array2 = factory.constrain_size(array_t(Integer),2,2)
- calculator.assignable?(tuple1, array2).should == true
+ expect(calculator.assignable?(tuple1, array2)).to eq(true)
factory.constrain_size(tuple1, 3, 3)
- calculator.assignable?(tuple1, array2).should == false
+ expect(calculator.assignable?(tuple1, array2)).to eq(false)
end
it 'should accept matching array' do
tuple1 = tuple_t(1,2)
array = array_t(Integer)
factory.constrain_size(array, 2, 2)
- calculator.assignable?(tuple1, array).should == true
- calculator.assignable?(array, tuple1).should == true
+ expect(calculator.assignable?(tuple1, array)).to eq(true)
+ expect(calculator.assignable?(array, tuple1)).to eq(true)
end
it 'should accept empty array when tuple allows min of 0' do
tuple1 = tuple_t(Integer)
factory.constrain_size(tuple1, 0, 1)
array = array_t(Integer)
factory.constrain_size(array, 0, 0)
- calculator.assignable?(tuple1, array).should == true
- calculator.assignable?(array, tuple1).should == false
+ expect(calculator.assignable?(tuple1, array)).to eq(true)
+ expect(calculator.assignable?(array, tuple1)).to eq(false)
end
end
context 'when dealing with structs' do
it 'should accept matching structs' do
struct1 = struct_t({'a'=>Integer, 'b'=>Integer})
struct2 = struct_t({'a'=>Integer, 'b'=>Integer})
- calculator.assignable?(struct1, struct2).should == true
- calculator.assignable?(struct2, struct1).should == true
+ expect(calculator.assignable?(struct1, struct2)).to eq(true)
+ expect(calculator.assignable?(struct2, struct1)).to eq(true)
end
it 'should accept matching structs where one is more general than the other' do
struct1 = struct_t({'a'=>Integer, 'b'=>Integer})
struct2 = struct_t({'a'=>Numeric, 'b'=>Numeric})
- calculator.assignable?(struct1, struct2).should == false
- calculator.assignable?(struct2, struct1).should == true
+ expect(calculator.assignable?(struct1, struct2)).to eq(false)
+ expect(calculator.assignable?(struct2, struct1)).to eq(true)
end
it 'should accept matching hash' do
struct1 = struct_t({'a'=>Integer, 'b'=>Integer})
non_empty_string = string_t()
non_empty_string.size_type = range_t(1, nil)
hsh = hash_t(non_empty_string, Integer)
factory.constrain_size(hsh, 2, 2)
- calculator.assignable?(struct1, hsh).should == true
- calculator.assignable?(hsh, struct1).should == true
+ expect(calculator.assignable?(struct1, hsh)).to eq(true)
+ expect(calculator.assignable?(hsh, struct1)).to eq(true)
end
end
it 'should recognize ruby type inheritance' do
class Foo
end
class Bar < Foo
end
fooType = calculator.infer(Foo.new)
barType = calculator.infer(Bar.new)
- calculator.assignable?(fooType, fooType).should == true
- calculator.assignable?(Foo, fooType).should == true
+ expect(calculator.assignable?(fooType, fooType)).to eq(true)
+ expect(calculator.assignable?(Foo, fooType)).to eq(true)
- calculator.assignable?(fooType, barType).should == true
- calculator.assignable?(Foo, barType).should == true
+ expect(calculator.assignable?(fooType, barType)).to eq(true)
+ expect(calculator.assignable?(Foo, barType)).to eq(true)
- calculator.assignable?(barType, fooType).should == false
- calculator.assignable?(Bar, fooType).should == false
+ expect(calculator.assignable?(barType, fooType)).to eq(false)
+ expect(calculator.assignable?(Bar, fooType)).to eq(false)
end
it "should allow host class with same name" do
hc1 = Puppet::Pops::Types::TypeFactory.host_class('the_name')
hc2 = Puppet::Pops::Types::TypeFactory.host_class('the_name')
- calculator.assignable?(hc1, hc2).should == true
+ expect(calculator.assignable?(hc1, hc2)).to eq(true)
end
it "should allow host class with name assigned to hostclass without name" do
hc1 = Puppet::Pops::Types::TypeFactory.host_class()
hc2 = Puppet::Pops::Types::TypeFactory.host_class('the_name')
- calculator.assignable?(hc1, hc2).should == true
+ expect(calculator.assignable?(hc1, hc2)).to eq(true)
end
it "should reject host classes with different names" do
hc1 = Puppet::Pops::Types::TypeFactory.host_class('the_name')
hc2 = Puppet::Pops::Types::TypeFactory.host_class('another_name')
- calculator.assignable?(hc1, hc2).should == false
+ expect(calculator.assignable?(hc1, hc2)).to eq(false)
end
it "should reject host classes without name assigned to host class with name" do
hc1 = Puppet::Pops::Types::TypeFactory.host_class('the_name')
hc2 = Puppet::Pops::Types::TypeFactory.host_class()
- calculator.assignable?(hc1, hc2).should == false
+ expect(calculator.assignable?(hc1, hc2)).to eq(false)
end
it "should allow resource with same type_name and title" do
r1 = Puppet::Pops::Types::TypeFactory.resource('file', 'foo')
r2 = Puppet::Pops::Types::TypeFactory.resource('file', 'foo')
- calculator.assignable?(r1, r2).should == true
+ expect(calculator.assignable?(r1, r2)).to eq(true)
end
it "should allow more specific resource assignment" do
r1 = Puppet::Pops::Types::TypeFactory.resource()
r2 = Puppet::Pops::Types::TypeFactory.resource('file')
- calculator.assignable?(r1, r2).should == true
+ expect(calculator.assignable?(r1, r2)).to eq(true)
r2 = Puppet::Pops::Types::TypeFactory.resource('file', '/tmp/foo')
- calculator.assignable?(r1, r2).should == true
+ expect(calculator.assignable?(r1, r2)).to eq(true)
r1 = Puppet::Pops::Types::TypeFactory.resource('file')
- calculator.assignable?(r1, r2).should == true
+ expect(calculator.assignable?(r1, r2)).to eq(true)
end
it "should reject less specific resource assignment" do
r1 = Puppet::Pops::Types::TypeFactory.resource('file', '/tmp/foo')
r2 = Puppet::Pops::Types::TypeFactory.resource('file')
- calculator.assignable?(r1, r2).should == false
+ expect(calculator.assignable?(r1, r2)).to eq(false)
r2 = Puppet::Pops::Types::TypeFactory.resource()
- calculator.assignable?(r1, r2).should == false
+ expect(calculator.assignable?(r1, r2)).to eq(false)
end
end
context 'when testing if x is instance of type t' do
include_context "types_setup"
it 'should consider undef to be instance of Any, NilType, and optional' do
- calculator.instance?(Puppet::Pops::Types::PNilType.new(), nil).should == true
- calculator.instance?(Puppet::Pops::Types::PAnyType.new(), nil).should == true
- calculator.instance?(Puppet::Pops::Types::POptionalType.new(), nil).should == true
+ expect(calculator.instance?(Puppet::Pops::Types::PNilType.new(), nil)).to eq(true)
+ expect(calculator.instance?(Puppet::Pops::Types::PAnyType.new(), nil)).to eq(true)
+ expect(calculator.instance?(Puppet::Pops::Types::POptionalType.new(), nil)).to eq(true)
end
it 'all types should be (ruby) instance of PAnyType' do
all_types.each do |t|
- t.new.is_a?(Puppet::Pops::Types::PAnyType).should == true
+ expect(t.new.is_a?(Puppet::Pops::Types::PAnyType)).to eq(true)
end
end
it "should consider :undef to be instance of Runtime['ruby', 'Symbol]" do
- calculator.instance?(Puppet::Pops::Types::PRuntimeType.new(:runtime => :ruby, :runtime_type_name => 'Symbol'), :undef).should == true
+ expect(calculator.instance?(Puppet::Pops::Types::PRuntimeType.new(:runtime => :ruby, :runtime_type_name => 'Symbol'), :undef)).to eq(true)
end
it "should consider :undef to be instance of an Optional type" do
- calculator.instance?(Puppet::Pops::Types::POptionalType.new(), :undef).should == true
+ expect(calculator.instance?(Puppet::Pops::Types::POptionalType.new(), :undef)).to eq(true)
end
it 'should not consider undef to be an instance of any other type than Any, NilType and Data' do
types_to_test = all_types - [
Puppet::Pops::Types::PAnyType,
Puppet::Pops::Types::PNilType,
Puppet::Pops::Types::PDataType,
Puppet::Pops::Types::POptionalType,
]
- types_to_test.each {|t| calculator.instance?(t.new, nil).should == false }
- types_to_test.each {|t| calculator.instance?(t.new, :undef).should == false }
+ types_to_test.each {|t| expect(calculator.instance?(t.new, nil)).to eq(false) }
+ types_to_test.each {|t| expect(calculator.instance?(t.new, :undef)).to eq(false) }
end
it 'should consider default to be instance of Default and Any' do
- calculator.instance?(Puppet::Pops::Types::PDefaultType.new(), :default).should == true
- calculator.instance?(Puppet::Pops::Types::PAnyType.new(), :default).should == true
+ expect(calculator.instance?(Puppet::Pops::Types::PDefaultType.new(), :default)).to eq(true)
+ expect(calculator.instance?(Puppet::Pops::Types::PAnyType.new(), :default)).to eq(true)
end
it 'should not consider "default" to be an instance of anything but Default, and Any' do
types_to_test = all_types - [
Puppet::Pops::Types::PAnyType,
Puppet::Pops::Types::PDefaultType,
]
- types_to_test.each {|t| calculator.instance?(t.new, :default).should == false }
+ types_to_test.each {|t| expect(calculator.instance?(t.new, :default)).to eq(false) }
end
it 'should consider fixnum instanceof PIntegerType' do
- calculator.instance?(Puppet::Pops::Types::PIntegerType.new(), 1).should == true
+ expect(calculator.instance?(Puppet::Pops::Types::PIntegerType.new(), 1)).to eq(true)
end
it 'should consider fixnum instanceof Fixnum' do
- calculator.instance?(Fixnum, 1).should == true
+ expect(calculator.instance?(Fixnum, 1)).to eq(true)
end
it 'should consider integer in range' do
range = range_t(0,10)
- calculator.instance?(range, 1).should == true
- calculator.instance?(range, 10).should == true
- calculator.instance?(range, -1).should == false
- calculator.instance?(range, 11).should == false
+ expect(calculator.instance?(range, 1)).to eq(true)
+ expect(calculator.instance?(range, 10)).to eq(true)
+ expect(calculator.instance?(range, -1)).to eq(false)
+ expect(calculator.instance?(range, 11)).to eq(false)
end
it 'should consider string in length range' do
range = factory.constrain_size(string_t, 1,3)
- calculator.instance?(range, 'a').should == true
- calculator.instance?(range, 'abc').should == true
- calculator.instance?(range, '').should == false
- calculator.instance?(range, 'abcd').should == false
+ expect(calculator.instance?(range, 'a')).to eq(true)
+ expect(calculator.instance?(range, 'abc')).to eq(true)
+ expect(calculator.instance?(range, '')).to eq(false)
+ expect(calculator.instance?(range, 'abcd')).to eq(false)
end
it 'should consider array in length range' do
range = factory.constrain_size(array_t(integer_t), 1,3)
- calculator.instance?(range, [1]).should == true
- calculator.instance?(range, [1,2,3]).should == true
- calculator.instance?(range, []).should == false
- calculator.instance?(range, [1,2,3,4]).should == false
+ expect(calculator.instance?(range, [1])).to eq(true)
+ expect(calculator.instance?(range, [1,2,3])).to eq(true)
+ expect(calculator.instance?(range, [])).to eq(false)
+ expect(calculator.instance?(range, [1,2,3,4])).to eq(false)
end
it 'should consider hash in length range' do
range = factory.constrain_size(hash_t(integer_t, integer_t), 1,2)
- calculator.instance?(range, {1=>1}).should == true
- calculator.instance?(range, {1=>1, 2=>2}).should == true
- calculator.instance?(range, {}).should == false
- calculator.instance?(range, {1=>1, 2=>2, 3=>3}).should == false
+ expect(calculator.instance?(range, {1=>1})).to eq(true)
+ expect(calculator.instance?(range, {1=>1, 2=>2})).to eq(true)
+ expect(calculator.instance?(range, {})).to eq(false)
+ expect(calculator.instance?(range, {1=>1, 2=>2, 3=>3})).to eq(false)
end
it 'should consider collection in length range for array ' do
range = factory.constrain_size(collection_t, 1,3)
- calculator.instance?(range, [1]).should == true
- calculator.instance?(range, [1,2,3]).should == true
- calculator.instance?(range, []).should == false
- calculator.instance?(range, [1,2,3,4]).should == false
+ expect(calculator.instance?(range, [1])).to eq(true)
+ expect(calculator.instance?(range, [1,2,3])).to eq(true)
+ expect(calculator.instance?(range, [])).to eq(false)
+ expect(calculator.instance?(range, [1,2,3,4])).to eq(false)
end
it 'should consider collection in length range for hash' do
range = factory.constrain_size(collection_t, 1,2)
- calculator.instance?(range, {1=>1}).should == true
- calculator.instance?(range, {1=>1, 2=>2}).should == true
- calculator.instance?(range, {}).should == false
- calculator.instance?(range, {1=>1, 2=>2, 3=>3}).should == false
+ expect(calculator.instance?(range, {1=>1})).to eq(true)
+ expect(calculator.instance?(range, {1=>1, 2=>2})).to eq(true)
+ expect(calculator.instance?(range, {})).to eq(false)
+ expect(calculator.instance?(range, {1=>1, 2=>2, 3=>3})).to eq(false)
end
it 'should consider string matching enum as instanceof' do
enum = enum_t('XS', 'S', 'M', 'L', 'XL', '0')
- calculator.instance?(enum, 'XS').should == true
- calculator.instance?(enum, 'S').should == true
- calculator.instance?(enum, 'XXL').should == false
- calculator.instance?(enum, '').should == false
- calculator.instance?(enum, '0').should == true
- calculator.instance?(enum, 0).should == false
+ expect(calculator.instance?(enum, 'XS')).to eq(true)
+ expect(calculator.instance?(enum, 'S')).to eq(true)
+ expect(calculator.instance?(enum, 'XXL')).to eq(false)
+ expect(calculator.instance?(enum, '')).to eq(false)
+ expect(calculator.instance?(enum, '0')).to eq(true)
+ expect(calculator.instance?(enum, 0)).to eq(false)
end
it 'should consider array[string] as instance of Array[Enum] when strings are instance of Enum' do
enum = enum_t('XS', 'S', 'M', 'L', 'XL', '0')
array = array_t(enum)
- calculator.instance?(array, ['XS', 'S', 'XL']).should == true
- calculator.instance?(array, ['XS', 'S', 'XXL']).should == false
+ expect(calculator.instance?(array, ['XS', 'S', 'XL'])).to eq(true)
+ expect(calculator.instance?(array, ['XS', 'S', 'XXL'])).to eq(false)
end
it 'should consider array[mixed] as instance of Variant[mixed] when mixed types are listed in Variant' do
enum = enum_t('XS', 'S', 'M', 'L', 'XL')
sizes = range_t(30, 50)
array = array_t(variant_t(enum, sizes))
- calculator.instance?(array, ['XS', 'S', 30, 50]).should == true
- calculator.instance?(array, ['XS', 'S', 'XXL']).should == false
- calculator.instance?(array, ['XS', 'S', 29]).should == false
+ expect(calculator.instance?(array, ['XS', 'S', 30, 50])).to eq(true)
+ expect(calculator.instance?(array, ['XS', 'S', 'XXL'])).to eq(false)
+ expect(calculator.instance?(array, ['XS', 'S', 29])).to eq(false)
end
it 'should consider array[seq] as instance of Tuple[seq] when elements of seq are instance of' do
tuple = tuple_t(Integer, String, Float)
- calculator.instance?(tuple, [1, 'a', 3.14]).should == true
- calculator.instance?(tuple, [1.2, 'a', 3.14]).should == false
- calculator.instance?(tuple, [1, 1, 3.14]).should == false
- calculator.instance?(tuple, [1, 'a', 1]).should == false
+ expect(calculator.instance?(tuple, [1, 'a', 3.14])).to eq(true)
+ expect(calculator.instance?(tuple, [1.2, 'a', 3.14])).to eq(false)
+ expect(calculator.instance?(tuple, [1, 1, 3.14])).to eq(false)
+ expect(calculator.instance?(tuple, [1, 'a', 1])).to eq(false)
end
it 'should consider hash[cont] as instance of Struct[cont-t]' do
struct = struct_t({'a'=>Integer, 'b'=>String, 'c'=>Float})
- calculator.instance?(struct, {'a'=>1, 'b'=>'a', 'c'=>3.14}).should == true
- calculator.instance?(struct, {'a'=>1.2, 'b'=>'a', 'c'=>3.14}).should == false
- calculator.instance?(struct, {'a'=>1, 'b'=>1, 'c'=>3.14}).should == false
- calculator.instance?(struct, {'a'=>1, 'b'=>'a', 'c'=>1}).should == false
+ expect(calculator.instance?(struct, {'a'=>1, 'b'=>'a', 'c'=>3.14})).to eq(true)
+ expect(calculator.instance?(struct, {'a'=>1.2, 'b'=>'a', 'c'=>3.14})).to eq(false)
+ expect(calculator.instance?(struct, {'a'=>1, 'b'=>1, 'c'=>3.14})).to eq(false)
+ expect(calculator.instance?(struct, {'a'=>1, 'b'=>'a', 'c'=>1})).to eq(false)
end
context 'and t is Data' do
it 'undef should be considered instance of Data' do
- calculator.instance?(data_t, nil).should == true
+ expect(calculator.instance?(data_t, nil)).to eq(true)
end
it 'other symbols should not be considered instance of Data' do
- calculator.instance?(data_t, :love).should == false
+ expect(calculator.instance?(data_t, :love)).to eq(false)
end
it 'an empty array should be considered instance of Data' do
- calculator.instance?(data_t, []).should == true
+ expect(calculator.instance?(data_t, [])).to eq(true)
end
it 'an empty hash should be considered instance of Data' do
- calculator.instance?(data_t, {}).should == true
+ expect(calculator.instance?(data_t, {})).to eq(true)
end
it 'a hash with nil/undef data should be considered instance of Data' do
- calculator.instance?(data_t, {'a' => nil}).should == true
+ expect(calculator.instance?(data_t, {'a' => nil})).to eq(true)
end
it 'a hash with nil/default key should not considered instance of Data' do
- calculator.instance?(data_t, {nil => 10}).should == false
- calculator.instance?(data_t, {:default => 10}).should == false
+ expect(calculator.instance?(data_t, {nil => 10})).to eq(false)
+ expect(calculator.instance?(data_t, {:default => 10})).to eq(false)
end
it 'an array with nil entries should be considered instance of Data' do
- calculator.instance?(data_t, [nil]).should == true
+ expect(calculator.instance?(data_t, [nil])).to eq(true)
end
it 'an array with nil + data entries should be considered instance of Data' do
- calculator.instance?(data_t, [1, nil, 'a']).should == true
+ expect(calculator.instance?(data_t, [1, nil, 'a'])).to eq(true)
end
end
context "and t is something Callable" do
it 'a Closure should be considered a Callable' do
factory = Puppet::Pops::Model::Factory
params = [factory.PARAM('a')]
the_block = factory.LAMBDA(params,factory.literal(42))
the_closure = Puppet::Pops::Evaluator::Closure.new(:fake_evaluator, the_block, :fake_scope)
- expect(calculator.instance?(all_callables_t, the_closure)).to be_true
- expect(calculator.instance?(callable_t(object_t), the_closure)).to be_true
- expect(calculator.instance?(callable_t(object_t, object_t), the_closure)).to be_false
+ expect(calculator.instance?(all_callables_t, the_closure)).to be_truthy
+ expect(calculator.instance?(callable_t(object_t), the_closure)).to be_truthy
+ expect(calculator.instance?(callable_t(object_t, object_t), the_closure)).to be_falsey
end
it 'a Function instance should be considered a Callable' do
fc = Puppet::Functions.create_function(:foo) do
dispatch :foo do
param 'String', :a
end
def foo(a)
a
end
end
f = fc.new(:closure_scope, :loader)
# Any callable
- expect(calculator.instance?(all_callables_t, f)).to be_true
+ expect(calculator.instance?(all_callables_t, f)).to be_truthy
# Callable[String]
- expect(calculator.instance?(callable_t(String), f)).to be_true
+ expect(calculator.instance?(callable_t(String), f)).to be_truthy
end
end
end
context 'when converting a ruby class' do
it 'should yield \'PIntegerType\' for Integer, Fixnum, and Bignum' do
[Integer,Fixnum,Bignum].each do |c|
- calculator.type(c).class.should == Puppet::Pops::Types::PIntegerType
+ expect(calculator.type(c).class).to eq(Puppet::Pops::Types::PIntegerType)
end
end
it 'should yield \'PFloatType\' for Float' do
- calculator.type(Float).class.should == Puppet::Pops::Types::PFloatType
+ expect(calculator.type(Float).class).to eq(Puppet::Pops::Types::PFloatType)
end
it 'should yield \'PBooleanType\' for FalseClass and TrueClass' do
[FalseClass,TrueClass].each do |c|
- calculator.type(c).class.should == Puppet::Pops::Types::PBooleanType
+ expect(calculator.type(c).class).to eq(Puppet::Pops::Types::PBooleanType)
end
end
it 'should yield \'PNilType\' for NilClass' do
- calculator.type(NilClass).class.should == Puppet::Pops::Types::PNilType
+ expect(calculator.type(NilClass).class).to eq(Puppet::Pops::Types::PNilType)
end
it 'should yield \'PStringType\' for String' do
- calculator.type(String).class.should == Puppet::Pops::Types::PStringType
+ expect(calculator.type(String).class).to eq(Puppet::Pops::Types::PStringType)
end
it 'should yield \'PRegexpType\' for Regexp' do
- calculator.type(Regexp).class.should == Puppet::Pops::Types::PRegexpType
+ expect(calculator.type(Regexp).class).to eq(Puppet::Pops::Types::PRegexpType)
end
it 'should yield \'PArrayType[PDataType]\' for Array' do
t = calculator.type(Array)
- t.class.should == Puppet::Pops::Types::PArrayType
- t.element_type.class.should == Puppet::Pops::Types::PDataType
+ expect(t.class).to eq(Puppet::Pops::Types::PArrayType)
+ expect(t.element_type.class).to eq(Puppet::Pops::Types::PDataType)
end
it 'should yield \'PHashType[PScalarType,PDataType]\' for Hash' do
t = calculator.type(Hash)
- t.class.should == Puppet::Pops::Types::PHashType
- t.key_type.class.should == Puppet::Pops::Types::PScalarType
- t.element_type.class.should == Puppet::Pops::Types::PDataType
+ expect(t.class).to eq(Puppet::Pops::Types::PHashType)
+ expect(t.key_type.class).to eq(Puppet::Pops::Types::PScalarType)
+ expect(t.element_type.class).to eq(Puppet::Pops::Types::PDataType)
end
end
context 'when representing the type as string' do
it 'should yield \'Type\' for PType' do
- calculator.string(Puppet::Pops::Types::PType.new()).should == 'Type'
+ expect(calculator.string(Puppet::Pops::Types::PType.new())).to eq('Type')
end
it 'should yield \'Object\' for PAnyType' do
- calculator.string(Puppet::Pops::Types::PAnyType.new()).should == 'Any'
+ expect(calculator.string(Puppet::Pops::Types::PAnyType.new())).to eq('Any')
end
it 'should yield \'Scalar\' for PScalarType' do
- calculator.string(Puppet::Pops::Types::PScalarType.new()).should == 'Scalar'
+ expect(calculator.string(Puppet::Pops::Types::PScalarType.new())).to eq('Scalar')
end
it 'should yield \'Boolean\' for PBooleanType' do
- calculator.string(Puppet::Pops::Types::PBooleanType.new()).should == 'Boolean'
+ expect(calculator.string(Puppet::Pops::Types::PBooleanType.new())).to eq('Boolean')
end
it 'should yield \'Data\' for PDataType' do
- calculator.string(Puppet::Pops::Types::PDataType.new()).should == 'Data'
+ expect(calculator.string(Puppet::Pops::Types::PDataType.new())).to eq('Data')
end
it 'should yield \'Numeric\' for PNumericType' do
- calculator.string(Puppet::Pops::Types::PNumericType.new()).should == 'Numeric'
+ expect(calculator.string(Puppet::Pops::Types::PNumericType.new())).to eq('Numeric')
end
it 'should yield \'Integer\' and from/to for PIntegerType' do
int_T = Puppet::Pops::Types::PIntegerType
- calculator.string(int_T.new()).should == 'Integer'
+ expect(calculator.string(int_T.new())).to eq('Integer')
int = int_T.new()
int.from = 1
int.to = 1
- calculator.string(int).should == 'Integer[1, 1]'
+ expect(calculator.string(int)).to eq('Integer[1, 1]')
int = int_T.new()
int.from = 1
int.to = 2
- calculator.string(int).should == 'Integer[1, 2]'
+ expect(calculator.string(int)).to eq('Integer[1, 2]')
int = int_T.new()
int.from = nil
int.to = 2
- calculator.string(int).should == 'Integer[default, 2]'
+ expect(calculator.string(int)).to eq('Integer[default, 2]')
int = int_T.new()
int.from = 2
int.to = nil
- calculator.string(int).should == 'Integer[2, default]'
+ expect(calculator.string(int)).to eq('Integer[2, default]')
end
it 'should yield \'Float\' for PFloatType' do
- calculator.string(Puppet::Pops::Types::PFloatType.new()).should == 'Float'
+ expect(calculator.string(Puppet::Pops::Types::PFloatType.new())).to eq('Float')
end
it 'should yield \'Regexp\' for PRegexpType' do
- calculator.string(Puppet::Pops::Types::PRegexpType.new()).should == 'Regexp'
+ expect(calculator.string(Puppet::Pops::Types::PRegexpType.new())).to eq('Regexp')
end
it 'should yield \'Regexp[/pat/]\' for parameterized PRegexpType' do
t = Puppet::Pops::Types::PRegexpType.new()
t.pattern = ('a/b')
- calculator.string(Puppet::Pops::Types::PRegexpType.new()).should == 'Regexp'
+ expect(calculator.string(Puppet::Pops::Types::PRegexpType.new())).to eq('Regexp')
end
it 'should yield \'String\' for PStringType' do
- calculator.string(Puppet::Pops::Types::PStringType.new()).should == 'String'
+ expect(calculator.string(Puppet::Pops::Types::PStringType.new())).to eq('String')
end
it 'should yield \'String\' for PStringType with multiple values' do
- calculator.string(string_t('a', 'b', 'c')).should == 'String'
+ expect(calculator.string(string_t('a', 'b', 'c'))).to eq('String')
end
it 'should yield \'String\' and from/to for PStringType' do
string_T = Puppet::Pops::Types::PStringType
- calculator.string(factory.constrain_size(string_T.new(), 1,1)).should == 'String[1, 1]'
- calculator.string(factory.constrain_size(string_T.new(), 1,2)).should == 'String[1, 2]'
- calculator.string(factory.constrain_size(string_T.new(), :default, 2)).should == 'String[default, 2]'
- calculator.string(factory.constrain_size(string_T.new(), 2, :default)).should == 'String[2, default]'
+ expect(calculator.string(factory.constrain_size(string_T.new(), 1,1))).to eq('String[1, 1]')
+ expect(calculator.string(factory.constrain_size(string_T.new(), 1,2))).to eq('String[1, 2]')
+ expect(calculator.string(factory.constrain_size(string_T.new(), :default, 2))).to eq('String[default, 2]')
+ expect(calculator.string(factory.constrain_size(string_T.new(), 2, :default))).to eq('String[2, default]')
end
it 'should yield \'Array[Integer]\' for PArrayType[PIntegerType]' do
t = Puppet::Pops::Types::PArrayType.new()
t.element_type = Puppet::Pops::Types::PIntegerType.new()
- calculator.string(t).should == 'Array[Integer]'
+ expect(calculator.string(t)).to eq('Array[Integer]')
end
it 'should yield \'Collection\' and from/to for PCollectionType' do
col = collection_t()
- calculator.string(factory.constrain_size(col.copy, 1,1)).should == 'Collection[1, 1]'
- calculator.string(factory.constrain_size(col.copy, 1,2)).should == 'Collection[1, 2]'
- calculator.string(factory.constrain_size(col.copy, :default, 2)).should == 'Collection[default, 2]'
- calculator.string(factory.constrain_size(col.copy, 2, :default)).should == 'Collection[2, default]'
+ expect(calculator.string(factory.constrain_size(col.copy, 1,1))).to eq('Collection[1, 1]')
+ expect(calculator.string(factory.constrain_size(col.copy, 1,2))).to eq('Collection[1, 2]')
+ expect(calculator.string(factory.constrain_size(col.copy, :default, 2))).to eq('Collection[default, 2]')
+ expect(calculator.string(factory.constrain_size(col.copy, 2, :default))).to eq('Collection[2, default]')
end
it 'should yield \'Array\' and from/to for PArrayType' do
arr = array_t(string_t)
- calculator.string(factory.constrain_size(arr.copy, 1,1)).should == 'Array[String, 1, 1]'
- calculator.string(factory.constrain_size(arr.copy, 1,2)).should == 'Array[String, 1, 2]'
- calculator.string(factory.constrain_size(arr.copy, :default, 2)).should == 'Array[String, default, 2]'
- calculator.string(factory.constrain_size(arr.copy, 2, :default)).should == 'Array[String, 2, default]'
+ expect(calculator.string(factory.constrain_size(arr.copy, 1,1))).to eq('Array[String, 1, 1]')
+ expect(calculator.string(factory.constrain_size(arr.copy, 1,2))).to eq('Array[String, 1, 2]')
+ expect(calculator.string(factory.constrain_size(arr.copy, :default, 2))).to eq('Array[String, default, 2]')
+ expect(calculator.string(factory.constrain_size(arr.copy, 2, :default))).to eq('Array[String, 2, default]')
end
it 'should yield \'Tuple[Integer]\' for PTupleType[PIntegerType]' do
t = Puppet::Pops::Types::PTupleType.new()
t.addTypes(Puppet::Pops::Types::PIntegerType.new())
- calculator.string(t).should == 'Tuple[Integer]'
+ expect(calculator.string(t)).to eq('Tuple[Integer]')
end
it 'should yield \'Tuple[T, T,..]\' for PTupleType[T, T, ...]' do
t = Puppet::Pops::Types::PTupleType.new()
t.addTypes(Puppet::Pops::Types::PIntegerType.new())
t.addTypes(Puppet::Pops::Types::PIntegerType.new())
t.addTypes(Puppet::Pops::Types::PStringType.new())
- calculator.string(t).should == 'Tuple[Integer, Integer, String]'
+ expect(calculator.string(t)).to eq('Tuple[Integer, Integer, String]')
end
it 'should yield \'Tuple\' and from/to for PTupleType' do
tuple_t = tuple_t(string_t)
- calculator.string(factory.constrain_size(tuple_t.copy, 1,1)).should == 'Tuple[String, 1, 1]'
- calculator.string(factory.constrain_size(tuple_t.copy, 1,2)).should == 'Tuple[String, 1, 2]'
- calculator.string(factory.constrain_size(tuple_t.copy, :default, 2)).should == 'Tuple[String, default, 2]'
- calculator.string(factory.constrain_size(tuple_t.copy, 2, :default)).should == 'Tuple[String, 2, default]'
+ expect(calculator.string(factory.constrain_size(tuple_t.copy, 1,1))).to eq('Tuple[String, 1, 1]')
+ expect(calculator.string(factory.constrain_size(tuple_t.copy, 1,2))).to eq('Tuple[String, 1, 2]')
+ expect(calculator.string(factory.constrain_size(tuple_t.copy, :default, 2))).to eq('Tuple[String, default, 2]')
+ expect(calculator.string(factory.constrain_size(tuple_t.copy, 2, :default))).to eq('Tuple[String, 2, default]')
end
it 'should yield \'Struct\' and details for PStructType' do
struct_t = struct_t({'a'=>Integer, 'b'=>String})
- calculator.string(struct_t).should == "Struct[{'a'=>Integer, 'b'=>String}]"
+ expect(calculator.string(struct_t)).to eq("Struct[{'a'=>Integer, 'b'=>String}]")
struct_t = struct_t({})
- calculator.string(struct_t).should == "Struct"
+ expect(calculator.string(struct_t)).to eq("Struct")
end
it 'should yield \'Hash[String, Integer]\' for PHashType[PStringType, PIntegerType]' do
t = Puppet::Pops::Types::PHashType.new()
t.key_type = Puppet::Pops::Types::PStringType.new()
t.element_type = Puppet::Pops::Types::PIntegerType.new()
- calculator.string(t).should == 'Hash[String, Integer]'
+ expect(calculator.string(t)).to eq('Hash[String, Integer]')
end
it 'should yield \'Hash\' and from/to for PHashType' do
hsh = hash_t(string_t, string_t)
- calculator.string(factory.constrain_size(hsh.copy, 1,1)).should == 'Hash[String, String, 1, 1]'
- calculator.string(factory.constrain_size(hsh.copy, 1,2)).should == 'Hash[String, String, 1, 2]'
- calculator.string(factory.constrain_size(hsh.copy, :default, 2)).should == 'Hash[String, String, default, 2]'
- calculator.string(factory.constrain_size(hsh.copy, 2, :default)).should == 'Hash[String, String, 2, default]'
+ expect(calculator.string(factory.constrain_size(hsh.copy, 1,1))).to eq('Hash[String, String, 1, 1]')
+ expect(calculator.string(factory.constrain_size(hsh.copy, 1,2))).to eq('Hash[String, String, 1, 2]')
+ expect(calculator.string(factory.constrain_size(hsh.copy, :default, 2))).to eq('Hash[String, String, default, 2]')
+ expect(calculator.string(factory.constrain_size(hsh.copy, 2, :default))).to eq('Hash[String, String, 2, default]')
end
it "should yield 'Class' for a PHostClassType" do
t = Puppet::Pops::Types::PHostClassType.new()
- calculator.string(t).should == 'Class'
+ expect(calculator.string(t)).to eq('Class')
end
it "should yield 'Class[x]' for a PHostClassType[x]" do
t = Puppet::Pops::Types::PHostClassType.new()
t.class_name = 'x'
- calculator.string(t).should == 'Class[x]'
+ expect(calculator.string(t)).to eq('Class[x]')
end
it "should yield 'Resource' for a PResourceType" do
t = Puppet::Pops::Types::PResourceType.new()
- calculator.string(t).should == 'Resource'
+ expect(calculator.string(t)).to eq('Resource')
end
it 'should yield \'File\' for a PResourceType[\'File\']' do
t = Puppet::Pops::Types::PResourceType.new()
t.type_name = 'File'
- calculator.string(t).should == 'File'
+ expect(calculator.string(t)).to eq('File')
end
it "should yield 'File['/tmp/foo']' for a PResourceType['File', '/tmp/foo']" do
t = Puppet::Pops::Types::PResourceType.new()
t.type_name = 'File'
t.title = '/tmp/foo'
- calculator.string(t).should == "File['/tmp/foo']"
+ expect(calculator.string(t)).to eq("File['/tmp/foo']")
end
it "should yield 'Enum[s,...]' for a PEnumType[s,...]" do
t = enum_t('a', 'b', 'c')
- calculator.string(t).should == "Enum['a', 'b', 'c']"
+ expect(calculator.string(t)).to eq("Enum['a', 'b', 'c']")
end
it "should yield 'Pattern[/pat/,...]' for a PPatternType['pat',...]" do
t = pattern_t('a')
t2 = pattern_t('a', 'b', 'c')
- calculator.string(t).should == "Pattern[/a/]"
- calculator.string(t2).should == "Pattern[/a/, /b/, /c/]"
+ expect(calculator.string(t)).to eq("Pattern[/a/]")
+ expect(calculator.string(t2)).to eq("Pattern[/a/, /b/, /c/]")
end
it "should escape special characters in the string for a PPatternType['pat',...]" do
t = pattern_t('a/b')
- calculator.string(t).should == "Pattern[/a\\/b/]"
+ expect(calculator.string(t)).to eq("Pattern[/a\\/b/]")
end
it "should yield 'Variant[t1,t2,...]' for a PVariantType[t1, t2,...]" do
t1 = string_t()
t2 = integer_t()
t3 = pattern_t('a')
t = variant_t(t1, t2, t3)
- calculator.string(t).should == "Variant[String, Integer, Pattern[/a/]]"
+ expect(calculator.string(t)).to eq("Variant[String, Integer, Pattern[/a/]]")
end
it "should yield 'Callable' for generic callable" do
expect(calculator.string(all_callables_t)).to eql("Callable")
end
it "should yield 'Callable[0,0]' for callable without params" do
expect(calculator.string(callable_t)).to eql("Callable[0, 0]")
end
it "should yield 'Callable[t,t]' for callable with typed parameters" do
expect(calculator.string(callable_t(String, Integer))).to eql("Callable[String, Integer]")
end
it "should yield 'Callable[t,min,max]' for callable with size constraint (infinite max)" do
expect(calculator.string(callable_t(String, 0))).to eql("Callable[String, 0, default]")
end
it "should yield 'Callable[t,min,max]' for callable with size constraint (capped max)" do
expect(calculator.string(callable_t(String, 0, 3))).to eql("Callable[String, 0, 3]")
end
it "should yield 'Callable[min,max]' callable with size > 0" do
expect(calculator.string(callable_t(0, 0))).to eql("Callable[0, 0]")
expect(calculator.string(callable_t(0, 1))).to eql("Callable[0, 1]")
expect(calculator.string(callable_t(0, :default))).to eql("Callable[0, default]")
end
it "should yield 'Callable[Callable]' for callable with block" do
expect(calculator.string(callable_t(all_callables_t))).to eql("Callable[0, 0, Callable]")
expect(calculator.string(callable_t(string_t, all_callables_t))).to eql("Callable[String, Callable]")
expect(calculator.string(callable_t(string_t, 1,1, all_callables_t))).to eql("Callable[String, 1, 1, Callable]")
end
it "should yield Unit for a Unit type" do
expect(calculator.string(unit_t)).to eql('Unit')
end
end
context 'when processing meta type' do
it 'should infer PType as the type of all other types' do
ptype = Puppet::Pops::Types::PType
- calculator.infer(Puppet::Pops::Types::PNilType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PDataType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PScalarType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PStringType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PNumericType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PIntegerType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PFloatType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PRegexpType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PBooleanType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PCollectionType.new()).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PArrayType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PHashType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PRuntimeType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PHostClassType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PResourceType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PEnumType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PPatternType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PVariantType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PTupleType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::POptionalType.new() ).is_a?(ptype).should() == true
- calculator.infer(Puppet::Pops::Types::PCallableType.new() ).is_a?(ptype).should() == true
+ expect(calculator.infer(Puppet::Pops::Types::PNilType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PDataType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PScalarType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PStringType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PNumericType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PIntegerType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PFloatType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PRegexpType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PBooleanType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PCollectionType.new()).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PArrayType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PHashType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PRuntimeType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PHostClassType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PResourceType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PEnumType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PPatternType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PVariantType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PTupleType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::POptionalType.new() ).is_a?(ptype)).to eq(true)
+ expect(calculator.infer(Puppet::Pops::Types::PCallableType.new() ).is_a?(ptype)).to eq(true)
end
it 'should infer PType as the type of all other types' do
ptype = Puppet::Pops::Types::PType
- calculator.string(calculator.infer(Puppet::Pops::Types::PNilType.new() )).should == "Type[Undef]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PDataType.new() )).should == "Type[Data]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PScalarType.new() )).should == "Type[Scalar]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PStringType.new() )).should == "Type[String]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PNumericType.new() )).should == "Type[Numeric]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PIntegerType.new() )).should == "Type[Integer]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PFloatType.new() )).should == "Type[Float]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PRegexpType.new() )).should == "Type[Regexp]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PBooleanType.new() )).should == "Type[Boolean]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PCollectionType.new())).should == "Type[Collection]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PArrayType.new() )).should == "Type[Array[?]]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PHashType.new() )).should == "Type[Hash[?, ?]]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PRuntimeType.new() )).should == "Type[Runtime[?, ?]]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PHostClassType.new() )).should == "Type[Class]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PResourceType.new() )).should == "Type[Resource]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PEnumType.new() )).should == "Type[Enum]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PVariantType.new() )).should == "Type[Variant]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PPatternType.new() )).should == "Type[Pattern]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PTupleType.new() )).should == "Type[Tuple]"
- calculator.string(calculator.infer(Puppet::Pops::Types::POptionalType.new() )).should == "Type[Optional]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PCallableType.new() )).should == "Type[Callable]"
-
- calculator.infer(Puppet::Pops::Types::PResourceType.new(:type_name => 'foo::fee::fum')).to_s.should == "Type[Foo::Fee::Fum]"
- calculator.string(calculator.infer(Puppet::Pops::Types::PResourceType.new(:type_name => 'foo::fee::fum'))).should == "Type[Foo::Fee::Fum]"
- calculator.infer(Puppet::Pops::Types::PResourceType.new(:type_name => 'Foo::Fee::Fum')).to_s.should == "Type[Foo::Fee::Fum]"
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PNilType.new() ))).to eq("Type[Undef]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PDataType.new() ))).to eq("Type[Data]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PScalarType.new() ))).to eq("Type[Scalar]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PStringType.new() ))).to eq("Type[String]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PNumericType.new() ))).to eq("Type[Numeric]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PIntegerType.new() ))).to eq("Type[Integer]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PFloatType.new() ))).to eq("Type[Float]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PRegexpType.new() ))).to eq("Type[Regexp]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PBooleanType.new() ))).to eq("Type[Boolean]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PCollectionType.new()))).to eq("Type[Collection]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PArrayType.new() ))).to eq("Type[Array[?]]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PHashType.new() ))).to eq("Type[Hash[?, ?]]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PRuntimeType.new() ))).to eq("Type[Runtime[?, ?]]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PHostClassType.new() ))).to eq("Type[Class]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PResourceType.new() ))).to eq("Type[Resource]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PEnumType.new() ))).to eq("Type[Enum]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PVariantType.new() ))).to eq("Type[Variant]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PPatternType.new() ))).to eq("Type[Pattern]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PTupleType.new() ))).to eq("Type[Tuple]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::POptionalType.new() ))).to eq("Type[Optional]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PCallableType.new() ))).to eq("Type[Callable]")
+
+ expect(calculator.infer(Puppet::Pops::Types::PResourceType.new(:type_name => 'foo::fee::fum')).to_s).to eq("Type[Foo::Fee::Fum]")
+ expect(calculator.string(calculator.infer(Puppet::Pops::Types::PResourceType.new(:type_name => 'foo::fee::fum')))).to eq("Type[Foo::Fee::Fum]")
+ expect(calculator.infer(Puppet::Pops::Types::PResourceType.new(:type_name => 'Foo::Fee::Fum')).to_s).to eq("Type[Foo::Fee::Fum]")
end
it "computes the common type of PType's type parameter" do
int_t = Puppet::Pops::Types::PIntegerType.new()
string_t = Puppet::Pops::Types::PStringType.new()
- calculator.string(calculator.infer([int_t])).should == "Array[Type[Integer], 1, 1]"
- calculator.string(calculator.infer([int_t, string_t])).should == "Array[Type[Scalar], 2, 2]"
+ expect(calculator.string(calculator.infer([int_t]))).to eq("Array[Type[Integer], 1, 1]")
+ expect(calculator.string(calculator.infer([int_t, string_t]))).to eq("Array[Type[Scalar], 2, 2]")
end
it 'should infer PType as the type of ruby classes' do
class Foo
end
[Object, Numeric, Integer, Fixnum, Bignum, Float, String, Regexp, Array, Hash, Foo].each do |c|
- calculator.infer(c).is_a?(Puppet::Pops::Types::PType).should() == true
+ expect(calculator.infer(c).is_a?(Puppet::Pops::Types::PType)).to eq(true)
end
end
it 'should infer PType as the type of PType (meta regression short-circuit)' do
- calculator.infer(Puppet::Pops::Types::PType.new()).is_a?(Puppet::Pops::Types::PType).should() == true
+ expect(calculator.infer(Puppet::Pops::Types::PType.new()).is_a?(Puppet::Pops::Types::PType)).to eq(true)
end
it 'computes instance? to be true if parameterized and type match' do
int_t = Puppet::Pops::Types::PIntegerType.new()
type_t = Puppet::Pops::Types::TypeFactory.type_type(int_t)
type_type_t = Puppet::Pops::Types::TypeFactory.type_type(type_t)
- calculator.instance?(type_type_t, type_t).should == true
+ expect(calculator.instance?(type_type_t, type_t)).to eq(true)
end
it 'computes instance? to be false if parameterized and type do not match' do
int_t = Puppet::Pops::Types::PIntegerType.new()
string_t = Puppet::Pops::Types::PStringType.new()
type_t = Puppet::Pops::Types::TypeFactory.type_type(int_t)
type_t2 = Puppet::Pops::Types::TypeFactory.type_type(string_t)
type_type_t = Puppet::Pops::Types::TypeFactory.type_type(type_t)
# i.e. Type[Integer] =~ Type[Type[Integer]] # false
- calculator.instance?(type_type_t, type_t2).should == false
+ expect(calculator.instance?(type_type_t, type_t2)).to eq(false)
end
it 'computes instance? to be true if unparameterized and matched against a type[?]' do
int_t = Puppet::Pops::Types::PIntegerType.new()
type_t = Puppet::Pops::Types::TypeFactory.type_type(int_t)
- calculator.instance?(Puppet::Pops::Types::PType.new, type_t).should == true
+ expect(calculator.instance?(Puppet::Pops::Types::PType.new, type_t)).to eq(true)
end
end
context "when asking for an enumerable " do
it "should produce an enumerable for an Integer range that is not infinite" do
t = Puppet::Pops::Types::PIntegerType.new()
t.from = 1
t.to = 10
- calculator.enumerable(t).respond_to?(:each).should == true
+ expect(calculator.enumerable(t).respond_to?(:each)).to eq(true)
end
it "should not produce an enumerable for an Integer range that has an infinite side" do
t = Puppet::Pops::Types::PIntegerType.new()
t.from = nil
t.to = 10
- calculator.enumerable(t).should == nil
+ expect(calculator.enumerable(t)).to eq(nil)
t = Puppet::Pops::Types::PIntegerType.new()
t.from = 1
t.to = nil
- calculator.enumerable(t).should == nil
+ expect(calculator.enumerable(t)).to eq(nil)
end
it "all but Integer range are not enumerable" do
[Object, Numeric, Float, String, Regexp, Array, Hash].each do |t|
- calculator.enumerable(calculator.type(t)).should == nil
+ expect(calculator.enumerable(calculator.type(t))).to eq(nil)
end
end
end
context "when dealing with different types of inference" do
it "an instance specific inference is produced by infer" do
- calculator.infer(['a','b']).element_type.values.should == ['a', 'b']
+ expect(calculator.infer(['a','b']).element_type.values).to eq(['a', 'b'])
end
it "a generic inference is produced using infer_generic" do
- calculator.infer_generic(['a','b']).element_type.values.should == []
+ expect(calculator.infer_generic(['a','b']).element_type.values).to eq([])
end
it "a generic result is created by generalize! given an instance specific result for an Array" do
generic = calculator.infer(['a','b'])
- generic.element_type.values.should == ['a', 'b']
+ expect(generic.element_type.values).to eq(['a', 'b'])
calculator.generalize!(generic)
- generic.element_type.values.should == []
+ expect(generic.element_type.values).to eq([])
end
it "a generic result is created by generalize! given an instance specific result for a Hash" do
generic = calculator.infer({'a' =>1,'b' => 2})
- generic.key_type.values.sort.should == ['a', 'b']
- generic.element_type.from.should == 1
- generic.element_type.to.should == 2
+ expect(generic.key_type.values.sort).to eq(['a', 'b'])
+ expect(generic.element_type.from).to eq(1)
+ expect(generic.element_type.to).to eq(2)
calculator.generalize!(generic)
- generic.key_type.values.should == []
- generic.element_type.from.should == nil
- generic.element_type.to.should == nil
+ expect(generic.key_type.values).to eq([])
+ expect(generic.element_type.from).to eq(nil)
+ expect(generic.element_type.to).to eq(nil)
end
it "does not reduce by combining types when using infer_set" do
element_type = calculator.infer(['a','b',1,2]).element_type
- element_type.class.should == Puppet::Pops::Types::PScalarType
+ expect(element_type.class).to eq(Puppet::Pops::Types::PScalarType)
inferred_type = calculator.infer_set(['a','b',1,2])
- inferred_type.class.should == Puppet::Pops::Types::PTupleType
+ expect(inferred_type.class).to eq(Puppet::Pops::Types::PTupleType)
element_types = inferred_type.types
- element_types[0].class.should == Puppet::Pops::Types::PStringType
- element_types[1].class.should == Puppet::Pops::Types::PStringType
- element_types[2].class.should == Puppet::Pops::Types::PIntegerType
- element_types[3].class.should == Puppet::Pops::Types::PIntegerType
+ expect(element_types[0].class).to eq(Puppet::Pops::Types::PStringType)
+ expect(element_types[1].class).to eq(Puppet::Pops::Types::PStringType)
+ expect(element_types[2].class).to eq(Puppet::Pops::Types::PIntegerType)
+ expect(element_types[3].class).to eq(Puppet::Pops::Types::PIntegerType)
end
it "does not reduce by combining types when using infer_set and values are undef" do
element_type = calculator.infer(['a',nil]).element_type
- element_type.class.should == Puppet::Pops::Types::PStringType
+ expect(element_type.class).to eq(Puppet::Pops::Types::PStringType)
inferred_type = calculator.infer_set(['a',nil])
- inferred_type.class.should == Puppet::Pops::Types::PTupleType
+ expect(inferred_type.class).to eq(Puppet::Pops::Types::PTupleType)
element_types = inferred_type.types
- element_types[0].class.should == Puppet::Pops::Types::PStringType
- element_types[1].class.should == Puppet::Pops::Types::PNilType
+ expect(element_types[0].class).to eq(Puppet::Pops::Types::PStringType)
+ expect(element_types[1].class).to eq(Puppet::Pops::Types::PNilType)
end
end
context 'when determening callability' do
context 'and given is exact' do
it 'with callable' do
required = callable_t(string_t)
given = callable_t(string_t)
- calculator.callable?(required, given).should == true
+ expect(calculator.callable?(required, given)).to eq(true)
end
it 'with args tuple' do
required = callable_t(string_t)
given = tuple_t(string_t)
- calculator.callable?(required, given).should == true
+ expect(calculator.callable?(required, given)).to eq(true)
end
it 'with args tuple having a block' do
required = callable_t(string_t, callable_t(string_t))
given = tuple_t(string_t, callable_t(string_t))
- calculator.callable?(required, given).should == true
+ expect(calculator.callable?(required, given)).to eq(true)
end
it 'with args array' do
required = callable_t(string_t)
given = array_t(string_t)
factory.constrain_size(given, 1, 1)
- calculator.callable?(required, given).should == true
+ expect(calculator.callable?(required, given)).to eq(true)
end
end
context 'and given is more generic' do
it 'with callable' do
required = callable_t(string_t)
given = callable_t(object_t)
- calculator.callable?(required, given).should == true
+ expect(calculator.callable?(required, given)).to eq(true)
end
it 'with args tuple' do
required = callable_t(string_t)
given = tuple_t(object_t)
- calculator.callable?(required, given).should == false
+ expect(calculator.callable?(required, given)).to eq(false)
end
it 'with args tuple having a block' do
required = callable_t(string_t, callable_t(string_t))
given = tuple_t(string_t, callable_t(object_t))
- calculator.callable?(required, given).should == true
+ expect(calculator.callable?(required, given)).to eq(true)
end
it 'with args tuple having a block with captures rest' do
required = callable_t(string_t, callable_t(string_t))
given = tuple_t(string_t, callable_t(object_t, 0, :default))
- calculator.callable?(required, given).should == true
+ expect(calculator.callable?(required, given)).to eq(true)
end
end
context 'and given is more specific' do
it 'with callable' do
required = callable_t(object_t)
given = callable_t(string_t)
- calculator.callable?(required, given).should == false
+ expect(calculator.callable?(required, given)).to eq(false)
end
it 'with args tuple' do
required = callable_t(object_t)
given = tuple_t(string_t)
- calculator.callable?(required, given).should == true
+ expect(calculator.callable?(required, given)).to eq(true)
end
it 'with args tuple having a block' do
required = callable_t(string_t, callable_t(object_t))
given = tuple_t(string_t, callable_t(string_t))
- calculator.callable?(required, given).should == false
+ expect(calculator.callable?(required, given)).to eq(false)
end
it 'with args tuple having a block with captures rest' do
required = callable_t(string_t, callable_t(object_t))
given = tuple_t(string_t, callable_t(string_t, 0, :default))
- calculator.callable?(required, given).should == false
+ expect(calculator.callable?(required, given)).to eq(false)
end
end
end
matcher :be_assignable_to do |type|
calc = Puppet::Pops::Types::TypeCalculator.new
match do |actual|
calc.assignable?(type, actual)
end
- failure_message_for_should do |actual|
+ failure_message do |actual|
"#{calc.string(actual)} should be assignable to #{calc.string(type)}"
end
- failure_message_for_should_not do |actual|
+ failure_message_when_negated do |actual|
"#{calc.string(actual)} is assignable to #{calc.string(type)} when it should not"
end
end
end
diff --git a/spec/unit/pops/types/type_factory_spec.rb b/spec/unit/pops/types/type_factory_spec.rb
index cca19a75c..7dc9f3967 100644
--- a/spec/unit/pops/types/type_factory_spec.rb
+++ b/spec/unit/pops/types/type_factory_spec.rb
@@ -1,281 +1,281 @@
require 'spec_helper'
require 'puppet/pops'
describe 'The type factory' do
context 'when creating' do
it 'integer() returns PIntegerType' do
- Puppet::Pops::Types::TypeFactory.integer().class().should == Puppet::Pops::Types::PIntegerType
+ expect(Puppet::Pops::Types::TypeFactory.integer().class()).to eq(Puppet::Pops::Types::PIntegerType)
end
it 'float() returns PFloatType' do
- Puppet::Pops::Types::TypeFactory.float().class().should == Puppet::Pops::Types::PFloatType
+ expect(Puppet::Pops::Types::TypeFactory.float().class()).to eq(Puppet::Pops::Types::PFloatType)
end
it 'string() returns PStringType' do
- Puppet::Pops::Types::TypeFactory.string().class().should == Puppet::Pops::Types::PStringType
+ expect(Puppet::Pops::Types::TypeFactory.string().class()).to eq(Puppet::Pops::Types::PStringType)
end
it 'boolean() returns PBooleanType' do
- Puppet::Pops::Types::TypeFactory.boolean().class().should == Puppet::Pops::Types::PBooleanType
+ expect(Puppet::Pops::Types::TypeFactory.boolean().class()).to eq(Puppet::Pops::Types::PBooleanType)
end
it 'pattern() returns PPatternType' do
- Puppet::Pops::Types::TypeFactory.pattern().class().should == Puppet::Pops::Types::PPatternType
+ expect(Puppet::Pops::Types::TypeFactory.pattern().class()).to eq(Puppet::Pops::Types::PPatternType)
end
it 'regexp() returns PRegexpType' do
- Puppet::Pops::Types::TypeFactory.regexp().class().should == Puppet::Pops::Types::PRegexpType
+ expect(Puppet::Pops::Types::TypeFactory.regexp().class()).to eq(Puppet::Pops::Types::PRegexpType)
end
it 'enum() returns PEnumType' do
- Puppet::Pops::Types::TypeFactory.enum().class().should == Puppet::Pops::Types::PEnumType
+ expect(Puppet::Pops::Types::TypeFactory.enum().class()).to eq(Puppet::Pops::Types::PEnumType)
end
it 'variant() returns PVariantType' do
- Puppet::Pops::Types::TypeFactory.variant().class().should == Puppet::Pops::Types::PVariantType
+ expect(Puppet::Pops::Types::TypeFactory.variant().class()).to eq(Puppet::Pops::Types::PVariantType)
end
it 'scalar() returns PScalarType' do
- Puppet::Pops::Types::TypeFactory.scalar().class().should == Puppet::Pops::Types::PScalarType
+ expect(Puppet::Pops::Types::TypeFactory.scalar().class()).to eq(Puppet::Pops::Types::PScalarType)
end
it 'data() returns PDataType' do
- Puppet::Pops::Types::TypeFactory.data().class().should == Puppet::Pops::Types::PDataType
+ expect(Puppet::Pops::Types::TypeFactory.data().class()).to eq(Puppet::Pops::Types::PDataType)
end
it 'optional() returns POptionalType' do
- Puppet::Pops::Types::TypeFactory.optional().class().should == Puppet::Pops::Types::POptionalType
+ expect(Puppet::Pops::Types::TypeFactory.optional().class()).to eq(Puppet::Pops::Types::POptionalType)
end
it 'collection() returns PCollectionType' do
- Puppet::Pops::Types::TypeFactory.collection().class().should == Puppet::Pops::Types::PCollectionType
+ expect(Puppet::Pops::Types::TypeFactory.collection().class()).to eq(Puppet::Pops::Types::PCollectionType)
end
it 'catalog_entry() returns PCatalogEntryType' do
- Puppet::Pops::Types::TypeFactory.catalog_entry().class().should == Puppet::Pops::Types::PCatalogEntryType
+ expect(Puppet::Pops::Types::TypeFactory.catalog_entry().class()).to eq(Puppet::Pops::Types::PCatalogEntryType)
end
it 'struct() returns PStructType' do
- Puppet::Pops::Types::TypeFactory.struct().class().should == Puppet::Pops::Types::PStructType
+ expect(Puppet::Pops::Types::TypeFactory.struct().class()).to eq(Puppet::Pops::Types::PStructType)
end
it 'tuple() returns PTupleType' do
- Puppet::Pops::Types::TypeFactory.tuple().class().should == Puppet::Pops::Types::PTupleType
+ expect(Puppet::Pops::Types::TypeFactory.tuple().class()).to eq(Puppet::Pops::Types::PTupleType)
end
it 'undef() returns PNilType' do
- Puppet::Pops::Types::TypeFactory.undef().class().should == Puppet::Pops::Types::PNilType
+ expect(Puppet::Pops::Types::TypeFactory.undef().class()).to eq(Puppet::Pops::Types::PNilType)
end
it 'default() returns PDefaultType' do
- Puppet::Pops::Types::TypeFactory.default().class().should == Puppet::Pops::Types::PDefaultType
+ expect(Puppet::Pops::Types::TypeFactory.default().class()).to eq(Puppet::Pops::Types::PDefaultType)
end
it 'range(to, from) returns PIntegerType' do
t = Puppet::Pops::Types::TypeFactory.range(1,2)
- t.class().should == Puppet::Pops::Types::PIntegerType
- t.from.should == 1
- t.to.should == 2
+ expect(t.class()).to eq(Puppet::Pops::Types::PIntegerType)
+ expect(t.from).to eq(1)
+ expect(t.to).to eq(2)
end
it 'range(default, default) returns PIntegerType' do
t = Puppet::Pops::Types::TypeFactory.range(:default,:default)
- t.class().should == Puppet::Pops::Types::PIntegerType
- t.from.should == nil
- t.to.should == nil
+ expect(t.class()).to eq(Puppet::Pops::Types::PIntegerType)
+ expect(t.from).to eq(nil)
+ expect(t.to).to eq(nil)
end
it 'float_range(to, from) returns PFloatType' do
t = Puppet::Pops::Types::TypeFactory.float_range(1.0, 2.0)
- t.class().should == Puppet::Pops::Types::PFloatType
- t.from.should == 1.0
- t.to.should == 2.0
+ expect(t.class()).to eq(Puppet::Pops::Types::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 = Puppet::Pops::Types::TypeFactory.float_range(:default, :default)
- t.class().should == Puppet::Pops::Types::PFloatType
- t.from.should == nil
- t.to.should == nil
+ expect(t.class()).to eq(Puppet::Pops::Types::PFloatType)
+ expect(t.from).to eq(nil)
+ expect(t.to).to eq(nil)
end
it 'resource() creates a generic PResourceType' do
pr = Puppet::Pops::Types::TypeFactory.resource()
- pr.class().should == Puppet::Pops::Types::PResourceType
- pr.type_name.should == nil
+ expect(pr.class()).to eq(Puppet::Pops::Types::PResourceType)
+ expect(pr.type_name).to eq(nil)
end
it 'resource(x) creates a PResourceType[x]' do
pr = Puppet::Pops::Types::TypeFactory.resource('x')
- pr.class().should == Puppet::Pops::Types::PResourceType
- pr.type_name.should == 'x'
+ expect(pr.class()).to eq(Puppet::Pops::Types::PResourceType)
+ expect(pr.type_name).to eq('x')
end
it 'host_class() creates a generic PHostClassType' do
hc = Puppet::Pops::Types::TypeFactory.host_class()
- hc.class().should == Puppet::Pops::Types::PHostClassType
- hc.class_name.should == nil
+ expect(hc.class()).to eq(Puppet::Pops::Types::PHostClassType)
+ expect(hc.class_name).to eq(nil)
end
it 'host_class(x) creates a PHostClassType[x]' do
hc = Puppet::Pops::Types::TypeFactory.host_class('x')
- hc.class().should == Puppet::Pops::Types::PHostClassType
- hc.class_name.should == 'x'
+ expect(hc.class()).to eq(Puppet::Pops::Types::PHostClassType)
+ expect(hc.class_name).to eq('x')
end
it 'host_class(::x) creates a PHostClassType[x]' do
hc = Puppet::Pops::Types::TypeFactory.host_class('::x')
- hc.class().should == Puppet::Pops::Types::PHostClassType
- hc.class_name.should == 'x'
+ expect(hc.class()).to eq(Puppet::Pops::Types::PHostClassType)
+ expect(hc.class_name).to eq('x')
end
it 'array_of(fixnum) returns PArrayType[PIntegerType]' do
at = Puppet::Pops::Types::TypeFactory.array_of(1)
- at.class().should == Puppet::Pops::Types::PArrayType
- at.element_type.class.should == Puppet::Pops::Types::PIntegerType
+ expect(at.class()).to eq(Puppet::Pops::Types::PArrayType)
+ expect(at.element_type.class).to eq(Puppet::Pops::Types::PIntegerType)
end
it 'array_of(PIntegerType) returns PArrayType[PIntegerType]' do
at = Puppet::Pops::Types::TypeFactory.array_of(Puppet::Pops::Types::PIntegerType.new())
- at.class().should == Puppet::Pops::Types::PArrayType
- at.element_type.class.should == Puppet::Pops::Types::PIntegerType
+ expect(at.class()).to eq(Puppet::Pops::Types::PArrayType)
+ expect(at.element_type.class).to eq(Puppet::Pops::Types::PIntegerType)
end
it 'array_of_data returns PArrayType[PDataType]' do
at = Puppet::Pops::Types::TypeFactory.array_of_data
- at.class().should == Puppet::Pops::Types::PArrayType
- at.element_type.class.should == Puppet::Pops::Types::PDataType
+ expect(at.class()).to eq(Puppet::Pops::Types::PArrayType)
+ expect(at.element_type.class).to eq(Puppet::Pops::Types::PDataType)
end
it 'hash_of_data returns PHashType[PScalarType,PDataType]' do
ht = Puppet::Pops::Types::TypeFactory.hash_of_data
- ht.class().should == Puppet::Pops::Types::PHashType
- ht.key_type.class.should == Puppet::Pops::Types::PScalarType
- ht.element_type.class.should == Puppet::Pops::Types::PDataType
+ expect(ht.class()).to eq(Puppet::Pops::Types::PHashType)
+ expect(ht.key_type.class).to eq(Puppet::Pops::Types::PScalarType)
+ expect(ht.element_type.class).to eq(Puppet::Pops::Types::PDataType)
end
it 'ruby(1) returns PRuntimeType[ruby, \'Fixnum\']' do
ht = Puppet::Pops::Types::TypeFactory.ruby(1)
- ht.class().should == Puppet::Pops::Types::PRuntimeType
- ht.runtime.should == :ruby
- ht.runtime_type_name.should == 'Fixnum'
+ expect(ht.class()).to eq(Puppet::Pops::Types::PRuntimeType)
+ expect(ht.runtime).to eq(:ruby)
+ expect(ht.runtime_type_name).to eq('Fixnum')
end
it 'a size constrained collection can be created from array' do
t = Puppet::Pops::Types::TypeFactory.array_of_data()
- Puppet::Pops::Types::TypeFactory.constrain_size(t, 1,2).should == t
- t.size_type.class.should == Puppet::Pops::Types::PIntegerType
- t.size_type.from.should == 1
- t.size_type.to.should == 2
+ expect(Puppet::Pops::Types::TypeFactory.constrain_size(t, 1,2)).to eq(t)
+ expect(t.size_type.class).to eq(Puppet::Pops::Types::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 = Puppet::Pops::Types::TypeFactory.hash_of_data()
- Puppet::Pops::Types::TypeFactory.constrain_size(t, 1,2).should == t
- t.size_type.class.should == Puppet::Pops::Types::PIntegerType
- t.size_type.from.should == 1
- t.size_type.to.should == 2
+ expect(Puppet::Pops::Types::TypeFactory.constrain_size(t, 1,2)).to eq(t)
+ expect(t.size_type.class).to eq(Puppet::Pops::Types::PIntegerType)
+ expect(t.size_type.from).to eq(1)
+ expect(t.size_type.to).to eq(2)
end
context 'callable types' do
it 'the callable methods produces a Callable' do
t = Puppet::Pops::Types::TypeFactory.callable()
expect(t.class).to be(Puppet::Pops::Types::PCallableType)
expect(t.param_types.class).to be(Puppet::Pops::Types::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 = Puppet::Pops::Types::TypeFactory
t = tf.callable(tf.integer, tf.string)
expect(t.class).to be(Puppet::Pops::Types::PCallableType)
expect(t.param_types.class).to be(Puppet::Pops::Types::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 = Puppet::Pops::Types::TypeFactory
t = tf.callable(tf.integer, tf.string, 1)
expect(t.class).to be(Puppet::Pops::Types::PCallableType)
expect(t.param_types.class).to be(Puppet::Pops::Types::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 = Puppet::Pops::Types::TypeFactory
t = tf.callable(tf.integer, tf.string, 1, 3)
expect(t.class).to be(Puppet::Pops::Types::PCallableType)
expect(t.param_types.class).to be(Puppet::Pops::Types::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 = Puppet::Pops::Types::TypeFactory
t = tf.callable(tf.integer, tf.string, 1, :default)
expect(t.class).to be(Puppet::Pops::Types::PCallableType)
expect(t.param_types.class).to be(Puppet::Pops::Types::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 = Puppet::Pops::Types::TypeFactory.all_callables()
expect(t.class).to be(Puppet::Pops::Types::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 = Puppet::Pops::Types::TypeFactory.callable(String)
t = Puppet::Pops::Types::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 = Puppet::Pops::Types::TypeFactory.callable(String)
t = Puppet::Pops::Types::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 = Puppet::Pops::Types::TypeFactory.callable(String)
t = Puppet::Pops::Types::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 = Puppet::Pops::Types::TypeFactory.callable()
t2 = Puppet::Pops::Types::TypeFactory.with_block(t)
block_t = t2.block_type
# given t is returned after mutation
expect(t2).to be(t)
expect(block_t.class).to be(Puppet::Pops::Types::PCallableType)
expect(block_t.param_types.class).to be(Puppet::Pops::Types::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
t = Puppet::Pops::Types::TypeFactory.callable()
t2 = Puppet::Pops::Types::TypeFactory.with_optional_block(t)
opt_t = t2.block_type
expect(opt_t.class).to be(Puppet::Pops::Types::POptionalType)
block_t = opt_t.optional_type
# given t is returned after mutation
expect(t2).to be(t)
expect(block_t.class).to be(Puppet::Pops::Types::PCallableType)
expect(block_t.param_types.class).to be(Puppet::Pops::Types::PTupleType)
expect(block_t.param_types.types).to be_empty
expect(block_t.block_type).to be_nil
end
end
end
end
diff --git a/spec/unit/pops/types/type_parser_spec.rb b/spec/unit/pops/types/type_parser_spec.rb
index 080e3b44a..84049dce2 100644
--- a/spec/unit/pops/types/type_parser_spec.rb
+++ b/spec/unit/pops/types/type_parser_spec.rb
@@ -1,240 +1,240 @@
require 'spec_helper'
require 'puppet/pops'
describe Puppet::Pops::Types::TypeParser do
extend RSpec::Matchers::DSL
let(:parser) { Puppet::Pops::Types::TypeParser.new }
let(:types) { Puppet::Pops::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
[
'Any', 'Data', 'CatalogEntry', 'Boolean', '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 Data" do
expect(parser.parse("Array")).to be_the_type(types.array_of_data)
end
it "interprets an unparameterized Hash as a Hash of Scalar to Data" do
expect(parser.parse("Hash")).to be_the_type(types.hash_of_data)
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 "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.constrain_size(parameterized_array, 1,2)
parameterized_hash = types.hash_of(types.integer, types.boolean)
types.constrain_size(parameterized_hash, 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.constrain_size(parameterized_array, 1,:default)
parameterized_hash = types.hash_of(types.integer, types.boolean)
types.constrain_size(parameterized_hash, 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 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.constrain_size(tuple_t, 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(Puppet::Pops::Types::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
it "interprets anything that is not a built in type to be a resource type" do
expect(parser.parse("File")).to be_the_type(types.resource('file'))
end
it "parses a resource type with title" do
expect(parser.parse("File['/tmp/foo']")).to be_the_type(types.resource('file', '/tmp/foo'))
end
it "parses a resource type using 'Resource[type]' form" do
expect(parser.parse("Resource[File]")).to be_the_type(types.resource('file'))
end
it "parses a resource type with title using 'Resource[type, title]'" do
expect(parser.parse("Resource[File, '/tmp/foo']")).to be_the_type(types.resource('file', '/tmp/foo'))
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 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.constrain_size(types.collection,1,2))
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
expect(parser.parse("Callable")).to be_the_type(types.all_callables())
end
it 'parses a parameterized callable type' do
expect(parser.parse("Callable[String, Integer]")).to be_the_type(types.callable(String, Integer))
end
it 'parses a parameterized callable type with min/max' do
expect(parser.parse("Callable[String, Integer, 1, default]")).to be_the_type(types.callable(String, Integer, 1, :default))
end
it 'parses a parameterized callable type with block' do
expect(parser.parse("Callable[String, Callable[Boolean]]")).to be_the_type(types.callable(String, types.callable(true)))
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())
expect(t.param_types.types).to be_empty
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(Puppet::Pops::Types::PUnitType.new())
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_for_should do |actual|
+ 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)
calc = Puppet::Pops::Types::TypeCalculator.new
calc.string(type)
end
end
diff --git a/spec/unit/pops/visitor_spec.rb b/spec/unit/pops/visitor_spec.rb
index c5858c2c2..228598bb1 100644
--- a/spec/unit/pops/visitor_spec.rb
+++ b/spec/unit/pops/visitor_spec.rb
@@ -1,94 +1,94 @@
#! /usr/bin/env ruby
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
- duck_processor.hi(duck).should == "Hi Duck"
+ 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
- duck_processor.hi(42).should == "Howdy Fixnum"
+ expect(duck_processor.hi(42)).to eq("Howdy Fixnum")
end
it "should select method for superclass" do
duck_processor = DuckProcessor.new
- duck_processor.hi(42.0).should == "Howdy Float"
+ 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
- duck_processor.hi(duck, "water").should == "Hi Duck, drink=water, eat=grain"
+ 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
diff --git a/spec/unit/property/boolean_spec.rb b/spec/unit/property/boolean_spec.rb
index 154fc9752..b3b7c7d12 100644
--- a/spec/unit/property/boolean_spec.rb
+++ b/spec/unit/property/boolean_spec.rb
@@ -1,24 +1,24 @@
require 'spec_helper'
require 'puppet/property/boolean'
describe Puppet::Property::Boolean do
let (:resource) { mock('resource') }
subject { described_class.new(:resource => resource) }
[ true, :true, 'true', :yes, 'yes', 'TrUe', 'yEs' ].each do |arg|
it "should munge #{arg.inspect} as true" do
- subject.munge(arg).should == true
+ expect(subject.munge(arg)).to eq(true)
end
end
[ false, :false, 'false', :no, 'no', 'FaLSE', 'nO' ].each do |arg|
it "should munge #{arg.inspect} as false" do
- subject.munge(arg).should == false
+ expect(subject.munge(arg)).to eq(false)
end
end
[ nil, :undef, 'undef', '0', 0, '1', 1, 9284 ].each do |arg|
it "should fail to munge #{arg.inspect}" do
expect { subject.munge(arg) }.to raise_error Puppet::Error
end
end
end
diff --git a/spec/unit/property/ensure_spec.rb b/spec/unit/property/ensure_spec.rb
index 41809f9f8..b1deeb0f4 100755
--- a/spec/unit/property/ensure_spec.rb
+++ b/spec/unit/property/ensure_spec.rb
@@ -1,12 +1,12 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/property/ensure'
klass = Puppet::Property::Ensure
describe klass do
it "should be a subclass of Property" do
- klass.superclass.must == Puppet::Property
+ expect(klass.superclass).to eq(Puppet::Property)
end
end
diff --git a/spec/unit/property/keyvalue_spec.rb b/spec/unit/property/keyvalue_spec.rb
index 616c92756..62c1f859b 100755
--- a/spec/unit/property/keyvalue_spec.rb
+++ b/spec/unit/property/keyvalue_spec.rb
@@ -1,170 +1,170 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/property/keyvalue'
klass = Puppet::Property::KeyValue
describe klass do
it "should be a subclass of Property" do
- klass.superclass.must == Puppet::Property
+ expect(klass.superclass).to eq(Puppet::Property)
end
describe "as an instance" do
before do
# Wow that's a messy interface to the resource.
klass.initvars
@resource = stub 'resource', :[]= => nil, :property => nil
@property = klass.new(:resource => @resource)
end
it "should have a , as default delimiter" do
- @property.delimiter.should == ";"
+ expect(@property.delimiter).to eq(";")
end
it "should have a = as default separator" do
- @property.separator.should == "="
+ expect(@property.separator).to eq("=")
end
it "should have a :membership as default membership" do
- @property.membership.should == :key_value_membership
+ expect(@property.membership).to eq(:key_value_membership)
end
it "should return the same value passed into should_to_s" do
@property.should_to_s({:foo => "baz", :bar => "boo"}) == "foo=baz;bar=boo"
end
it "should return the passed in hash values joined with the delimiter from is_to_s" do
s = @property.is_to_s({"foo" => "baz" , "bar" => "boo"})
# We can't predict the order the hash is processed in...
- ["foo=baz;bar=boo", "bar=boo;foo=baz"].should be_include s
+ expect(["foo=baz;bar=boo", "bar=boo;foo=baz"]).to be_include s
end
describe "when calling inclusive?" do
it "should use the membership method to look up on the @resource" do
@property.expects(:membership).returns(:key_value_membership)
@resource.expects(:[]).with(:key_value_membership)
@property.inclusive?
end
it "should return true when @resource[membership] == inclusive" do
@property.stubs(:membership).returns(:key_value_membership)
@resource.stubs(:[]).with(:key_value_membership).returns(:inclusive)
- @property.inclusive?.must == true
+ expect(@property.inclusive?).to eq(true)
end
it "should return false when @resource[membership] != inclusive" do
@property.stubs(:membership).returns(:key_value_membership)
@resource.stubs(:[]).with(:key_value_membership).returns(:minimum)
- @property.inclusive?.must == false
+ expect(@property.inclusive?).to eq(false)
end
end
describe "when calling process_current_hash" do
it "should return {} if hash is :absent" do
- @property.process_current_hash(:absent).must == {}
+ expect(@property.process_current_hash(:absent)).to eq({})
end
it "should set every key to nil if inclusive?" do
@property.stubs(:inclusive?).returns(true)
- @property.process_current_hash({:foo => "bar", :do => "re"}).must == { :foo => nil, :do => nil }
+ expect(@property.process_current_hash({:foo => "bar", :do => "re"})).to eq({ :foo => nil, :do => nil })
end
it "should return the hash if !inclusive?" do
@property.stubs(:inclusive?).returns(false)
- @property.process_current_hash({:foo => "bar", :do => "re"}).must == {:foo => "bar", :do => "re"}
+ expect(@property.process_current_hash({:foo => "bar", :do => "re"})).to eq({:foo => "bar", :do => "re"})
end
end
describe "when calling should" do
it "should return nil if @should is nil" do
- @property.should.must == nil
+ expect(@property.should).to eq(nil)
end
it "should call process_current_hash" do
@property.should = ["foo=baz", "bar=boo"]
@property.stubs(:retrieve).returns({:do => "re", :mi => "fa" })
@property.expects(:process_current_hash).returns({})
@property.should
end
it "should return the hashed values of @should and the nilled values of retrieve if inclusive" do
@property.should = ["foo=baz", "bar=boo"]
@property.expects(:retrieve).returns({:do => "re", :mi => "fa" })
@property.expects(:inclusive?).returns(true)
- @property.should.must == { :foo => "baz", :bar => "boo", :do => nil, :mi => nil }
+ expect(@property.should).to eq({ :foo => "baz", :bar => "boo", :do => nil, :mi => nil })
end
it "should return the hashed @should + the unique values of retrieve if !inclusive" do
@property.should = ["foo=baz", "bar=boo"]
@property.expects(:retrieve).returns({:foo => "diff", :do => "re", :mi => "fa"})
@property.expects(:inclusive?).returns(false)
- @property.should.must == { :foo => "baz", :bar => "boo", :do => "re", :mi => "fa" }
+ expect(@property.should).to eq({ :foo => "baz", :bar => "boo", :do => "re", :mi => "fa" })
end
end
describe "when calling retrieve" do
before do
@provider = mock("provider")
@property.stubs(:provider).returns(@provider)
end
it "should send 'name' to the provider" do
@provider.expects(:send).with(:keys)
@property.expects(:name).returns(:keys)
@property.retrieve
end
it "should return a hash with the provider returned info" do
@provider.stubs(:send).with(:keys).returns({"do" => "re", "mi" => "fa" })
@property.stubs(:name).returns(:keys)
@property.retrieve == {"do" => "re", "mi" => "fa" }
end
it "should return :absent when the provider returns :absent" do
@provider.stubs(:send).with(:keys).returns(:absent)
@property.stubs(:name).returns(:keys)
@property.retrieve == :absent
end
end
describe "when calling hashify" do
it "should return the array hashified" do
- @property.hashify(["foo=baz", "bar=boo"]).must == { :foo => "baz", :bar => "boo" }
+ expect(@property.hashify(["foo=baz", "bar=boo"])).to eq({ :foo => "baz", :bar => "boo" })
end
end
describe "when calling safe_insync?" do
before do
@provider = mock("provider")
@property.stubs(:provider).returns(@provider)
@property.stubs(:name).returns(:prop_name)
end
it "should return true unless @should is defined and not nil" do
@property.safe_insync?("foo") == true
end
it "should return true if the passed in values is nil" do
@property.should = "foo"
@property.safe_insync?(nil) == true
end
it "should return true if hashified should value == (retrieved) value passed in" do
@provider.stubs(:prop_name).returns({ :foo => "baz", :bar => "boo" })
@property.should = ["foo=baz", "bar=boo"]
@property.expects(:inclusive?).returns(true)
- @property.safe_insync?({ :foo => "baz", :bar => "boo" }).must == true
+ expect(@property.safe_insync?({ :foo => "baz", :bar => "boo" })).to eq(true)
end
it "should return false if prepared value != should value" do
@provider.stubs(:prop_name).returns({ "foo" => "bee", "bar" => "boo" })
@property.should = ["foo=baz", "bar=boo"]
@property.expects(:inclusive?).returns(true)
- @property.safe_insync?({ "foo" => "bee", "bar" => "boo" }).must == false
+ expect(@property.safe_insync?({ "foo" => "bee", "bar" => "boo" })).to eq(false)
end
end
end
end
diff --git a/spec/unit/property/list_spec.rb b/spec/unit/property/list_spec.rb
index 80a19ee85..06e7db491 100755
--- a/spec/unit/property/list_spec.rb
+++ b/spec/unit/property/list_spec.rb
@@ -1,173 +1,173 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/property/list'
list_class = Puppet::Property::List
describe list_class do
it "should be a subclass of Property" do
- list_class.superclass.must == Puppet::Property
+ expect(list_class.superclass).to eq(Puppet::Property)
end
describe "as an instance" do
before do
# Wow that's a messy interface to the resource.
list_class.initvars
@resource = stub 'resource', :[]= => nil, :property => nil
@property = list_class.new(:resource => @resource)
end
it "should have a , as default delimiter" do
- @property.delimiter.should == ","
+ expect(@property.delimiter).to eq(",")
end
it "should have a :membership as default membership" do
- @property.membership.should == :membership
+ expect(@property.membership).to eq(:membership)
end
it "should return the same value passed into should_to_s" do
@property.should_to_s("foo") == "foo"
end
it "should return the passed in array values joined with the delimiter from is_to_s" do
- @property.is_to_s(["foo","bar"]).should == "foo,bar"
+ expect(@property.is_to_s(["foo","bar"])).to eq("foo,bar")
end
it "should be able to correctly convert ':absent' to a string" do
- @property.is_to_s(:absent).should == "absent"
+ expect(@property.is_to_s(:absent)).to eq("absent")
end
describe "when adding should to current" do
it "should add the arrays when current is an array" do
- @property.add_should_with_current(["foo"], ["bar"]).should == ["foo", "bar"]
+ expect(@property.add_should_with_current(["foo"], ["bar"])).to eq(["foo", "bar"])
end
it "should return should if current is not an array" do
- @property.add_should_with_current(["foo"], :absent).should == ["foo"]
+ expect(@property.add_should_with_current(["foo"], :absent)).to eq(["foo"])
end
it "should return only the uniq elements" do
- @property.add_should_with_current(["foo", "bar"], ["foo", "baz"]).should == ["foo", "bar", "baz"]
+ expect(@property.add_should_with_current(["foo", "bar"], ["foo", "baz"])).to eq(["foo", "bar", "baz"])
end
end
describe "when calling inclusive?" do
it "should use the membership method to look up on the @resource" do
@property.expects(:membership).returns(:membership)
@resource.expects(:[]).with(:membership)
@property.inclusive?
end
it "should return true when @resource[membership] == inclusive" do
@property.stubs(:membership).returns(:membership)
@resource.stubs(:[]).with(:membership).returns(:inclusive)
- @property.inclusive?.must == true
+ expect(@property.inclusive?).to eq(true)
end
it "should return false when @resource[membership] != inclusive" do
@property.stubs(:membership).returns(:membership)
@resource.stubs(:[]).with(:membership).returns(:minimum)
- @property.inclusive?.must == false
+ expect(@property.inclusive?).to eq(false)
end
end
describe "when calling should" do
it "should return nil if @should is nil" do
- @property.should.must == nil
+ expect(@property.should).to eq(nil)
end
it "should return the sorted values of @should as a string if inclusive" do
@property.should = ["foo", "bar"]
@property.expects(:inclusive?).returns(true)
- @property.should.must == "bar,foo"
+ expect(@property.should).to eq("bar,foo")
end
it "should return the uniq sorted values of @should + retrieve as a string if !inclusive" do
@property.should = ["foo", "bar"]
@property.expects(:inclusive?).returns(false)
@property.expects(:retrieve).returns(["foo","baz"])
- @property.should.must == "bar,baz,foo"
+ expect(@property.should).to eq("bar,baz,foo")
end
end
describe "when calling retrieve" do
let(:provider) { @provider }
before do
@provider = mock("provider")
@property.stubs(:provider).returns(provider)
end
it "should send 'name' to the provider" do
@provider.expects(:send).with(:group)
@property.expects(:name).returns(:group)
@property.retrieve
end
it "should return an array with the provider returned info" do
@provider.stubs(:send).with(:group).returns("foo,bar,baz")
@property.stubs(:name).returns(:group)
@property.retrieve == ["foo", "bar", "baz"]
end
it "should return :absent when the provider returns :absent" do
@provider.stubs(:send).with(:group).returns(:absent)
@property.stubs(:name).returns(:group)
@property.retrieve == :absent
end
context "and provider is nil" do
let(:provider) { nil }
it "should return :absent" do
@property.retrieve == :absent
end
end
end
describe "when calling safe_insync?" do
it "should return true unless @should is defined and not nil" do
- @property.must be_safe_insync("foo")
+ expect(@property).to be_safe_insync("foo")
end
it "should return true unless the passed in values is not nil" do
@property.should = "foo"
- @property.must be_safe_insync(nil)
+ expect(@property).to be_safe_insync(nil)
end
it "should call prepare_is_for_comparison with value passed in and should" do
@property.should = "foo"
@property.expects(:prepare_is_for_comparison).with("bar")
@property.expects(:should)
@property.safe_insync?("bar")
end
it "should return true if 'is' value is array of comma delimited should values" do
@property.should = "bar,foo"
@property.expects(:inclusive?).returns(true)
- @property.must be_safe_insync(["bar","foo"])
+ expect(@property).to be_safe_insync(["bar","foo"])
end
it "should return true if 'is' value is :absent and should value is empty string" do
@property.should = ""
@property.expects(:inclusive?).returns(true)
- @property.must be_safe_insync([])
+ expect(@property).to be_safe_insync([])
end
it "should return false if prepared value != should value" do
@property.should = "bar,baz,foo"
@property.expects(:inclusive?).returns(true)
- @property.must_not be_safe_insync(["bar","foo"])
+ expect(@property).to_not be_safe_insync(["bar","foo"])
end
end
describe "when calling dearrayify" do
it "should sort and join the array with 'delimiter'" do
array = mock "array"
array.expects(:sort).returns(array)
array.expects(:join).with(@property.delimiter)
@property.dearrayify(array)
end
end
end
end
diff --git a/spec/unit/property/ordered_list_spec.rb b/spec/unit/property/ordered_list_spec.rb
index 0155d8c51..f27da4106 100755
--- a/spec/unit/property/ordered_list_spec.rb
+++ b/spec/unit/property/ordered_list_spec.rb
@@ -1,63 +1,63 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/property/ordered_list'
ordered_list_class = Puppet::Property::OrderedList
describe ordered_list_class do
it "should be a subclass of List" do
- ordered_list_class.superclass.must == Puppet::Property::List
+ expect(ordered_list_class.superclass).to eq(Puppet::Property::List)
end
describe "as an instance" do
before do
# Wow that's a messy interface to the resource.
ordered_list_class.initvars
@resource = stub 'resource', :[]= => nil, :property => nil
@property = ordered_list_class.new(:resource => @resource)
end
describe "when adding should to current" do
it "should add the arrays when current is an array" do
- @property.add_should_with_current(["should"], ["current"]).should == ["should", "current"]
+ expect(@property.add_should_with_current(["should"], ["current"])).to eq(["should", "current"])
end
it "should return 'should' if current is not an array" do
- @property.add_should_with_current(["should"], :absent).should == ["should"]
+ expect(@property.add_should_with_current(["should"], :absent)).to eq(["should"])
end
it "should return only the uniq elements leading with the order of 'should'" do
- @property.add_should_with_current(["this", "is", "should"], ["is", "this", "current"]).should == ["this", "is", "should", "current"]
+ expect(@property.add_should_with_current(["this", "is", "should"], ["is", "this", "current"])).to eq(["this", "is", "should", "current"])
end
end
describe "when calling should" do
it "should return nil if @should is nil" do
- @property.should.must == nil
+ expect(@property.should).to eq(nil)
end
it "should return the values of @should (without sorting) as a string if inclusive" do
@property.should = ["foo", "bar"]
@property.expects(:inclusive?).returns(true)
- @property.should.must == "foo,bar"
+ expect(@property.should).to eq("foo,bar")
end
it "should return the uniq values of @should + retrieve as a string if !inclusive with the @ values leading" do
@property.should = ["foo", "bar"]
@property.expects(:inclusive?).returns(false)
@property.expects(:retrieve).returns(["foo","baz"])
- @property.should.must == "foo,bar,baz"
+ expect(@property.should).to eq("foo,bar,baz")
end
end
describe "when calling dearrayify" do
it "should join the array with the delimiter" do
array = mock "array"
array.expects(:join).with(@property.delimiter)
@property.dearrayify(array)
end
end
end
end
diff --git a/spec/unit/property_spec.rb b/spec/unit/property_spec.rb
index df855ac5b..03435622d 100755
--- a/spec/unit/property_spec.rb
+++ b/spec/unit/property_spec.rb
@@ -1,511 +1,511 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/property'
describe Puppet::Property do
let :resource do Puppet::Type.type(:host).new :name => "foo" end
let :subclass do
# We need a completely fresh subclass every time, because we modify both
# class and instance level things inside the tests.
subclass = Class.new(Puppet::Property) do
class << self
attr_accessor :name
end
@name = :foo
end
subclass.initvars
subclass
end
let :property do subclass.new :resource => resource end
it "should be able to look up the modified name for a given value" do
subclass.newvalue(:foo)
- subclass.value_name("foo").should == :foo
+ expect(subclass.value_name("foo")).to eq(:foo)
end
it "should be able to look up the modified name for a given value matching a regex" do
subclass.newvalue(%r{.})
- subclass.value_name("foo").should == %r{.}
+ expect(subclass.value_name("foo")).to eq(%r{.})
end
it "should be able to look up a given value option" do
subclass.newvalue(:foo, :event => :whatever)
- subclass.value_option(:foo, :event).should == :whatever
+ expect(subclass.value_option(:foo, :event)).to eq(:whatever)
end
it "should be able to specify required features" do
- subclass.should respond_to(:required_features=)
+ expect(subclass).to respond_to(:required_features=)
end
{"one" => [:one],:one => [:one],%w{a} => [:a],[:b] => [:b],%w{one two} => [:one,:two],[:a,:b] => [:a,:b]}.each { |in_value,out_value|
it "should always convert required features into an array of symbols (e.g. #{in_value.inspect} --> #{out_value.inspect})" do
subclass.required_features = in_value
- subclass.required_features.should == out_value
+ expect(subclass.required_features).to eq(out_value)
end
}
it "should return its name as a string when converted to a string" do
- property.to_s.should == property.name.to_s
+ expect(property.to_s).to eq(property.name.to_s)
end
describe "when returning the default event name" do
it "should use the current 'should' value to pick the event name" do
property.expects(:should).returns "myvalue"
subclass.expects(:value_option).with('myvalue', :event).returns :event_name
property.event_name
end
it "should return any event defined with the specified value" do
property.expects(:should).returns :myval
subclass.expects(:value_option).with(:myval, :event).returns :event_name
- property.event_name.should == :event_name
+ expect(property.event_name).to eq(:event_name)
end
describe "and the property is 'ensure'" do
before :each do
property.stubs(:name).returns :ensure
resource.expects(:type).returns :mytype
end
it "should use <type>_created if the 'should' value is 'present'" do
property.expects(:should).returns :present
- property.event_name.should == :mytype_created
+ expect(property.event_name).to eq(:mytype_created)
end
it "should use <type>_removed if the 'should' value is 'absent'" do
property.expects(:should).returns :absent
- property.event_name.should == :mytype_removed
+ expect(property.event_name).to eq(:mytype_removed)
end
it "should use <type>_changed if the 'should' value is not 'absent' or 'present'" do
property.expects(:should).returns :foo
- property.event_name.should == :mytype_changed
+ expect(property.event_name).to eq(:mytype_changed)
end
it "should use <type>_changed if the 'should value is nil" do
property.expects(:should).returns nil
- property.event_name.should == :mytype_changed
+ expect(property.event_name).to eq(:mytype_changed)
end
end
it "should use <property>_changed if the property is not 'ensure'" do
property.stubs(:name).returns :myparam
property.expects(:should).returns :foo
- property.event_name.should == :myparam_changed
+ expect(property.event_name).to eq(:myparam_changed)
end
it "should use <property>_changed if no 'should' value is set" do
property.stubs(:name).returns :myparam
property.expects(:should).returns nil
- property.event_name.should == :myparam_changed
+ expect(property.event_name).to eq(:myparam_changed)
end
end
describe "when creating an event" do
before :each do
property.stubs(:should).returns "myval"
end
it "should use an event from the resource as the base event" do
event = Puppet::Transaction::Event.new
resource.expects(:event).returns event
- property.event.should equal(event)
+ expect(property.event).to equal(event)
end
it "should have the default event name" do
property.expects(:event_name).returns :my_event
- property.event.name.should == :my_event
+ expect(property.event.name).to eq(:my_event)
end
it "should have the property's name" do
- property.event.property.should == property.name.to_s
+ expect(property.event.property).to eq(property.name.to_s)
end
it "should have the 'should' value set" do
property.stubs(:should).returns "foo"
- property.event.desired_value.should == "foo"
+ expect(property.event.desired_value).to eq("foo")
end
it "should provide its path as the source description" do
property.stubs(:path).returns "/my/param"
- property.event.source_description.should == "/my/param"
+ expect(property.event.source_description).to eq("/my/param")
end
it "should have the 'invalidate_refreshes' value set if set on a value" do
property.stubs(:event_name).returns :my_event
property.stubs(:should).returns "foo"
foo = mock()
foo.expects(:invalidate_refreshes).returns(true)
collection = mock()
collection.expects(:match?).with("foo").returns(foo)
property.class.stubs(:value_collection).returns(collection)
- property.event.invalidate_refreshes.should be_true
+ expect(property.event.invalidate_refreshes).to be_truthy
end
end
describe "when defining new values" do
it "should define a method for each value created with a block that's not a regex" do
subclass.newvalue(:foo) { }
- property.must respond_to(:set_foo)
+ expect(property).to respond_to(:set_foo)
end
end
describe "when assigning the value" do
it "should just set the 'should' value" do
property.value = "foo"
- property.should.must == "foo"
+ expect(property.should).to eq("foo")
end
it "should validate each value separately" do
property.expects(:validate).with("one")
property.expects(:validate).with("two")
property.value = %w{one two}
end
it "should munge each value separately and use any result as the actual value" do
property.expects(:munge).with("one").returns :one
property.expects(:munge).with("two").returns :two
# Do this so we get the whole array back.
subclass.array_matching = :all
property.value = %w{one two}
- property.should.must == [:one, :two]
+ expect(property.should).to eq([:one, :two])
end
it "should return any set value" do
- (property.value = :one).should == :one
+ expect(property.value = :one).to eq(:one)
end
end
describe "when returning the value" do
it "should return nil if no value is set" do
- property.should.must be_nil
+ expect(property.should).to be_nil
end
it "should return the first set 'should' value if :array_matching is set to :first" do
subclass.array_matching = :first
property.should = %w{one two}
- property.should.must == "one"
+ expect(property.should).to eq("one")
end
it "should return all set 'should' values as an array if :array_matching is set to :all" do
subclass.array_matching = :all
property.should = %w{one two}
- property.should.must == %w{one two}
+ expect(property.should).to eq(%w{one two})
end
it "should default to :first array_matching" do
- subclass.array_matching.should == :first
+ expect(subclass.array_matching).to eq(:first)
end
it "should unmunge the returned value if :array_matching is set to :first" do
property.class.unmunge do |v| v.to_sym end
subclass.array_matching = :first
property.should = %w{one two}
- property.should.must == :one
+ expect(property.should).to eq(:one)
end
it "should unmunge all the returned values if :array_matching is set to :all" do
property.class.unmunge do |v| v.to_sym end
subclass.array_matching = :all
property.should = %w{one two}
- property.should.must == [:one, :two]
+ expect(property.should).to eq([:one, :two])
end
end
describe "when validating values" do
it "should do nothing if no values or regexes have been defined" do
- lambda { property.should = "foo" }.should_not raise_error
+ expect { property.should = "foo" }.not_to raise_error
end
it "should fail if the value is not a defined value or alias and does not match a regex" do
subclass.newvalue(:foo)
- lambda { property.should = "bar" }.should raise_error
+ expect { property.should = "bar" }.to raise_error
end
it "should succeeed if the value is one of the defined values" do
subclass.newvalue(:foo)
- lambda { property.should = :foo }.should_not raise_error
+ expect { property.should = :foo }.not_to raise_error
end
it "should succeeed if the value is one of the defined values even if the definition uses a symbol and the validation uses a string" do
subclass.newvalue(:foo)
- lambda { property.should = "foo" }.should_not raise_error
+ expect { property.should = "foo" }.not_to raise_error
end
it "should succeeed if the value is one of the defined values even if the definition uses a string and the validation uses a symbol" do
subclass.newvalue("foo")
- lambda { property.should = :foo }.should_not raise_error
+ expect { property.should = :foo }.not_to raise_error
end
it "should succeed if the value is one of the defined aliases" do
subclass.newvalue("foo")
subclass.aliasvalue("bar", "foo")
- lambda { property.should = :bar }.should_not raise_error
+ expect { property.should = :bar }.not_to raise_error
end
it "should succeed if the value matches one of the regexes" do
subclass.newvalue(/./)
- lambda { property.should = "bar" }.should_not raise_error
+ expect { property.should = "bar" }.not_to raise_error
end
it "should validate that all required features are present" do
subclass.newvalue(:foo, :required_features => [:a, :b])
resource.provider.expects(:satisfies?).with([:a, :b]).returns true
property.should = :foo
end
it "should fail if required features are missing" do
subclass.newvalue(:foo, :required_features => [:a, :b])
resource.provider.expects(:satisfies?).with([:a, :b]).returns false
- lambda { property.should = :foo }.should raise_error(Puppet::Error)
+ expect { property.should = :foo }.to raise_error(Puppet::Error)
end
it "should internally raise an ArgumentError if required features are missing" do
subclass.newvalue(:foo, :required_features => [:a, :b])
resource.provider.expects(:satisfies?).with([:a, :b]).returns false
- lambda { property.validate_features_per_value :foo }.should raise_error(ArgumentError)
+ expect { property.validate_features_per_value :foo }.to raise_error(ArgumentError)
end
it "should validate that all required features are present for regexes" do
value = subclass.newvalue(/./, :required_features => [:a, :b])
resource.provider.expects(:satisfies?).with([:a, :b]).returns true
property.should = "foo"
end
it "should support specifying an individual required feature" do
value = subclass.newvalue(/./, :required_features => :a)
resource.provider.expects(:satisfies?).returns true
property.should = "foo"
end
end
describe "when munging values" do
it "should do nothing if no values or regexes have been defined" do
- property.munge("foo").should == "foo"
+ expect(property.munge("foo")).to eq("foo")
end
it "should return return any matching defined values" do
subclass.newvalue(:foo)
- property.munge("foo").should == :foo
+ expect(property.munge("foo")).to eq(:foo)
end
it "should return any matching aliases" do
subclass.newvalue(:foo)
subclass.aliasvalue(:bar, :foo)
- property.munge("bar").should == :foo
+ expect(property.munge("bar")).to eq(:foo)
end
it "should return the value if it matches a regex" do
subclass.newvalue(/./)
- property.munge("bar").should == "bar"
+ expect(property.munge("bar")).to eq("bar")
end
it "should return the value if no other option is matched" do
subclass.newvalue(:foo)
- property.munge("bar").should == "bar"
+ expect(property.munge("bar")).to eq("bar")
end
end
describe "when syncing the 'should' value" do
it "should set the value" do
subclass.newvalue(:foo)
property.should = :foo
property.expects(:set).with(:foo)
property.sync
end
end
describe "when setting a value" do
it "should catch exceptions and raise Puppet::Error" do
subclass.newvalue(:foo) { raise "eh" }
- lambda { property.set(:foo) }.should raise_error(Puppet::Error)
+ expect { property.set(:foo) }.to raise_error(Puppet::Error)
end
it "fails when the provider does not handle the attribute" do
subclass.name = "unknown"
- lambda { property.set(:a_value) }.should raise_error(Puppet::Error)
+ expect { property.set(:a_value) }.to raise_error(Puppet::Error)
end
it "propogates the errors about missing methods from the provider" do
provider = resource.provider
def provider.bad_method=(value)
value.this_method_does_not_exist
end
subclass.name = :bad_method
- lambda { property.set(:a_value) }.should raise_error(NoMethodError, /this_method_does_not_exist/)
+ expect { property.set(:a_value) }.to raise_error(NoMethodError, /this_method_does_not_exist/)
end
describe "that was defined without a block" do
it "should call the settor on the provider" do
subclass.newvalue(:bar)
resource.provider.expects(:foo=).with :bar
property.set(:bar)
end
end
describe "that was defined with a block" do
it "should call the method created for the value if the value is not a regex" do
subclass.newvalue(:bar) {}
property.expects(:set_bar)
property.set(:bar)
end
it "should call the provided block if the value is a regex" do
subclass.newvalue(/./) { self.test }
property.expects(:test)
property.set("foo")
end
end
end
describe "when producing a change log" do
it "should say 'defined' when the current value is 'absent'" do
- property.change_to_s(:absent, "foo").should =~ /^defined/
+ expect(property.change_to_s(:absent, "foo")).to match(/^defined/)
end
it "should say 'undefined' when the new value is 'absent'" do
- property.change_to_s("foo", :absent).should =~ /^undefined/
+ expect(property.change_to_s("foo", :absent)).to match(/^undefined/)
end
it "should say 'changed' when neither value is 'absent'" do
- property.change_to_s("foo", "bar").should =~ /changed/
+ expect(property.change_to_s("foo", "bar")).to match(/changed/)
end
end
shared_examples_for "#insync?" do
# We share a lot of behaviour between the all and first matching, so we
# use a shared behaviour set to emulate that. The outside world makes
# sure the class, etc, point to the right content.
[[], [12], [12, 13]].each do |input|
it "should return true if should is empty with is => #{input.inspect}" do
property.should = []
- property.must be_insync(input)
+ expect(property).to be_insync(input)
end
end
end
describe "#insync?" do
context "array_matching :all" do
# `@should` is an array of scalar values, and `is` is an array of scalar values.
before :each do
property.class.array_matching = :all
end
it_should_behave_like "#insync?"
context "if the should value is an array" do
before :each do property.should = [1, 2] end
it "should match if is exactly matches" do
- property.must be_insync [1, 2]
+ expect(property).to be_insync [1, 2]
end
it "should match if it matches, but all stringified" do
- property.must be_insync ["1", "2"]
+ expect(property).to be_insync ["1", "2"]
end
it "should not match if some-but-not-all values are stringified" do
- property.must_not be_insync ["1", 2]
- property.must_not be_insync [1, "2"]
+ expect(property).to_not be_insync ["1", 2]
+ expect(property).to_not be_insync [1, "2"]
end
it "should not match if order is different but content the same" do
- property.must_not be_insync [2, 1]
+ expect(property).to_not be_insync [2, 1]
end
it "should not match if there are more items in should than is" do
- property.must_not be_insync [1]
+ expect(property).to_not be_insync [1]
end
it "should not match if there are less items in should than is" do
- property.must_not be_insync [1, 2, 3]
+ expect(property).to_not be_insync [1, 2, 3]
end
it "should not match if `is` is empty but `should` isn't" do
- property.must_not be_insync []
+ expect(property).to_not be_insync []
end
end
end
context "array_matching :first" do
# `@should` is an array of scalar values, and `is` is a scalar value.
before :each do
property.class.array_matching = :first
end
it_should_behave_like "#insync?"
[[1], # only the value
[1, 2], # matching value first
[2, 1], # matching value last
[0, 1, 2], # matching value in the middle
].each do |input|
it "should by true if one unmodified should value of #{input.inspect} matches what is" do
property.should = input
- property.must be_insync 1
+ expect(property).to be_insync 1
end
it "should be true if one stringified should value of #{input.inspect} matches what is" do
property.should = input
- property.must be_insync "1"
+ expect(property).to be_insync "1"
end
end
it "should not match if we expect a string but get the non-stringified value" do
property.should = ["1"]
- property.must_not be_insync 1
+ expect(property).to_not be_insync 1
end
[[0], [0, 2]].each do |input|
it "should not match if no should values match what is" do
property.should = input
- property.must_not be_insync 1
- property.must_not be_insync "1" # shouldn't match either.
+ expect(property).to_not be_insync 1
+ expect(property).to_not be_insync "1" # shouldn't match either.
end
end
end
end
describe "#property_matches?" do
[1, "1", [1], :one].each do |input|
it "should treat two equal objects as equal (#{input.inspect})" do
- property.property_matches?(input, input).should be_true
+ expect(property.property_matches?(input, input)).to be_truthy
end
end
it "should treat two objects as equal if the first argument is the stringified version of the second" do
- property.property_matches?("1", 1).should be_true
+ expect(property.property_matches?("1", 1)).to be_truthy
end
it "should NOT treat two objects as equal if the first argument is not a string, and the second argument is a string, even if it stringifies to the first" do
- property.property_matches?(1, "1").should be_false
+ expect(property.property_matches?(1, "1")).to be_falsey
end
end
end
diff --git a/spec/unit/provider/aixobject_spec.rb b/spec/unit/provider/aixobject_spec.rb
index 0aeccf3ef..11774f263 100644
--- a/spec/unit/provider/aixobject_spec.rb
+++ b/spec/unit/provider/aixobject_spec.rb
@@ -1,101 +1,101 @@
require 'spec_helper'
require 'puppet/provider/aixobject'
describe Puppet::Provider::AixObject do
let(:resource) do
Puppet::Type.type(:user).new(
:name => 'test_aix_user',
:ensure => :present
)
end
let(:provider) do
provider = Puppet::Provider::AixObject.new resource
end
describe "base provider methods" do
[ :lscmd,
:addcmd,
:modifycmd,
:deletecmd
].each do |method|
it "should raise an error when unimplemented method #{method} called" do
- lambda do
+ expect do
provider.send(method)
- end.should raise_error(Puppet::Error, /not defined/)
+ end.to raise_error(Puppet::Error, /not defined/)
end
end
end
describe "attribute mapping methods" do
let(:mapping) do
[
{ :aix_attr => :test_aix_property,
:puppet_prop => :test_puppet_property,
:to => :test_convert_to_aix_method,
:from => :test_convert_to_puppet_method
}
]
end
before(:each) do
provider.class.attribute_mapping = mapping
end
describe ".attribute_mapping_to" do
before(:each) do
if provider.class.instance_variable_defined? :@attribute_mapping_to
provider.class.send(:remove_instance_variable, :@attribute_mapping_to)
end
end
it "should create a hash where the key is the puppet property and the value is a hash with the aix property and the conversion method" do
hash = provider.class.attribute_mapping_to
- hash.should have_key :test_puppet_property
+ expect(hash).to have_key :test_puppet_property
sub_hash = hash[:test_puppet_property]
- sub_hash.should have_key :key
- sub_hash.should have_key :method
- sub_hash[:key].should == :test_aix_property
- sub_hash[:method].should == :test_convert_to_aix_method
+ expect(sub_hash).to have_key :key
+ expect(sub_hash).to have_key :method
+ expect(sub_hash[:key]).to eq(:test_aix_property)
+ expect(sub_hash[:method]).to eq(:test_convert_to_aix_method)
end
it "should cache results between calls" do
provider.class.expects(:attribute_mapping).returns(mapping).once
provider.class.attribute_mapping_to
provider.class.attribute_mapping_to
end
end
describe ".attribute_mapping_from" do
before(:each) do
if provider.class.instance_variable_defined? :@attribute_mapping_from
provider.class.send(:remove_instance_variable, :@attribute_mapping_from)
end
end
it "should create a hash where the key is the aix property and the value is a hash with the puppet property and the conversion method" do
hash = provider.class.attribute_mapping_from
- hash.should have_key :test_aix_property
+ expect(hash).to have_key :test_aix_property
sub_hash = hash[:test_aix_property]
- sub_hash.should have_key :key
- sub_hash.should have_key :method
- sub_hash[:key].should == :test_puppet_property
- sub_hash[:method].should == :test_convert_to_puppet_method
+ expect(sub_hash).to have_key :key
+ expect(sub_hash).to have_key :method
+ expect(sub_hash[:key]).to eq(:test_puppet_property)
+ expect(sub_hash[:method]).to eq(:test_convert_to_puppet_method)
end
it "should cache results between calls" do
provider.class.expects(:attribute_mapping).returns(mapping).once
provider.class.attribute_mapping_from
provider.class.attribute_mapping_from
end
end
end
describe "#getinfo" do
it "should only execute the system command once" do
provider.stubs(:lscmd).returns "ls"
provider.expects(:execute).returns("bob=frank").once
provider.getinfo(true)
end
end
end
\ No newline at end of file
diff --git a/spec/unit/provider/augeas/augeas_spec.rb b/spec/unit/provider/augeas/augeas_spec.rb
index 2c394cafc..a2a97dd93 100755
--- a/spec/unit/provider/augeas/augeas_spec.rb
+++ b/spec/unit/provider/augeas/augeas_spec.rb
@@ -1,966 +1,966 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/package'
provider_class = Puppet::Type.type(:augeas).provider(:augeas)
describe provider_class do
before(:each) do
@resource = Puppet::Type.type(:augeas).new(
:name => "test",
:root => my_fixture_dir,
:provider => :augeas
)
@provider = provider_class.new(@resource)
end
after(:each) do
@provider.close_augeas
end
describe "command parsing" do
it "should break apart a single line into three tokens and clean up the context" do
@resource[:context] = "/context"
tokens = @provider.parse_commands("set Jar/Jar Binks")
- tokens.size.should == 1
- tokens[0].size.should == 3
- tokens[0][0].should == "set"
- tokens[0][1].should == "/context/Jar/Jar"
- tokens[0][2].should == "Binks"
+ expect(tokens.size).to eq(1)
+ expect(tokens[0].size).to eq(3)
+ expect(tokens[0][0]).to eq("set")
+ expect(tokens[0][1]).to eq("/context/Jar/Jar")
+ expect(tokens[0][2]).to eq("Binks")
end
it "should break apart a multiple line into six tokens" do
tokens = @provider.parse_commands("set /Jar/Jar Binks\nrm anakin")
- tokens.size.should == 2
- tokens[0].size.should == 3
- tokens[1].size.should == 2
- tokens[0][0].should == "set"
- tokens[0][1].should == "/Jar/Jar"
- tokens[0][2].should == "Binks"
- tokens[1][0].should == "rm"
- tokens[1][1].should == "anakin"
+ expect(tokens.size).to eq(2)
+ expect(tokens[0].size).to eq(3)
+ expect(tokens[1].size).to eq(2)
+ expect(tokens[0][0]).to eq("set")
+ expect(tokens[0][1]).to eq("/Jar/Jar")
+ expect(tokens[0][2]).to eq("Binks")
+ expect(tokens[1][0]).to eq("rm")
+ expect(tokens[1][1]).to eq("anakin")
end
it "should strip whitespace and ignore blank lines" do
tokens = @provider.parse_commands(" set /Jar/Jar Binks \t\n \n\n rm anakin ")
- tokens.size.should == 2
- tokens[0].size.should == 3
- tokens[1].size.should == 2
- tokens[0][0].should == "set"
- tokens[0][1].should == "/Jar/Jar"
- tokens[0][2].should == "Binks"
- tokens[1][0].should == "rm"
- tokens[1][1].should == "anakin"
+ expect(tokens.size).to eq(2)
+ expect(tokens[0].size).to eq(3)
+ expect(tokens[1].size).to eq(2)
+ expect(tokens[0][0]).to eq("set")
+ expect(tokens[0][1]).to eq("/Jar/Jar")
+ expect(tokens[0][2]).to eq("Binks")
+ expect(tokens[1][0]).to eq("rm")
+ expect(tokens[1][1]).to eq("anakin")
end
it "should handle arrays" do
@resource[:context] = "/foo/"
commands = ["set /Jar/Jar Binks", "rm anakin"]
tokens = @provider.parse_commands(commands)
- tokens.size.should == 2
- tokens[0].size.should == 3
- tokens[1].size.should == 2
- tokens[0][0].should == "set"
- tokens[0][1].should == "/Jar/Jar"
- tokens[0][2].should == "Binks"
- tokens[1][0].should == "rm"
- tokens[1][1].should == "/foo/anakin"
+ expect(tokens.size).to eq(2)
+ expect(tokens[0].size).to eq(3)
+ expect(tokens[1].size).to eq(2)
+ expect(tokens[0][0]).to eq("set")
+ expect(tokens[0][1]).to eq("/Jar/Jar")
+ expect(tokens[0][2]).to eq("Binks")
+ expect(tokens[1][0]).to eq("rm")
+ expect(tokens[1][1]).to eq("/foo/anakin")
end
# This is not supported in the new parsing class
#it "should concat the last values" do
# provider = provider_class.new
# tokens = provider.parse_commands("set /Jar/Jar Binks is my copilot")
# tokens.size.should == 1
# tokens[0].size.should == 3
# tokens[0][0].should == "set"
# tokens[0][1].should == "/Jar/Jar"
# tokens[0][2].should == "Binks is my copilot"
#end
it "should accept spaces in the value and single ticks" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands("set JarJar 'Binks is my copilot'")
- tokens.size.should == 1
- tokens[0].size.should == 3
- tokens[0][0].should == "set"
- tokens[0][1].should == "/foo/JarJar"
- tokens[0][2].should == "Binks is my copilot"
+ expect(tokens.size).to eq(1)
+ expect(tokens[0].size).to eq(3)
+ expect(tokens[0][0]).to eq("set")
+ expect(tokens[0][1]).to eq("/foo/JarJar")
+ expect(tokens[0][2]).to eq("Binks is my copilot")
end
it "should accept spaces in the value and double ticks" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands('set /JarJar "Binks is my copilot"')
- tokens.size.should == 1
- tokens[0].size.should == 3
- tokens[0][0].should == "set"
- tokens[0][1].should == '/JarJar'
- tokens[0][2].should == 'Binks is my copilot'
+ expect(tokens.size).to eq(1)
+ expect(tokens[0].size).to eq(3)
+ expect(tokens[0][0]).to eq("set")
+ expect(tokens[0][1]).to eq('/JarJar')
+ expect(tokens[0][2]).to eq('Binks is my copilot')
end
it "should accept mixed ticks" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands('set JarJar "Some \'Test\'"')
- tokens.size.should == 1
- tokens[0].size.should == 3
- tokens[0][0].should == "set"
- tokens[0][1].should == '/foo/JarJar'
- tokens[0][2].should == "Some \'Test\'"
+ expect(tokens.size).to eq(1)
+ expect(tokens[0].size).to eq(3)
+ expect(tokens[0][0]).to eq("set")
+ expect(tokens[0][1]).to eq('/foo/JarJar')
+ expect(tokens[0][2]).to eq("Some \'Test\'")
end
it "should handle predicates with literals" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands("rm */*[module='pam_console.so']")
- tokens.should == [["rm", "/foo/*/*[module='pam_console.so']"]]
+ expect(tokens).to eq([["rm", "/foo/*/*[module='pam_console.so']"]])
end
it "should handle whitespace in predicates" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands("ins 42 before /files/etc/hosts/*/ipaddr[ . = '127.0.0.1' ]")
- tokens.should == [["ins", "42", "before","/files/etc/hosts/*/ipaddr[ . = '127.0.0.1' ]"]]
+ expect(tokens).to eq([["ins", "42", "before","/files/etc/hosts/*/ipaddr[ . = '127.0.0.1' ]"]])
end
it "should handle multiple predicates" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands("clear pam.d/*/*[module = 'system-auth'][type = 'account']")
- tokens.should == [["clear", "/foo/pam.d/*/*[module = 'system-auth'][type = 'account']"]]
+ expect(tokens).to eq([["clear", "/foo/pam.d/*/*[module = 'system-auth'][type = 'account']"]])
end
it "should handle nested predicates" do
@resource[:context] = "/foo/"
args = ["clear", "/foo/pam.d/*/*[module[ ../type = 'type] = 'system-auth'][type[last()] = 'account']"]
tokens = @provider.parse_commands(args.join(" "))
- tokens.should == [ args ]
+ expect(tokens).to eq([ args ])
end
it "should handle escaped doublequotes in doublequoted string" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands("set /foo \"''\\\"''\"")
- tokens.should == [[ "set", "/foo", "''\\\"''" ]]
+ expect(tokens).to eq([[ "set", "/foo", "''\\\"''" ]])
end
it "should allow escaped spaces and brackets in paths" do
@resource[:context] = "/foo/"
args = [ "set", "/white\\ space/\\[section", "value" ]
tokens = @provider.parse_commands(args.join(" \t "))
- tokens.should == [ args ]
+ expect(tokens).to eq([ args ])
end
it "should allow single quoted escaped spaces in paths" do
@resource[:context] = "/foo/"
args = [ "set", "'/white\\ space/key'", "value" ]
tokens = @provider.parse_commands(args.join(" \t "))
- tokens.should == [[ "set", "/white\\ space/key", "value" ]]
+ expect(tokens).to eq([[ "set", "/white\\ space/key", "value" ]])
end
it "should allow double quoted escaped spaces in paths" do
@resource[:context] = "/foo/"
args = [ "set", '"/white\\ space/key"', "value" ]
tokens = @provider.parse_commands(args.join(" \t "))
- tokens.should == [[ "set", "/white\\ space/key", "value" ]]
+ expect(tokens).to eq([[ "set", "/white\\ space/key", "value" ]])
end
it "should remove trailing slashes" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands("set foo/ bar")
- tokens.should == [[ "set", "/foo/foo", "bar" ]]
+ expect(tokens).to eq([[ "set", "/foo/foo", "bar" ]])
end
end
describe "get filters" do
before do
augeas = stub("augeas", :get => "value")
augeas.stubs("close")
@provider.aug = augeas
end
it "should return false for a = nonmatch" do
command = ["get", "fake value", "==", "value"]
- @provider.process_get(command).should == true
+ expect(@provider.process_get(command)).to eq(true)
end
it "should return true for a != match" do
command = ["get", "fake value", "!=", "value"]
- @provider.process_get(command).should == false
+ expect(@provider.process_get(command)).to eq(false)
end
it "should return true for a =~ match" do
command = ["get", "fake value", "=~", "val*"]
- @provider.process_get(command).should == true
+ expect(@provider.process_get(command)).to eq(true)
end
it "should return false for a == nonmatch" do
command = ["get", "fake value", "=~", "num*"]
- @provider.process_get(command).should == false
+ expect(@provider.process_get(command)).to eq(false)
end
end
describe "match filters" do
before do
augeas = stub("augeas", :match => ["set", "of", "values"])
augeas.stubs("close")
@provider = provider_class.new(@resource)
@provider.aug = augeas
end
it "should return true for size match" do
command = ["match", "fake value", "size == 3"]
- @provider.process_match(command).should == true
+ expect(@provider.process_match(command)).to eq(true)
end
it "should return false for a size non match" do
command = ["match", "fake value", "size < 3"]
- @provider.process_match(command).should == false
+ expect(@provider.process_match(command)).to eq(false)
end
it "should return true for includes match" do
command = ["match", "fake value", "include values"]
- @provider.process_match(command).should == true
+ expect(@provider.process_match(command)).to eq(true)
end
it "should return false for includes non match" do
command = ["match", "fake value", "include JarJar"]
- @provider.process_match(command).should == false
+ expect(@provider.process_match(command)).to eq(false)
end
it "should return true for includes match" do
command = ["match", "fake value", "not_include JarJar"]
- @provider.process_match(command).should == true
+ expect(@provider.process_match(command)).to eq(true)
end
it "should return false for includes non match" do
command = ["match", "fake value", "not_include values"]
- @provider.process_match(command).should == false
+ expect(@provider.process_match(command)).to eq(false)
end
it "should return true for an array match" do
command = ["match", "fake value", "== ['set', 'of', 'values']"]
- @provider.process_match(command).should == true
+ expect(@provider.process_match(command)).to eq(true)
end
it "should return false for an array non match" do
command = ["match", "fake value", "== ['this', 'should', 'not', 'match']"]
- @provider.process_match(command).should == false
+ expect(@provider.process_match(command)).to eq(false)
end
it "should return false for an array match with noteq" do
command = ["match", "fake value", "!= ['set', 'of', 'values']"]
- @provider.process_match(command).should == false
+ expect(@provider.process_match(command)).to eq(false)
end
it "should return true for an array non match with noteq" do
command = ["match", "fake value", "!= ['this', 'should', 'not', 'match']"]
- @provider.process_match(command).should == true
+ expect(@provider.process_match(command)).to eq(true)
end
end
describe "need to run" do
before(:each) do
@augeas = stub("augeas")
@augeas.stubs("close")
@provider.aug = @augeas
# These tests pretend to be an earlier version so the provider doesn't
# attempt to make the change in the need_to_run? method
@provider.stubs(:get_augeas_version).returns("0.3.5")
end
it "should handle no filters" do
@augeas.stubs("match").returns(["set", "of", "values"])
- @provider.need_to_run?.should == true
+ expect(@provider.need_to_run?).to eq(true)
end
it "should return true when a get filter matches" do
@resource[:onlyif] = "get path == value"
@augeas.stubs("get").returns("value")
- @provider.need_to_run?.should == true
+ expect(@provider.need_to_run?).to eq(true)
end
describe "performing numeric comparisons (#22617)" do
it "should return true when a get string compare is true" do
@resource[:onlyif] = "get bpath > a"
@augeas.stubs("get").returns("b")
- @provider.need_to_run?.should == true
+ expect(@provider.need_to_run?).to eq(true)
end
it "should return false when a get string compare is false" do
@resource[:onlyif] = "get a19path > a2"
@augeas.stubs("get").returns("a19")
- @provider.need_to_run?.should == false
+ expect(@provider.need_to_run?).to eq(false)
end
it "should return true when a get int gt compare is true" do
@resource[:onlyif] = "get path19 > 2"
@augeas.stubs("get").returns("19")
- @provider.need_to_run?.should == true
+ expect(@provider.need_to_run?).to eq(true)
end
it "should return true when a get int ge compare is true" do
@resource[:onlyif] = "get path19 >= 2"
@augeas.stubs("get").returns("19")
- @provider.need_to_run?.should == true
+ expect(@provider.need_to_run?).to eq(true)
end
it "should return true when a get int lt compare is true" do
@resource[:onlyif] = "get path2 < 19"
@augeas.stubs("get").returns("2")
- @provider.need_to_run?.should == true
+ expect(@provider.need_to_run?).to eq(true)
end
it "should return false when a get int le compare is false" do
@resource[:onlyif] = "get path39 <= 4"
@augeas.stubs("get").returns("39")
- @provider.need_to_run?.should == false
+ expect(@provider.need_to_run?).to eq(false)
end
end
describe "performing is_numeric checks (#22617)" do
it "should return false for nil" do
- @provider.is_numeric?(nil).should == false
+ expect(@provider.is_numeric?(nil)).to eq(false)
end
it "should return true for Fixnums" do
- @provider.is_numeric?(9).should == true
+ expect(@provider.is_numeric?(9)).to eq(true)
end
it "should return true for numbers in Strings" do
- @provider.is_numeric?('9').should == true
+ expect(@provider.is_numeric?('9')).to eq(true)
end
it "should return false for non-number Strings" do
- @provider.is_numeric?('x9').should == false
+ expect(@provider.is_numeric?('x9')).to eq(false)
end
it "should return false for other types" do
- @provider.is_numeric?([true]).should == false
+ expect(@provider.is_numeric?([true])).to eq(false)
end
end
it "should return false when a get filter does not match" do
@resource[:onlyif] = "get path == another value"
@augeas.stubs("get").returns("value")
- @provider.need_to_run?.should == false
+ expect(@provider.need_to_run?).to eq(false)
end
it "should return true when a match filter matches" do
@resource[:onlyif] = "match path size == 3"
@augeas.stubs("match").returns(["set", "of", "values"])
- @provider.need_to_run?.should == true
+ expect(@provider.need_to_run?).to eq(true)
end
it "should return false when a match filter does not match" do
@resource[:onlyif] = "match path size == 2"
@augeas.stubs("match").returns(["set", "of", "values"])
- @provider.need_to_run?.should == false
+ expect(@provider.need_to_run?).to eq(false)
end
# Now setting force to true
it "setting force should not change the above logic" do
@resource[:force] = true
@resource[:onlyif] = "match path size == 2"
@augeas.stubs("match").returns(["set", "of", "values"])
- @provider.need_to_run?.should == false
+ expect(@provider.need_to_run?).to eq(false)
end
#Ticket 5211 testing
it "should return true when a size != the provided value" do
@resource[:onlyif] = "match path size != 17"
@augeas.stubs("match").returns(["set", "of", "values"])
- @provider.need_to_run?.should == true
+ expect(@provider.need_to_run?).to eq(true)
end
#Ticket 5211 testing
it "should return false when a size does equal the provided value" do
@resource[:onlyif] = "match path size != 3"
@augeas.stubs("match").returns(["set", "of", "values"])
- @provider.need_to_run?.should == false
+ expect(@provider.need_to_run?).to eq(false)
end
[true, false].product([true, false]) do |cfg, param|
describe "and Puppet[:show_diff] is #{cfg} and show_diff => #{param}" do
let(:file) { "/some/random/file" }
before(:each) do
Puppet[:show_diff] = cfg
@resource[:show_diff] = param
@resource[:root] = ""
@resource[:context] = "/files"
@resource[:changes] = ["set #{file}/foo bar"]
File.stubs(:delete)
@provider.stubs(:get_augeas_version).returns("0.10.0")
@provider.stubs("diff").with("#{file}", "#{file}.augnew").returns("diff")
@augeas.stubs(:set).returns(true)
@augeas.stubs(:save).returns(true)
@augeas.stubs(:match).with("/augeas/events/saved").returns(["/augeas/events/saved"])
@augeas.stubs(:get).with("/augeas/events/saved").returns("/files#{file}")
@augeas.stubs(:set).with("/augeas/save", "newfile")
end
if cfg && param
it "should display a diff" do
- @provider.should be_need_to_run
+ expect(@provider).to be_need_to_run
expect(@logs[0].message).to eq("\ndiff")
end
else
it "should not display a diff" do
- @provider.should be_need_to_run
+ expect(@provider).to be_need_to_run
- @logs.should be_empty
+ expect(@logs).to be_empty
end
end
end
end
# Ticket 2728 (diff files)
describe "and configured to show diffs" do
before(:each) do
Puppet[:show_diff] = true
@resource[:show_diff] = true
@resource[:root] = ""
@provider.stubs(:get_augeas_version).returns("0.10.0")
@augeas.stubs(:set).returns(true)
@augeas.stubs(:save).returns(true)
end
it "should display a diff when a single file is shown to have been changed" do
file = "/etc/hosts"
File.stubs(:delete)
@resource[:loglevel] = "crit"
@resource[:context] = "/files"
@resource[:changes] = ["set #{file}/foo bar"]
@augeas.stubs(:match).with("/augeas/events/saved").returns(["/augeas/events/saved"])
@augeas.stubs(:get).with("/augeas/events/saved").returns("/files#{file}")
@augeas.expects(:set).with("/augeas/save", "newfile")
@provider.expects("diff").with("#{file}", "#{file}.augnew").returns("diff")
- @provider.should be_need_to_run
+ expect(@provider).to be_need_to_run
expect(@logs[0].message).to eq("\ndiff")
expect(@logs[0].level).to eq(:crit)
end
it "should display a diff for each file that is changed when changing many files" do
file1 = "/etc/hosts"
file2 = "/etc/resolv.conf"
File.stubs(:delete)
@resource[:context] = "/files"
@resource[:changes] = ["set #{file1}/foo bar", "set #{file2}/baz biz"]
@augeas.stubs(:match).with("/augeas/events/saved").returns(["/augeas/events/saved[1]", "/augeas/events/saved[2]"])
@augeas.stubs(:get).with("/augeas/events/saved[1]").returns("/files#{file1}")
@augeas.stubs(:get).with("/augeas/events/saved[2]").returns("/files#{file2}")
@augeas.expects(:set).with("/augeas/save", "newfile")
@provider.expects(:diff).with("#{file1}", "#{file1}.augnew").returns("diff #{file1}")
@provider.expects(:diff).with("#{file2}", "#{file2}.augnew").returns("diff #{file2}")
- @provider.should be_need_to_run
+ expect(@provider).to be_need_to_run
expect(@logs.collect(&:message)).to include("\ndiff #{file1}", "\ndiff #{file2}")
expect(@logs.collect(&:level)).to eq([:notice, :notice])
end
describe "and resource[:root] is set" do
it "should call diff when a file is shown to have been changed" do
root = "/tmp/foo"
file = "/etc/hosts"
File.stubs(:delete)
@resource[:context] = "/files"
@resource[:changes] = ["set #{file}/foo bar"]
@resource[:root] = root
@augeas.stubs(:match).with("/augeas/events/saved").returns(["/augeas/events/saved"])
@augeas.stubs(:get).with("/augeas/events/saved").returns("/files#{file}")
@augeas.expects(:set).with("/augeas/save", "newfile")
@provider.expects(:diff).with("#{root}#{file}", "#{root}#{file}.augnew").returns("diff")
- @provider.should be_need_to_run
+ expect(@provider).to be_need_to_run
expect(@logs[0].message).to eq("\ndiff")
expect(@logs[0].level).to eq(:notice)
end
end
it "should not call diff if no files change" do
file = "/etc/hosts"
@resource[:context] = "/files"
@resource[:changes] = ["set #{file}/foo bar"]
@augeas.stubs(:match).with("/augeas/events/saved").returns([])
@augeas.expects(:set).with("/augeas/save", "newfile")
@augeas.expects(:get).with("/augeas/events/saved").never()
@augeas.expects(:close)
@provider.expects(:diff).never()
- @provider.should_not be_need_to_run
+ expect(@provider).not_to be_need_to_run
end
it "should cleanup the .augnew file" do
file = "/etc/hosts"
@resource[:context] = "/files"
@resource[:changes] = ["set #{file}/foo bar"]
@augeas.stubs(:match).with("/augeas/events/saved").returns(["/augeas/events/saved"])
@augeas.stubs(:get).with("/augeas/events/saved").returns("/files#{file}")
@augeas.expects(:set).with("/augeas/save", "newfile")
@augeas.expects(:close)
File.expects(:delete).with(file + ".augnew")
@provider.expects(:diff).with("#{file}", "#{file}.augnew").returns("")
- @provider.should be_need_to_run
+ expect(@provider).to be_need_to_run
end
# Workaround for Augeas bug #264 which reports filenames twice
it "should handle duplicate /augeas/events/saved filenames" do
file = "/etc/hosts"
@resource[:context] = "/files"
@resource[:changes] = ["set #{file}/foo bar"]
@augeas.stubs(:match).with("/augeas/events/saved").returns(["/augeas/events/saved[1]", "/augeas/events/saved[2]"])
@augeas.stubs(:get).with("/augeas/events/saved[1]").returns("/files#{file}")
@augeas.stubs(:get).with("/augeas/events/saved[2]").returns("/files#{file}")
@augeas.expects(:set).with("/augeas/save", "newfile")
@augeas.expects(:close)
File.expects(:delete).with(file + ".augnew").once()
@provider.expects(:diff).with("#{file}", "#{file}.augnew").returns("").once()
- @provider.should be_need_to_run
+ expect(@provider).to be_need_to_run
end
it "should fail with an error if saving fails" do
file = "/etc/hosts"
@resource[:context] = "/files"
@resource[:changes] = ["set #{file}/foo bar"]
@augeas.stubs(:save).returns(false)
@augeas.stubs(:match).with("/augeas/events/saved").returns([])
@augeas.expects(:close)
@provider.expects(:diff).never()
@provider.expects(:print_put_errors)
- lambda { @provider.need_to_run? }.should raise_error(Puppet::Error)
+ expect { @provider.need_to_run? }.to raise_error(Puppet::Error)
end
end
end
describe "augeas execution integration" do
before do
@augeas = stub("augeas", :load)
@augeas.stubs("close")
@augeas.stubs(:match).with("/augeas/events/saved").returns([])
@provider.aug = @augeas
@provider.stubs(:get_augeas_version).returns("0.3.5")
end
it "should handle set commands" do
@resource[:changes] = "set JarJar Binks"
@resource[:context] = "/some/path/"
@augeas.expects(:set).with("/some/path/JarJar", "Binks").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
it "should handle rm commands" do
@resource[:changes] = "rm /Jar/Jar"
@augeas.expects(:rm).with("/Jar/Jar")
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
it "should handle remove commands" do
@resource[:changes] = "remove /Jar/Jar"
@augeas.expects(:rm).with("/Jar/Jar")
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
it "should handle clear commands" do
@resource[:changes] = "clear Jar/Jar"
@resource[:context] = "/foo/"
@augeas.expects(:clear).with("/foo/Jar/Jar").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
describe "touch command" do
it "should clear missing path" do
@resource[:changes] = "touch Jar/Jar"
@resource[:context] = "/foo/"
@augeas.expects(:match).with("/foo/Jar/Jar").returns([])
@augeas.expects(:clear).with("/foo/Jar/Jar").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
it "should not change on existing path" do
@resource[:changes] = "touch Jar/Jar"
@resource[:context] = "/foo/"
@augeas.expects(:match).with("/foo/Jar/Jar").returns(["/foo/Jar/Jar"])
@augeas.expects(:clear).never
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
end
it "should handle ins commands with before" do
@resource[:changes] = "ins Binks before Jar/Jar"
@resource[:context] = "/foo"
@augeas.expects(:insert).with("/foo/Jar/Jar", "Binks", true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
it "should handle ins commands with after" do
@resource[:changes] = "ins Binks after /Jar/Jar"
@resource[:context] = "/foo"
@augeas.expects(:insert).with("/Jar/Jar", "Binks", false)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
it "should handle ins with no context" do
@resource[:changes] = "ins Binks after /Jar/Jar"
@augeas.expects(:insert).with("/Jar/Jar", "Binks", false)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
it "should handle multiple commands" do
@resource[:changes] = ["ins Binks after /Jar/Jar", "clear Jar/Jar"]
@resource[:context] = "/foo/"
@augeas.expects(:insert).with("/Jar/Jar", "Binks", false)
@augeas.expects(:clear).with("/foo/Jar/Jar").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
it "should handle defvar commands" do
@resource[:changes] = "defvar myjar Jar/Jar"
@resource[:context] = "/foo/"
@augeas.expects(:defvar).with("myjar", "/foo/Jar/Jar").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
it "should pass through augeas variables without context" do
@resource[:changes] = ["defvar myjar Jar/Jar","set $myjar/Binks 1"]
@resource[:context] = "/foo/"
@augeas.expects(:defvar).with("myjar", "/foo/Jar/Jar").returns(true)
# this is the important bit, shouldn't be /foo/$myjar/Binks
@augeas.expects(:set).with("$myjar/Binks", "1").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
it "should handle defnode commands" do
@resource[:changes] = "defnode newjar Jar/Jar[last()+1] Binks"
@resource[:context] = "/foo/"
@augeas.expects(:defnode).with("newjar", "/foo/Jar/Jar[last()+1]", "Binks").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
it "should handle mv commands" do
@resource[:changes] = "mv Jar/Jar Binks"
@resource[:context] = "/foo/"
@augeas.expects(:mv).with("/foo/Jar/Jar", "/foo/Binks").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
it "should handle setm commands" do
@resource[:changes] = ["set test[1]/Jar/Jar Foo","set test[2]/Jar/Jar Bar","setm test Jar/Jar Binks"]
@resource[:context] = "/foo/"
@augeas.expects(:respond_to?).with("setm").returns(true)
@augeas.expects(:set).with("/foo/test[1]/Jar/Jar", "Foo").returns(true)
@augeas.expects(:set).with("/foo/test[2]/Jar/Jar", "Bar").returns(true)
@augeas.expects(:setm).with("/foo/test", "Jar/Jar", "Binks").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
it "should throw error if setm command not supported" do
@resource[:changes] = ["set test[1]/Jar/Jar Foo","set test[2]/Jar/Jar Bar","setm test Jar/Jar Binks"]
@resource[:context] = "/foo/"
@augeas.expects(:respond_to?).with("setm").returns(false)
@augeas.expects(:set).with("/foo/test[1]/Jar/Jar", "Foo").returns(true)
@augeas.expects(:set).with("/foo/test[2]/Jar/Jar", "Bar").returns(true)
expect { @provider.execute_changes }.to raise_error RuntimeError, /command 'setm' not supported/
end
it "should handle clearm commands" do
@resource[:changes] = ["set test[1]/Jar/Jar Foo","set test[2]/Jar/Jar Bar","clearm test Jar/Jar"]
@resource[:context] = "/foo/"
@augeas.expects(:respond_to?).with("clearm").returns(true)
@augeas.expects(:set).with("/foo/test[1]/Jar/Jar", "Foo").returns(true)
@augeas.expects(:set).with("/foo/test[2]/Jar/Jar", "Bar").returns(true)
@augeas.expects(:clearm).with("/foo/test", "Jar/Jar").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
- @provider.execute_changes.should == :executed
+ expect(@provider.execute_changes).to eq(:executed)
end
it "should throw error if clearm command not supported" do
@resource[:changes] = ["set test[1]/Jar/Jar Foo","set test[2]/Jar/Jar Bar","clearm test Jar/Jar"]
@resource[:context] = "/foo/"
@augeas.expects(:respond_to?).with("clearm").returns(false)
@augeas.expects(:set).with("/foo/test[1]/Jar/Jar", "Foo").returns(true)
@augeas.expects(:set).with("/foo/test[2]/Jar/Jar", "Bar").returns(true)
expect { @provider.execute_changes }.to raise_error(RuntimeError, /command 'clearm' not supported/)
end
it "should throw error if saving failed" do
@resource[:changes] = ["set test[1]/Jar/Jar Foo","set test[2]/Jar/Jar Bar","clearm test Jar/Jar"]
@resource[:context] = "/foo/"
@augeas.expects(:respond_to?).with("clearm").returns(true)
@augeas.expects(:set).with("/foo/test[1]/Jar/Jar", "Foo").returns(true)
@augeas.expects(:set).with("/foo/test[2]/Jar/Jar", "Bar").returns(true)
@augeas.expects(:clearm).with("/foo/test", "Jar/Jar").returns(true)
@augeas.expects(:save).returns(false)
@provider.expects(:print_put_errors)
@augeas.expects(:match).returns([])
expect { @provider.execute_changes }.to raise_error(Puppet::Error)
end
end
describe "when making changes", :if => Puppet.features.augeas? do
include PuppetSpec::Files
it "should not clobber the file if it's a symlink" do
Puppet::Util::Storage.stubs(:store)
link = tmpfile('link')
target = tmpfile('target')
FileUtils.touch(target)
Puppet::FileSystem.symlink(target, link)
resource = Puppet::Type.type(:augeas).new(
:name => 'test',
:incl => link,
:lens => 'Sshd.lns',
:changes => "set PermitRootLogin no"
)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource resource
catalog.apply
- File.ftype(link).should == 'link'
- Puppet::FileSystem.readlink(link).should == target
- File.read(target).should =~ /PermitRootLogin no/
+ expect(File.ftype(link)).to eq('link')
+ expect(Puppet::FileSystem.readlink(link)).to eq(target)
+ expect(File.read(target)).to match(/PermitRootLogin no/)
end
end
describe "load/save failure reporting" do
before do
@augeas = stub("augeas")
@augeas.stubs("close")
@provider.aug = @augeas
end
describe "should find load errors" do
before do
@augeas.expects(:match).with("/augeas//error").returns(["/augeas/files/foo/error"])
@augeas.expects(:match).with("/augeas/files/foo/error/*").returns(["/augeas/files/foo/error/path", "/augeas/files/foo/error/message"])
@augeas.expects(:get).with("/augeas/files/foo/error").returns("some_failure")
@augeas.expects(:get).with("/augeas/files/foo/error/path").returns("/foo")
@augeas.expects(:get).with("/augeas/files/foo/error/message").returns("Failed to...")
end
it "and output only to debug when no path supplied" do
@provider.expects(:debug).times(5)
@provider.expects(:warning).never()
@provider.print_load_errors(nil)
end
it "and output a warning and to debug when path supplied" do
@augeas.expects(:match).with("/augeas/files/foo//error").returns(["/augeas/files/foo/error"])
@provider.expects(:warning).once()
@provider.expects(:debug).times(4)
@provider.print_load_errors('/augeas/files/foo//error')
end
it "and output only to debug when path doesn't match" do
@augeas.expects(:match).with("/augeas/files/foo//error").returns([])
@provider.expects(:warning).never()
@provider.expects(:debug).times(5)
@provider.print_load_errors('/augeas/files/foo//error')
end
end
it "should find load errors from lenses" do
@augeas.expects(:match).with("/augeas//error").twice.returns(["/augeas/load/Xfm/error"])
@augeas.expects(:match).with("/augeas/load/Xfm/error/*").returns([])
@augeas.expects(:get).with("/augeas/load/Xfm/error").returns(["Could not find lens php.aug"])
@provider.expects(:warning).once()
@provider.expects(:debug).twice()
@provider.print_load_errors('/augeas//error')
end
it "should find save errors and output to debug" do
@augeas.expects(:match).with("/augeas//error[. = 'put_failed']").returns(["/augeas/files/foo/error"])
@augeas.expects(:match).with("/augeas/files/foo/error/*").returns(["/augeas/files/foo/error/path", "/augeas/files/foo/error/message"])
@augeas.expects(:get).with("/augeas/files/foo/error").returns("some_failure")
@augeas.expects(:get).with("/augeas/files/foo/error/path").returns("/foo")
@augeas.expects(:get).with("/augeas/files/foo/error/message").returns("Failed to...")
@provider.expects(:debug).times(5)
@provider.print_put_errors
end
end
# Run initialisation tests of the real Augeas library to test our open_augeas
# method. This relies on Augeas and ruby-augeas on the host to be
# functioning.
describe "augeas lib initialisation", :if => Puppet.features.augeas? do
# Expect lenses for fstab and hosts
it "should have loaded standard files by default" do
aug = @provider.open_augeas
- aug.should_not == nil
- aug.match("/files/etc/fstab").should == ["/files/etc/fstab"]
- aug.match("/files/etc/hosts").should == ["/files/etc/hosts"]
- aug.match("/files/etc/test").should == []
+ expect(aug).not_to eq(nil)
+ expect(aug.match("/files/etc/fstab")).to eq(["/files/etc/fstab"])
+ expect(aug.match("/files/etc/hosts")).to eq(["/files/etc/hosts"])
+ expect(aug.match("/files/etc/test")).to eq([])
end
it "should report load errors to debug only" do
@provider.expects(:print_load_errors).with(nil)
aug = @provider.open_augeas
- aug.should_not == nil
+ expect(aug).not_to eq(nil)
end
# Only the file specified should be loaded
it "should load one file if incl/lens used" do
@resource[:incl] = "/etc/hosts"
@resource[:lens] = "Hosts.lns"
@provider.expects(:print_load_errors).with('/augeas//error')
aug = @provider.open_augeas
- aug.should_not == nil
- aug.match("/files/etc/fstab").should == []
- aug.match("/files/etc/hosts").should == ["/files/etc/hosts"]
- aug.match("/files/etc/test").should == []
+ expect(aug).not_to eq(nil)
+ expect(aug.match("/files/etc/fstab")).to eq([])
+ expect(aug.match("/files/etc/hosts")).to eq(["/files/etc/hosts"])
+ expect(aug.match("/files/etc/test")).to eq([])
end
it "should also load lenses from load_path" do
@resource[:load_path] = my_fixture_dir
aug = @provider.open_augeas
- aug.should_not == nil
- aug.match("/files/etc/fstab").should == ["/files/etc/fstab"]
- aug.match("/files/etc/hosts").should == ["/files/etc/hosts"]
- aug.match("/files/etc/test").should == ["/files/etc/test"]
+ expect(aug).not_to eq(nil)
+ expect(aug.match("/files/etc/fstab")).to eq(["/files/etc/fstab"])
+ expect(aug.match("/files/etc/hosts")).to eq(["/files/etc/hosts"])
+ expect(aug.match("/files/etc/test")).to eq(["/files/etc/test"])
end
it "should also load lenses from pluginsync'd path" do
Puppet[:libdir] = my_fixture_dir
aug = @provider.open_augeas
- aug.should_not == nil
- aug.match("/files/etc/fstab").should == ["/files/etc/fstab"]
- aug.match("/files/etc/hosts").should == ["/files/etc/hosts"]
- aug.match("/files/etc/test").should == ["/files/etc/test"]
+ expect(aug).not_to eq(nil)
+ expect(aug.match("/files/etc/fstab")).to eq(["/files/etc/fstab"])
+ expect(aug.match("/files/etc/hosts")).to eq(["/files/etc/hosts"])
+ expect(aug.match("/files/etc/test")).to eq(["/files/etc/test"])
end
# Optimisations added for Augeas 0.8.2 or higher is available, see #7285
describe ">= 0.8.2 optimisations", :if => Puppet.features.augeas? && Facter.value(:augeasversion) && Puppet::Util::Package.versioncmp(Facter.value(:augeasversion), "0.8.2") >= 0 do
it "should only load one file if relevant context given" do
@resource[:context] = "/files/etc/fstab"
@provider.expects(:print_load_errors).with('/augeas/files/etc/fstab//error')
aug = @provider.open_augeas
- aug.should_not == nil
- aug.match("/files/etc/fstab").should == ["/files/etc/fstab"]
- aug.match("/files/etc/hosts").should == []
+ expect(aug).not_to eq(nil)
+ expect(aug.match("/files/etc/fstab")).to eq(["/files/etc/fstab"])
+ expect(aug.match("/files/etc/hosts")).to eq([])
end
it "should only load one lens from load_path if context given" do
@resource[:context] = "/files/etc/test"
@resource[:load_path] = my_fixture_dir
@provider.expects(:print_load_errors).with('/augeas/files/etc/test//error')
aug = @provider.open_augeas
- aug.should_not == nil
- aug.match("/files/etc/fstab").should == []
- aug.match("/files/etc/hosts").should == []
- aug.match("/files/etc/test").should == ["/files/etc/test"]
+ expect(aug).not_to eq(nil)
+ expect(aug.match("/files/etc/fstab")).to eq([])
+ expect(aug.match("/files/etc/hosts")).to eq([])
+ expect(aug.match("/files/etc/test")).to eq(["/files/etc/test"])
end
it "should load standard files if context isn't specific" do
@resource[:context] = "/files/etc"
@provider.expects(:print_load_errors).with(nil)
aug = @provider.open_augeas
- aug.should_not == nil
- aug.match("/files/etc/fstab").should == ["/files/etc/fstab"]
- aug.match("/files/etc/hosts").should == ["/files/etc/hosts"]
+ expect(aug).not_to eq(nil)
+ expect(aug.match("/files/etc/fstab")).to eq(["/files/etc/fstab"])
+ expect(aug.match("/files/etc/hosts")).to eq(["/files/etc/hosts"])
end
it "should not optimise if the context is a complex path" do
@resource[:context] = "/files/*[label()='etc']"
@provider.expects(:print_load_errors).with(nil)
aug = @provider.open_augeas
- aug.should_not == nil
- aug.match("/files/etc/fstab").should == ["/files/etc/fstab"]
- aug.match("/files/etc/hosts").should == ["/files/etc/hosts"]
+ expect(aug).not_to eq(nil)
+ expect(aug.match("/files/etc/fstab")).to eq(["/files/etc/fstab"])
+ expect(aug.match("/files/etc/hosts")).to eq(["/files/etc/hosts"])
end
end
end
describe "get_load_path" do
it "should offer no load_path by default" do
- @provider.get_load_path(@resource).should == ""
+ expect(@provider.get_load_path(@resource)).to eq("")
end
it "should offer one path from load_path" do
@resource[:load_path] = "/foo"
- @provider.get_load_path(@resource).should == "/foo"
+ expect(@provider.get_load_path(@resource)).to eq("/foo")
end
it "should offer multiple colon-separated paths from load_path" do
@resource[:load_path] = "/foo:/bar:/baz"
- @provider.get_load_path(@resource).should == "/foo:/bar:/baz"
+ expect(@provider.get_load_path(@resource)).to eq("/foo:/bar:/baz")
end
it "should offer multiple paths in array from load_path" do
@resource[:load_path] = ["/foo", "/bar", "/baz"]
- @provider.get_load_path(@resource).should == "/foo:/bar:/baz"
+ expect(@provider.get_load_path(@resource)).to eq("/foo:/bar:/baz")
end
it "should offer pluginsync augeas/lenses subdir" do
Puppet[:libdir] = my_fixture_dir
- @provider.get_load_path(@resource).should == "#{my_fixture_dir}/augeas/lenses"
+ expect(@provider.get_load_path(@resource)).to eq("#{my_fixture_dir}/augeas/lenses")
end
it "should offer both pluginsync and load_path paths" do
Puppet[:libdir] = my_fixture_dir
@resource[:load_path] = ["/foo", "/bar", "/baz"]
- @provider.get_load_path(@resource).should == "/foo:/bar:/baz:#{my_fixture_dir}/augeas/lenses"
+ expect(@provider.get_load_path(@resource)).to eq("/foo:/bar:/baz:#{my_fixture_dir}/augeas/lenses")
end
end
end
diff --git a/spec/unit/provider/cisco_spec.rb b/spec/unit/provider/cisco_spec.rb
index 6dec1713d..c03ed390d 100755
--- a/spec/unit/provider/cisco_spec.rb
+++ b/spec/unit/provider/cisco_spec.rb
@@ -1,15 +1,15 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/provider/cisco'
describe Puppet::Provider::Cisco do
it "should implement a device class method" do
- Puppet::Provider::Cisco.should respond_to(:device)
+ expect(Puppet::Provider::Cisco).to respond_to(:device)
end
it "should create a cisco device instance" do
Puppet::Util::NetworkDevice::Cisco::Device.expects(:new).returns :device
- Puppet::Provider::Cisco.device(:url).should == :device
+ expect(Puppet::Provider::Cisco.device(:url)).to eq(:device)
end
end
diff --git a/spec/unit/provider/command_spec.rb b/spec/unit/provider/command_spec.rb
index 1afe019ee..c50cd61a0 100755
--- a/spec/unit/provider/command_spec.rb
+++ b/spec/unit/provider/command_spec.rb
@@ -1,62 +1,62 @@
require 'spec_helper'
require 'puppet/provider/command'
describe Puppet::Provider::Command do
let(:name) { "the name" }
let(:the_options) { { :option => 1 } }
let(:no_options) { {} }
let(:executable) { "foo" }
let(:executable_absolute_path) { "/foo/bar" }
let(:executor) { mock('executor') }
let(:resolver) { mock('resolver') }
let(:path_resolves_to_itself) do
resolves = Object.new
class << resolves
def which(path)
path
end
end
resolves
end
it "executes a simple command" do
executor.expects(:execute).with([executable], no_options)
command = Puppet::Provider::Command.new(name, executable, path_resolves_to_itself, executor)
command.execute()
end
it "executes a command with extra options" do
executor.expects(:execute).with([executable], the_options)
command = Puppet::Provider::Command.new(name, executable, path_resolves_to_itself, executor, the_options)
command.execute()
end
it "executes a command with arguments" do
executor.expects(:execute).with([executable, "arg1", "arg2"], no_options)
command = Puppet::Provider::Command.new(name, executable, path_resolves_to_itself, executor)
command.execute("arg1", "arg2")
end
it "resolves to an absolute path for better execution" do
resolver.expects(:which).with(executable).returns(executable_absolute_path)
executor.expects(:execute).with([executable_absolute_path], no_options)
command = Puppet::Provider::Command.new(name, executable, resolver, executor)
command.execute()
end
it "errors when the executable resolves to nothing" do
resolver.expects(:which).with(executable).returns(nil)
executor.expects(:execute).never
command = Puppet::Provider::Command.new(name, executable, resolver, executor)
- lambda { command.execute() }.should raise_error(Puppet::Error, "Command #{name} is missing")
+ expect { command.execute() }.to raise_error(Puppet::Error, "Command #{name} is missing")
end
end
diff --git a/spec/unit/provider/cron/crontab_spec.rb b/spec/unit/provider/cron/crontab_spec.rb
index e980428cb..726540e61 100755
--- a/spec/unit/provider/cron/crontab_spec.rb
+++ b/spec/unit/provider/cron/crontab_spec.rb
@@ -1,207 +1,207 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:cron).provider(:crontab) do
subject do
provider = Puppet::Type.type(:cron).provider(:crontab)
provider.initvars
provider
end
def compare_crontab_text(have, want)
# We should have four header lines, and then the text...
- have.lines.to_a[0..3].should be_all {|x| x =~ /^# / }
- have.lines.to_a[4..-1].join('').should == want
+ expect(have.lines.to_a[0..3]).to be_all {|x| x =~ /^# / }
+ expect(have.lines.to_a[4..-1].join('')).to eq(want)
end
context "with the simple samples" do
FIELDS = {
:crontab => %w{command minute hour month monthday weekday}.collect { |o| o.intern },
:environment => [:line],
:blank => [:line],
:comment => [:line],
}
def compare_crontab_record(have, want)
want.each do |param, value|
- have.should be_key param
- have[param].should == value
+ expect(have).to be_key param
+ expect(have[param]).to eq(value)
end
(FIELDS[have[:record_type]] - want.keys).each do |name|
- have[name].should == :absent
+ expect(have[name]).to eq(:absent)
end
end
########################################################################
# Simple input fixtures for testing.
samples = YAML.load(File.read(my_fixture('single_line.yaml')))
samples.each do |name, data|
it "should parse crontab line #{name} correctly" do
compare_crontab_record subject.parse_line(data[:text]), data[:record]
end
it "should reconstruct the crontab line #{name} from the record" do
- subject.to_line(data[:record]).should == data[:text]
+ expect(subject.to_line(data[:record])).to eq(data[:text])
end
end
records = []
text = ""
# Sorting is from the original, and avoids :empty being the last line,
# since the provider will ignore that and cause this to fail.
samples.sort_by {|x| x.first.to_s }.each do |name, data|
records << data[:record]
text << data[:text] + "\n"
end
it "should parse all sample records at once" do
subject.parse(text).zip(records).each do |round|
compare_crontab_record *round
end
end
it "should reconstitute the file from the records" do
compare_crontab_text subject.to_file(records), text
end
context "multi-line crontabs" do
tests = { :simple => [:spaces_in_command_with_times],
:with_name => [:name, :spaces_in_command_with_times],
:with_env => [:environment, :spaces_in_command_with_times],
:with_multiple_envs => [:environment, :lowercase_environment, :spaces_in_command_with_times],
:with_name_and_env => [:name_with_spaces, :another_env, :spaces_in_command_with_times],
:with_name_and_multiple_envs => [:long_name, :another_env, :fourth_env, :spaces_in_command_with_times]
}
all_records = []
all_text = ''
tests.each do |name, content|
data = content.map {|x| samples[x] or raise "missing sample data #{x}" }
text = data.map {|x| x[:text] }.join("\n") + "\n"
records = data.map {|x| x[:record] }
# Capture the whole thing for later, too...
all_records += records
all_text += text
context name.to_s.gsub('_', ' ') do
it "should regenerate the text from the record" do
compare_crontab_text subject.to_file(records), text
end
it "should parse the records from the text" do
subject.parse(text).zip(records).each do |round|
compare_crontab_record *round
end
end
end
end
it "should parse the whole set of records from the text" do
subject.parse(all_text).zip(all_records).each do |round|
compare_crontab_record *round
end
end
it "should regenerate the whole text from the set of all records" do
compare_crontab_text subject.to_file(all_records), all_text
end
end
end
context "when receiving a vixie cron header from the cron interface" do
it "should not write that header back to disk" do
vixie_header = File.read(my_fixture('vixie_header.txt'))
vixie_records = subject.parse(vixie_header)
compare_crontab_text subject.to_file(vixie_records), ""
end
end
context "when adding a cronjob with the same command as an existing job" do
let(:record) { {:name => "existing", :user => "root", :command => "/bin/true", :record_type => :crontab} }
let(:resource) { Puppet::Type::Cron.new(:name => "test", :user => "root", :command => "/bin/true") }
let(:resources) { { "test" => resource } }
before :each do
subject.stubs(:prefetch_all_targets).returns([record])
end
# this would be a more fitting test, but I haven't yet
# figured out how to get it working
# it "should include both jobs in the output" do
# subject.prefetch(resources)
# class Puppet::Provider::ParsedFile
# def self.records
# @records
# end
# end
# subject.to_file(subject.records).should match /Puppet name: test/
# end
it "should not base the new resource's provider on the existing record" do
subject.expects(:new).with(record).never
subject.stubs(:new)
subject.prefetch(resources)
end
end
context "when prefetching an entry now managed for another user" do
let(:resource) do
s = stub(:resource)
s.stubs(:[]).with(:user).returns 'root'
s.stubs(:[]).with(:target).returns 'root'
s
end
let(:record) { {:name => "test", :user => "nobody", :command => "/bin/true", :record_type => :crontab} }
let(:resources) { { "test" => resource } }
before :each do
subject.stubs(:prefetch_all_targets).returns([record])
end
it "should try and use the match method to find a more fitting record" do
subject.expects(:match).with(record, resources)
subject.prefetch(resources)
end
it "should not match a provider to the resource" do
resource.expects(:provider=).never
subject.prefetch(resources)
end
it "should not find the resource when looking up the on-disk record" do
subject.prefetch(resources)
- subject.resource_for_record(record, resources).should be_nil
+ expect(subject.resource_for_record(record, resources)).to be_nil
end
end
context "when matching resources to existing crontab entries" do
let(:first_resource) { Puppet::Type::Cron.new(:name => :one, :user => 'root', :command => '/bin/true') }
let(:second_resource) { Puppet::Type::Cron.new(:name => :two, :user => 'nobody', :command => '/bin/false') }
let(:resources) {{:one => first_resource, :two => second_resource}}
describe "with a record with a matching name and mismatching user (#2251)" do
# Puppet::Resource objects have #should defined on them, so in these
# examples we have to use the monkey patched `must` alias for the rspec
# `should` method.
it "doesn't match the record to the resource" do
record = {:name => :one, :user => 'notroot', :record_type => :crontab}
- subject.resource_for_record(record, resources).must be_nil
+ expect(subject.resource_for_record(record, resources)).to be_nil
end
end
describe "with a record with a matching name and matching user" do
it "matches the record to the resource" do
record = {:name => :two, :target => 'nobody', :command => '/bin/false'}
- subject.resource_for_record(record, resources).must == second_resource
+ expect(subject.resource_for_record(record, resources)).to eq(second_resource)
end
end
end
end
diff --git a/spec/unit/provider/cron/parsed_spec.rb b/spec/unit/provider/cron/parsed_spec.rb
index 1a038eae5..43e855e8d 100644
--- a/spec/unit/provider/cron/parsed_spec.rb
+++ b/spec/unit/provider/cron/parsed_spec.rb
@@ -1,357 +1,357 @@
#!/usr/bin/env rspec
require 'spec_helper'
describe Puppet::Type.type(:cron).provider(:crontab) do
let :provider do
described_class.new(:command => '/bin/true')
end
let :resource do
Puppet::Type.type(:cron).new(
:minute => %w{0 15 30 45},
:hour => %w{8-18 20-22},
:monthday => %w{31},
:month => %w{12},
:weekday => %w{7},
:name => 'basic',
:command => '/bin/true',
:target => 'root',
:provider => provider
)
end
let :resource_special do
Puppet::Type.type(:cron).new(
:special => 'reboot',
:name => 'special',
:command => '/bin/true',
:target => 'nobody'
)
end
let :resource_sparse do
Puppet::Type.type(:cron).new(
:minute => %w{42},
:target => 'root',
:name => 'sparse'
)
end
let :record_special do
{
:record_type => :crontab,
:special => 'reboot',
:command => '/bin/true',
:on_disk => true,
:target => 'nobody'
}
end
let :record do
{
:record_type => :crontab,
:minute => %w{0 15 30 45},
:hour => %w{8-18 20-22},
:monthday => %w{31},
:month => %w{12},
:weekday => %w{7},
:special => :absent,
:command => '/bin/true',
:on_disk => true,
:target => 'root'
}
end
describe "when determining the correct filetype" do
it "should use the suntab filetype on Solaris" do
Facter.stubs(:value).with(:osfamily).returns 'Solaris'
- described_class.filetype.should == Puppet::Util::FileType::FileTypeSuntab
+ expect(described_class.filetype).to eq(Puppet::Util::FileType::FileTypeSuntab)
end
it "should use the aixtab filetype on AIX" do
Facter.stubs(:value).with(:osfamily).returns 'AIX'
- described_class.filetype.should == Puppet::Util::FileType::FileTypeAixtab
+ expect(described_class.filetype).to eq(Puppet::Util::FileType::FileTypeAixtab)
end
it "should use the crontab filetype on other platforms" do
Facter.stubs(:value).with(:osfamily).returns 'Not a real operating system family'
- described_class.filetype.should == Puppet::Util::FileType::FileTypeCrontab
+ expect(described_class.filetype).to eq(Puppet::Util::FileType::FileTypeCrontab)
end
end
# I'd use ENV.expects(:[]).with('USER') but this does not work because
# ENV["USER"] is evaluated at load time.
describe "when determining the default target" do
it "should use the current user #{ENV['USER']}", :if => ENV['USER'] do
- described_class.default_target.should == ENV['USER']
+ expect(described_class.default_target).to eq(ENV['USER'])
end
it "should fallback to root", :unless => ENV['USER'] do
- described_class.default_target.should == "root"
+ expect(described_class.default_target).to eq("root")
end
end
describe ".targets" do
let(:tabs) { [ described_class.default_target ] + %w{foo bar} }
before do
File.expects(:readable?).returns true
File.stubs(:file?).returns true
File.stubs(:writable?).returns true
end
after do
File.unstub :readable?, :file?, :writable?
Dir.unstub :foreach
end
it "should add all crontabs as targets" do
Dir.expects(:foreach).multiple_yields(*tabs)
- described_class.targets.should == tabs
+ expect(described_class.targets).to eq(tabs)
end
end
describe "when parsing a record" do
it "should parse a comment" do
- described_class.parse_line("# This is a test").should == {
+ expect(described_class.parse_line("# This is a test")).to eq({
:record_type => :comment,
:line => "# This is a test",
- }
+ })
end
it "should get the resource name of a PUPPET NAME comment" do
- described_class.parse_line('# Puppet Name: My Fancy Cronjob').should == {
+ expect(described_class.parse_line('# Puppet Name: My Fancy Cronjob')).to eq({
:record_type => :comment,
:name => 'My Fancy Cronjob',
:line => '# Puppet Name: My Fancy Cronjob',
- }
+ })
end
it "should ignore blank lines" do
- described_class.parse_line('').should == {:record_type => :blank, :line => ''}
- described_class.parse_line(' ').should == {:record_type => :blank, :line => ' '}
- described_class.parse_line("\t").should == {:record_type => :blank, :line => "\t"}
- described_class.parse_line(" \t ").should == {:record_type => :blank, :line => " \t "}
+ expect(described_class.parse_line('')).to eq({:record_type => :blank, :line => ''})
+ expect(described_class.parse_line(' ')).to eq({:record_type => :blank, :line => ' '})
+ expect(described_class.parse_line("\t")).to eq({:record_type => :blank, :line => "\t"})
+ expect(described_class.parse_line(" \t ")).to eq({:record_type => :blank, :line => " \t "})
end
it "should extract environment assignments" do
# man 5 crontab: MAILTO="" with no value can be used to surpress sending
# mails at all
- described_class.parse_line('MAILTO=""').should == {:record_type => :environment, :line => 'MAILTO=""'}
- described_class.parse_line('FOO=BAR').should == {:record_type => :environment, :line => 'FOO=BAR'}
- described_class.parse_line('FOO_BAR=BAR').should == {:record_type => :environment, :line => 'FOO_BAR=BAR'}
+ expect(described_class.parse_line('MAILTO=""')).to eq({:record_type => :environment, :line => 'MAILTO=""'})
+ expect(described_class.parse_line('FOO=BAR')).to eq({:record_type => :environment, :line => 'FOO=BAR'})
+ expect(described_class.parse_line('FOO_BAR=BAR')).to eq({:record_type => :environment, :line => 'FOO_BAR=BAR'})
end
it "should extract a cron entry" do
- described_class.parse_line('* * * * * /bin/true').should == {
+ expect(described_class.parse_line('* * * * * /bin/true')).to eq({
:record_type => :crontab,
:hour => :absent,
:minute => :absent,
:month => :absent,
:weekday => :absent,
:monthday => :absent,
:special => :absent,
:command => '/bin/true'
- }
- described_class.parse_line('0,15,30,45 8-18,20-22 31 12 7 /bin/true').should == {
+ })
+ expect(described_class.parse_line('0,15,30,45 8-18,20-22 31 12 7 /bin/true')).to eq({
:record_type => :crontab,
:minute => %w{0 15 30 45},
:hour => %w{8-18 20-22},
:monthday => %w{31},
:month => %w{12},
:weekday => %w{7},
:special => :absent,
:command => '/bin/true'
- }
+ })
# A percent sign will cause the rest of the string to be passed as
# standard input and will also act as a newline character. Not sure
# if puppet should convert % to a \n as the command property so the
# test covers the current behaviour: Do not do any conversions
- described_class.parse_line('0 22 * * 1-5 mail -s "It\'s 10pm" joe%Joe,%%Where are your kids?%').should == {
+ expect(described_class.parse_line('0 22 * * 1-5 mail -s "It\'s 10pm" joe%Joe,%%Where are your kids?%')).to eq({
:record_type => :crontab,
:minute => %w{0},
:hour => %w{22},
:monthday => :absent,
:month => :absent,
:weekday => %w{1-5},
:special => :absent,
:command => 'mail -s "It\'s 10pm" joe%Joe,%%Where are your kids?%'
- }
+ })
end
describe "it should support special strings" do
['reboot','yearly','anually','monthly', 'weekly', 'daily', 'midnight', 'hourly'].each do |special|
it "should support @#{special}" do
- described_class.parse_line("@#{special} /bin/true").should == {
+ expect(described_class.parse_line("@#{special} /bin/true")).to eq({
:record_type => :crontab,
:hour => :absent,
:minute => :absent,
:month => :absent,
:weekday => :absent,
:monthday => :absent,
:special => special,
:command => '/bin/true'
- }
+ })
end
end
end
end
describe ".instances" do
before :each do
described_class.stubs(:default_target).returns 'foobar'
end
describe "on linux" do
before do
Facter.stubs(:value).with(:osfamily).returns 'Linux'
Facter.stubs(:value).with(:operatingsystem)
end
it "should contain no resources for a user who has no crontab" do
# `crontab...` does only capture stdout here. On vixie-cron-4.1
# STDERR shows "no crontab for foobar" but stderr is ignored as
# well as the exitcode.
described_class.target_object('foobar').expects(:`).with('crontab -u foobar -l 2>/dev/null').returns ""
- described_class.instances.select { |resource|
+ expect(described_class.instances.select { |resource|
resource.get('target') == 'foobar'
- }.should be_empty
+ }).to be_empty
end
it "should contain no resources for a user who is absent" do
# `crontab...` does only capture stdout. On vixie-cron-4.1
# STDERR shows "crontab: user `foobar' unknown" but stderr is
# ignored as well as the exitcode
described_class.target_object('foobar').expects(:`).with('crontab -u foobar -l 2>/dev/null').returns ""
- described_class.instances.select { |resource|
+ expect(described_class.instances.select { |resource|
resource.get('target') == 'foobar'
- }.should be_empty
+ }).to be_empty
end
it "should be able to create records from not-managed records" do
described_class.stubs(:target_object).returns File.new(my_fixture('simple'))
parameters = described_class.instances.map do |p|
h = {:name => p.get(:name)}
Puppet::Type.type(:cron).validproperties.each do |property|
h[property] = p.get(property)
end
h
end
expect(parameters[0][:name]).to match(%r{unmanaged:\$HOME/bin/daily.job_>>_\$HOME/tmp/out_2>&1-\d+})
expect(parameters[0][:minute]).to eq(['5'])
expect(parameters[0][:hour]).to eq(['0'])
expect(parameters[0][:weekday]).to eq(:absent)
expect(parameters[0][:month]).to eq(:absent)
expect(parameters[0][:monthday]).to eq(:absent)
expect(parameters[0][:special]).to eq(:absent)
expect(parameters[0][:command]).to match(%r{\$HOME/bin/daily.job >> \$HOME/tmp/out 2>&1})
expect(parameters[0][:ensure]).to eq(:present)
expect(parameters[0][:environment]).to eq(:absent)
expect(parameters[0][:user]).to eq(:absent)
expect(parameters[1][:name]).to match(%r{unmanaged:\$HOME/bin/monthly-\d+})
expect(parameters[1][:minute]).to eq(['15'])
expect(parameters[1][:hour]).to eq(['14'])
expect(parameters[1][:weekday]).to eq(:absent)
expect(parameters[1][:month]).to eq(:absent)
expect(parameters[1][:monthday]).to eq(['1'])
expect(parameters[1][:special]).to eq(:absent)
expect(parameters[1][:command]).to match(%r{\$HOME/bin/monthly})
expect(parameters[1][:ensure]).to eq(:present)
expect(parameters[1][:environment]).to eq(:absent)
expect(parameters[1][:user]).to eq(:absent)
expect(parameters[1][:target]).to eq('foobar')
end
it "should be able to parse puppet managed cronjobs" do
described_class.stubs(:target_object).returns File.new(my_fixture('managed'))
- described_class.instances.map do |p|
+ expect(described_class.instances.map do |p|
h = {:name => p.get(:name)}
Puppet::Type.type(:cron).validproperties.each do |property|
h[property] = p.get(property)
end
h
- end.should == [
+ end).to eq([
{
:name => 'real_job',
:minute => :absent,
:hour => :absent,
:weekday => :absent,
:month => :absent,
:monthday => :absent,
:special => :absent,
:command => '/bin/true',
:ensure => :present,
:environment => :absent,
:user => :absent,
:target => 'foobar'
},
{
:name => 'complex_job',
:minute => :absent,
:hour => :absent,
:weekday => :absent,
:month => :absent,
:monthday => :absent,
:special => 'reboot',
:command => '/bin/true >> /dev/null 2>&1',
:ensure => :present,
:environment => [
'MAILTO=foo@example.com',
'SHELL=/bin/sh'
],
:user => :absent,
:target => 'foobar'
}
- ]
+ ])
end
end
end
describe ".match" do
describe "normal records" do
it "should match when all fields are the same" do
- described_class.match(record,{resource[:name] => resource}).must == resource
+ expect(described_class.match(record,{resource[:name] => resource})).to eq(resource)
end
{
:minute => %w{0 15 31 45},
:hour => %w{8-18},
:monthday => %w{30 31},
:month => %w{12 23},
:weekday => %w{4},
:command => '/bin/false',
:target => 'nobody'
}.each_pair do |field, new_value|
it "should not match a record when #{field} does not match" do
record[field] = new_value
- described_class.match(record,{resource[:name] => resource}).must be_false
+ expect(described_class.match(record,{resource[:name] => resource})).to be_falsey
end
end
end
describe "special records" do
it "should match when all fields are the same" do
- described_class.match(record_special,{resource_special[:name] => resource_special}).must == resource_special
+ expect(described_class.match(record_special,{resource_special[:name] => resource_special})).to eq(resource_special)
end
{
:special => 'monthly',
:command => '/bin/false',
:target => 'root'
}.each_pair do |field, new_value|
it "should not match a record when #{field} does not match" do
record_special[field] = new_value
- described_class.match(record_special,{resource_special[:name] => resource_special}).must be_false
+ expect(described_class.match(record_special,{resource_special[:name] => resource_special})).to be_falsey
end
end
end
describe "with a resource without a command" do
it "should not raise an error" do
expect { described_class.match(record,{resource_sparse[:name] => resource_sparse}) }.to_not raise_error
end
end
end
end
diff --git a/spec/unit/provider/exec/posix_spec.rb b/spec/unit/provider/exec/posix_spec.rb
index 9192e949b..9dc432de9 100755
--- a/spec/unit/provider/exec/posix_spec.rb
+++ b/spec/unit/provider/exec/posix_spec.rb
@@ -1,209 +1,209 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:exec).provider(:posix), :if => Puppet.features.posix? do
include PuppetSpec::Files
def make_exe
cmdpath = tmpdir('cmdpath')
exepath = tmpfile('my_command', cmdpath)
FileUtils.touch(exepath)
File.chmod(0755, exepath)
exepath
end
let(:resource) { Puppet::Type.type(:exec).new(:title => '/foo', :provider => :posix) }
let(:provider) { described_class.new(resource) }
describe "#validatecmd" do
it "should fail if no path is specified and the command is not fully qualified" do
expect { provider.validatecmd("foo") }.to raise_error(
Puppet::Error,
"'foo' is not qualified and no path was specified. Please qualify the command or specify a path."
)
end
it "should pass if a path is given" do
provider.resource[:path] = ['/bogus/bin']
provider.validatecmd("../foo")
end
it "should pass if command is fully qualifed" do
provider.resource[:path] = ['/bogus/bin']
provider.validatecmd("/bin/blah/foo")
end
end
describe "#run" do
describe "when the command is an absolute path" do
let(:command) { tmpfile('foo') }
it "should fail if the command doesn't exist" do
expect { provider.run(command) }.to raise_error(ArgumentError, "Could not find command '#{command}'")
end
it "should fail if the command isn't a file" do
FileUtils.mkdir(command)
FileUtils.chmod(0755, command)
expect { provider.run(command) }.to raise_error(ArgumentError, "'#{command}' is a directory, not a file")
end
it "should fail if the command isn't executable" do
FileUtils.touch(command)
File.stubs(:executable?).with(command).returns(false)
expect { provider.run(command) }.to raise_error(ArgumentError, "'#{command}' is not executable")
end
end
describe "when the command is a relative path" do
it "should execute the command if it finds it in the path and is executable" do
command = make_exe
provider.resource[:path] = [File.dirname(command)]
filename = File.basename(command)
Puppet::Util::Execution.expects(:execute).with(filename, instance_of(Hash)).returns(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.run(filename)
end
it "should fail if the command isn't in the path" do
resource[:path] = ["/fake/path"]
expect { provider.run('foo') }.to raise_error(ArgumentError, "Could not find command 'foo'")
end
it "should fail if the command is in the path but not executable" do
command = make_exe
File.chmod(0644, command)
FileTest.stubs(:executable?).with(command).returns(false)
resource[:path] = [File.dirname(command)]
filename = File.basename(command)
expect { provider.run(filename) }.to raise_error(ArgumentError, "Could not find command '#{filename}'")
end
end
it "should not be able to execute shell builtins" do
provider.resource[:path] = ['/bogus/bin']
expect { provider.run("cd ..") }.to raise_error(ArgumentError, "Could not find command 'cd'")
end
it "should execute the command if the command given includes arguments or subcommands" do
provider.resource[:path] = ['/bogus/bin']
command = make_exe
Puppet::Util::Execution.expects(:execute).with("#{command} bar --sillyarg=true --blah", instance_of(Hash)).returns(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.run("#{command} bar --sillyarg=true --blah")
end
it "should fail if quoted command doesn't exist" do
provider.resource[:path] = ['/bogus/bin']
command = "/foo bar --sillyarg=true --blah"
expect { provider.run(%Q["#{command}"]) }.to raise_error(ArgumentError, "Could not find command '#{command}'")
end
it "should warn if you're overriding something in environment" do
provider.resource[:environment] = ['WHATEVER=/something/else', 'WHATEVER=/foo']
command = make_exe
Puppet::Util::Execution.expects(:execute).with(command, instance_of(Hash)).returns(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.run(command)
- @logs.map {|l| "#{l.level}: #{l.message}" }.should == ["warning: Overriding environment setting 'WHATEVER' with '/foo'"]
+ expect(@logs.map {|l| "#{l.level}: #{l.message}" }).to eq(["warning: Overriding environment setting 'WHATEVER' with '/foo'"])
end
it "should set umask before execution if umask parameter is in use" do
provider.resource[:umask] = '0027'
Puppet::Util.expects(:withumask).with(0027)
provider.run(provider.resource[:command])
end
describe "posix locale settings" do
# a sentinel value that we can use to emulate what locale environment variables might be set to on an international
# system.
lang_sentinel_value = "en_US.UTF-8"
# a temporary hash that contains sentinel values for each of the locale environment variables that we override in
# "exec"
locale_sentinel_env = {}
Puppet::Util::POSIX::LOCALE_ENV_VARS.each { |var| locale_sentinel_env[var] = lang_sentinel_value }
command = "/bin/echo $%s"
it "should not override user's locale during execution" do
# we'll do this once without any sentinel values, to give us a little more test coverage
orig_env = {}
Puppet::Util::POSIX::LOCALE_ENV_VARS.each { |var| orig_env[var] = ENV[var] if ENV[var] }
orig_env.keys.each do |var|
output, status = provider.run(command % var)
- output.strip.should == orig_env[var]
+ expect(output.strip).to eq(orig_env[var])
end
# now, once more... but with our sentinel values
Puppet::Util.withenv(locale_sentinel_env) do
Puppet::Util::POSIX::LOCALE_ENV_VARS.each do |var|
output, status = provider.run(command % var)
- output.strip.should == locale_sentinel_env[var]
+ expect(output.strip).to eq(locale_sentinel_env[var])
end
end
end
it "should respect locale overrides in user's 'environment' configuration" do
provider.resource[:environment] = ['LANG=C', 'LC_ALL=C']
output, status = provider.run(command % 'LANG')
- output.strip.should == 'C'
+ expect(output.strip).to eq('C')
output, status = provider.run(command % 'LC_ALL')
- output.strip.should == 'C'
+ expect(output.strip).to eq('C')
end
end
describe "posix user-related environment vars" do
# a temporary hash that contains sentinel values for each of the user-related environment variables that we
# are expected to unset during an "exec"
user_sentinel_env = {}
Puppet::Util::POSIX::USER_ENV_VARS.each { |var| user_sentinel_env[var] = "Abracadabra" }
command = "/bin/echo $%s"
it "should unset user-related environment vars during execution" do
# first we set up a temporary execution environment with sentinel values for the user-related environment vars
# that we care about.
Puppet::Util.withenv(user_sentinel_env) do
# with this environment, we loop over the vars in question
Puppet::Util::POSIX::USER_ENV_VARS.each do |var|
# ensure that our temporary environment is set up as we expect
- ENV[var].should == user_sentinel_env[var]
+ expect(ENV[var]).to eq(user_sentinel_env[var])
# run an "exec" via the provider and ensure that it unsets the vars
output, status = provider.run(command % var)
- output.strip.should == ""
+ expect(output.strip).to eq("")
# ensure that after the exec, our temporary env is still intact
- ENV[var].should == user_sentinel_env[var]
+ expect(ENV[var]).to eq(user_sentinel_env[var])
end
end
end
it "should respect overrides to user-related environment vars in caller's 'environment' configuration" do
sentinel_value = "Abracadabra"
# set the "environment" property of the resource, populating it with a hash containing sentinel values for
# each of the user-related posix environment variables
provider.resource[:environment] = Puppet::Util::POSIX::USER_ENV_VARS.collect { |var| "#{var}=#{sentinel_value}"}
# loop over the posix user-related environment variables
Puppet::Util::POSIX::USER_ENV_VARS.each do |var|
# run an 'exec' to get the value of each variable
output, status = provider.run(command % var)
# ensure that it matches our expected sentinel value
- output.strip.should == sentinel_value
+ expect(output.strip).to eq(sentinel_value)
end
end
end
end
end
diff --git a/spec/unit/provider/exec/shell_spec.rb b/spec/unit/provider/exec/shell_spec.rb
index 932f46b6a..229915447 100755
--- a/spec/unit/provider/exec/shell_spec.rb
+++ b/spec/unit/provider/exec/shell_spec.rb
@@ -1,53 +1,53 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:exec).provider(:shell), :unless => Puppet.features.microsoft_windows? do
let(:resource) { Puppet::Type.type(:exec).new(:title => 'foo', :provider => 'shell') }
let(:provider) { described_class.new(resource) }
describe "#run" do
it "should be able to run builtin shell commands" do
output, status = provider.run("if [ 1 = 1 ]; then echo 'blah'; fi")
- status.exitstatus.should == 0
- output.should == "blah\n"
+ expect(status.exitstatus).to eq(0)
+ expect(output).to eq("blah\n")
end
it "should be able to run commands with single quotes in them" do
output, status = provider.run("echo 'foo bar'")
- status.exitstatus.should == 0
- output.should == "foo bar\n"
+ expect(status.exitstatus).to eq(0)
+ expect(output).to eq("foo bar\n")
end
it "should be able to run commands with double quotes in them" do
output, status = provider.run('echo "foo bar"')
- status.exitstatus.should == 0
- output.should == "foo bar\n"
+ expect(status.exitstatus).to eq(0)
+ expect(output).to eq("foo bar\n")
end
it "should be able to run multiple commands separated by a semicolon" do
output, status = provider.run("echo 'foo' ; echo 'bar'")
- status.exitstatus.should == 0
- output.should == "foo\nbar\n"
+ expect(status.exitstatus).to eq(0)
+ expect(output).to eq("foo\nbar\n")
end
it "should be able to read values from the environment parameter" do
resource[:environment] = "FOO=bar"
output, status = provider.run("echo $FOO")
- status.exitstatus.should == 0
- output.should == "bar\n"
+ expect(status.exitstatus).to eq(0)
+ expect(output).to eq("bar\n")
end
it "#14060: should interpolate inside the subshell, not outside it" do
resource[:environment] = "foo=outer"
output, status = provider.run("foo=inner; echo \"foo is $foo\"")
- status.exitstatus.should == 0
- output.should == "foo is inner\n"
+ expect(status.exitstatus).to eq(0)
+ expect(output).to eq("foo is inner\n")
end
end
describe "#validatecmd" do
it "should always return true because builtins don't need path or to be fully qualified" do
- provider.validatecmd('whateverdoesntmatter').should == true
+ expect(provider.validatecmd('whateverdoesntmatter')).to eq(true)
end
end
end
diff --git a/spec/unit/provider/exec/windows_spec.rb b/spec/unit/provider/exec/windows_spec.rb
index eb3f91eaf..b18bd467d 100755
--- a/spec/unit/provider/exec/windows_spec.rb
+++ b/spec/unit/provider/exec/windows_spec.rb
@@ -1,107 +1,107 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:exec).provider(:windows), :if => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
let(:resource) { Puppet::Type.type(:exec).new(:title => 'C:\foo', :provider => :windows) }
let(:provider) { described_class.new(resource) }
after :all do
# This provider may not be suitable on some machines, so we want to reset
# the default so it isn't used by mistake in future specs.
Puppet::Type.type(:exec).defaultprovider = nil
end
describe "#extractexe" do
describe "when the command has no arguments" do
it "should return the command if it's quoted" do
- provider.extractexe('"foo"').should == 'foo'
+ expect(provider.extractexe('"foo"')).to eq('foo')
end
it "should return the command if it's quoted and contains spaces" do
- provider.extractexe('"foo bar"').should == 'foo bar'
+ expect(provider.extractexe('"foo bar"')).to eq('foo bar')
end
it "should return the command if it's not quoted" do
- provider.extractexe('foo').should == 'foo'
+ expect(provider.extractexe('foo')).to eq('foo')
end
end
describe "when the command has arguments" do
it "should return the command if it's quoted" do
- provider.extractexe('"foo" bar baz').should == 'foo'
+ expect(provider.extractexe('"foo" bar baz')).to eq('foo')
end
it "should return the command if it's quoted and contains spaces" do
- provider.extractexe('"foo bar" baz "quux quiz"').should == 'foo bar'
+ expect(provider.extractexe('"foo bar" baz "quux quiz"')).to eq('foo bar')
end
it "should return the command if it's not quoted" do
- provider.extractexe('foo bar baz').should == 'foo'
+ expect(provider.extractexe('foo bar baz')).to eq('foo')
end
end
end
describe "#checkexe" do
describe "when the command is absolute", :if => Puppet.features.microsoft_windows? do
it "should return if the command exists and is a file" do
command = tmpfile('command')
FileUtils.touch(command)
- provider.checkexe(command).should == nil
+ expect(provider.checkexe(command)).to eq(nil)
end
it "should fail if the command doesn't exist" do
command = tmpfile('command')
expect { provider.checkexe(command) }.to raise_error(ArgumentError, "Could not find command '#{command}'")
end
it "should fail if the command isn't a file" do
command = tmpfile('command')
FileUtils.mkdir(command)
expect { provider.checkexe(command) }.to raise_error(ArgumentError, "'#{command}' is a directory, not a file")
end
end
describe "when the command is relative" do
describe "and a path is specified" do
before :each do
provider.stubs(:which)
end
it "should search for executables with no extension" do
provider.resource[:path] = [File.expand_path('/bogus/bin')]
provider.expects(:which).with('foo').returns('foo')
provider.checkexe('foo')
end
it "should fail if the command isn't in the path" do
expect { provider.checkexe('foo') }.to raise_error(ArgumentError, "Could not find command 'foo'")
end
end
it "should fail if no path is specified" do
expect { provider.checkexe('foo') }.to raise_error(ArgumentError, "Could not find command 'foo'")
end
end
end
describe "#validatecmd" do
it "should fail if the command isn't absolute and there is no path" do
expect { provider.validatecmd('foo') }.to raise_error(Puppet::Error, /'foo' is not qualified and no path was specified/)
end
it "should not fail if the command is absolute and there is no path" do
- provider.validatecmd('C:\foo').should == nil
+ expect(provider.validatecmd('C:\foo')).to eq(nil)
end
it "should not fail if the command is not absolute and there is a path" do
resource[:path] = 'C:\path;C:\another_path'
- provider.validatecmd('foo').should == nil
+ expect(provider.validatecmd('foo')).to eq(nil)
end
end
end
diff --git a/spec/unit/provider/exec_spec.rb b/spec/unit/provider/exec_spec.rb
index 6e98da1c5..1ece0801b 100755
--- a/spec/unit/provider/exec_spec.rb
+++ b/spec/unit/provider/exec_spec.rb
@@ -1,35 +1,35 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/provider/exec'
describe Puppet::Provider::Exec do
describe "#extractexe" do
it "should return the first element of an array" do
- subject.extractexe(['one', 'two']).should == 'one'
+ expect(subject.extractexe(['one', 'two'])).to eq('one')
end
{
# double-quoted commands
%q{"/has whitespace"} => "/has whitespace",
%q{"/no/whitespace"} => "/no/whitespace",
# singe-quoted commands
%q{'/has whitespace'} => "/has whitespace",
%q{'/no/whitespace'} => "/no/whitespace",
# combinations
%q{"'/has whitespace'"} => "'/has whitespace'",
%q{'"/has whitespace"'} => '"/has whitespace"',
%q{"/has 'special' characters"} => "/has 'special' characters",
%q{'/has "special" characters'} => '/has "special" characters',
# whitespace split commands
%q{/has whitespace} => "/has",
%q{/no/whitespace} => "/no/whitespace",
}.each do |base_command, exe|
['', ' and args', ' "and args"', " 'and args'"].each do |args|
command = base_command + args
it "should extract #{exe.inspect} from #{command.inspect}" do
- subject.extractexe(command).should == exe
+ expect(subject.extractexe(command)).to eq(exe)
end
end
end
end
end
diff --git a/spec/unit/provider/file/posix_spec.rb b/spec/unit/provider/file/posix_spec.rb
index 4de9df7ac..d02cad589 100755
--- a/spec/unit/provider/file/posix_spec.rb
+++ b/spec/unit/provider/file/posix_spec.rb
@@ -1,232 +1,232 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:file).provider(:posix), :if => Puppet.features.posix? do
include PuppetSpec::Files
let(:path) { tmpfile('posix_file_spec') }
let(:resource) { Puppet::Type.type(:file).new :path => path, :mode => '0777', :provider => described_class.name }
let(:provider) { resource.provider }
describe "#mode" do
it "should return a string with the higher-order bits stripped away" do
FileUtils.touch(path)
File.chmod(0644, path)
- provider.mode.should == '0644'
+ expect(provider.mode).to eq('0644')
end
it "should return absent if the file doesn't exist" do
- provider.mode.should == :absent
+ expect(provider.mode).to eq(:absent)
end
end
describe "#mode=" do
it "should chmod the file to the specified value" do
FileUtils.touch(path)
File.chmod(0644, path)
provider.mode = '0755'
- provider.mode.should == '0755'
+ expect(provider.mode).to eq('0755')
end
it "should pass along any errors encountered" do
expect do
provider.mode = '0644'
end.to raise_error(Puppet::Error, /failed to set mode/)
end
end
describe "#uid2name" do
it "should return the name of the user identified by the id" do
Etc.stubs(:getpwuid).with(501).returns(Struct::Passwd.new('jilluser', nil, 501))
- provider.uid2name(501).should == 'jilluser'
+ expect(provider.uid2name(501)).to eq('jilluser')
end
it "should return the argument if it's already a name" do
- provider.uid2name('jilluser').should == 'jilluser'
+ expect(provider.uid2name('jilluser')).to eq('jilluser')
end
it "should return nil if the argument is above the maximum uid" do
- provider.uid2name(Puppet[:maximum_uid] + 1).should == nil
+ expect(provider.uid2name(Puppet[:maximum_uid] + 1)).to eq(nil)
end
it "should return nil if the user doesn't exist" do
Etc.expects(:getpwuid).raises(ArgumentError, "can't find user for 999")
- provider.uid2name(999).should == nil
+ expect(provider.uid2name(999)).to eq(nil)
end
end
describe "#name2uid" do
it "should return the id of the user if it exists" do
passwd = Struct::Passwd.new('bobbo', nil, 502)
Etc.stubs(:getpwnam).with('bobbo').returns(passwd)
Etc.stubs(:getpwuid).with(502).returns(passwd)
- provider.name2uid('bobbo').should == 502
+ expect(provider.name2uid('bobbo')).to eq(502)
end
it "should return the argument if it's already an id" do
- provider.name2uid('503').should == 503
+ expect(provider.name2uid('503')).to eq(503)
end
it "should return false if the user doesn't exist" do
Etc.stubs(:getpwnam).with('chuck').raises(ArgumentError, "can't find user for chuck")
- provider.name2uid('chuck').should == false
+ expect(provider.name2uid('chuck')).to eq(false)
end
end
describe "#owner" do
it "should return the uid of the file owner" do
FileUtils.touch(path)
owner = Puppet::FileSystem.stat(path).uid
- provider.owner.should == owner
+ expect(provider.owner).to eq(owner)
end
it "should return absent if the file can't be statted" do
- provider.owner.should == :absent
+ expect(provider.owner).to eq(:absent)
end
it "should warn and return :silly if the value is beyond the maximum uid" do
stat = stub('stat', :uid => Puppet[:maximum_uid] + 1)
resource.stubs(:stat).returns(stat)
- provider.owner.should == :silly
- @logs.should be_any {|log| log.level == :warning and log.message =~ /Apparently using negative UID/}
+ expect(provider.owner).to eq(:silly)
+ expect(@logs).to be_any {|log| log.level == :warning and log.message =~ /Apparently using negative UID/}
end
end
describe "#owner=" do
it "should set the owner but not the group of the file" do
File.expects(:lchown).with(15, nil, resource[:path])
provider.owner = 15
end
it "should chown a link if managing links" do
resource[:links] = :manage
File.expects(:lchown).with(20, nil, resource[:path])
provider.owner = 20
end
it "should chown a link target if following links" do
resource[:links] = :follow
File.expects(:chown).with(20, nil, resource[:path])
provider.owner = 20
end
it "should pass along any error encountered setting the owner" do
File.expects(:lchown).raises(ArgumentError)
expect { provider.owner = 25 }.to raise_error(Puppet::Error, /Failed to set owner to '25'/)
end
end
describe "#gid2name" do
it "should return the name of the group identified by the id" do
Etc.stubs(:getgrgid).with(501).returns(Struct::Passwd.new('unicorns', nil, nil, 501))
- provider.gid2name(501).should == 'unicorns'
+ expect(provider.gid2name(501)).to eq('unicorns')
end
it "should return the argument if it's already a name" do
- provider.gid2name('leprechauns').should == 'leprechauns'
+ expect(provider.gid2name('leprechauns')).to eq('leprechauns')
end
it "should return nil if the argument is above the maximum gid" do
- provider.gid2name(Puppet[:maximum_uid] + 1).should == nil
+ expect(provider.gid2name(Puppet[:maximum_uid] + 1)).to eq(nil)
end
it "should return nil if the group doesn't exist" do
Etc.expects(:getgrgid).raises(ArgumentError, "can't find group for 999")
- provider.gid2name(999).should == nil
+ expect(provider.gid2name(999)).to eq(nil)
end
end
describe "#name2gid" do
it "should return the id of the group if it exists" do
passwd = Struct::Passwd.new('penguins', nil, nil, 502)
Etc.stubs(:getgrnam).with('penguins').returns(passwd)
Etc.stubs(:getgrgid).with(502).returns(passwd)
- provider.name2gid('penguins').should == 502
+ expect(provider.name2gid('penguins')).to eq(502)
end
it "should return the argument if it's already an id" do
- provider.name2gid('503').should == 503
+ expect(provider.name2gid('503')).to eq(503)
end
it "should return false if the group doesn't exist" do
Etc.stubs(:getgrnam).with('wombats').raises(ArgumentError, "can't find group for wombats")
- provider.name2gid('wombats').should == false
+ expect(provider.name2gid('wombats')).to eq(false)
end
end
describe "#group" do
it "should return the gid of the file group" do
FileUtils.touch(path)
group = Puppet::FileSystem.stat(path).gid
- provider.group.should == group
+ expect(provider.group).to eq(group)
end
it "should return absent if the file can't be statted" do
- provider.group.should == :absent
+ expect(provider.group).to eq(:absent)
end
it "should warn and return :silly if the value is beyond the maximum gid" do
stat = stub('stat', :gid => Puppet[:maximum_uid] + 1)
resource.stubs(:stat).returns(stat)
- provider.group.should == :silly
- @logs.should be_any {|log| log.level == :warning and log.message =~ /Apparently using negative GID/}
+ expect(provider.group).to eq(:silly)
+ expect(@logs).to be_any {|log| log.level == :warning and log.message =~ /Apparently using negative GID/}
end
end
describe "#group=" do
it "should set the group but not the owner of the file" do
File.expects(:lchown).with(nil, 15, resource[:path])
provider.group = 15
end
it "should change the group for a link if managing links" do
resource[:links] = :manage
File.expects(:lchown).with(nil, 20, resource[:path])
provider.group = 20
end
it "should change the group for a link target if following links" do
resource[:links] = :follow
File.expects(:chown).with(nil, 20, resource[:path])
provider.group = 20
end
it "should pass along any error encountered setting the group" do
File.expects(:lchown).raises(ArgumentError)
expect { provider.group = 25 }.to raise_error(Puppet::Error, /Failed to set group to '25'/)
end
end
describe "when validating" do
it "should not perform any validation" do
resource.validate
end
end
end
diff --git a/spec/unit/provider/file/windows_spec.rb b/spec/unit/provider/file/windows_spec.rb
index fb8aee9f7..3e1cb63a2 100755
--- a/spec/unit/provider/file/windows_spec.rb
+++ b/spec/unit/provider/file/windows_spec.rb
@@ -1,154 +1,154 @@
#! /usr/bin/env ruby
require 'spec_helper'
if Puppet.features.microsoft_windows?
require 'puppet/util/windows'
class WindowsSecurity
extend Puppet::Util::Windows::Security
end
end
describe Puppet::Type.type(:file).provider(:windows), :if => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
let(:path) { tmpfile('windows_file_spec') }
let(:resource) { Puppet::Type.type(:file).new :path => path, :mode => '0777', :provider => described_class.name }
let(:provider) { resource.provider }
let(:sid) { 'S-1-1-50' }
let(:account) { 'quinn' }
describe "#mode" do
it "should return a string representing the mode in 4-digit octal notation" do
FileUtils.touch(path)
WindowsSecurity.set_mode(0644, path)
- provider.mode.should == '0644'
+ expect(provider.mode).to eq('0644')
end
it "should return absent if the file doesn't exist" do
- provider.mode.should == :absent
+ expect(provider.mode).to eq(:absent)
end
end
describe "#mode=" do
it "should chmod the file to the specified value" do
FileUtils.touch(path)
WindowsSecurity.set_mode(0644, path)
provider.mode = '0755'
- provider.mode.should == '0755'
+ expect(provider.mode).to eq('0755')
end
it "should pass along any errors encountered" do
expect do
provider.mode = '0644'
end.to raise_error(Puppet::Error, /failed to set mode/)
end
end
describe "#id2name" do
it "should return the name of the user identified by the sid" do
Puppet::Util::Windows::SID.expects(:valid_sid?).with(sid).returns(true)
Puppet::Util::Windows::SID.expects(:sid_to_name).with(sid).returns(account)
- provider.id2name(sid).should == account
+ expect(provider.id2name(sid)).to eq(account)
end
it "should return the argument if it's already a name" do
Puppet::Util::Windows::SID.expects(:valid_sid?).with(account).returns(false)
Puppet::Util::Windows::SID.expects(:sid_to_name).never
- provider.id2name(account).should == account
+ expect(provider.id2name(account)).to eq(account)
end
it "should return nil if the user doesn't exist" do
Puppet::Util::Windows::SID.expects(:valid_sid?).with(sid).returns(true)
Puppet::Util::Windows::SID.expects(:sid_to_name).with(sid).returns(nil)
- provider.id2name(sid).should == nil
+ expect(provider.id2name(sid)).to eq(nil)
end
end
describe "#name2id" do
it "should delegate to name_to_sid" do
Puppet::Util::Windows::SID.expects(:name_to_sid).with(account).returns(sid)
- provider.name2id(account).should == sid
+ expect(provider.name2id(account)).to eq(sid)
end
end
describe "#owner" do
it "should return the sid of the owner if the file does exist" do
FileUtils.touch(resource[:path])
provider.stubs(:get_owner).with(resource[:path]).returns(sid)
- provider.owner.should == sid
+ expect(provider.owner).to eq(sid)
end
it "should return absent if the file doesn't exist" do
- provider.owner.should == :absent
+ expect(provider.owner).to eq(:absent)
end
end
describe "#owner=" do
it "should set the owner to the specified value" do
provider.expects(:set_owner).with(sid, resource[:path])
provider.owner = sid
end
it "should propagate any errors encountered when setting the owner" do
provider.stubs(:set_owner).raises(ArgumentError)
expect {
provider.owner = sid
}.to raise_error(Puppet::Error, /Failed to set owner/)
end
end
describe "#group" do
it "should return the sid of the group if the file does exist" do
FileUtils.touch(resource[:path])
provider.stubs(:get_group).with(resource[:path]).returns(sid)
- provider.group.should == sid
+ expect(provider.group).to eq(sid)
end
it "should return absent if the file doesn't exist" do
- provider.group.should == :absent
+ expect(provider.group).to eq(:absent)
end
end
describe "#group=" do
it "should set the group to the specified value" do
provider.expects(:set_group).with(sid, resource[:path])
provider.group = sid
end
it "should propagate any errors encountered when setting the group" do
provider.stubs(:set_group).raises(ArgumentError)
expect {
provider.group = sid
}.to raise_error(Puppet::Error, /Failed to set group/)
end
end
describe "when validating" do
{:owner => 'foo', :group => 'foo', :mode => '0777'}.each do |k,v|
it "should fail if the filesystem doesn't support ACLs and we're managing #{k}" do
described_class.any_instance.stubs(:supports_acl?).returns false
expect {
Puppet::Type.type(:file).new :path => path, k => v
}.to raise_error(Puppet::Error, /Can only manage owner, group, and mode on filesystems that support Windows ACLs, such as NTFS/)
end
end
it "should not fail if the filesystem doesn't support ACLs and we're not managing permissions" do
described_class.any_instance.stubs(:supports_acl?).returns false
Puppet::Type.type(:file).new :path => path
end
end
end
diff --git a/spec/unit/provider/group/groupadd_spec.rb b/spec/unit/provider/group/groupadd_spec.rb
index 4e6141af3..9b4d2390c 100755
--- a/spec/unit/provider/group/groupadd_spec.rb
+++ b/spec/unit/provider/group/groupadd_spec.rb
@@ -1,76 +1,76 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:group).provider(:groupadd) do
before do
described_class.stubs(:command).with(:add).returns '/usr/sbin/groupadd'
described_class.stubs(:command).with(:delete).returns '/usr/sbin/groupdel'
described_class.stubs(:command).with(:modify).returns '/usr/sbin/groupmod'
described_class.stubs(:command).with(:localadd).returns '/usr/sbin/lgroupadd'
end
let(:resource) { Puppet::Type.type(:group).new(:name => 'mygroup', :provider => provider) }
let(:provider) { described_class.new(:name => 'mygroup') }
describe "#create" do
before do
provider.stubs(:exists?).returns(false)
end
it "should add -o when allowdupe is enabled and the group is being created" do
resource[:allowdupe] = :true
provider.expects(:execute).with(['/usr/sbin/groupadd', '-o', 'mygroup'], kind_of(Hash))
provider.create
end
describe "on system that feature system_groups", :if => described_class.system_groups? do
it "should add -r when system is enabled and the group is being created" do
resource[:system] = :true
provider.expects(:execute).with(['/usr/sbin/groupadd', '-r', 'mygroup'], kind_of(Hash))
provider.create
end
end
describe "on system that do not feature system_groups", :unless => described_class.system_groups? do
it "should not add -r when system is enabled and the group is being created" do
resource[:system] = :true
provider.expects(:execute).with(['/usr/sbin/groupadd', 'mygroup'], kind_of(Hash))
provider.create
end
end
describe "on systems with the libuser and forcelocal=true" do
before do
described_class.has_feature(:libuser)
resource[:forcelocal] = :true
end
it "should use lgroupadd instead of groupadd" do
provider.expects(:execute).with(includes('/usr/sbin/lgroupadd'), has_entry(:custom_environment, has_key('LIBUSER_CONF')))
provider.create
end
it "should NOT pass -o to lgroupadd" do
resource[:allowdupe] = :true
provider.expects(:execute).with(Not(includes('-o')), has_entry(:custom_environment, has_key('LIBUSER_CONF')))
provider.create
end
it "should raise an exception for duplicate GID if allowdupe is not set and duplicate GIDs exist" do
resource[:gid] = 505
provider.stubs(:findgroup).returns(true)
- lambda { provider.create }.should raise_error(Puppet::Error, "GID 505 already exists, use allowdupe to force group creation")
+ expect { provider.create }.to raise_error(Puppet::Error, "GID 505 already exists, use allowdupe to force group creation")
end
end
end
describe "#gid=" do
it "should add -o when allowdupe is enabled and the gid is being modified" do
resource[:allowdupe] = :true
provider.expects(:execute).with(['/usr/sbin/groupmod', '-g', 150, '-o', 'mygroup'])
provider.gid = 150
end
end
end
diff --git a/spec/unit/provider/group/ldap_spec.rb b/spec/unit/provider/group/ldap_spec.rb
index cfee79932..1cfd473cf 100755
--- a/spec/unit/provider/group/ldap_spec.rb
+++ b/spec/unit/provider/group/ldap_spec.rb
@@ -1,101 +1,101 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:group).provider(:ldap)
describe provider_class do
it "should have the Ldap provider class as its baseclass" do
- provider_class.superclass.should equal(Puppet::Provider::Ldap)
+ expect(provider_class.superclass).to equal(Puppet::Provider::Ldap)
end
it "should manage :posixGroup objectclass" do
- provider_class.manager.objectclasses.should == [:posixGroup]
+ expect(provider_class.manager.objectclasses).to eq([:posixGroup])
end
it "should use 'ou=Groups' as its relative base" do
- provider_class.manager.location.should == "ou=Groups"
+ expect(provider_class.manager.location).to eq("ou=Groups")
end
it "should use :cn as its rdn" do
- provider_class.manager.rdn.should == :cn
+ expect(provider_class.manager.rdn).to eq(:cn)
end
it "should map :name to 'cn'" do
- provider_class.manager.ldap_name(:name).should == 'cn'
+ expect(provider_class.manager.ldap_name(:name)).to eq('cn')
end
it "should map :gid to 'gidNumber'" do
- provider_class.manager.ldap_name(:gid).should == 'gidNumber'
+ expect(provider_class.manager.ldap_name(:gid)).to eq('gidNumber')
end
it "should map :members to 'memberUid', to be used by the user ldap provider" do
- provider_class.manager.ldap_name(:members).should == 'memberUid'
+ expect(provider_class.manager.ldap_name(:members)).to eq('memberUid')
end
describe "when being created" do
before do
# So we don't try to actually talk to ldap
@connection = mock 'connection'
provider_class.manager.stubs(:connect).yields @connection
end
describe "with no gid specified" do
it "should pick the first available GID after the largest existing GID" do
low = {:name=>["luke"], :gid=>["600"]}
high = {:name=>["testing"], :gid=>["640"]}
provider_class.manager.expects(:search).returns([low, high])
resource = stub 'resource', :should => %w{whatever}
resource.stubs(:should).with(:gid).returns nil
resource.stubs(:should).with(:ensure).returns :present
instance = provider_class.new(:name => "luke", :ensure => :absent)
instance.stubs(:resource).returns resource
@connection.expects(:add).with { |dn, attrs| attrs["gidNumber"] == ["641"] }
instance.create
instance.flush
end
it "should pick '501' as its GID if no groups are found" do
provider_class.manager.expects(:search).returns nil
resource = stub 'resource', :should => %w{whatever}
resource.stubs(:should).with(:gid).returns nil
resource.stubs(:should).with(:ensure).returns :present
instance = provider_class.new(:name => "luke", :ensure => :absent)
instance.stubs(:resource).returns resource
@connection.expects(:add).with { |dn, attrs| attrs["gidNumber"] == ["501"] }
instance.create
instance.flush
end
end
end
it "should have a method for converting group names to GIDs" do
- provider_class.should respond_to(:name2id)
+ expect(provider_class).to respond_to(:name2id)
end
describe "when converting from a group name to GID" do
it "should use the ldap manager to look up the GID" do
provider_class.manager.expects(:search).with("cn=foo")
provider_class.name2id("foo")
end
it "should return nil if no group is found" do
provider_class.manager.expects(:search).with("cn=foo").returns nil
- provider_class.name2id("foo").should be_nil
+ expect(provider_class.name2id("foo")).to be_nil
provider_class.manager.expects(:search).with("cn=bar").returns []
- provider_class.name2id("bar").should be_nil
+ expect(provider_class.name2id("bar")).to be_nil
end
# We shouldn't ever actually have more than one gid, but it doesn't hurt
# to test for the possibility.
it "should return the first gid from the first returned group" do
provider_class.manager.expects(:search).with("cn=foo").returns [{:name => "foo", :gid => [10, 11]}, {:name => :bar, :gid => [20, 21]}]
- provider_class.name2id("foo").should == 10
+ expect(provider_class.name2id("foo")).to eq(10)
end
end
end
diff --git a/spec/unit/provider/group/pw_spec.rb b/spec/unit/provider/group/pw_spec.rb
index 5d7d470e0..c611411a0 100755
--- a/spec/unit/provider/group/pw_spec.rb
+++ b/spec/unit/provider/group/pw_spec.rb
@@ -1,81 +1,81 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:group).provider(:pw)
describe provider_class do
let :resource do
Puppet::Type.type(:group).new(:name => "testgroup", :provider => :pw)
end
let :provider do
resource.provider
end
describe "when creating groups" do
let :provider do
prov = resource.provider
prov.expects(:exists?).returns nil
prov
end
it "should run pw with no additional flags when no properties are given" do
- provider.addcmd.must == [provider_class.command(:pw), "groupadd", "testgroup"]
+ expect(provider.addcmd).to eq([provider_class.command(:pw), "groupadd", "testgroup"])
provider.expects(:execute).with([provider_class.command(:pw), "groupadd", "testgroup"], kind_of(Hash))
provider.create
end
it "should use -o when allowdupe is enabled" do
resource[:allowdupe] = true
provider.expects(:execute).with(includes("-o"), kind_of(Hash))
provider.create
end
it "should use -g with the correct argument when the gid property is set" do
resource[:gid] = 12345
provider.expects(:execute).with(all_of(includes("-g"), includes(12345)), kind_of(Hash))
provider.create
end
it "should use -M with the correct argument when the members property is set" do
resource[:members] = "user1"
provider.expects(:execute).with(all_of(includes("-M"), includes("user1")), kind_of(Hash))
provider.create
end
it "should use -M with all the given users when the members property is set to an array" do
resource[:members] = ["user1", "user2"]
provider.expects(:execute).with(all_of(includes("-M"), includes("user1,user2")), kind_of(Hash))
provider.create
end
end
describe "when deleting groups" do
it "should run pw with no additional flags" do
provider.expects(:exists?).returns true
- provider.deletecmd.must == [provider_class.command(:pw), "groupdel", "testgroup"]
+ expect(provider.deletecmd).to eq([provider_class.command(:pw), "groupdel", "testgroup"])
provider.expects(:execute).with([provider_class.command(:pw), "groupdel", "testgroup"])
provider.delete
end
end
describe "when modifying groups" do
it "should run pw with the correct arguments" do
- provider.modifycmd("gid", 12345).must == [provider_class.command(:pw), "groupmod", "testgroup", "-g", 12345]
+ expect(provider.modifycmd("gid", 12345)).to eq([provider_class.command(:pw), "groupmod", "testgroup", "-g", 12345])
provider.expects(:execute).with([provider_class.command(:pw), "groupmod", "testgroup", "-g", 12345])
provider.gid = 12345
end
it "should use -M with the correct argument when the members property is changed" do
resource[:members] = "user1"
provider.expects(:execute).with(all_of(includes("-M"), includes("user2")))
provider.members = "user2"
end
it "should use -M with all the given users when the members property is changed with an array" do
resource[:members] = ["user1", "user2"]
provider.expects(:execute).with(all_of(includes("-M"), includes("user3,user4")))
provider.members = ["user3", "user4"]
end
end
end
diff --git a/spec/unit/provider/group/windows_adsi_spec.rb b/spec/unit/provider/group/windows_adsi_spec.rb
index 22c482c32..3c44396e6 100644
--- a/spec/unit/provider/group/windows_adsi_spec.rb
+++ b/spec/unit/provider/group/windows_adsi_spec.rb
@@ -1,223 +1,223 @@
#!/usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:group).provider(:windows_adsi), :if => Puppet.features.microsoft_windows? do
let(:resource) do
Puppet::Type.type(:group).new(
:title => 'testers',
:provider => :windows_adsi
)
end
let(:provider) { resource.provider }
let(:connection) { stub 'connection' }
before :each do
Puppet::Util::Windows::ADSI.stubs(:computer_name).returns('testcomputername')
Puppet::Util::Windows::ADSI.stubs(:connect).returns connection
end
describe ".instances" do
it "should enumerate all groups" do
names = ['group1', 'group2', 'group3']
stub_groups = names.map{|n| stub(:name => n)}
connection.stubs(:execquery).with('select name from win32_group where localaccount = "TRUE"').returns stub_groups
- described_class.instances.map(&:name).should =~ names
+ expect(described_class.instances.map(&:name)).to match(names)
end
end
describe "group type :members property helpers" do
let(:user1) { stub(:account => 'user1', :domain => '.', :to_s => 'user1sid') }
let(:user2) { stub(:account => 'user2', :domain => '.', :to_s => 'user2sid') }
let(:user3) { stub(:account => 'user3', :domain => '.', :to_s => 'user3sid') }
before :each do
Puppet::Util::Windows::SID.stubs(:name_to_sid_object).with('user1').returns(user1)
Puppet::Util::Windows::SID.stubs(:name_to_sid_object).with('user2').returns(user2)
Puppet::Util::Windows::SID.stubs(:name_to_sid_object).with('user3').returns(user3)
end
describe "#members_insync?" do
it "should return false when current is nil" do
- provider.members_insync?(nil, ['user2']).should be_false
+ expect(provider.members_insync?(nil, ['user2'])).to be_falsey
end
it "should return false when should is nil" do
- provider.members_insync?(['user1'], nil).should be_false
+ expect(provider.members_insync?(['user1'], nil)).to be_falsey
end
it "should return true for same lists of members" do
- provider.members_insync?(['user1', 'user2'], ['user1', 'user2']).should be_true
+ expect(provider.members_insync?(['user1', 'user2'], ['user1', 'user2'])).to be_truthy
end
it "should return true for same lists of unordered members" do
- provider.members_insync?(['user1', 'user2'], ['user2', 'user1']).should be_true
+ expect(provider.members_insync?(['user1', 'user2'], ['user2', 'user1'])).to be_truthy
end
it "should return true for same lists of members irrespective of duplicates" do
- provider.members_insync?(['user1', 'user2', 'user2'], ['user2', 'user1', 'user1']).should be_true
+ expect(provider.members_insync?(['user1', 'user2', 'user2'], ['user2', 'user1', 'user1'])).to be_truthy
end
context "when auth_membership => true" do
before :each do
resource[:auth_membership] = true
end
it "should return false when current contains different users than should" do
- provider.members_insync?(['user1'], ['user2']).should be_false
+ expect(provider.members_insync?(['user1'], ['user2'])).to be_falsey
end
it "should return false when current contains members and should is empty" do
- provider.members_insync?(['user1'], []).should be_false
+ expect(provider.members_insync?(['user1'], [])).to be_falsey
end
it "should return false when current is empty and should contains members" do
- provider.members_insync?([], ['user2']).should be_false
+ expect(provider.members_insync?([], ['user2'])).to be_falsey
end
it "should return false when should user(s) are not the only items in the current" do
- provider.members_insync?(['user1', 'user2'], ['user1']).should be_false
+ expect(provider.members_insync?(['user1', 'user2'], ['user1'])).to be_falsey
end
end
context "when auth_membership => false" do
before :each do
# this is also the default
resource[:auth_membership] = false
end
it "should return false when current contains different users than should" do
- provider.members_insync?(['user1'], ['user2']).should be_false
+ expect(provider.members_insync?(['user1'], ['user2'])).to be_falsey
end
it "should return true when current contains members and should is empty" do
- provider.members_insync?(['user1'], []).should be_true
+ expect(provider.members_insync?(['user1'], [])).to be_truthy
end
it "should return false when current is empty and should contains members" do
- provider.members_insync?([], ['user2']).should be_false
+ expect(provider.members_insync?([], ['user2'])).to be_falsey
end
it "should return true when current user(s) contains at least the should list" do
- provider.members_insync?(['user1','user2'], ['user1']).should be_true
+ expect(provider.members_insync?(['user1','user2'], ['user1'])).to be_truthy
end
it "should return true when current user(s) contains at least the should list, even unordered" do
- provider.members_insync?(['user3','user1','user2'], ['user2','user1']).should be_true
+ expect(provider.members_insync?(['user3','user1','user2'], ['user2','user1'])).to be_truthy
end
end
end
describe "#members_to_s" do
it "should return an empty string on non-array input" do
[Object.new, {}, 1, :symbol, ''].each do |input|
- provider.members_to_s(input).should be_empty
+ expect(provider.members_to_s(input)).to be_empty
end
end
it "should return an empty string on empty or nil users" do
- provider.members_to_s([]).should be_empty
- provider.members_to_s(nil).should be_empty
+ expect(provider.members_to_s([])).to be_empty
+ expect(provider.members_to_s(nil)).to be_empty
end
it "should return a user string like DOMAIN\\USER" do
- provider.members_to_s(['user1']).should == '.\user1'
+ expect(provider.members_to_s(['user1'])).to eq('.\user1')
end
it "should return a user string like DOMAIN\\USER,DOMAIN2\\USER2" do
- provider.members_to_s(['user1', 'user2']).should == '.\user1,.\user2'
+ expect(provider.members_to_s(['user1', 'user2'])).to eq('.\user1,.\user2')
end
end
end
describe "when managing members" do
before :each do
resource[:auth_membership] = true
end
it "should be able to provide a list of members" do
provider.group.stubs(:members).returns ['user1', 'user2', 'user3']
- provider.members.should =~ ['user1', 'user2', 'user3']
+ expect(provider.members).to match_array(['user1', 'user2', 'user3'])
end
it "should be able to set group members" do
provider.group.stubs(:members).returns ['user1', 'user2']
member_sids = [
stub(:account => 'user1', :domain => 'testcomputername'),
stub(:account => 'user2', :domain => 'testcomputername'),
stub(:account => 'user3', :domain => 'testcomputername'),
]
provider.group.stubs(:member_sids).returns(member_sids[0..1])
Puppet::Util::Windows::SID.expects(:name_to_sid_object).with('user2').returns(member_sids[1])
Puppet::Util::Windows::SID.expects(:name_to_sid_object).with('user3').returns(member_sids[2])
provider.group.expects(:remove_member_sids).with(member_sids[0])
provider.group.expects(:add_member_sids).with(member_sids[2])
provider.members = ['user2', 'user3']
end
end
describe 'when creating groups' do
it "should be able to create a group" do
resource[:members] = ['user1', 'user2']
group = stub 'group'
Puppet::Util::Windows::ADSI::Group.expects(:create).with('testers').returns group
create = sequence('create')
group.expects(:commit).in_sequence(create)
# due to PUP-1967, defaultto false will set the default to nil
group.expects(:set_members).with(['user1', 'user2'], nil).in_sequence(create)
provider.create
end
it 'should not create a group if a user by the same name exists' do
Puppet::Util::Windows::ADSI::Group.expects(:create).with('testers').raises( Puppet::Error.new("Cannot create group if user 'testers' exists.") )
expect{ provider.create }.to raise_error( Puppet::Error,
/Cannot create group if user 'testers' exists./ )
end
it 'should commit a newly created group' do
provider.group.expects( :commit )
provider.flush
end
end
it "should be able to test whether a group exists" do
Puppet::Util::Windows::ADSI.stubs(:sid_uri_safe).returns(nil)
Puppet::Util::Windows::ADSI.stubs(:connect).returns stub('connection')
- provider.should be_exists
+ expect(provider).to be_exists
Puppet::Util::Windows::ADSI.stubs(:connect).returns nil
- provider.should_not be_exists
+ expect(provider).not_to be_exists
end
it "should be able to delete a group" do
connection.expects(:Delete).with('group', 'testers')
provider.delete
end
it "should report the group's SID as gid" do
Puppet::Util::Windows::SID.expects(:name_to_sid).with('testers').returns('S-1-5-32-547')
- provider.gid.should == 'S-1-5-32-547'
+ expect(provider.gid).to eq('S-1-5-32-547')
end
it "should fail when trying to manage the gid property" do
provider.expects(:fail).with { |msg| msg =~ /gid is read-only/ }
provider.send(:gid=, 500)
end
it "should prefer the domain component from the resolved SID" do
- provider.members_to_s(['.\Administrators']).should == 'BUILTIN\Administrators'
+ expect(provider.members_to_s(['.\Administrators'])).to eq('BUILTIN\Administrators')
end
end
diff --git a/spec/unit/provider/host/parsed_spec.rb b/spec/unit/provider/host/parsed_spec.rb
index f50b39ab8..b2cba7658 100755
--- a/spec/unit/provider/host/parsed_spec.rb
+++ b/spec/unit/provider/host/parsed_spec.rb
@@ -1,233 +1,233 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'shared_behaviours/all_parsedfile_providers'
require 'puppet_spec/files'
provider_class = Puppet::Type.type(:host).provider(:parsed)
describe provider_class do
include PuppetSpec::Files
before do
@host_class = Puppet::Type.type(:host)
@provider = @host_class.provider(:parsed)
@hostfile = tmpfile('hosts')
@provider.any_instance.stubs(:target).returns @hostfile
end
after :each do
@provider.initvars
end
def mkhost(args)
hostresource = Puppet::Type::Host.new(:name => args[:name])
hostresource.stubs(:should).with(:target).returns @hostfile
# Using setters of provider to build our testobject
# Note: We already proved, that in case of host_aliases
# the provider setter "host_aliases=(value)" will be
# called with the joined array, so we just simulate that
host = @provider.new(hostresource)
args.each do |property,value|
value = value.join(" ") if property == :host_aliases and value.is_a?(Array)
host.send("#{property}=", value)
end
host
end
def genhost(host)
@provider.stubs(:filetype).returns(Puppet::Util::FileType::FileTypeRam)
File.stubs(:chown)
File.stubs(:chmod)
Puppet::Util::SUIDManager.stubs(:asuser).yields
host.flush
@provider.target_object(@hostfile).read
end
describe "when parsing on incomplete line" do
it "should work for only ip" do
- @provider.parse_line("127.0.0.1")[:line].should == "127.0.0.1"
+ expect(@provider.parse_line("127.0.0.1")[:line]).to eq("127.0.0.1")
end
it "should work for only hostname" do
- @provider.parse_line("www.example.com")[:line].should == "www.example.com"
+ expect(@provider.parse_line("www.example.com")[:line]).to eq("www.example.com")
end
it "should work for ip and space" do
- @provider.parse_line("127.0.0.1 ")[:line].should == "127.0.0.1 "
+ expect(@provider.parse_line("127.0.0.1 ")[:line]).to eq("127.0.0.1 ")
end
it "should work for hostname and space" do
- @provider.parse_line("www.example.com ")[:line].should == "www.example.com "
+ expect(@provider.parse_line("www.example.com ")[:line]).to eq("www.example.com ")
end
it "should work for hostname and host_aliases" do
- @provider.parse_line("www.example.com www xyz")[:line].should == "www.example.com www xyz"
+ expect(@provider.parse_line("www.example.com www xyz")[:line]).to eq("www.example.com www xyz")
end
it "should work for ip and comment" do
- @provider.parse_line("127.0.0.1 #www xyz")[:line].should == "127.0.0.1 #www xyz"
+ expect(@provider.parse_line("127.0.0.1 #www xyz")[:line]).to eq("127.0.0.1 #www xyz")
end
it "should work for hostname and comment" do
- @provider.parse_line("xyz #www test123")[:line].should == "xyz #www test123"
+ expect(@provider.parse_line("xyz #www test123")[:line]).to eq("xyz #www test123")
end
it "should work for crazy incomplete lines" do
- @provider.parse_line("%th1s is a\t cr$zy !incompl1t line")[:line].should == "%th1s is a\t cr$zy !incompl1t line"
+ expect(@provider.parse_line("%th1s is a\t cr$zy !incompl1t line")[:line]).to eq("%th1s is a\t cr$zy !incompl1t line")
end
end
describe "when parsing a line with ip and hostname" do
it "should parse an ipv4 from the first field" do
- @provider.parse_line("127.0.0.1 localhost")[:ip].should == "127.0.0.1"
+ expect(@provider.parse_line("127.0.0.1 localhost")[:ip]).to eq("127.0.0.1")
end
it "should parse an ipv6 from the first field" do
- @provider.parse_line("::1 localhost")[:ip].should == "::1"
+ expect(@provider.parse_line("::1 localhost")[:ip]).to eq("::1")
end
it "should parse the name from the second field" do
- @provider.parse_line("::1 localhost")[:name].should == "localhost"
+ expect(@provider.parse_line("::1 localhost")[:name]).to eq("localhost")
end
it "should set an empty comment" do
- @provider.parse_line("::1 localhost")[:comment].should == ""
+ expect(@provider.parse_line("::1 localhost")[:comment]).to eq("")
end
it "should set host_aliases to :absent" do
- @provider.parse_line("::1 localhost")[:host_aliases].should == :absent
+ expect(@provider.parse_line("::1 localhost")[:host_aliases]).to eq(:absent)
end
end
describe "when parsing a line with ip, hostname and comment" do
before do
@testline = "127.0.0.1 localhost # A comment with a #-char"
end
it "should parse the ip from the first field" do
- @provider.parse_line(@testline)[:ip].should == "127.0.0.1"
+ expect(@provider.parse_line(@testline)[:ip]).to eq("127.0.0.1")
end
it "should parse the hostname from the second field" do
- @provider.parse_line(@testline)[:name].should == "localhost"
+ expect(@provider.parse_line(@testline)[:name]).to eq("localhost")
end
it "should parse the comment after the first '#' character" do
- @provider.parse_line(@testline)[:comment].should == 'A comment with a #-char'
+ expect(@provider.parse_line(@testline)[:comment]).to eq('A comment with a #-char')
end
end
describe "when parsing a line with ip, hostname and aliases" do
it "should parse alias from the third field" do
- @provider.parse_line("127.0.0.1 localhost localhost.localdomain")[:host_aliases].should == "localhost.localdomain"
+ expect(@provider.parse_line("127.0.0.1 localhost localhost.localdomain")[:host_aliases]).to eq("localhost.localdomain")
end
it "should parse multiple aliases" do
- @provider.parse_line("127.0.0.1 host alias1 alias2")[:host_aliases].should == 'alias1 alias2'
- @provider.parse_line("127.0.0.1 host alias1\talias2")[:host_aliases].should == 'alias1 alias2'
- @provider.parse_line("127.0.0.1 host alias1\talias2 alias3")[:host_aliases].should == 'alias1 alias2 alias3'
+ expect(@provider.parse_line("127.0.0.1 host alias1 alias2")[:host_aliases]).to eq('alias1 alias2')
+ expect(@provider.parse_line("127.0.0.1 host alias1\talias2")[:host_aliases]).to eq('alias1 alias2')
+ expect(@provider.parse_line("127.0.0.1 host alias1\talias2 alias3")[:host_aliases]).to eq('alias1 alias2 alias3')
end
end
describe "when parsing a line with ip, hostname, aliases and comment" do
before do
# Just playing with a few different delimiters
@testline = "127.0.0.1\t host alias1\talias2 alias3 # A comment with a #-char"
end
it "should parse the ip from the first field" do
- @provider.parse_line(@testline)[:ip].should == "127.0.0.1"
+ expect(@provider.parse_line(@testline)[:ip]).to eq("127.0.0.1")
end
it "should parse the hostname from the second field" do
- @provider.parse_line(@testline)[:name].should == "host"
+ expect(@provider.parse_line(@testline)[:name]).to eq("host")
end
it "should parse all host_aliases from the third field" do
- @provider.parse_line(@testline)[:host_aliases].should == 'alias1 alias2 alias3'
+ expect(@provider.parse_line(@testline)[:host_aliases]).to eq('alias1 alias2 alias3')
end
it "should parse the comment after the first '#' character" do
- @provider.parse_line(@testline)[:comment].should == 'A comment with a #-char'
+ expect(@provider.parse_line(@testline)[:comment]).to eq('A comment with a #-char')
end
end
describe "when operating on /etc/hosts like files" do
it_should_behave_like "all parsedfile providers",
provider_class, my_fixtures('valid*')
it "should be able to generate a simple hostfile entry" do
host = mkhost(
:name => 'localhost',
:ip => '127.0.0.1',
:ensure => :present
)
- genhost(host).should == "127.0.0.1\tlocalhost\n"
+ expect(genhost(host)).to eq("127.0.0.1\tlocalhost\n")
end
it "should be able to generate an entry with one alias" do
host = mkhost(
:name => 'localhost.localdomain',
:ip => '127.0.0.1',
:host_aliases => 'localhost',
:ensure => :present
)
- genhost(host).should == "127.0.0.1\tlocalhost.localdomain\tlocalhost\n"
+ expect(genhost(host)).to eq("127.0.0.1\tlocalhost.localdomain\tlocalhost\n")
end
it "should be able to generate an entry with more than one alias" do
host = mkhost(
:name => 'host',
:ip => '192.0.0.1',
:host_aliases => [ 'a1','a2','a3','a4' ],
:ensure => :present
)
- genhost(host).should == "192.0.0.1\thost\ta1 a2 a3 a4\n"
+ expect(genhost(host)).to eq("192.0.0.1\thost\ta1 a2 a3 a4\n")
end
it "should be able to generate a simple hostfile entry with comments" do
host = mkhost(
:name => 'localhost',
:ip => '127.0.0.1',
:comment => 'Bazinga!',
:ensure => :present
)
- genhost(host).should == "127.0.0.1\tlocalhost\t# Bazinga!\n"
+ expect(genhost(host)).to eq("127.0.0.1\tlocalhost\t# Bazinga!\n")
end
it "should be able to generate an entry with one alias and a comment" do
host = mkhost(
:name => 'localhost.localdomain',
:ip => '127.0.0.1',
:host_aliases => 'localhost',
:comment => 'Bazinga!',
:ensure => :present
)
- genhost(host).should == "127.0.0.1\tlocalhost.localdomain\tlocalhost\t# Bazinga!\n"
+ expect(genhost(host)).to eq("127.0.0.1\tlocalhost.localdomain\tlocalhost\t# Bazinga!\n")
end
it "should be able to generate an entry with more than one alias and a comment" do
host = mkhost(
:name => 'host',
:ip => '192.0.0.1',
:host_aliases => [ 'a1','a2','a3','a4' ],
:comment => 'Bazinga!',
:ensure => :present
)
- genhost(host).should == "192.0.0.1\thost\ta1 a2 a3 a4\t# Bazinga!\n"
+ expect(genhost(host)).to eq("192.0.0.1\thost\ta1 a2 a3 a4\t# Bazinga!\n")
end
end
end
diff --git a/spec/unit/provider/interface/cisco_spec.rb b/spec/unit/provider/interface/cisco_spec.rb
index eeea90de0..ae5741b34 100755
--- a/spec/unit/provider/interface/cisco_spec.rb
+++ b/spec/unit/provider/interface/cisco_spec.rb
@@ -1,57 +1,57 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/provider/interface/cisco'
provider_class = Puppet::Type.type(:interface).provider(:cisco)
describe provider_class do
before do
@device = stub_everything 'device'
@resource = stub("resource", :name => "Fa0/1")
@provider = provider_class.new(@device, @resource)
end
it "should have a parent of Puppet::Provider::Cisco" do
- provider_class.should < Puppet::Provider::Cisco
+ expect(provider_class).to be < Puppet::Provider::Cisco
end
it "should have an instances method" do
- provider_class.should respond_to(:instances)
+ expect(provider_class).to respond_to(:instances)
end
describe "when looking up instances at prefetch" do
before do
@device.stubs(:command).yields(@device)
end
it "should delegate to the device interface fetcher" do
@device.expects(:interface)
provider_class.lookup(@device, "Fa0/1")
end
it "should return the given interface data" do
@device.expects(:interface).returns({ :description => "thisone", :mode => :access})
- provider_class.lookup(@device, "Fa0").should == {:description => "thisone", :mode => :access }
+ expect(provider_class.lookup(@device, "Fa0")).to eq({:description => "thisone", :mode => :access })
end
end
describe "when an instance is being flushed" do
it "should call the device interface update method with current and past properties" do
@instance = provider_class.new(@device, :ensure => :present, :name => "Fa0/1", :description => "myinterface")
@instance.description = "newdesc"
@instance.resource = @resource
@resource.stubs(:[]).with(:name).returns("Fa0/1")
device = stub_everything 'device'
@instance.stubs(:device).returns(device)
device.expects(:command).yields(device)
interface = stub 'interface'
device.expects(:new_interface).with("Fa0/1").returns(interface)
interface.expects(:update).with( {:ensure => :present, :name => "Fa0/1", :description => "myinterface"},
{:ensure => :present, :name => "Fa0/1", :description => "newdesc"})
@instance.flush
end
end
end
diff --git a/spec/unit/provider/ldap_spec.rb b/spec/unit/provider/ldap_spec.rb
index 6582f6b21..8067a40b4 100755
--- a/spec/unit/provider/ldap_spec.rb
+++ b/spec/unit/provider/ldap_spec.rb
@@ -1,244 +1,244 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/provider/ldap'
describe Puppet::Provider::Ldap do
before do
@class = Class.new(Puppet::Provider::Ldap)
end
it "should be able to define its manager" do
manager = mock 'manager'
Puppet::Util::Ldap::Manager.expects(:new).returns manager
@class.stubs :mk_resource_methods
manager.expects(:manages).with(:one)
- @class.manages(:one).should equal(manager)
- @class.manager.should equal(manager)
+ expect(@class.manages(:one)).to equal(manager)
+ expect(@class.manager).to equal(manager)
end
it "should be able to prefetch instances from ldap" do
- @class.should respond_to(:prefetch)
+ expect(@class).to respond_to(:prefetch)
end
it "should create its resource getter/setter methods when the manager is defined" do
manager = mock 'manager'
Puppet::Util::Ldap::Manager.expects(:new).returns manager
@class.expects :mk_resource_methods
manager.stubs(:manages)
- @class.manages(:one).should equal(manager)
+ expect(@class.manages(:one)).to equal(manager)
end
it "should have an instances method" do
- @class.should respond_to(:instances)
+ expect(@class).to respond_to(:instances)
end
describe "when providing a list of instances" do
it "should convert all results returned from the manager's :search method into provider instances" do
manager = mock 'manager'
@class.stubs(:manager).returns manager
manager.expects(:search).returns %w{one two three}
@class.expects(:new).with("one").returns(1)
@class.expects(:new).with("two").returns(2)
@class.expects(:new).with("three").returns(3)
- @class.instances.should == [1,2,3]
+ expect(@class.instances).to eq([1,2,3])
end
end
it "should have a prefetch method" do
- @class.should respond_to(:prefetch)
+ expect(@class).to respond_to(:prefetch)
end
describe "when prefetching" do
before do
@manager = mock 'manager'
@class.stubs(:manager).returns @manager
@resource = mock 'resource'
@resources = {"one" => @resource}
end
it "should find an entry for each passed resource" do
@manager.expects(:find).with("one").returns nil
@class.stubs(:new)
@resource.stubs(:provider=)
@class.prefetch(@resources)
end
describe "resources that do not exist" do
it "should create a provider with :ensure => :absent" do
result = mock 'result'
@manager.expects(:find).with("one").returns nil
@class.expects(:new).with(:ensure => :absent).returns "myprovider"
@resource.expects(:provider=).with("myprovider")
@class.prefetch(@resources)
end
end
describe "resources that exist" do
it "should create a provider with the results of the find" do
@manager.expects(:find).with("one").returns("one" => "two")
@class.expects(:new).with("one" => "two", :ensure => :present).returns "myprovider"
@resource.expects(:provider=).with("myprovider")
@class.prefetch(@resources)
end
it "should set :ensure to :present in the returned values" do
@manager.expects(:find).with("one").returns("one" => "two")
@class.expects(:new).with("one" => "two", :ensure => :present).returns "myprovider"
@resource.expects(:provider=).with("myprovider")
@class.prefetch(@resources)
end
end
end
describe "when being initialized" do
it "should fail if no manager has been defined" do
- lambda { @class.new }.should raise_error(Puppet::DevError)
+ expect { @class.new }.to raise_error(Puppet::DevError)
end
it "should fail if the manager is invalid" do
manager = stub "manager", :valid? => false
@class.stubs(:manager).returns manager
- lambda { @class.new }.should raise_error(Puppet::DevError)
+ expect { @class.new }.to raise_error(Puppet::DevError)
end
describe "with a hash" do
before do
@manager = stub "manager", :valid? => true
@class.stubs(:manager).returns @manager
@resource_class = mock 'resource_class'
@class.stubs(:resource_type).returns @resource_class
@property_class = stub 'property_class', :array_matching => :all, :superclass => Puppet::Property
@resource_class.stubs(:attrclass).with(:one).returns(@property_class)
@resource_class.stubs(:valid_parameter?).returns true
end
it "should store a copy of the hash as its ldap_properties" do
instance = @class.new(:one => :two)
- instance.ldap_properties.should == {:one => :two}
+ expect(instance.ldap_properties).to eq({:one => :two})
end
it "should only store the first value of each value array for those attributes that do not match all values" do
@property_class.expects(:array_matching).returns :first
instance = @class.new(:one => %w{two three})
- instance.properties.should == {:one => "two"}
+ expect(instance.properties).to eq({:one => "two"})
end
it "should store the whole value array for those attributes that match all values" do
@property_class.expects(:array_matching).returns :all
instance = @class.new(:one => %w{two three})
- instance.properties.should == {:one => %w{two three}}
+ expect(instance.properties).to eq({:one => %w{two three}})
end
it "should only use the first value for attributes that are not properties" do
# Yay. hackish, but easier than mocking everything.
@resource_class.expects(:attrclass).with(:a).returns Puppet::Type.type(:user).attrclass(:name)
@property_class.stubs(:array_matching).returns :all
instance = @class.new(:one => %w{two three}, :a => %w{b c})
- instance.properties.should == {:one => %w{two three}, :a => "b"}
+ expect(instance.properties).to eq({:one => %w{two three}, :a => "b"})
end
it "should discard any properties not valid in the resource class" do
@resource_class.expects(:valid_parameter?).with(:a).returns false
@property_class.stubs(:array_matching).returns :all
instance = @class.new(:one => %w{two three}, :a => %w{b})
- instance.properties.should == {:one => %w{two three}}
+ expect(instance.properties).to eq({:one => %w{two three}})
end
end
end
describe "when an instance" do
before do
@manager = stub "manager", :valid? => true
@class.stubs(:manager).returns @manager
@instance = @class.new
@property_class = stub 'property_class', :array_matching => :all, :superclass => Puppet::Property
@resource_class = stub 'resource_class', :attrclass => @property_class, :valid_parameter? => true, :validproperties => [:one, :two]
@class.stubs(:resource_type).returns @resource_class
end
it "should have a method for creating the ldap entry" do
- @instance.should respond_to(:create)
+ expect(@instance).to respond_to(:create)
end
it "should have a method for removing the ldap entry" do
- @instance.should respond_to(:delete)
+ expect(@instance).to respond_to(:delete)
end
it "should have a method for returning the class's manager" do
- @instance.manager.should equal(@manager)
+ expect(@instance.manager).to equal(@manager)
end
it "should indicate when the ldap entry already exists" do
@instance = @class.new(:ensure => :present)
- @instance.exists?.should be_true
+ expect(@instance.exists?).to be_truthy
end
it "should indicate when the ldap entry does not exist" do
@instance = @class.new(:ensure => :absent)
- @instance.exists?.should be_false
+ expect(@instance.exists?).to be_falsey
end
describe "is being flushed" do
it "should call the manager's :update method with its name, current attributes, and desired attributes" do
@instance.stubs(:name).returns "myname"
@instance.stubs(:ldap_properties).returns(:one => :two)
@instance.stubs(:properties).returns(:three => :four)
@manager.expects(:update).with(@instance.name, {:one => :two}, {:three => :four})
@instance.flush
end
end
describe "is being created" do
before do
@rclass = mock 'resource_class'
@rclass.stubs(:validproperties).returns([:one, :two])
@resource = mock 'resource'
@resource.stubs(:class).returns @rclass
@resource.stubs(:should).returns nil
@instance.stubs(:resource).returns @resource
end
it "should set its :ensure value to :present" do
@instance.create
- @instance.properties[:ensure].should == :present
+ expect(@instance.properties[:ensure]).to eq(:present)
end
it "should set all of the other attributes from the resource" do
@resource.expects(:should).with(:one).returns "oneval"
@resource.expects(:should).with(:two).returns "twoval"
@instance.create
- @instance.properties[:one].should == "oneval"
- @instance.properties[:two].should == "twoval"
+ expect(@instance.properties[:one]).to eq("oneval")
+ expect(@instance.properties[:two]).to eq("twoval")
end
end
describe "is being deleted" do
it "should set its :ensure value to :absent" do
@instance.delete
- @instance.properties[:ensure].should == :absent
+ expect(@instance.properties[:ensure]).to eq(:absent)
end
end
end
end
diff --git a/spec/unit/provider/macauthorization_spec.rb b/spec/unit/provider/macauthorization_spec.rb
index d933e6001..2cabf3dbe 100755
--- a/spec/unit/provider/macauthorization_spec.rb
+++ b/spec/unit/provider/macauthorization_spec.rb
@@ -1,152 +1,152 @@
#! /usr/bin/env ruby
#
# Unit testing for the macauthorization provider
#
require 'spec_helper'
require 'puppet'
require 'facter/util/plist'
provider_class = Puppet::Type.type(:macauthorization).provider(:macauthorization)
describe provider_class do
before :each do
# Create a mock resource
@resource = stub 'resource'
@authname = "foo.spam.eggs.puppettest"
@authplist = {}
@rules = {@authname => @authplist}
authdb = {}
authdb["rules"] = { "foorule" => "foo" }
authdb["rights"] = { "fooright" => "foo" }
# Stub out Plist::parse_xml
Plist.stubs(:parse_xml).returns(authdb)
# A catch all; no parameters set
@resource.stubs(:[]).returns(nil)
# But set name, ensure
@resource.stubs(:[]).with(:name).returns @authname
@resource.stubs(:[]).with(:ensure).returns :present
@resource.stubs(:ref).returns "MacAuthorization[#{@authname}]"
@provider = provider_class.new(@resource)
end
it "should have a create method" do
- @provider.should respond_to(:create)
+ expect(@provider).to respond_to(:create)
end
it "should have a destroy method" do
- @provider.should respond_to(:destroy)
+ expect(@provider).to respond_to(:destroy)
end
it "should have an exists? method" do
- @provider.should respond_to(:exists?)
+ expect(@provider).to respond_to(:exists?)
end
it "should have a flush method" do
- @provider.should respond_to(:flush)
+ expect(@provider).to respond_to(:flush)
end
properties = [ :allow_root, :authenticate_user, :auth_class, :comment,
:group, :k_of_n, :mechanisms, :rule, :session_owner,
:shared, :timeout, :tries, :auth_type ]
properties.each do |prop|
it "should have a #{prop.to_s} method" do
- @provider.should respond_to(prop.to_s)
+ expect(@provider).to respond_to(prop.to_s)
end
it "should have a #{prop.to_s}= method" do
- @provider.should respond_to(prop.to_s + "=")
+ expect(@provider).to respond_to(prop.to_s + "=")
end
end
describe "when destroying a right" do
before :each do
@resource.stubs(:[]).with(:auth_type).returns(:right)
end
it "should call the internal method destroy_right" do
@provider.expects(:destroy_right)
@provider.destroy
end
it "should call the external command 'security authorizationdb remove @authname" do
@provider.expects(:security).with("authorizationdb", :remove, @authname)
@provider.destroy
end
end
describe "when destroying a rule" do
before :each do
@resource.stubs(:[]).with(:auth_type).returns(:rule)
end
it "should call the internal method destroy_rule" do
@provider.expects(:destroy_rule)
@provider.destroy
end
end
describe "when flushing a right" do
before :each do
@resource.stubs(:[]).with(:auth_type).returns(:right)
end
it "should call the internal method flush_right" do
@provider.expects(:flush_right)
@provider.flush
end
it "should call the internal method set_right" do
@provider.expects(:execute).with { |cmds, args|
cmds.include?("read") and
cmds.include?(@authname) and
args[:combine] == false
}.once
@provider.expects(:set_right)
@provider.flush
end
it "should read and write to the auth database with the right arguments" do
@provider.expects(:execute).with { |cmds, args|
cmds.include?("read") and
cmds.include?(@authname) and
args[:combine] == false
}.once
@provider.expects(:execute).with { |cmds, args|
cmds.include?("write") and
cmds.include?(@authname) and
args[:combine] == false and
args[:stdinfile] != nil
}.once
@provider.flush
end
end
describe "when flushing a rule" do
before :each do
@resource.stubs(:[]).with(:auth_type).returns(:rule)
end
it "should call the internal method flush_rule" do
@provider.expects(:flush_rule)
@provider.flush
end
it "should call the internal method set_rule" do
@provider.expects(:set_rule)
@provider.flush
end
end
end
diff --git a/spec/unit/provider/mcx/mcxcontent_spec.rb b/spec/unit/provider/mcx/mcxcontent_spec.rb
index b015b226a..122f5acb1 100755
--- a/spec/unit/provider/mcx/mcxcontent_spec.rb
+++ b/spec/unit/provider/mcx/mcxcontent_spec.rb
@@ -1,192 +1,192 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:mcx).provider(:mcxcontent)
# describe creates a new ExampleGroup object.
describe provider_class do
# :each executes before each test.
# :all executes once for the test group and before :each.
before :each do
# Create a mock resource
@resource = stub 'resource'
@provider = provider_class.new
@attached_to = "/Users/foobar"
@ds_path = "/Local/Default/Users/foobar"
# A catch all; no parameters set
@resource.stubs(:[]).returns(nil)
# But set name, ensure and enable
@resource.stubs(:[]).with(:name).returns @attached_to
@resource.stubs(:[]).with(:ensure).returns :present
@resource.stubs(:ref).returns "Mcx[#{@attached_to}]"
# stub out the provider methods that actually touch the filesystem
# or execute commands
@provider.class.stubs(:execute).returns('')
@provider.stubs(:execute).returns('')
@provider.stubs(:resource).returns @resource
end
it "should have a create method." do
- @provider.should respond_to(:create)
+ expect(@provider).to respond_to(:create)
end
it "should have a destroy method." do
- @provider.should respond_to(:destroy)
+ expect(@provider).to respond_to(:destroy)
end
it "should have an exists? method." do
- @provider.should respond_to(:exists?)
+ expect(@provider).to respond_to(:exists?)
end
it "should have a content method." do
- @provider.should respond_to(:content)
+ expect(@provider).to respond_to(:content)
end
it "should have a content= method." do
- @provider.should respond_to(:content=)
+ expect(@provider).to respond_to(:content=)
end
describe "when managing the resource" do
it "should execute external command dscl from :create" do
@provider.stubs(:has_mcx?).returns(false)
@provider.class.expects(:dscl).returns('').once
@provider.create
end
it "deletes existing mcx prior to import from :create" do
@provider.stubs(:has_mcx?).returns(true)
@provider.class.expects(:dscl).with('localhost', '-mcxdelete', @ds_path, anything()).once
@provider.class.expects(:dscl).with('localhost', '-mcximport', @ds_path, anything()).once
@provider.create
end
it "should execute external command dscl from :destroy" do
@provider.class.expects(:dscl).with('localhost', '-mcxdelete', @ds_path).returns('').once
@provider.destroy
end
it "should execute external command dscl from :exists?" do
@provider.class.expects(:dscl).with('localhost', '-mcxexport', @ds_path).returns('').once
@provider.exists?
end
it "should execute external command dscl from :content" do
@provider.class.expects(:dscl).with('localhost', '-mcxexport', @ds_path).returns('')
@provider.content
end
it "should execute external command dscl from :content=" do
@provider.stubs(:has_mcx?).returns(false)
@provider.class.expects(:dscl).returns('').once
@provider.content=''
end
it "deletes existing mcx prior to import from :content=" do
@provider.stubs(:has_mcx?).returns(true)
@provider.class.expects(:dscl).with('localhost', '-mcxdelete', @ds_path, anything()).once
@provider.class.expects(:dscl).with('localhost', '-mcximport', @ds_path, anything()).once
@provider.content=''
end
end
describe "when creating and parsing the name for ds_type" do
before :each do
@provider.class.stubs(:dscl).returns('')
@resource.stubs(:[]).with(:name).returns "/Foo/bar"
end
it "should not accept /Foo/bar" do
expect { @provider.create }.to raise_error(MCXContentProviderException)
end
it "should accept /Foo/bar with ds_type => user" do
@resource.stubs(:[]).with(:ds_type).returns "user"
expect { @provider.create }.to_not raise_error
end
it "should accept /Foo/bar with ds_type => group" do
@resource.stubs(:[]).with(:ds_type).returns "group"
expect { @provider.create }.to_not raise_error
end
it "should accept /Foo/bar with ds_type => computer" do
@resource.stubs(:[]).with(:ds_type).returns "computer"
expect { @provider.create }.to_not raise_error
end
it "should accept :name => /Foo/bar with ds_type => computerlist" do
@resource.stubs(:[]).with(:ds_type).returns "computerlist"
expect { @provider.create }.to_not raise_error
end
end
describe "when creating and :name => foobar" do
before :each do
@provider.class.stubs(:dscl).returns('')
@resource.stubs(:[]).with(:name).returns "foobar"
end
it "should not accept unspecified :ds_type and :ds_name" do
expect { @provider.create }.to raise_error(MCXContentProviderException)
end
it "should not accept unspecified :ds_type" do
@resource.stubs(:[]).with(:ds_type).returns "user"
expect { @provider.create }.to raise_error(MCXContentProviderException)
end
it "should not accept unspecified :ds_name" do
@resource.stubs(:[]).with(:ds_name).returns "foo"
expect { @provider.create }.to raise_error(MCXContentProviderException)
end
it "should accept :ds_type => user, ds_name => foo" do
@resource.stubs(:[]).with(:ds_type).returns "user"
@resource.stubs(:[]).with(:ds_name).returns "foo"
expect { @provider.create }.to_not raise_error
end
it "should accept :ds_type => group, ds_name => foo" do
@resource.stubs(:[]).with(:ds_type).returns "group"
@resource.stubs(:[]).with(:ds_name).returns "foo"
expect { @provider.create }.to_not raise_error
end
it "should accept :ds_type => computer, ds_name => foo" do
@resource.stubs(:[]).with(:ds_type).returns "computer"
@resource.stubs(:[]).with(:ds_name).returns "foo"
expect { @provider.create }.to_not raise_error
end
it "should accept :ds_type => computerlist, ds_name => foo" do
@resource.stubs(:[]).with(:ds_type).returns "computerlist"
@resource.stubs(:[]).with(:ds_name).returns "foo"
expect { @provider.create }.to_not raise_error
end
it "should not accept :ds_type => bogustype, ds_name => foo" do
@resource.stubs(:[]).with(:ds_type).returns "bogustype"
@resource.stubs(:[]).with(:ds_name).returns "foo"
expect { @provider.create }.to raise_error(MCXContentProviderException)
end
end
describe "when gathering existing instances" do
it "should define an instances class method." do
- @provider.class.should respond_to(:instances)
+ expect(@provider.class).to respond_to(:instances)
end
it "should call external command dscl -list /Local/Default/<ds_type> on each known ds_type" do
@provider.class.expects(:dscl).with('localhost', '-list', "/Local/Default/Users").returns('')
@provider.class.expects(:dscl).with('localhost', '-list', "/Local/Default/Groups").returns('')
@provider.class.expects(:dscl).with('localhost', '-list', "/Local/Default/Computers").returns('')
@provider.class.expects(:dscl).with('localhost', '-list', "/Local/Default/ComputerLists").returns('')
@provider.class.instances
end
end
end
diff --git a/spec/unit/provider/mount/parsed_spec.rb b/spec/unit/provider/mount/parsed_spec.rb
index 196dd4635..1b07fcb01 100755
--- a/spec/unit/provider/mount/parsed_spec.rb
+++ b/spec/unit/provider/mount/parsed_spec.rb
@@ -1,283 +1,291 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'shared_behaviours/all_parsedfile_providers'
+# TODO: We've recently dropped running specs on Solaris because it was poor ROI.
+# This file has a ton of tiptoeing around Solaris that we should ultimately
+# remove, but I don't want to do so just yet, in case we get pushback to
+# restore Solaris spec tests.
+
describe Puppet::Type.type(:mount).provider(:parsed), :unless => Puppet.features.microsoft_windows? do
let :vfstab_sample do
"/dev/dsk/c0d0s0 /dev/rdsk/c0d0s0 \t\t / \t ufs 1 no\t-"
end
let :fstab_sample do
"/dev/vg00/lv01\t/spare \t \t ext3 defaults\t1 2"
end
# LAK:FIXME I can't mock Facter because this test happens at parse-time.
it "should default to /etc/vfstab on Solaris" do
- pending "This test only works on Solaris" unless Facter.value(:osfamily) == 'Solaris'
- described_class.default_target.should == '/etc/vfstab'
+ if Facter.value(:osfamily) != 'Solaris'
+ skip("This test only works on Solaris")
+ else
+ expect(described_class.default_target).to eq('/etc/vfstab')
+ end
end
it "should default to /etc/fstab on anything else" do
- pending "This test does not work on Solaris" if Facter.value(:osfamily) == 'Solaris'
- described_class.default_target.should == '/etc/fstab'
+ if Facter.value(:osfamily) == 'Solaris'
+ skip("This test only does not work on Solaris")
+ else
+ expect(described_class.default_target).to eq('/etc/fstab')
+ end
end
describe "when parsing a line" do
it "should not crash on incomplete lines in fstab" do
parse = described_class.parse <<-FSTAB
/dev/incomplete
/dev/device name
FSTAB
expect { described_class.to_line(parse[0]) }.to_not raise_error
end
# it_should_behave_like "all parsedfile providers",
# provider_class, my_fixtures('*.fstab')
describe "on Solaris", :if => Facter.value(:osfamily) == 'Solaris' do
it "should extract device from the first field" do
- described_class.parse_line(vfstab_sample)[:device].should == '/dev/dsk/c0d0s0'
+ expect(described_class.parse_line(vfstab_sample)[:device]).to eq('/dev/dsk/c0d0s0')
end
it "should extract blockdevice from second field" do
- described_class.parse_line(vfstab_sample)[:blockdevice].should == "/dev/rdsk/c0d0s0"
+ expect(described_class.parse_line(vfstab_sample)[:blockdevice]).to eq("/dev/rdsk/c0d0s0")
end
it "should extract name from third field" do
- described_class.parse_line(vfstab_sample)[:name].should == "/"
+ expect(described_class.parse_line(vfstab_sample)[:name]).to eq("/")
end
it "should extract fstype from fourth field" do
- described_class.parse_line(vfstab_sample)[:fstype].should == "ufs"
+ expect(described_class.parse_line(vfstab_sample)[:fstype]).to eq("ufs")
end
it "should extract pass from fifth field" do
- described_class.parse_line(vfstab_sample)[:pass].should == "1"
+ expect(described_class.parse_line(vfstab_sample)[:pass]).to eq("1")
end
it "should extract atboot from sixth field" do
- described_class.parse_line(vfstab_sample)[:atboot].should == "no"
+ expect(described_class.parse_line(vfstab_sample)[:atboot]).to eq("no")
end
it "should extract options from seventh field" do
- described_class.parse_line(vfstab_sample)[:options].should == "-"
+ expect(described_class.parse_line(vfstab_sample)[:options]).to eq("-")
end
end
describe "on other platforms than Solaris", :if => Facter.value(:osfamily) != 'Solaris' do
it "should extract device from the first field" do
- described_class.parse_line(fstab_sample)[:device].should == '/dev/vg00/lv01'
+ expect(described_class.parse_line(fstab_sample)[:device]).to eq('/dev/vg00/lv01')
end
it "should extract name from second field" do
- described_class.parse_line(fstab_sample)[:name].should == "/spare"
+ expect(described_class.parse_line(fstab_sample)[:name]).to eq("/spare")
end
it "should extract fstype from third field" do
- described_class.parse_line(fstab_sample)[:fstype].should == "ext3"
+ expect(described_class.parse_line(fstab_sample)[:fstype]).to eq("ext3")
end
it "should extract options from fourth field" do
- described_class.parse_line(fstab_sample)[:options].should == "defaults"
+ expect(described_class.parse_line(fstab_sample)[:options]).to eq("defaults")
end
it "should extract dump from fifth field" do
- described_class.parse_line(fstab_sample)[:dump].should == "1"
+ expect(described_class.parse_line(fstab_sample)[:dump]).to eq("1")
end
it "should extract options from sixth field" do
- described_class.parse_line(fstab_sample)[:pass].should == "2"
+ expect(described_class.parse_line(fstab_sample)[:pass]).to eq("2")
end
end
end
describe "mountinstances" do
it "should get name from mountoutput found on Solaris" do
Facter.stubs(:value).with(:osfamily).returns 'Solaris'
described_class.stubs(:mountcmd).returns(File.read(my_fixture('solaris.mount')))
mounts = described_class.mountinstances
- mounts.size.should == 6
- mounts[0].should == { :name => '/', :mounted => :yes }
- mounts[1].should == { :name => '/proc', :mounted => :yes }
- mounts[2].should == { :name => '/etc/mnttab', :mounted => :yes }
- mounts[3].should == { :name => '/tmp', :mounted => :yes }
- mounts[4].should == { :name => '/export/home', :mounted => :yes }
- mounts[5].should == { :name => '/ghost', :mounted => :yes }
+ expect(mounts.size).to eq(6)
+ expect(mounts[0]).to eq({ :name => '/', :mounted => :yes })
+ expect(mounts[1]).to eq({ :name => '/proc', :mounted => :yes })
+ expect(mounts[2]).to eq({ :name => '/etc/mnttab', :mounted => :yes })
+ expect(mounts[3]).to eq({ :name => '/tmp', :mounted => :yes })
+ expect(mounts[4]).to eq({ :name => '/export/home', :mounted => :yes })
+ expect(mounts[5]).to eq({ :name => '/ghost', :mounted => :yes })
end
it "should get name from mountoutput found on HP-UX" do
Facter.stubs(:value).with(:osfamily).returns 'HP-UX'
described_class.stubs(:mountcmd).returns(File.read(my_fixture('hpux.mount')))
mounts = described_class.mountinstances
- mounts.size.should == 17
- mounts[0].should == { :name => '/', :mounted => :yes }
- mounts[1].should == { :name => '/devices', :mounted => :yes }
- mounts[2].should == { :name => '/dev', :mounted => :yes }
- mounts[3].should == { :name => '/system/contract', :mounted => :yes }
- mounts[4].should == { :name => '/proc', :mounted => :yes }
- mounts[5].should == { :name => '/etc/mnttab', :mounted => :yes }
- mounts[6].should == { :name => '/etc/svc/volatile', :mounted => :yes }
- mounts[7].should == { :name => '/system/object', :mounted => :yes }
- mounts[8].should == { :name => '/etc/dfs/sharetab', :mounted => :yes }
- mounts[9].should == { :name => '/lib/libc.so.1', :mounted => :yes }
- mounts[10].should == { :name => '/dev/fd', :mounted => :yes }
- mounts[11].should == { :name => '/tmp', :mounted => :yes }
- mounts[12].should == { :name => '/var/run', :mounted => :yes }
- mounts[13].should == { :name => '/export', :mounted => :yes }
- mounts[14].should == { :name => '/export/home', :mounted => :yes }
- mounts[15].should == { :name => '/rpool', :mounted => :yes }
- mounts[16].should == { :name => '/ghost', :mounted => :yes }
+ expect(mounts.size).to eq(17)
+ expect(mounts[0]).to eq({ :name => '/', :mounted => :yes })
+ expect(mounts[1]).to eq({ :name => '/devices', :mounted => :yes })
+ expect(mounts[2]).to eq({ :name => '/dev', :mounted => :yes })
+ expect(mounts[3]).to eq({ :name => '/system/contract', :mounted => :yes })
+ expect(mounts[4]).to eq({ :name => '/proc', :mounted => :yes })
+ expect(mounts[5]).to eq({ :name => '/etc/mnttab', :mounted => :yes })
+ expect(mounts[6]).to eq({ :name => '/etc/svc/volatile', :mounted => :yes })
+ expect(mounts[7]).to eq({ :name => '/system/object', :mounted => :yes })
+ expect(mounts[8]).to eq({ :name => '/etc/dfs/sharetab', :mounted => :yes })
+ expect(mounts[9]).to eq({ :name => '/lib/libc.so.1', :mounted => :yes })
+ expect(mounts[10]).to eq({ :name => '/dev/fd', :mounted => :yes })
+ expect(mounts[11]).to eq({ :name => '/tmp', :mounted => :yes })
+ expect(mounts[12]).to eq({ :name => '/var/run', :mounted => :yes })
+ expect(mounts[13]).to eq({ :name => '/export', :mounted => :yes })
+ expect(mounts[14]).to eq({ :name => '/export/home', :mounted => :yes })
+ expect(mounts[15]).to eq({ :name => '/rpool', :mounted => :yes })
+ expect(mounts[16]).to eq({ :name => '/ghost', :mounted => :yes })
end
it "should get name from mountoutput found on Darwin" do
Facter.stubs(:value).with(:osfamily).returns 'Darwin'
described_class.stubs(:mountcmd).returns(File.read(my_fixture('darwin.mount')))
mounts = described_class.mountinstances
- mounts.size.should == 6
- mounts[0].should == { :name => '/', :mounted => :yes }
- mounts[1].should == { :name => '/dev', :mounted => :yes }
- mounts[2].should == { :name => '/net', :mounted => :yes }
- mounts[3].should == { :name => '/home', :mounted => :yes }
- mounts[4].should == { :name => '/usr', :mounted => :yes }
- mounts[5].should == { :name => '/ghost', :mounted => :yes }
+ expect(mounts.size).to eq(6)
+ expect(mounts[0]).to eq({ :name => '/', :mounted => :yes })
+ expect(mounts[1]).to eq({ :name => '/dev', :mounted => :yes })
+ expect(mounts[2]).to eq({ :name => '/net', :mounted => :yes })
+ expect(mounts[3]).to eq({ :name => '/home', :mounted => :yes })
+ expect(mounts[4]).to eq({ :name => '/usr', :mounted => :yes })
+ expect(mounts[5]).to eq({ :name => '/ghost', :mounted => :yes })
end
it "should get name from mountoutput found on Linux" do
Facter.stubs(:value).with(:osfamily).returns 'Gentoo'
described_class.stubs(:mountcmd).returns(File.read(my_fixture('linux.mount')))
mounts = described_class.mountinstances
- mounts[0].should == { :name => '/', :mounted => :yes }
- mounts[1].should == { :name => '/lib64/rc/init.d', :mounted => :yes }
- mounts[2].should == { :name => '/sys', :mounted => :yes }
- mounts[3].should == { :name => '/usr/portage', :mounted => :yes }
- mounts[4].should == { :name => '/ghost', :mounted => :yes }
+ expect(mounts[0]).to eq({ :name => '/', :mounted => :yes })
+ expect(mounts[1]).to eq({ :name => '/lib64/rc/init.d', :mounted => :yes })
+ expect(mounts[2]).to eq({ :name => '/sys', :mounted => :yes })
+ expect(mounts[3]).to eq({ :name => '/usr/portage', :mounted => :yes })
+ expect(mounts[4]).to eq({ :name => '/ghost', :mounted => :yes })
end
it "should get name from mountoutput found on AIX" do
Facter.stubs(:value).with(:osfamily).returns 'AIX'
described_class.stubs(:mountcmd).returns(File.read(my_fixture('aix.mount')))
mounts = described_class.mountinstances
- mounts[0].should == { :name => '/', :mounted => :yes }
- mounts[1].should == { :name => '/tmp', :mounted => :yes }
- mounts[2].should == { :name => '/home', :mounted => :yes }
- mounts[3].should == { :name => '/usr', :mounted => :yes }
- mounts[4].should == { :name => '/usr/code', :mounted => :yes }
+ expect(mounts[0]).to eq({ :name => '/', :mounted => :yes })
+ expect(mounts[1]).to eq({ :name => '/tmp', :mounted => :yes })
+ expect(mounts[2]).to eq({ :name => '/home', :mounted => :yes })
+ expect(mounts[3]).to eq({ :name => '/usr', :mounted => :yes })
+ expect(mounts[4]).to eq({ :name => '/usr/code', :mounted => :yes })
end
it "should raise an error if a line is not understandable" do
described_class.stubs(:mountcmd).returns("bazinga!")
expect { described_class.mountinstances }.to raise_error Puppet::Error, 'Could not understand line bazinga! from mount output'
end
end
it "should support AIX's paragraph based /etc/filesystems"
my_fixtures('*.fstab').each do |fstab|
platform = File.basename(fstab, '.fstab')
describe "when calling instances on #{platform}" do
before :each do
if Facter[:osfamily] == "Solaris" then
platform == 'solaris' or
- pending "We need to stub the operatingsystem fact at load time, but can't"
+ skip "We need to stub the operatingsystem fact at load time, but can't"
else
platform != 'solaris' or
- pending "We need to stub the operatingsystem fact at load time, but can't"
+ skip "We need to stub the operatingsystem fact at load time, but can't"
end
# Stub the mount output to our fixture.
begin
mount = my_fixture(platform + '.mount')
described_class.stubs(:mountcmd).returns File.read(mount)
rescue
- pending "is #{platform}.mount missing at this point?"
+ skip "is #{platform}.mount missing at this point?"
end
# Note: we have to stub default_target before creating resources
# because it is used by Puppet::Type::Mount.new to populate the
# :target property.
described_class.stubs(:default_target).returns fstab
@retrieve = described_class.instances.collect { |prov| {:name => prov.get(:name), :ensure => prov.get(:ensure)}}
end
# Following mountpoint are present in all fstabs/mountoutputs
- it "should include unmounted resources" do
- pending("Solaris:Unable to stub Operating System Fact at runtime", :if => Facter.value(:osfamily) == 'Solaris' )
- @retrieve.should include(:name => '/', :ensure => :mounted)
- end
+ describe "on other platforms than Solaris", :if => Facter.value(:osfamily) != 'Solaris' do
+ it "should include unmounted resources" do
+ expect(@retrieve).to include(:name => '/', :ensure => :mounted)
+ end
- it "should include mounted resources" do
- pending("Solaris:Unable to stub Operating System Fact at runtime", :if => Facter.value(:osfamily) == "Solaris")
- @retrieve.should include(:name => '/boot', :ensure => :unmounted)
- end
+ it "should include mounted resources" do
+ expect(@retrieve).to include(:name => '/boot', :ensure => :unmounted)
+ end
- it "should include ghost resources" do
- pending("Solaris:Unable to stub Operating System Fact at runtime", :if => Facter.value(:osfamily) == "Solaris")
- @retrieve.should include(:name => '/ghost', :ensure => :ghost)
+ it "should include ghost resources" do
+ expect(@retrieve).to include(:name => '/ghost', :ensure => :ghost)
+ end
end
-
end
describe "when prefetching on #{platform}" do
before :each do
if Facter[:osfamily] == "Solaris" then
platform == 'solaris' or
- pending "We need to stub the operatingsystem fact at load time, but can't"
+ skip "We need to stub the operatingsystem fact at load time, but can't"
else
platform != 'solaris' or
- pending "We need to stub the operatingsystem fact at load time, but can't"
+ skip "We need to stub the operatingsystem fact at load time, but can't"
end
# Stub the mount output to our fixture.
begin
mount = my_fixture(platform + '.mount')
described_class.stubs(:mountcmd).returns File.read(mount)
rescue
- pending "is #{platform}.mount missing at this point?"
+ skip "is #{platform}.mount missing at this point?"
end
# Note: we have to stub default_target before creating resources
# because it is used by Puppet::Type::Mount.new to populate the
# :target property.
described_class.stubs(:default_target).returns fstab
@res_ghost = Puppet::Type::Mount.new(:name => '/ghost') # in no fake fstab
@res_mounted = Puppet::Type::Mount.new(:name => '/') # in every fake fstab
@res_unmounted = Puppet::Type::Mount.new(:name => '/boot') # in every fake fstab
@res_absent = Puppet::Type::Mount.new(:name => '/absent') # in no fake fstab
# Simulate transaction.rb:prefetch
@resource_hash = {}
[@res_ghost, @res_mounted, @res_unmounted, @res_absent].each do |resource|
@resource_hash[resource.name] = resource
end
end
- it "should set :ensure to :unmounted if found in fstab but not mounted" do
- pending("Solaris:Unable to stub Operating System Fact at runtime", :if => Facter.value(:osfamily) == "Solaris")
- described_class.prefetch(@resource_hash)
- @res_unmounted.provider.get(:ensure).should == :unmounted
- end
+ describe "on other platforms than Solaris", :if => Facter.value(:osfamily) != 'Solaris' do
+ it "should set :ensure to :unmounted if found in fstab but not mounted" do
+ described_class.prefetch(@resource_hash)
+ expect(@res_unmounted.provider.get(:ensure)).to eq(:unmounted)
+ end
- it "should set :ensure to :ghost if not found in fstab but mounted" do
- pending("Solaris:Unable to stub Operating System Fact at runtime", :if => Facter.value(:osfamily) == "Solaris")
- described_class.prefetch(@resource_hash)
- @res_ghost.provider.get(:ensure).should == :ghost
- end
+ it "should set :ensure to :ghost if not found in fstab but mounted" do
+ described_class.prefetch(@resource_hash)
+ expect(@res_ghost.provider.get(:ensure)).to eq(:ghost)
+ end
- it "should set :ensure to :mounted if found in fstab and mounted" do
- pending("Solaris:Unable to stub Operating System Fact at runtime", :if => Facter.value(:osfamily) == "Solaris")
- described_class.prefetch(@resource_hash)
- @res_mounted.provider.get(:ensure).should == :mounted
+ it "should set :ensure to :mounted if found in fstab and mounted" do
+ described_class.prefetch(@resource_hash)
+ expect(@res_mounted.provider.get(:ensure)).to eq(:mounted)
+ end
end
it "should set :ensure to :absent if not found in fstab and not mounted" do
described_class.prefetch(@resource_hash)
- @res_absent.provider.get(:ensure).should == :absent
+ expect(@res_absent.provider.get(:ensure)).to eq(:absent)
end
end
end
end
diff --git a/spec/unit/provider/naginator_spec.rb b/spec/unit/provider/naginator_spec.rb
index d3f89e290..4d559a212 100755
--- a/spec/unit/provider/naginator_spec.rb
+++ b/spec/unit/provider/naginator_spec.rb
@@ -1,79 +1,79 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/provider/naginator'
describe Puppet::Provider::Naginator do
before do
@resource_type = stub 'resource_type', :name => :nagios_test
@class = Class.new(Puppet::Provider::Naginator)
@class.stubs(:resource_type).returns @resource_type
end
it "should be able to look up the associated Nagios type" do
nagios_type = mock "nagios_type"
nagios_type.stubs :attr_accessor
Nagios::Base.expects(:type).with(:test).returns nagios_type
- @class.nagios_type.should equal(nagios_type)
+ expect(@class.nagios_type).to equal(nagios_type)
end
it "should use the Nagios type to determine whether an attribute is valid" do
nagios_type = mock "nagios_type"
nagios_type.stubs :attr_accessor
Nagios::Base.expects(:type).with(:test).returns nagios_type
nagios_type.expects(:parameters).returns [:foo, :bar]
- @class.valid_attr?(:test, :foo).should be_true
+ expect(@class.valid_attr?(:test, :foo)).to be_truthy
end
it "should use Naginator to parse configuration snippets" do
parser = mock 'parser'
parser.expects(:parse).with("my text").returns "my instances"
Nagios::Parser.expects(:new).returns(parser)
- @class.parse("my text").should == "my instances"
+ expect(@class.parse("my text")).to eq("my instances")
end
it "should join Nagios::Base records with '\\n' when asked to convert them to text" do
@class.expects(:header).returns "myheader\n"
- @class.to_file([:one, :two]).should == "myheader\none\ntwo"
+ expect(@class.to_file([:one, :two])).to eq("myheader\none\ntwo")
end
it "should be able to prefetch instance from configuration files" do
- @class.should respond_to(:prefetch)
+ expect(@class).to respond_to(:prefetch)
end
it "should be able to generate a list of instances" do
- @class.should respond_to(:instances)
+ expect(@class).to respond_to(:instances)
end
it "should never skip records" do
- @class.should_not be_skip_record("foo")
+ expect(@class).not_to be_skip_record("foo")
end
end
describe Nagios::Base do
it "should not turn set parameters into arrays #17871" do
obj = Nagios::Base.create('host')
obj.host_name = "my_hostname"
- obj.host_name.should == "my_hostname"
+ expect(obj.host_name).to eq("my_hostname")
end
end
describe Nagios::Parser do
include PuppetSpec::Files
subject do
described_class.new
end
let(:config) { File.new( my_fixture('define_empty_param') ).read }
it "should handle empty parameter values" do
expect { subject.parse(config) }.to_not raise_error
end
end
diff --git a/spec/unit/provider/nameservice/directoryservice_spec.rb b/spec/unit/provider/nameservice/directoryservice_spec.rb
index 9dcf0715a..0f5626099 100755
--- a/spec/unit/provider/nameservice/directoryservice_spec.rb
+++ b/spec/unit/provider/nameservice/directoryservice_spec.rb
@@ -1,167 +1,167 @@
#! /usr/bin/env ruby
require 'spec_helper'
# We use this as a reasonable way to obtain all the support infrastructure.
[:group].each do |type_for_this_round|
provider_class = Puppet::Type.type(type_for_this_round).provider(:directoryservice)
describe provider_class do
before do
@resource = stub("resource")
@provider = provider_class.new(@resource)
end
it "[#6009] should handle nested arrays of members" do
current = ["foo", "bar", "baz"]
desired = ["foo", ["quux"], "qorp"]
group = 'example'
@resource.stubs(:[]).with(:name).returns(group)
@resource.stubs(:[]).with(:auth_membership).returns(true)
@provider.instance_variable_set(:@property_value_cache_hash,
{ :members => current })
%w{bar baz}.each do |del|
@provider.expects(:execute).once.
with([:dseditgroup, '-o', 'edit', '-n', '.', '-d', del, group])
end
%w{quux qorp}.each do |add|
@provider.expects(:execute).once.
with([:dseditgroup, '-o', 'edit', '-n', '.', '-a', add, group])
end
expect { @provider.set(:members, desired) }.to_not raise_error
end
end
end
describe 'DirectoryService.single_report' do
it 'should use plist data' do
Puppet::Provider::NameService::DirectoryService.stubs(:get_ds_path).returns('Users')
Puppet::Provider::NameService::DirectoryService.stubs(:list_all_present).returns(
['root', 'user1', 'user2', 'resource_name']
)
Puppet::Provider::NameService::DirectoryService.stubs(:generate_attribute_hash)
Puppet::Provider::NameService::DirectoryService.stubs(:execute)
Puppet::Provider::NameService::DirectoryService.expects(:parse_dscl_plist_data)
Puppet::Provider::NameService::DirectoryService.single_report('resource_name')
end
end
describe 'DirectoryService.get_exec_preamble' do
it 'should use plist data' do
Puppet::Provider::NameService::DirectoryService.stubs(:get_ds_path).returns('Users')
- Puppet::Provider::NameService::DirectoryService.get_exec_preamble('-list').should include("-plist")
+ expect(Puppet::Provider::NameService::DirectoryService.get_exec_preamble('-list')).to include("-plist")
end
end
describe 'DirectoryService password behavior' do
# The below is a binary plist containing a ShadowHashData key which CONTAINS
# another binary plist. The nested binary plist contains a 'SALTED-SHA512'
# key that contains a base64 encoded salted-SHA512 password hash...
let (:binary_plist) { "bplist00\324\001\002\003\004\005\006\a\bXCRAM-MD5RNT]SALTED-SHA512[RECOVERABLEO\020 \231k2\3360\200GI\201\355J\216\202\215y\243\001\206J\300\363\032\031\022\006\2359\024\257\217<\361O\020\020F\353\at\377\277\226\276c\306\254\031\037J(\235O\020D\335\006{\3744g@\377z\204\322\r\332t\021\330\n\003\246K\223\356\034!P\261\305t\035\346\352p\206\003n\247MMA\310\301Z<\366\246\023\0161W3\340\357\000\317T\t\301\311+\204\246L7\276\370\320*\245O\021\002\000k\024\221\270x\353\001\237\346D}\377?\265]\356+\243\v[\350\316a\340h\376<\322\266\327\016\306n\272r\t\212A\253L\216\214\205\016\241 [\360/\335\002#\\A\372\241a\261\346\346\\\251\330\312\365\016\n\341\017\016\225&;\322\\\004*\ru\316\372\a \362?8\031\247\231\030\030\267\315\023\v\343{@\227\301s\372h\212\000a\244&\231\366\nt\277\2036,\027bZ+\223W\212g\333`\264\331N\306\307\362\257(^~ b\262\247&\231\261t\341\231%\244\247\203eOt\365\271\201\273\330\350\363C^A\327F\214!\217hgf\e\320k\260n\315u~\336\371M\t\235k\230S\375\311\303\240\351\037d\273\321y\335=K\016`_\317\230\2612_\023K\036\350\v\232\323Y\310\317_\035\227%\237\v\340\023\016\243\233\025\306:\227\351\370\364x\234\231\266\367\016w\275\333-\351\210}\375x\034\262\272kRuHa\362T/F!\347B\231O`K\304\037'k$$\245h)e\363\365mT\b\317\\2\361\026\351\254\375Jl1~\r\371\267\352\2322I\341\272\376\243^Un\266E7\230[VocUJ\220N\2116D/\025f=\213\314\325\vG}\311\360\377DT\307m\261&\263\340\272\243_\020\271rG^BW\210\030l\344\0324\335\233\300\023\272\225Im\330\n\227*Yv[\006\315\330y'\a\321\373\273A\240\305F{S\246I#/\355\2425\031\031GGF\270y\n\331\004\023G@\331\000\361\343\350\264$\032\355_\210y\000\205\342\375\212q\024\004\026W:\205 \363v?\035\270L-\270=\022\323\2003\v\336\277\t\237\356\374\n\267n\003\367\342\330;\371S\326\016`B6@Njm>\240\021%\336\345\002(P\204Yn\3279l\0228\264\254\304\2528t\372h\217\347sA\314\345\245\337)]\000\b\000\021\000\032\000\035\000+\0007\000Z\000m\000\264\000\000\000\000\000\000\002\001\000\000\000\000\000\000\000\t\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002\270" }
# The below is a base64 encoded salted-SHA512 password hash.
let (:pw_string) { "\335\006{\3744g@\377z\204\322\r\332t\021\330\n\003\246K\223\356\034!P\261\305t\035\346\352p\206\003n\247MMA\310\301Z<\366\246\023\0161W3\340\357\000\317T\t\301\311+\204\246L7\276\370\320*\245" }
# The below is a salted-SHA512 password hash in hex.
let (:sha512_hash) { 'dd067bfc346740ff7a84d20dda7411d80a03a64b93ee1c2150b1c5741de6ea7086036ea74d4d41c8c15a3cf6a6130e315733e0ef00cf5409c1c92b84a64c37bef8d02aa5' }
let :plist_path do
'/var/db/dslocal/nodes/Default/users/jeff.plist'
end
let :ds_provider do
Puppet::Provider::NameService::DirectoryService
end
let :shadow_hash_data do
{'ShadowHashData' => [StringIO.new(binary_plist)]}
end
subject do
Puppet::Provider::NameService::DirectoryService
end
it 'should execute convert_binary_to_xml once when getting the password' do
subject.expects(:convert_binary_to_xml).returns({'SALTED-SHA512' => StringIO.new(pw_string)})
Puppet::FileSystem.expects(:exist?).with(plist_path).once.returns(true)
Plist.expects(:parse_xml).returns(shadow_hash_data)
# On Mac OS X 10.7 we first need to convert to xml when reading the password
subject.expects(:plutil).with('-convert', 'xml1', '-o', '/dev/stdout', plist_path)
subject.get_password('uid', 'jeff')
end
it 'should fail if a salted-SHA512 password hash is not passed in' do
expect {
subject.set_password('jeff', 'uid', 'badpassword')
}.to raise_error(RuntimeError, /OS X 10.7 requires a Salted SHA512 hash password of 136 characters./)
end
it 'should convert xml-to-binary and binary-to-xml when setting the pw on >= 10.7' do
subject.expects(:convert_binary_to_xml).returns({'SALTED-SHA512' => StringIO.new(pw_string)})
subject.expects(:convert_xml_to_binary).returns(binary_plist)
Puppet::FileSystem.expects(:exist?).with(plist_path).once.returns(true)
Plist.expects(:parse_xml).returns(shadow_hash_data)
# On Mac OS X 10.7 we first need to convert to xml
subject.expects(:plutil).with('-convert', 'xml1', '-o', '/dev/stdout', plist_path)
# And again back to a binary plist or DirectoryService will complain
subject.expects(:plutil).with('-convert', 'binary1', plist_path)
Plist::Emit.expects(:save_plist).with(shadow_hash_data, plist_path)
subject.set_password('jeff', 'uid', sha512_hash)
end
it '[#13686] should handle an empty ShadowHashData field in the users plist' do
subject.expects(:convert_xml_to_binary).returns(binary_plist)
Puppet::FileSystem.expects(:exist?).with(plist_path).once.returns(true)
Plist.expects(:parse_xml).returns({'ShadowHashData' => nil})
subject.expects(:plutil).with('-convert', 'xml1', '-o', '/dev/stdout', plist_path)
subject.expects(:plutil).with('-convert', 'binary1', plist_path)
Plist::Emit.expects(:save_plist)
subject.set_password('jeff', 'uid', sha512_hash)
end
end
describe '(#4855) directoryservice group resource failure' do
let :provider_class do
Puppet::Type.type(:group).provider(:directoryservice)
end
let :group_members do
['root','jeff']
end
let :user_account do
['root']
end
let :stub_resource do
stub('resource')
end
subject do
provider_class.new(stub_resource)
end
before :each do
@resource = stub("resource")
@provider = provider_class.new(@resource)
end
it 'should delete a group member if the user does not exist' do
stub_resource.stubs(:[]).with(:name).returns('fake_group')
stub_resource.stubs(:name).returns('fake_group')
subject.expects(:execute).with([:dseditgroup, '-o', 'edit', '-n', '.',
'-d', 'jeff',
'fake_group']).raises(Puppet::ExecutionFailure,
'it broke')
subject.expects(:execute).with([:dscl, '.', '-delete',
'/Groups/fake_group', 'GroupMembership',
'jeff'])
subject.remove_unwanted_members(group_members, user_account)
end
end
diff --git a/spec/unit/provider/nameservice_spec.rb b/spec/unit/provider/nameservice_spec.rb
index c79f7bdfe..31903fb5e 100755
--- a/spec/unit/provider/nameservice_spec.rb
+++ b/spec/unit/provider/nameservice_spec.rb
@@ -1,304 +1,304 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/provider/nameservice'
require 'etc'
describe Puppet::Provider::NameService do
before :each do
described_class.initvars
described_class.resource_type = faketype
end
# These are values getpwent might give you
let :users do
[
Struct::Passwd.new('root', 'x', 0, 0),
Struct::Passwd.new('foo', 'x', 1000, 2000),
nil
]
end
# These are values getgrent might give you
let :groups do
[
Struct::Group.new('root', 'x', 0, %w{root}),
Struct::Group.new('bin', 'x', 1, %w{root bin daemon}),
nil
]
end
# A fake struct besides Struct::Group and Struct::Passwd
let :fakestruct do
Struct.new(:foo, :bar)
end
# A fake value get<foo>ent might return
let :fakeetcobject do
fakestruct.new('fooval', 'barval')
end
# The provider sometimes relies on @resource for valid properties so let's
# create a fake type with properties that match our fake struct.
let :faketype do
Puppet::Type.newtype(:nameservice_dummytype) do
newparam(:name)
ensurable
newproperty(:foo)
newproperty(:bar)
end
end
let :provider do
described_class.new(:name => 'bob', :foo => 'fooval', :bar => 'barval')
end
let :resource do
resource = faketype.new(:name => 'bob', :ensure => :present)
resource.provider = provider
resource
end
describe "#options" do
it "should add options for a valid property" do
described_class.options :foo, :key1 => 'val1', :key2 => 'val2'
described_class.options :bar, :key3 => 'val3'
- described_class.option(:foo, :key1).should == 'val1'
- described_class.option(:foo, :key2).should == 'val2'
- described_class.option(:bar, :key3).should == 'val3'
+ expect(described_class.option(:foo, :key1)).to eq('val1')
+ expect(described_class.option(:foo, :key2)).to eq('val2')
+ expect(described_class.option(:bar, :key3)).to eq('val3')
end
it "should raise an error for an invalid property" do
expect { described_class.options :baz, :key1 => 'val1' }.to raise_error(
Puppet::Error, 'baz is not a valid attribute for nameservice_dummytype')
end
end
describe "#option" do
it "should return the correct value" do
described_class.options :foo, :key1 => 'val1', :key2 => 'val2'
- described_class.option(:foo, :key2).should == 'val2'
+ expect(described_class.option(:foo, :key2)).to eq('val2')
end
it "should symbolize the name first" do
described_class.options :foo, :key1 => 'val1', :key2 => 'val2'
- described_class.option('foo', :key2).should == 'val2'
+ expect(described_class.option('foo', :key2)).to eq('val2')
end
it "should return nil if no option has been specified earlier" do
- described_class.option(:foo, :key2).should be_nil
+ expect(described_class.option(:foo, :key2)).to be_nil
end
it "should return nil if no option for that property has been specified earlier" do
described_class.options :bar, :key2 => 'val2'
- described_class.option(:foo, :key2).should be_nil
+ expect(described_class.option(:foo, :key2)).to be_nil
end
it "should return nil if no matching key can be found for that property" do
described_class.options :foo, :key3 => 'val2'
- described_class.option(:foo, :key2).should be_nil
+ expect(described_class.option(:foo, :key2)).to be_nil
end
end
describe "#section" do
it "should raise an error if resource_type has not been set" do
described_class.expects(:resource_type).returns nil
expect { described_class.section }.to raise_error Puppet::Error, 'Cannot determine Etc section without a resource type'
end
# the return values are hard coded so I am using types that actually make
# use of the nameservice provider
it "should return pw for users" do
described_class.resource_type = Puppet::Type.type(:user)
- described_class.section.should == 'pw'
+ expect(described_class.section).to eq('pw')
end
it "should return gr for groups" do
described_class.resource_type = Puppet::Type.type(:group)
- described_class.section.should == 'gr'
+ expect(described_class.section).to eq('gr')
end
end
describe "#listbyname" do
it "should return a list of users if resource_type is user" do
described_class.resource_type = Puppet::Type.type(:user)
Etc.expects(:setpwent)
Etc.stubs(:getpwent).returns *users
Etc.expects(:endpwent)
- described_class.listbyname.should == %w{root foo}
+ expect(described_class.listbyname).to eq(%w{root foo})
end
it "should return a list of groups if resource_type is group", :unless => Puppet.features.microsoft_windows? do
described_class.resource_type = Puppet::Type.type(:group)
Etc.expects(:setgrent)
Etc.stubs(:getgrent).returns *groups
Etc.expects(:endgrent)
- described_class.listbyname.should == %w{root bin}
+ expect(described_class.listbyname).to eq(%w{root bin})
end
it "should yield if a block given" do
yield_results = []
described_class.resource_type = Puppet::Type.type(:user)
Etc.expects(:setpwent)
Etc.stubs(:getpwent).returns *users
Etc.expects(:endpwent)
described_class.listbyname {|x| yield_results << x }
- yield_results.should == %w{root foo}
+ expect(yield_results).to eq(%w{root foo})
end
end
describe "instances" do
it "should return a list of objects based on listbyname" do
described_class.expects(:listbyname).multiple_yields 'root', 'foo', 'nobody'
- described_class.instances.map(&:name).should == %w{root foo nobody}
+ expect(described_class.instances.map(&:name)).to eq(%w{root foo nobody})
end
end
describe "validate" do
it "should pass if no check is registered at all" do
expect { described_class.validate(:foo, 300) }.to_not raise_error
expect { described_class.validate('foo', 300) }.to_not raise_error
end
it "should pass if no check for that property is registered" do
described_class.verify(:bar, 'Must be 100') { |val| val == 100 }
expect { described_class.validate(:foo, 300) }.to_not raise_error
expect { described_class.validate('foo', 300) }.to_not raise_error
end
it "should pass if the value is valid" do
described_class.verify(:foo, 'Must be 100') { |val| val == 100 }
expect { described_class.validate(:foo, 100) }.to_not raise_error
expect { described_class.validate('foo', 100) }.to_not raise_error
end
it "should raise an error if the value is invalid" do
described_class.verify(:foo, 'Must be 100') { |val| val == 100 }
expect { described_class.validate(:foo, 200) }.to raise_error(ArgumentError, 'Invalid value 200: Must be 100')
expect { described_class.validate('foo', 200) }.to raise_error(ArgumentError, 'Invalid value 200: Must be 100')
end
end
describe "getinfo" do
before :each do
# with section=foo we'll call Etc.getfoonam instead of getpwnam or getgrnam
described_class.stubs(:section).returns 'foo'
resource # initialize the resource so our provider has a @resource instance variable
end
it "should return a hash if we can retrieve something" do
Etc.expects(:send).with(:getfoonam, 'bob').returns fakeetcobject
provider.expects(:info2hash).with(fakeetcobject).returns(:foo => 'fooval', :bar => 'barval')
- provider.getinfo(true).should == {:foo => 'fooval', :bar => 'barval'}
+ expect(provider.getinfo(true)).to eq({:foo => 'fooval', :bar => 'barval'})
end
it "should return nil if we cannot retrieve anything" do
Etc.expects(:send).with(:getfoonam, 'bob').raises(ArgumentError, "can't find bob")
provider.expects(:info2hash).never
- provider.getinfo(true).should be_nil
+ expect(provider.getinfo(true)).to be_nil
end
end
describe "info2hash" do
it "should return a hash with all properties" do
# we have to have an implementation of posixmethod which has to
# convert a propertyname (e.g. comment) into a fieldname of our
# Struct (e.g. gecos). I do not want to test posixmethod here so
# let's fake an implementation which does not do any translation. We
# expect two method invocations because info2hash calls the method
# twice if the Struct responds to the propertyname (our fake Struct
# provides values for :foo and :bar) TODO: Fix that
provider.expects(:posixmethod).with(:foo).returns(:foo).twice
provider.expects(:posixmethod).with(:bar).returns(:bar).twice
provider.expects(:posixmethod).with(:ensure).returns :ensure
- provider.info2hash(fakeetcobject).should == { :foo => 'fooval', :bar => 'barval' }
+ expect(provider.info2hash(fakeetcobject)).to eq({ :foo => 'fooval', :bar => 'barval' })
end
end
describe "munge" do
it "should return the input value if no munge method has be defined" do
- provider.munge(:foo, 100).should == 100
+ expect(provider.munge(:foo, 100)).to eq(100)
end
it "should return the munged value otherwise" do
described_class.options(:foo, :munge => proc { |x| x*2 })
- provider.munge(:foo, 100).should == 200
+ expect(provider.munge(:foo, 100)).to eq(200)
end
end
describe "unmunge" do
it "should return the input value if no unmunge method has been defined" do
- provider.unmunge(:foo, 200).should == 200
+ expect(provider.unmunge(:foo, 200)).to eq(200)
end
it "should return the unmunged value otherwise" do
described_class.options(:foo, :unmunge => proc { |x| x/2 })
- provider.unmunge(:foo, 200).should == 100
+ expect(provider.unmunge(:foo, 200)).to eq(100)
end
end
describe "exists?" do
it "should return true if we can retrieve anything" do
provider.expects(:getinfo).with(true).returns(:foo => 'fooval', :bar => 'barval')
- provider.should be_exists
+ expect(provider).to be_exists
end
it "should return false if we cannot retrieve anything" do
provider.expects(:getinfo).with(true).returns nil
- provider.should_not be_exists
+ expect(provider).not_to be_exists
end
end
describe "get" do
before(:each) {described_class.resource_type = faketype }
it "should return the correct getinfo value" do
provider.expects(:getinfo).with(false).returns(:foo => 'fooval', :bar => 'barval')
- provider.get(:bar).should == 'barval'
+ expect(provider.get(:bar)).to eq('barval')
end
it "should unmunge the value first" do
described_class.options(:bar, :munge => proc { |x| x*2}, :unmunge => proc {|x| x/2})
provider.expects(:getinfo).with(false).returns(:foo => 200, :bar => 500)
- provider.get(:bar).should == 250
+ expect(provider.get(:bar)).to eq(250)
end
it "should return nil if getinfo cannot retrieve the value" do
provider.expects(:getinfo).with(false).returns(:foo => 'fooval', :bar => 'barval')
- provider.get(:no_such_key).should be_nil
+ expect(provider.get(:no_such_key)).to be_nil
end
end
describe "set" do
before :each do
resource # initialize resource so our provider has a @resource object
described_class.verify(:foo, 'Must be 100') { |val| val == 100 }
end
it "should raise an error on invalid values" do
expect { provider.set(:foo, 200) }.to raise_error(ArgumentError, 'Invalid value 200: Must be 100')
end
it "should execute the modify command on valid values" do
provider.expects(:modifycmd).with(:foo, 100).returns ['/bin/modify', '-f', '100' ]
provider.expects(:execute).with ['/bin/modify', '-f', '100']
provider.set(:foo, 100)
end
it "should munge the value first" do
described_class.options(:foo, :munge => proc { |x| x*2}, :unmunge => proc {|x| x/2})
provider.expects(:modifycmd).with(:foo, 200).returns ['/bin/modify', '-f', '200' ]
provider.expects(:execute).with ['/bin/modify', '-f', '200']
provider.set(:foo, 100)
end
it "should fail if the modify command fails" do
provider.expects(:modifycmd).with(:foo, 100).returns ['/bin/modify', '-f', '100' ]
provider.expects(:execute).with(['/bin/modify', '-f', '100']).raises(Puppet::ExecutionFailure, "Execution of '/bin/modify' returned 1: some_failure")
expect { provider.set(:foo, 100) }.to raise_error Puppet::Error, /Could not set foo/
end
end
end
diff --git a/spec/unit/provider/network_device_spec.rb b/spec/unit/provider/network_device_spec.rb
index 683f7f9cf..495358e4c 100755
--- a/spec/unit/provider/network_device_spec.rb
+++ b/spec/unit/provider/network_device_spec.rb
@@ -1,152 +1,152 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/provider/network_device'
require 'ostruct'
Puppet::Type.type(:vlan).provide :test, :parent => Puppet::Provider::NetworkDevice do
mk_resource_methods
def self.lookup(device, name)
end
def self.device(url)
:device
end
end
provider_class = Puppet::Type.type(:vlan).provider(:test)
describe provider_class do
before do
@resource = stub("resource", :name => "test")
@provider = provider_class.new(@resource)
end
it "should be able to prefetch instances from the device" do
- provider_class.should respond_to(:prefetch)
+ expect(provider_class).to respond_to(:prefetch)
end
it "should have an instances method" do
- provider_class.should respond_to(:instances)
+ expect(provider_class).to respond_to(:instances)
end
describe "when prefetching" do
before do
@resource = stub_everything 'resource'
@resources = {"200" => @resource}
provider_class.stubs(:lookup)
end
it "should lookup an entry for each passed resource" do
provider_class.expects(:lookup).with{ |device,value| value == "200" }.returns nil
provider_class.stubs(:new)
@resource.stubs(:provider=)
provider_class.prefetch(@resources)
end
describe "resources that do not exist" do
it "should create a provider with :ensure => :absent" do
provider_class.stubs(:lookup).returns(nil)
provider_class.expects(:new).with(:device, :ensure => :absent).returns "myprovider"
@resource.expects(:provider=).with("myprovider")
provider_class.prefetch(@resources)
end
end
describe "resources that exist" do
it "should create a provider with the results of the find and ensure at present" do
provider_class.stubs(:lookup).returns({ :name => "200", :description => "myvlan"})
provider_class.expects(:new).with(:device, :name => "200", :description => "myvlan", :ensure => :present).returns "myprovider"
@resource.expects(:provider=).with("myprovider")
provider_class.prefetch(@resources)
end
end
end
describe "when being initialized" do
describe "with a hash" do
before do
@resource_class = mock 'resource_class'
provider_class.stubs(:resource_type).returns @resource_class
@property_class = stub 'property_class', :array_matching => :all, :superclass => Puppet::Property
@resource_class.stubs(:attrclass).with(:one).returns(@property_class)
@resource_class.stubs(:valid_parameter?).returns true
end
it "should store a copy of the hash as its vlan_properties" do
instance = provider_class.new(:device, :one => :two)
- instance.former_properties.should == {:one => :two}
+ expect(instance.former_properties).to eq({:one => :two})
end
end
end
describe "when an instance" do
before do
@instance = provider_class.new(:device)
@property_class = stub 'property_class', :array_matching => :all, :superclass => Puppet::Property
@resource_class = stub 'resource_class', :attrclass => @property_class, :valid_parameter? => true, :validproperties => [:description]
provider_class.stubs(:resource_type).returns @resource_class
end
it "should have a method for creating the instance" do
- @instance.should respond_to(:create)
+ expect(@instance).to respond_to(:create)
end
it "should have a method for removing the instance" do
- @instance.should respond_to(:destroy)
+ expect(@instance).to respond_to(:destroy)
end
it "should indicate when the instance already exists" do
@instance = provider_class.new(:device, :ensure => :present)
- @instance.exists?.should be_true
+ expect(@instance.exists?).to be_truthy
end
it "should indicate when the instance does not exist" do
@instance = provider_class.new(:device, :ensure => :absent)
- @instance.exists?.should be_false
+ expect(@instance.exists?).to be_falsey
end
describe "is being flushed" do
it "should flush properties" do
@instance = provider_class.new(:ensure => :present, :name => "200", :description => "myvlan")
@instance.flush
- @instance.properties.should be_empty
+ expect(@instance.properties).to be_empty
end
end
describe "is being created" do
before do
@rclass = mock 'resource_class'
@rclass.stubs(:validproperties).returns([:description])
@resource = stub_everything 'resource'
@resource.stubs(:class).returns @rclass
@resource.stubs(:should).returns nil
@instance.stubs(:resource).returns @resource
end
it "should set its :ensure value to :present" do
@instance.create
- @instance.properties[:ensure].should == :present
+ expect(@instance.properties[:ensure]).to eq(:present)
end
it "should set all of the other attributes from the resource" do
@resource.expects(:should).with(:description).returns "myvlan"
@instance.create
- @instance.properties[:description].should == "myvlan"
+ expect(@instance.properties[:description]).to eq("myvlan")
end
end
describe "is being destroyed" do
it "should set its :ensure value to :absent" do
@instance.destroy
- @instance.properties[:ensure].should == :absent
+ expect(@instance.properties[:ensure]).to eq(:absent)
end
end
end
end
diff --git a/spec/unit/provider/package/aix_spec.rb b/spec/unit/provider/package/aix_spec.rb
index ceae70cfb..568c55d1b 100755
--- a/spec/unit/provider/package/aix_spec.rb
+++ b/spec/unit/provider/package/aix_spec.rb
@@ -1,107 +1,107 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:package).provider(:aix)
describe provider_class do
before(:each) do
# Create a mock resource
@resource = Puppet::Type.type(:package).new(:name => 'mypackage', :ensure => :installed, :source => 'mysource', :provider => :aix)
@provider = @resource.provider
end
[:install, :uninstall, :latest, :query, :update].each do |method|
it "should have a #{method} method" do
- @provider.should respond_to(method)
+ expect(@provider).to respond_to(method)
end
end
it "should uninstall a package" do
@provider.expects(:installp).with('-gu', 'mypackage')
@provider.class.expects(:pkglist).with(:pkgname => 'mypackage').returns(nil)
@provider.uninstall
end
describe "when installing" do
it "should install a package" do
@resource.stubs(:should).with(:ensure).returns(:installed)
@provider.expects(:installp).with('-acgwXY', '-d', 'mysource', 'mypackage')
@provider.install
end
it "should install a specific package version" do
@resource.stubs(:should).with(:ensure).returns("1.2.3.4")
@provider.expects(:installp).with('-acgwXY', '-d', 'mysource', 'mypackage 1.2.3.4')
@provider.install
end
it "should fail if the specified version is superseded" do
@resource[:ensure] = '1.2.3.3'
@provider.stubs(:installp).returns <<-OUTPUT
+-----------------------------------------------------------------------------+
Pre-installation Verification...
+-----------------------------------------------------------------------------+
Verifying selections...done
Verifying requisites...done
Results...
WARNINGS
--------
Problems described in this section are not likely to be the source of any
immediate or serious failures, but further actions may be necessary or
desired.
Already Installed
-----------------
The number of selected filesets that are either already installed
or effectively installed through superseding filesets is 1. See
the summaries at the end of this installation for details.
NOTE: Base level filesets may be reinstalled using the "Force"
option (-F flag), or they may be removed, using the deinstall or
"Remove Software Products" facility (-u flag), and then reinstalled.
<< End of Warning Section >>
+-----------------------------------------------------------------------------+
BUILDDATE Verification ...
+-----------------------------------------------------------------------------+
Verifying build dates...done
FILESET STATISTICS
------------------
1 Selected to be installed, of which:
1 Already installed (directly or via superseding filesets)
----
0 Total to be installed
Pre-installation Failure/Warning Summary
----------------------------------------
Name Level Pre-installation Failure/Warning
-------------------------------------------------------------------------------
mypackage 1.2.3.3 Already superseded by 1.2.3.4
OUTPUT
expect { @provider.install }.to raise_error(Puppet::Error, "aix package provider is unable to downgrade packages")
end
end
describe "when finding the latest version" do
it "should return the current version when no later version is present" do
@provider.stubs(:latest_info).returns(nil)
@provider.stubs(:properties).returns( { :ensure => "1.2.3.4" } )
- @provider.latest.should == "1.2.3.4"
+ expect(@provider.latest).to eq("1.2.3.4")
end
it "should return the latest version of a package" do
@provider.stubs(:latest_info).returns( { :version => "1.2.3.5" } )
- @provider.latest.should == "1.2.3.5"
+ expect(@provider.latest).to eq("1.2.3.5")
end
end
it "update should install a package" do
@provider.expects(:install).with(false)
@provider.update
end
end
diff --git a/spec/unit/provider/package/apt_spec.rb b/spec/unit/provider/package/apt_spec.rb
index 155f4d608..18f7c84f5 100755
--- a/spec/unit/provider/package/apt_spec.rb
+++ b/spec/unit/provider/package/apt_spec.rb
@@ -1,160 +1,160 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:package).provider(:apt)
describe provider_class do
let(:name) { 'asdf' }
let(:resource) do
Puppet::Type.type(:package).new(
:name => name,
:provider => 'apt'
)
end
let(:provider) do
provider = provider_class.new
provider.resource = resource
provider
end
it "should be versionable" do
- provider_class.should be_versionable
+ expect(provider_class).to be_versionable
end
it "should use :install to update" do
provider.expects(:install)
provider.update
end
it "should use 'apt-get remove' to uninstall" do
provider.expects(:aptget).with("-y", "-q", :remove, name)
provider.uninstall
end
it "should use 'apt-get purge' and 'dpkg purge' to purge" do
provider.expects(:aptget).with("-y", "-q", :remove, "--purge", name)
provider.expects(:dpkg).with("--purge", name)
provider.purge
end
it "should use 'apt-cache policy' to determine the latest version of a package" do
provider.expects(:aptcache).with(:policy, name).returns "#{name}:
Installed: 1:1.0
Candidate: 1:1.1
Version table:
1:1.0
650 http://ftp.osuosl.org testing/main Packages
*** 1:1.1
100 /var/lib/dpkg/status"
- provider.latest.should == "1:1.1"
+ expect(provider.latest).to eq("1:1.1")
end
it "should print and error and return nil if no policy is found" do
provider.expects(:aptcache).with(:policy, name).returns "#{name}:"
provider.expects(:err)
- provider.latest.should be_nil
+ expect(provider.latest).to be_nil
end
it "should be able to preseed" do
- provider.should respond_to(:run_preseed)
+ expect(provider).to respond_to(:run_preseed)
end
it "should preseed with the provided responsefile when preseeding is called for" do
resource[:responsefile] = '/my/file'
Puppet::FileSystem.expects(:exist?).with('/my/file').returns true
provider.expects(:info)
provider.expects(:preseed).with('/my/file')
provider.run_preseed
end
it "should not preseed if no responsefile is provided" do
provider.expects(:info)
provider.expects(:preseed).never
provider.run_preseed
end
describe "when installing" do
it "should preseed if a responsefile is provided" do
resource[:responsefile] = "/my/file"
provider.expects(:run_preseed)
provider.stubs(:aptget)
provider.install
end
it "should check for a cdrom" do
provider.expects(:checkforcdrom)
provider.stubs(:aptget)
provider.install
end
it "should use 'apt-get install' with the package name if no version is asked for" do
resource[:ensure] = :installed
provider.expects(:aptget).with { |*command| command[-1] == name and command[-2] == :install }
provider.install
end
it "should specify the package version if one is asked for" do
resource[:ensure] = '1.0'
provider.expects(:aptget).with { |*command| command[-1] == "#{name}=1.0" }
provider.install
end
it "should use --force-yes if a package version is specified" do
resource[:ensure] = '1.0'
provider.expects(:aptget).with { |*command| command.include?("--force-yes") }
provider.install
end
it "should do a quiet install" do
provider.expects(:aptget).with { |*command| command.include?("-q") }
provider.install
end
it "should default to 'yes' for all questions" do
provider.expects(:aptget).with { |*command| command.include?("-y") }
provider.install
end
it "should keep config files if asked" do
resource[:configfiles] = :keep
provider.expects(:aptget).with { |*command| command.include?("DPkg::Options::=--force-confold") }
provider.install
end
it "should replace config files if asked" do
resource[:configfiles] = :replace
provider.expects(:aptget).with { |*command| command.include?("DPkg::Options::=--force-confnew") }
provider.install
end
it 'should support string install options' do
resource[:install_options] = ['--foo', '--bar']
provider.expects(:aptget).with('-q', '-y', '-o', 'DPkg::Options::=--force-confold', '--foo', '--bar', :install, name)
provider.install
end
it 'should support hash install options' do
resource[:install_options] = ['--foo', { '--bar' => 'baz', '--baz' => 'foo' }]
provider.expects(:aptget).with('-q', '-y', '-o', 'DPkg::Options::=--force-confold', '--foo', '--bar=baz', '--baz=foo', :install, name)
provider.install
end
end
end
diff --git a/spec/unit/provider/package/aptitude_spec.rb b/spec/unit/provider/package/aptitude_spec.rb
index 42dbb827e..bbf8dae9e 100755
--- a/spec/unit/provider/package/aptitude_spec.rb
+++ b/spec/unit/provider/package/aptitude_spec.rb
@@ -1,45 +1,45 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:package).provider(:aptitude) do
let :type do Puppet::Type.type(:package) end
let :pkg do
type.new(:name => 'faff', :provider => :aptitude, :source => '/tmp/faff.deb')
end
- it { should be_versionable }
+ it { is_expected.to be_versionable }
context "when retrieving ensure" do
let(:dpkgquery_path) { '/bin/dpkg-query' }
before do
Puppet::Util.stubs(:which).with('/usr/bin/dpkg-query').returns(dpkgquery_path)
end
{ :absent => "deinstall ok config-files faff 1.2.3-1\n",
"1.2.3-1" => "install ok installed faff 1.2.3-1\n",
}.each do |expect, output|
it "detects #{expect} packages" do
Puppet::Util::Execution.expects(:execute).with(
[dpkgquery_path, '-W', '--showformat', "'${Status} ${Package} ${Version}\\n'", 'faff'],
{:failonfail => true, :combine => true, :custom_environment => {}}
).returns(output)
expect(pkg.property(:ensure).retrieve).to eq(expect)
end
end
end
it "installs when asked" do
pkg.provider.expects(:aptitude).
with('-y', '-o', 'DPkg::Options::=--force-confold', :install, 'faff').
returns(0)
pkg.provider.install
end
it "purges when asked" do
pkg.provider.expects(:aptitude).with('-y', 'purge', 'faff').returns(0)
pkg.provider.purge
end
end
diff --git a/spec/unit/provider/package/aptrpm_spec.rb b/spec/unit/provider/package/aptrpm_spec.rb
index 5ae9ea012..eaff2b7ae 100755
--- a/spec/unit/provider/package/aptrpm_spec.rb
+++ b/spec/unit/provider/package/aptrpm_spec.rb
@@ -1,47 +1,47 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:package).provider(:aptrpm) do
let :type do Puppet::Type.type(:package) end
let :pkg do
type.new(:name => 'faff', :provider => :aptrpm, :source => '/tmp/faff.rpm')
end
- it { should be_versionable }
+ it { is_expected.to be_versionable }
context "when retrieving ensure" do
before(:each) do
Puppet::Util.stubs(:which).with("rpm").returns("/bin/rpm")
pkg.provider.stubs(:which).with("rpm").returns("/bin/rpm")
Puppet::Util::Execution.expects(:execute).with(["/bin/rpm", "--version"], {:combine => true, :custom_environment => {}, :failonfail => true}).returns("4.10.1\n").at_most_once
end
def rpm_args
['-q', 'faff', '--nosignature', '--nodigest', '--qf', "%{NAME} %|EPOCH?{%{EPOCH}}:{0}| %{VERSION} %{RELEASE} %{ARCH}\\n"]
end
def rpm(args = rpm_args)
pkg.provider.expects(:rpm).with(*args)
end
it "should report absent packages" do
rpm.raises(Puppet::ExecutionFailure, "couldn't find rpm")
- pkg.property(:ensure).retrieve.should == :absent
+ expect(pkg.property(:ensure).retrieve).to eq(:absent)
end
it "should report present packages correctly" do
rpm.returns("faff-1.2.3-1 0 1.2.3-1 5 i686\n")
- pkg.property(:ensure).retrieve.should == "1.2.3-1-5"
+ expect(pkg.property(:ensure).retrieve).to eq("1.2.3-1-5")
end
end
it "should try and install when asked" do
pkg.provider.expects(:aptget). with('-q', '-y', 'install', 'faff'). returns(0)
pkg.provider.install
end
it "should try and purge when asked" do
pkg.provider.expects(:aptget).with('-y', '-q', 'remove', '--purge', 'faff').returns(0)
pkg.provider.purge
end
end
diff --git a/spec/unit/provider/package/freebsd_spec.rb b/spec/unit/provider/package/freebsd_spec.rb
index 9116276c7..054445361 100755
--- a/spec/unit/provider/package/freebsd_spec.rb
+++ b/spec/unit/provider/package/freebsd_spec.rb
@@ -1,54 +1,54 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:package).provider(:freebsd)
describe provider_class do
before :each do
# Create a mock resource
@resource = stub 'resource'
# A catch all; no parameters set
@resource.stubs(:[]).returns(nil)
# But set name and source
@resource.stubs(:[]).with(:name).returns "mypackage"
@resource.stubs(:[]).with(:ensure).returns :installed
@provider = provider_class.new
@provider.resource = @resource
end
it "should have an install method" do
@provider = provider_class.new
- @provider.should respond_to(:install)
+ expect(@provider).to respond_to(:install)
end
describe "when installing" do
before :each do
@resource.stubs(:should).with(:ensure).returns(:installed)
end
it "should install a package from a path to a directory" do
# For better or worse, trailing '/' is needed. --daniel 2011-01-26
path = '/path/to/directory/'
@resource.stubs(:[]).with(:source).returns(path)
Puppet::Util.expects(:withenv).once.with({:PKG_PATH => path}).yields
@provider.expects(:pkgadd).once.with("mypackage")
expect { @provider.install }.to_not raise_error
end
%w{http https ftp}.each do |protocol|
it "should install a package via #{protocol}" do
# For better or worse, trailing '/' is needed. --daniel 2011-01-26
path = "#{protocol}://localhost/"
@resource.stubs(:[]).with(:source).returns(path)
Puppet::Util.expects(:withenv).once.with({:PACKAGESITE => path}).yields
@provider.expects(:pkgadd).once.with('-r', "mypackage")
expect { @provider.install }.to_not raise_error
end
end
end
end
diff --git a/spec/unit/provider/package/gem_spec.rb b/spec/unit/provider/package/gem_spec.rb
index 23aa2798d..ecab6c908 100755
--- a/spec/unit/provider/package/gem_spec.rb
+++ b/spec/unit/provider/package/gem_spec.rb
@@ -1,187 +1,187 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:package).provider(:gem)
describe provider_class do
let(:resource) do
Puppet::Type.type(:package).new(
:name => 'myresource',
:ensure => :installed
)
end
let(:provider) do
provider = provider_class.new
provider.resource = resource
provider
end
before :each do
resource.provider = provider
end
describe "when installing" do
it "should use the path to the gem" do
provider_class.stubs(:command).with(:gemcmd).returns "/my/gem"
provider.expects(:execute).with { |args| args[0] == "/my/gem" }.returns ""
provider.install
end
it "should specify that the gem is being installed" do
provider.expects(:execute).with { |args| args[1] == "install" }.returns ""
provider.install
end
it "should specify that documentation should not be included" do
provider.expects(:execute).with { |args| args[2] == "--no-rdoc" }.returns ""
provider.install
end
it "should specify that RI should not be included" do
provider.expects(:execute).with { |args| args[3] == "--no-ri" }.returns ""
provider.install
end
it "should specify the package name" do
provider.expects(:execute).with { |args| args[4] == "myresource" }.returns ""
provider.install
end
it "should not append install_options by default" do
provider.expects(:execute).with { |args| args.length == 5 }.returns ""
provider.install
end
it "should allow setting an install_options parameter" do
resource[:install_options] = [ '--force', {'--bindir' => '/usr/bin' } ]
provider.expects(:execute).with { |args| args[5] == '--force' && args[6] == '--bindir=/usr/bin' }.returns ''
provider.install
end
describe "when a source is specified" do
describe "as a normal file" do
it "should use the file name instead of the gem name" do
resource[:source] = "/my/file"
provider.expects(:execute).with { |args| args[2] == "/my/file" }.returns ""
provider.install
end
end
describe "as a file url" do
it "should use the file name instead of the gem name" do
resource[:source] = "file:///my/file"
provider.expects(:execute).with { |args| args[2] == "/my/file" }.returns ""
provider.install
end
end
describe "as a puppet url" do
it "should fail" do
resource[:source] = "puppet://my/file"
- lambda { provider.install }.should raise_error(Puppet::Error)
+ expect { provider.install }.to raise_error(Puppet::Error)
end
end
describe "as a non-file and non-puppet url" do
it "should treat the source as a gem repository" do
resource[:source] = "http://host/my/file"
provider.expects(:execute).with { |args| args[2..4] == ["--source", "http://host/my/file", "myresource"] }.returns ""
provider.install
end
end
describe "with an invalid uri" do
it "should fail" do
URI.expects(:parse).raises(ArgumentError)
resource[:source] = "http:::::uppet:/:/my/file"
- lambda { provider.install }.should raise_error(Puppet::Error)
+ expect { provider.install }.to raise_error(Puppet::Error)
end
end
end
end
describe "#latest" do
it "should return a single value for 'latest'" do
#gemlist is used for retrieving both local and remote version numbers, and there are cases
# (particularly local) where it makes sense for it to return an array. That doesn't make
# sense for '#latest', though.
provider.class.expects(:gemlist).with({ :justme => 'myresource'}).returns({
:name => 'myresource',
:ensure => ["3.0"],
:provider => :gem,
})
- provider.latest.should == "3.0"
+ expect(provider.latest).to eq("3.0")
end
it "should list from the specified source repository" do
resource[:source] = "http://foo.bar.baz/gems"
provider.class.expects(:gemlist).
with({:justme => 'myresource', :source => "http://foo.bar.baz/gems"}).
returns({
:name => 'myresource',
:ensure => ["3.0"],
:provider => :gem,
})
- provider.latest.should == "3.0"
+ expect(provider.latest).to eq("3.0")
end
end
describe "#instances" do
before do
provider_class.stubs(:command).with(:gemcmd).returns "/my/gem"
end
it "should return an empty array when no gems installed" do
provider_class.expects(:execute).with(%w{/my/gem list --local}).returns("\n")
- provider_class.instances.should == []
+ expect(provider_class.instances).to eq([])
end
it "should return ensure values as an array of installed versions" do
provider_class.expects(:execute).with(%w{/my/gem list --local}).returns <<-HEREDOC.gsub(/ /, '')
systemu (1.2.0)
vagrant (0.8.7, 0.6.9)
HEREDOC
- provider_class.instances.map {|p| p.properties}.should == [
+ expect(provider_class.instances.map {|p| p.properties}).to eq([
{:ensure => ["1.2.0"], :provider => :gem, :name => 'systemu'},
{:ensure => ["0.8.7", "0.6.9"], :provider => :gem, :name => 'vagrant'}
- ]
+ ])
end
it "should ignore platform specifications" do
provider_class.expects(:execute).with(%w{/my/gem list --local}).returns <<-HEREDOC.gsub(/ /, '')
systemu (1.2.0)
nokogiri (1.6.1 ruby java x86-mingw32 x86-mswin32-60, 1.4.4.1 x86-mswin32)
HEREDOC
- provider_class.instances.map {|p| p.properties}.should == [
+ expect(provider_class.instances.map {|p| p.properties}).to eq([
{:ensure => ["1.2.0"], :provider => :gem, :name => 'systemu'},
{:ensure => ["1.6.1", "1.4.4.1"], :provider => :gem, :name => 'nokogiri'}
- ]
+ ])
end
it "should not fail when an unmatched line is returned" do
provider_class.expects(:execute).with(%w{/my/gem list --local}).
returns(File.read(my_fixture('line-with-1.8.5-warning')))
- provider_class.instances.map {|p| p.properties}.
- should == [{:provider=>:gem, :ensure=>["0.3.2"], :name=>"columnize"},
+ expect(provider_class.instances.map {|p| p.properties}).
+ to eq([{:provider=>:gem, :ensure=>["0.3.2"], :name=>"columnize"},
{:provider=>:gem, :ensure=>["1.1.3"], :name=>"diff-lcs"},
{:provider=>:gem, :ensure=>["0.0.1"], :name=>"metaclass"},
{:provider=>:gem, :ensure=>["0.10.5"], :name=>"mocha"},
{:provider=>:gem, :ensure=>["0.8.7"], :name=>"rake"},
{:provider=>:gem, :ensure=>["2.9.0"], :name=>"rspec-core"},
{:provider=>:gem, :ensure=>["2.9.1"], :name=>"rspec-expectations"},
{:provider=>:gem, :ensure=>["2.9.0"], :name=>"rspec-mocks"},
{:provider=>:gem, :ensure=>["0.9.0"], :name=>"rubygems-bundler"},
- {:provider=>:gem, :ensure=>["1.11.3.3"], :name=>"rvm"}]
+ {:provider=>:gem, :ensure=>["1.11.3.3"], :name=>"rvm"}])
end
end
describe "listing gems" do
describe "searching for a single package" do
it "searches for an exact match" do
provider_class.expects(:execute).with(includes('^bundler$')).returns(File.read(my_fixture('gem-list-single-package')))
expected = {:name => 'bundler', :ensure => %w[1.6.2], :provider => :gem}
expect(provider_class.gemlist({:justme => 'bundler'})).to eq(expected)
end
end
end
end
diff --git a/spec/unit/provider/package/hpux_spec.rb b/spec/unit/provider/package/hpux_spec.rb
index 7af226ac5..f135a44a1 100755
--- a/spec/unit/provider/package/hpux_spec.rb
+++ b/spec/unit/provider/package/hpux_spec.rb
@@ -1,51 +1,51 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:package).provider(:hpux)
describe provider_class do
before(:each) do
# Create a mock resource
@resource = stub 'resource'
# A catch all; no parameters set
@resource.stubs(:[]).returns(nil)
# But set name and source
@resource.stubs(:[]).with(:name).returns "mypackage"
@resource.stubs(:[]).with(:source).returns "mysource"
@resource.stubs(:[]).with(:ensure).returns :installed
@provider = provider_class.new
@provider.stubs(:resource).returns @resource
end
it "should have an install method" do
@provider = provider_class.new
- @provider.should respond_to(:install)
+ expect(@provider).to respond_to(:install)
end
it "should have an uninstall method" do
@provider = provider_class.new
- @provider.should respond_to(:uninstall)
+ expect(@provider).to respond_to(:uninstall)
end
it "should have a swlist method" do
@provider = provider_class.new
- @provider.should respond_to(:swlist)
+ expect(@provider).to respond_to(:swlist)
end
describe "when installing" do
it "should use a command-line like 'swinstall -x mount_all_filesystems=false -s SOURCE PACKAGE-NAME'" do
@provider.expects(:swinstall).with('-x', 'mount_all_filesystems=false', '-s', 'mysource', 'mypackage')
@provider.install
end
end
describe "when uninstalling" do
it "should use a command-line like 'swremove -x mount_all_filesystems=false PACKAGE-NAME'" do
@provider.expects(:swremove).with('-x', 'mount_all_filesystems=false', 'mypackage')
@provider.uninstall
end
end
end
diff --git a/spec/unit/provider/package/macports_spec.rb b/spec/unit/provider/package/macports_spec.rb
index 0ae489ba2..d5d95ba9b 100755
--- a/spec/unit/provider/package/macports_spec.rb
+++ b/spec/unit/provider/package/macports_spec.rb
@@ -1,140 +1,140 @@
require 'spec_helper'
provider_class = Puppet::Type.type(:package).provider(:macports)
describe provider_class do
let :resource_name do
"foo"
end
let :resource do
Puppet::Type.type(:package).new(:name => resource_name, :provider => :macports)
end
let :provider do
prov = resource.provider
prov.expects(:execute).never
prov
end
let :current_hash do
{:name => resource_name, :ensure => "1.2.3", :revision => "1", :provider => :macports}
end
describe "provider features" do
subject { provider }
- it { should be_installable }
- it { should be_uninstallable }
- it { should be_upgradeable }
- it { should be_versionable }
+ it { is_expected.to be_installable }
+ it { is_expected.to be_uninstallable }
+ it { is_expected.to be_upgradeable }
+ it { is_expected.to be_versionable }
end
describe "when listing all instances" do
it "should call port -q installed" do
provider_class.expects(:port).with("-q", :installed).returns("")
provider_class.instances
end
it "should create instances from active ports" do
provider_class.expects(:port).returns("foo @1.234.5_2 (active)")
- provider_class.instances.size.should == 1
+ expect(provider_class.instances.size).to eq(1)
end
it "should ignore ports that aren't activated" do
provider_class.expects(:port).returns("foo @1.234.5_2")
- provider_class.instances.size.should == 0
+ expect(provider_class.instances.size).to eq(0)
end
it "should ignore variants" do
- provider_class.parse_installed_query_line("bar @1.0beta2_38_1+x11+java (active)").
- should == {:provider=>:macports, :revision=>"1", :name=>"bar", :ensure=>"1.0beta2_38"}
+ expect(provider_class.parse_installed_query_line("bar @1.0beta2_38_1+x11+java (active)")).
+ to eq({:provider=>:macports, :revision=>"1", :name=>"bar", :ensure=>"1.0beta2_38"})
end
end
describe "when installing" do
it "should not specify a version when ensure is set to latest" do
resource[:ensure] = :latest
provider.expects(:port).with { |flag, method, name, version|
- version.should be_nil
+ expect(version).to be_nil
}
provider.install
end
it "should not specify a version when ensure is set to present" do
resource[:ensure] = :present
provider.expects(:port).with { |flag, method, name, version|
- version.should be_nil
+ expect(version).to be_nil
}
provider.install
end
it "should specify a version when ensure is set to a version" do
resource[:ensure] = "1.2.3"
provider.expects(:port).with { |flag, method, name, version|
- version.should be
+ expect(version).to be
}
provider.install
end
end
describe "when querying for the latest version" do
let :new_info_line do
"1.2.3 2"
end
let :infoargs do
["/opt/local/bin/port", "-q", :info, "--line", "--version", "--revision", resource_name]
end
let(:arguments) do {:failonfail => false, :combine => false} end
before :each do
provider.stubs(:command).with(:port).returns("/opt/local/bin/port")
end
it "should return nil when the package cannot be found" do
resource[:name] = resource_name
provider.expects(:execute).with(infoargs, arguments).returns("")
- provider.latest.should == nil
+ expect(provider.latest).to eq(nil)
end
it "should return the current version if the installed port has the same revision" do
current_hash[:revision] = "2"
provider.expects(:execute).with(infoargs, arguments).returns(new_info_line)
provider.expects(:query).returns(current_hash)
- provider.latest.should == current_hash[:ensure]
+ expect(provider.latest).to eq(current_hash[:ensure])
end
it "should return the new version_revision if the installed port has a lower revision" do
current_hash[:revision] = "1"
provider.expects(:execute).with(infoargs, arguments).returns(new_info_line)
provider.expects(:query).returns(current_hash)
- provider.latest.should == "1.2.3_2"
+ expect(provider.latest).to eq("1.2.3_2")
end
it "should return the newest version if the port is not installed" do
resource[:name] = resource_name
provider.expects(:execute).with(infoargs, arguments).returns(new_info_line)
provider.expects(:execute).with(["/opt/local/bin/port", "-q", :installed, resource[:name]], arguments).returns("")
- provider.latest.should == "1.2.3_2"
+ expect(provider.latest).to eq("1.2.3_2")
end
end
describe "when updating a port" do
it "should execute port install if the port is installed" do
resource[:name] = resource_name
resource[:ensure] = :present
provider.stubs(:query).returns(current_hash)
provider.expects(:port).with("-q", :install, resource_name)
provider.update
end
it "should execute port install if the port is not installed" do
resource[:name] = resource_name
resource[:ensure] = :present
provider.stubs(:query).returns("")
provider.expects(:port).with("-q", :install, resource_name)
provider.update
end
end
end
diff --git a/spec/unit/provider/package/nim_spec.rb b/spec/unit/provider/package/nim_spec.rb
index 95754fcfc..4427e8710 100755
--- a/spec/unit/provider/package/nim_spec.rb
+++ b/spec/unit/provider/package/nim_spec.rb
@@ -1,250 +1,250 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:package).provider(:nim)
describe provider_class do
before(:each) do
# Create a mock resource
@resource = stub 'resource'
# A catch all; no parameters set
@resource.stubs(:[]).returns(nil)
# But set name and source
@resource.stubs(:[]).with(:name).returns "mypackage.foo"
@resource.stubs(:[]).with(:source).returns "mysource"
@resource.stubs(:[]).with(:ensure).returns :installed
@provider = provider_class.new
@provider.resource = @resource
end
it "should have an install method" do
@provider = provider_class.new
- @provider.should respond_to(:install)
+ expect(@provider).to respond_to(:install)
end
let(:bff_showres_output) {
<<END
mypackage.foo ALL @@I:mypackage.foo _all_filesets
@ 1.2.3.1 MyPackage Runtime Environment @@I:mypackage.foo 1.2.3.1
+ 1.2.3.4 MyPackage Runtime Environment @@I:mypackage.foo 1.2.3.4
+ 1.2.3.8 MyPackage Runtime Environment @@I:mypackage.foo 1.2.3.8
END
}
let(:rpm_showres_output) {
<<END
mypackage.foo ALL @@R:mypackage.foo _all_filesets
@@R:mypackage.foo-1.2.3-1 1.2.3-1
@@R:mypackage.foo-1.2.3-4 1.2.3-4
@@R:mypackage.foo-1.2.3-8 1.2.3-8
END
}
context "when installing" do
it "should install a package" do
@resource.stubs(:should).with(:ensure).returns(:installed)
Puppet::Util.expects(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo'").returns(bff_showres_output)
@provider.expects(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo 1.2.3.8")
@provider.install
end
context "when installing versioned packages" do
it "should fail if the package is not available on the lpp source" do
nimclient_showres_output = ""
@resource.stubs(:should).with(:ensure).returns("1.2.3.4")
Puppet::Util.expects(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\.4'").returns(nimclient_showres_output)
expect {
@provider.install
}.to raise_error(Puppet::Error, "Unable to find package 'mypackage.foo' with version '1.2.3.4' on lpp_source 'mysource'")
end
it "should succeed if a BFF/installp package is available on the lpp source" do
nimclient_sequence = sequence('nimclient')
@resource.stubs(:should).with(:ensure).returns("1.2.3.4")
Puppet::Util.expects(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\.4'").returns(bff_showres_output).in_sequence(nimclient_sequence)
@provider.expects(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo 1.2.3.4").in_sequence(nimclient_sequence)
@provider.install
end
it "should fail if the specified version of a BFF package is superseded" do
nimclient_sequence = sequence('nimclient')
install_output = <<OUTPUT
+-----------------------------------------------------------------------------+
Pre-installation Verification...
+-----------------------------------------------------------------------------+
Verifying selections...done
Verifying requisites...done
Results...
WARNINGS
--------
Problems described in this section are not likely to be the source of any
immediate or serious failures, but further actions may be necessary or
desired.
Already Installed
-----------------
The number of selected filesets that are either already installed
or effectively installed through superseding filesets is 1. See
the summaries at the end of this installation for details.
NOTE: Base level filesets may be reinstalled using the "Force"
option (-F flag), or they may be removed, using the deinstall or
"Remove Software Products" facility (-u flag), and then reinstalled.
<< End of Warning Section >>
+-----------------------------------------------------------------------------+
BUILDDATE Verification ...
+-----------------------------------------------------------------------------+
Verifying build dates...done
FILESET STATISTICS
------------------
1 Selected to be installed, of which:
1 Already installed (directly or via superseding filesets)
----
0 Total to be installed
Pre-installation Failure/Warning Summary
----------------------------------------
Name Level Pre-installation Failure/Warning
-------------------------------------------------------------------------------
mypackage.foo 1.2.3.1 Already superseded by 1.2.3.4
OUTPUT
@resource.stubs(:should).with(:ensure).returns("1.2.3.1")
Puppet::Util.expects(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\.1'").returns(bff_showres_output).in_sequence(nimclient_sequence)
@provider.expects(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo 1.2.3.1").in_sequence(nimclient_sequence).returns(install_output)
expect { @provider.install }.to raise_error(Puppet::Error, "NIM package provider is unable to downgrade packages")
end
it "should succeed if an RPM package is available on the lpp source" do
nimclient_sequence = sequence('nimclient')
@resource.stubs(:should).with(:ensure).returns("1.2.3-4")
Puppet::Util.expects(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\-4'").returns(rpm_showres_output).in_sequence(nimclient_sequence)
@provider.expects(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo-1.2.3-4").in_sequence(nimclient_sequence)
@provider.install
end
end
it "should fail if the specified version of a RPM package is superseded" do
nimclient_sequence = sequence('nimclient')
install_output = <<OUTPUT
Validating RPM package selections ...
Please wait...
+-----------------------------------------------------------------------------+
RPM Error Summary:
+-----------------------------------------------------------------------------+
The following RPM packages were requested for installation
but they are already installed or superseded by a package installed
at a higher level:
mypackage.foo-1.2.3-1 is superseded by mypackage.foo-1.2.3-4
OUTPUT
@resource.stubs(:should).with(:ensure).returns("1.2.3-1")
Puppet::Util.expects(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\-1'").returns(rpm_showres_output).in_sequence(nimclient_sequence)
@provider.expects(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo-1.2.3-1").in_sequence(nimclient_sequence).returns(install_output)
expect { @provider.install }.to raise_error(Puppet::Error, "NIM package provider is unable to downgrade packages")
end
end
context "when uninstalling" do
it "should call installp to uninstall a bff package" do
@provider.expects(:lslpp).with("-qLc", "mypackage.foo").returns("#bos.atm:bos.atm.atmle:7.1.2.0: : :C: :ATM LAN Emulation Client Support : : : : : : :0:0:/:1241")
@provider.expects(:installp).with("-gu", "mypackage.foo")
@provider.class.expects(:pkglist).with(:pkgname => 'mypackage.foo').returns(nil)
@provider.uninstall
end
it "should call rpm to uninstall an rpm package" do
@provider.expects(:lslpp).with("-qLc", "mypackage.foo").returns("cdrecord:cdrecord-1.9-6:1.9-6: : :C:R:A command line CD/DVD recording program.: :/bin/rpm -e cdrecord: : : : :0: :/opt/freeware:Wed Jun 29 09:41:32 PDT 2005")
@provider.expects(:rpm).with("-e", "mypackage.foo")
@provider.class.expects(:pkglist).with(:pkgname => 'mypackage.foo').returns(nil)
@provider.uninstall
end
end
context "when parsing nimclient showres output" do
describe "#parse_showres_output" do
it "should be able to parse installp/BFF package listings" do
packages = subject.send(:parse_showres_output, bff_showres_output)
- Set.new(packages.keys).should == Set.new(['mypackage.foo'])
+ expect(Set.new(packages.keys)).to eq(Set.new(['mypackage.foo']))
versions = packages['mypackage.foo']
['1.2.3.1', '1.2.3.4', '1.2.3.8'].each do |version|
- versions.has_key?(version).should == true
- versions[version].should == :installp
+ expect(versions.has_key?(version)).to eq(true)
+ expect(versions[version]).to eq(:installp)
end
end
it "should be able to parse RPM package listings" do
packages = subject.send(:parse_showres_output, rpm_showres_output)
- Set.new(packages.keys).should == Set.new(['mypackage.foo'])
+ expect(Set.new(packages.keys)).to eq(Set.new(['mypackage.foo']))
versions = packages['mypackage.foo']
['1.2.3-1', '1.2.3-4', '1.2.3-8'].each do |version|
- versions.has_key?(version).should == true
- versions[version].should == :rpm
+ expect(versions.has_key?(version)).to eq(true)
+ expect(versions[version]).to eq(:rpm)
end
end
end
describe "#determine_latest_version" do
context "when there are multiple versions" do
it "should return the latest version" do
- subject.send(:determine_latest_version, rpm_showres_output, 'mypackage.foo').should == [:rpm, '1.2.3-8']
+ expect(subject.send(:determine_latest_version, rpm_showres_output, 'mypackage.foo')).to eq([:rpm, '1.2.3-8'])
end
end
context "when there is only one version" do
it "should return the type specifier and `nil` for the version number" do
nimclient_showres_output = <<END
mypackage.foo ALL @@R:mypackage.foo _all_filesets
@@R:mypackage.foo-1.2.3-4 1.2.3-4
END
- subject.send(:determine_latest_version, nimclient_showres_output, 'mypackage.foo').should == [:rpm, nil]
+ expect(subject.send(:determine_latest_version, nimclient_showres_output, 'mypackage.foo')).to eq([:rpm, nil])
end
end
end
describe "#determine_package_type" do
it "should return :rpm for rpm packages" do
- subject.send(:determine_package_type, rpm_showres_output, 'mypackage.foo', '1.2.3-4').should == :rpm
+ expect(subject.send(:determine_package_type, rpm_showres_output, 'mypackage.foo', '1.2.3-4')).to eq(:rpm)
end
it "should return :installp for installp/bff packages" do
- subject.send(:determine_package_type, bff_showres_output, 'mypackage.foo', '1.2.3.4').should == :installp
+ expect(subject.send(:determine_package_type, bff_showres_output, 'mypackage.foo', '1.2.3.4')).to eq(:installp)
end
end
end
end
diff --git a/spec/unit/provider/package/openbsd_spec.rb b/spec/unit/provider/package/openbsd_spec.rb
index 7b16c289b..e2a91c335 100755
--- a/spec/unit/provider/package/openbsd_spec.rb
+++ b/spec/unit/provider/package/openbsd_spec.rb
@@ -1,403 +1,404 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'stringio'
provider_class = Puppet::Type.type(:package).provider(:openbsd)
describe provider_class do
let(:package) { Puppet::Type.type(:package).new(:name => 'bash', :provider => 'openbsd') }
let(:provider) { provider_class.new(package) }
def expect_read_from_pkgconf(lines)
pkgconf = stub(:readlines => lines)
Puppet::FileSystem.expects(:exist?).with('/etc/pkg.conf').returns(true)
File.expects(:open).with('/etc/pkg.conf', 'rb').returns(pkgconf)
end
def expect_pkgadd_with_source(source)
provider.expects(:pkgadd).with do |fullname|
- ENV.should_not be_key('PKG_PATH')
- fullname.should == [source]
+ expect(ENV).not_to be_key('PKG_PATH')
+ expect(fullname).to eq([source])
end
end
def expect_pkgadd_with_env_and_name(source, &block)
- ENV.should_not be_key('PKG_PATH')
+ expect(ENV).not_to be_key('PKG_PATH')
provider.expects(:pkgadd).with do |fullname|
- ENV.should be_key('PKG_PATH')
- ENV['PKG_PATH'].should == source
+ expect(ENV).to be_key('PKG_PATH')
+ expect(ENV['PKG_PATH']).to eq(source)
- fullname.should == [provider.resource[:name]]
+ expect(fullname).to eq([provider.resource[:name]])
end
provider.expects(:execpipe).with(['/bin/pkg_info', '-I', provider.resource[:name]]).yields('')
yield
- ENV.should_not be_key('PKG_PATH')
+ expect(ENV).not_to be_key('PKG_PATH')
end
describe 'provider features' do
- it { should be_installable }
- it { should be_install_options }
- it { should be_uninstallable }
- it { should be_uninstall_options }
- it { should be_upgradeable }
- it { should be_versionable }
+ it { is_expected.to be_installable }
+ it { is_expected.to be_install_options }
+ it { is_expected.to be_uninstallable }
+ it { is_expected.to be_uninstall_options }
+ it { is_expected.to be_upgradeable }
+ it { is_expected.to be_versionable }
end
before :each do
# Stub some provider methods to avoid needing the actual software
# installed, so we can test on whatever platform we want.
provider_class.stubs(:command).with(:pkginfo).returns('/bin/pkg_info')
provider_class.stubs(:command).with(:pkgadd).returns('/bin/pkg_add')
provider_class.stubs(:command).with(:pkgdelete).returns('/bin/pkg_delete')
end
context "#instances" do
it "should return nil if execution failed" do
provider_class.expects(:execpipe).raises(Puppet::ExecutionFailure, 'wawawa')
- provider_class.instances.should be_nil
+ expect(provider_class.instances).to be_nil
end
it "should return the empty set if no packages are listed" do
provider_class.expects(:execpipe).with(%w{/bin/pkg_info -a}).yields(StringIO.new(''))
- provider_class.instances.should be_empty
+ expect(provider_class.instances).to be_empty
end
it "should return all packages when invoked" do
fixture = File.read(my_fixture('pkginfo.list'))
provider_class.expects(:execpipe).with(%w{/bin/pkg_info -a}).yields(fixture)
- provider_class.instances.map(&:name).sort.should ==
+ expect(provider_class.instances.map(&:name).sort).to eq(
%w{bash bzip2 expat gettext libiconv lzo openvpn python vim wget}.sort
+ )
end
it "should return all flavors if set" do
fixture = File.read(my_fixture('pkginfo_flavors.list'))
provider_class.expects(:execpipe).with(%w{/bin/pkg_info -a}).yields(fixture)
instances = provider_class.instances.map {|p| {:name => p.get(:name),
:ensure => p.get(:ensure), :flavor => p.get(:flavor)}}
- instances.size.should == 2
- instances[0].should == {:name => 'bash', :ensure => '3.1.17', :flavor => 'static'}
- instances[1].should == {:name => 'vim', :ensure => '7.0.42', :flavor => 'no_x11'}
+ expect(instances.size).to eq(2)
+ expect(instances[0]).to eq({:name => 'bash', :ensure => '3.1.17', :flavor => 'static'})
+ expect(instances[1]).to eq({:name => 'vim', :ensure => '7.0.42', :flavor => 'no_x11'})
end
end
context "#install" do
it "should fail if the resource doesn't have a source" do
Puppet::FileSystem.expects(:exist?).with('/etc/pkg.conf').returns(false)
expect {
provider.install
}.to raise_error(Puppet::Error, /must specify a package source/)
end
it "should fail if /etc/pkg.conf exists, but is not readable" do
Puppet::FileSystem.expects(:exist?).with('/etc/pkg.conf').returns(true)
File.expects(:open).with('/etc/pkg.conf', 'rb').raises(Errno::EACCES)
expect {
provider.install
}.to raise_error(Errno::EACCES, /Permission denied/)
end
it "should fail if /etc/pkg.conf exists, but there is no installpath" do
expect_read_from_pkgconf([])
expect {
provider.install
}.to raise_error(Puppet::Error, /No valid installpath found in \/etc\/pkg\.conf and no source was set/)
end
it "should install correctly when given a directory-unlike source" do
source = '/whatever.tgz'
provider.resource[:source] = source
expect_pkgadd_with_source(source)
provider.install
end
it "should install correctly when given a directory-like source" do
source = '/whatever/'
provider.resource[:source] = source
expect_pkgadd_with_env_and_name(source) do
provider.install
end
end
it "should install correctly when given a CDROM installpath" do
dir = '/mnt/cdrom/5.2/packages/amd64/'
expect_read_from_pkgconf(["installpath = #{dir}"])
expect_pkgadd_with_env_and_name(dir) do
provider.install
end
end
it "should install correctly when given a ftp mirror" do
url = 'ftp://your.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/'
expect_read_from_pkgconf(["installpath = #{url}"])
expect_pkgadd_with_env_and_name(url) do
provider.install
end
end
it "should set the resource's source parameter" do
url = 'ftp://your.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/'
expect_read_from_pkgconf(["installpath = #{url}"])
expect_pkgadd_with_env_and_name(url) do
provider.install
end
- provider.resource[:source].should == url
+ expect(provider.resource[:source]).to eq(url)
end
it "should strip leading whitespace in installpath" do
dir = '/one/'
lines = ["# Notice the extra spaces after the ='s\n",
"installpath = #{dir}\n",
"# And notice how each line ends with a newline\n"]
expect_read_from_pkgconf(lines)
expect_pkgadd_with_env_and_name(dir) do
provider.install
end
end
it "should not require spaces around the equals" do
dir = '/one/'
lines = ["installpath=#{dir}"]
expect_read_from_pkgconf(lines)
expect_pkgadd_with_env_and_name(dir) do
provider.install
end
end
it "should be case-insensitive" do
dir = '/one/'
lines = ["INSTALLPATH = #{dir}"]
expect_read_from_pkgconf(lines)
expect_pkgadd_with_env_and_name(dir) do
provider.install
end
end
it "should ignore unknown keywords" do
dir = '/one/'
lines = ["foo = bar\n",
"installpath = #{dir}\n"]
expect_read_from_pkgconf(lines)
expect_pkgadd_with_env_and_name(dir) do
provider.install
end
end
it "should preserve trailing spaces" do
dir = '/one/ '
lines = ["installpath = #{dir}"]
expect_read_from_pkgconf(lines)
expect_pkgadd_with_source(dir)
provider.install
end
it "should append installpath" do
urls = ["ftp://your.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/",
"http://another.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/"]
lines = ["installpath = #{urls[0]}\n",
"installpath += #{urls[1]}\n"]
expect_read_from_pkgconf(lines)
expect_pkgadd_with_env_and_name(urls.join(":")) do
provider.install
end
end
it "should handle append on first installpath" do
url = "ftp://your.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/"
lines = ["installpath += #{url}\n"]
expect_read_from_pkgconf(lines)
expect_pkgadd_with_env_and_name(url) do
provider.install
end
end
%w{ installpath installpath= installpath+=}.each do |line|
it "should reject '#{line}'" do
expect_read_from_pkgconf([line])
expect {
provider.install
}.to raise_error(Puppet::Error, /No valid installpath found in \/etc\/pkg\.conf and no source was set/)
end
end
it 'should use install_options as Array' do
provider.resource[:source] = '/tma1/'
provider.resource[:install_options] = ['-r', '-z']
provider.expects(:pkgadd).with(['-r', '-z', 'bash'])
provider.install
end
end
context "#latest" do
before do
provider.resource[:source] = '/tmp/tcsh.tgz'
provider.resource[:name] = 'tcsh'
provider.stubs(:pkginfo).with('tcsh')
end
it "should return the ensure value if the package is already installed" do
provider.stubs(:properties).returns({:ensure => '4.2.45'})
provider.stubs(:pkginfo).with('-Q', 'tcsh')
- provider.latest.should == '4.2.45'
+ expect(provider.latest).to eq('4.2.45')
end
it "should recognize a new version" do
pkginfo_query = 'tcsh-6.18.01p1'
provider.stubs(:pkginfo).with('-Q', 'tcsh').returns(pkginfo_query)
- provider.latest.should == '6.18.01p1'
+ expect(provider.latest).to eq('6.18.01p1')
end
it "should recognize a newer version" do
provider.stubs(:properties).returns({:ensure => '1.6.8'})
pkginfo_query = 'tcsh-1.6.10'
provider.stubs(:pkginfo).with('-Q', 'tcsh').returns(pkginfo_query)
- provider.latest.should == '1.6.10'
+ expect(provider.latest).to eq('1.6.10')
end
it "should recognize a package that is already the newest" do
pkginfo_query = 'tcsh-6.18.01p0 (installed)'
provider.stubs(:pkginfo).with('-Q', 'tcsh').returns(pkginfo_query)
- provider.latest.should == '6.18.01p0'
+ expect(provider.latest).to eq('6.18.01p0')
end
end
context "#get_full_name" do
it "should return the full unversioned package name when updating with a flavor" do
provider.resource[:ensure] = 'latest'
provider.resource[:flavor] = 'static'
- provider.get_full_name.should == 'bash--static'
+ expect(provider.get_full_name).to eq('bash--static')
end
it "should return the full unversioned package name when updating without a flavor" do
provider.resource[:name] = 'puppet'
provider.resource[:ensure] = 'latest'
- provider.get_full_name.should == 'puppet'
+ expect(provider.get_full_name).to eq('puppet')
end
it "should use the ensure parameter if it is numeric" do
provider.resource[:name] = 'zsh'
provider.resource[:ensure] = '1.0'
- provider.get_full_name.should == 'zsh-1.0'
+ expect(provider.get_full_name).to eq('zsh-1.0')
end
it "should lookup the correct version" do
output = 'bash-3.1.17 GNU Bourne Again Shell'
provider.expects(:execpipe).with(%w{/bin/pkg_info -I bash}).yields(output)
- provider.get_full_name.should == 'bash-3.1.17'
+ expect(provider.get_full_name).to eq('bash-3.1.17')
end
it "should lookup the correction version with flavors" do
provider.resource[:name] = 'fossil'
provider.resource[:flavor] = 'static'
output = 'fossil-1.29v0-static simple distributed software configuration management'
provider.expects(:execpipe).with(%w{/bin/pkg_info -I fossil}).yields(output)
- provider.get_full_name.should == 'fossil-1.29v0-static'
+ expect(provider.get_full_name).to eq('fossil-1.29v0-static')
end
end
context "#get_version" do
it "should return nil if execution fails" do
provider.expects(:execpipe).raises(Puppet::ExecutionFailure, 'wawawa')
- provider.get_version.should be_nil
+ expect(provider.get_version).to be_nil
end
it "should return the package version if in the output" do
output = 'bash-3.1.17 GNU Bourne Again Shell'
provider.expects(:execpipe).with(%w{/bin/pkg_info -I bash}).yields(output)
- provider.get_version.should == '3.1.17'
+ expect(provider.get_version).to eq('3.1.17')
end
it "should return the empty string if the package is not present" do
provider.resource[:name] = 'zsh'
provider.expects(:execpipe).with(%w{/bin/pkg_info -I zsh}).yields(StringIO.new(''))
- provider.get_version.should == ''
+ expect(provider.get_version).to eq('')
end
end
context "#query" do
it "should return the installed version if present" do
fixture = File.read(my_fixture('pkginfo.detail'))
provider.expects(:pkginfo).with('bash').returns(fixture)
- provider.query.should == { :ensure => '3.1.17' }
+ expect(provider.query).to eq({ :ensure => '3.1.17' })
end
it "should return nothing if not present" do
provider.resource[:name] = 'zsh'
provider.expects(:pkginfo).with('zsh').returns('')
- provider.query.should be_nil
+ expect(provider.query).to be_nil
end
end
context "#install_options" do
it "should return nill by default" do
- provider.install_options.should be_nil
+ expect(provider.install_options).to be_nil
end
it "should return install_options when set" do
provider.resource[:install_options] = ['-n']
- provider.resource[:install_options].should == ['-n']
+ expect(provider.resource[:install_options]).to eq(['-n'])
end
it "should return multiple install_options when set" do
provider.resource[:install_options] = ['-L', '/opt/puppet']
- provider.resource[:install_options].should == ['-L', '/opt/puppet']
+ expect(provider.resource[:install_options]).to eq(['-L', '/opt/puppet'])
end
it 'should return install_options when set as hash' do
provider.resource[:install_options] = { '-Darch' => 'vax' }
- provider.install_options.should == ['-Darch=vax']
+ expect(provider.install_options).to eq(['-Darch=vax'])
end
end
context "#uninstall_options" do
it "should return nill by default" do
- provider.uninstall_options.should be_nil
+ expect(provider.uninstall_options).to be_nil
end
it "should return uninstall_options when set" do
provider.resource[:uninstall_options] = ['-n']
- provider.resource[:uninstall_options].should == ['-n']
+ expect(provider.resource[:uninstall_options]).to eq(['-n'])
end
it "should return multiple uninstall_options when set" do
provider.resource[:uninstall_options] = ['-q', '-c']
- provider.resource[:uninstall_options].should == ['-q', '-c']
+ expect(provider.resource[:uninstall_options]).to eq(['-q', '-c'])
end
it 'should return uninstall_options when set as hash' do
provider.resource[:uninstall_options] = { '-Dbaddepend' => '1' }
- provider.uninstall_options.should == ['-Dbaddepend=1']
+ expect(provider.uninstall_options).to eq(['-Dbaddepend=1'])
end
end
context "#uninstall" do
describe 'when uninstalling' do
it 'should use erase to purge' do
provider.expects(:pkgdelete).with('-c', '-q', 'bash')
provider.purge
end
end
describe 'with uninstall_options' do
it 'should use uninstall_options as Array' do
provider.resource[:uninstall_options] = ['-q', '-c']
provider.expects(:pkgdelete).with(['-q', '-c'], 'bash')
provider.uninstall
end
end
end
end
diff --git a/spec/unit/provider/package/opkg_spec.rb b/spec/unit/provider/package/opkg_spec.rb
index f017a2b97..7eb4bcd46 100755
--- a/spec/unit/provider/package/opkg_spec.rb
+++ b/spec/unit/provider/package/opkg_spec.rb
@@ -1,180 +1,183 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:package).provider(:opkg) do
let(:resource) do
Puppet::Type.type(:package).new(:name => 'package')
end
let(:provider) { described_class.new(resource) }
before do
Puppet::Util::Execution.stubs(:execute).never
Puppet::Util.stubs(:which).with("opkg").returns("/bin/opkg")
provider.stubs(:package_lists).returns ['.', '..', 'packages']
end
describe "when installing" do
before do
provider.stubs(:query).returns({ :ensure => '1.0' })
end
context "when the package list is absent" do
before do
provider.stubs(:package_lists).returns ['.', '..'] #empty, no package list
end
it "fetches the package list when installing" do
provider.expects(:opkg).with('update')
provider.expects(:opkg).with("--force-overwrite", "install", resource[:name])
provider.install
end
end
context "when the package list is present" do
before do
provider.stubs(:package_lists).returns ['.', '..', 'lists'] # With a pre-downloaded package list
end
it "fetches the package list when installing" do
provider.expects(:opkg).with('update').never
provider.expects(:opkg).with("--force-overwrite", "install", resource[:name])
provider.install
end
end
it "should call opkg install" do
Puppet::Util::Execution.expects(:execute).with(["/bin/opkg", "--force-overwrite", "install", resource[:name]], {:failonfail => true, :combine => true, :custom_environment => {}})
provider.install
end
context "when :source is specified" do
context "works on valid urls" do
%w{
/some/package/file
http://some.package.in/the/air
ftp://some.package.in/the/air
}.each do |source|
it "should install #{source} directly" do
resource[:source] = source
Puppet::Util::Execution.expects(:execute).with(["/bin/opkg", "--force-overwrite", "install", resource[:source]], {:failonfail => true, :combine => true, :custom_environment => {}})
provider.install
end
end
end
context "as a file:// URL" do
before do
@package_file = "file:///some/package/file"
@actual_file_path = "/some/package/file"
resource[:source] = @package_file
end
it "should install from the path segment of the URL" do
Puppet::Util::Execution.expects(:execute).returns("")
provider.install
end
end
context "with invalid URL for opkg" do
before do
# Emulate the `opkg` command returning a non-zero exit value
Puppet::Util::Execution.stubs(:execute).raises Puppet::ExecutionFailure, 'oops'
end
context "puppet://server/whatever" do
before do
resource[:source] = "puppet://server/whatever"
end
it "should fail" do
expect { provider.install }.to raise_error Puppet::ExecutionFailure
end
end
context "as a malformed URL" do
before do
resource[:source] = "blah://"
end
it "should fail" do
expect { provider.install }.to raise_error Puppet::ExecutionFailure
end
end
end
end # end when source is specified
end # end when installing
describe "when updating" do
it "should call install" do
provider.expects(:install).returns("install return value")
- provider.update.should == "install return value"
+ expect(provider.update).to eq("install return value")
end
end
describe "when uninstalling" do
it "should run opkg remove bla" do
Puppet::Util::Execution.expects(:execute).with(["/bin/opkg", "remove", resource[:name]], {:failonfail => true, :combine => true, :custom_environment => {}})
provider.uninstall
end
end
describe "when querying" do
describe "self.instances" do
let (:packages) do
<<-OPKG_OUTPUT
dropbear - 2011.54-2
kernel - 3.3.8-1-ba5cdb2523b4fc7722698b4a7ece6702
uhttpd - 2012-10-30-e57bf6d8bfa465a50eea2c30269acdfe751a46fd
OPKG_OUTPUT
end
it "returns an array of packages" do
Puppet::Util.stubs(:which).with("opkg").returns("/bin/opkg")
described_class.stubs(:which).with("opkg").returns("/bin/opkg")
described_class.expects(:execpipe).with("/bin/opkg list-installed").yields(packages)
installed_packages = described_class.instances
- installed_packages.length.should == 3
+ expect(installed_packages.length).to eq(3)
- installed_packages[0].properties.should ==
+ expect(installed_packages[0].properties).to eq(
{
:provider => :opkg,
:name => "dropbear",
:ensure => "2011.54-2"
}
- installed_packages[1].properties.should ==
+ )
+ expect(installed_packages[1].properties).to eq(
{
:provider => :opkg,
:name => "kernel",
:ensure => "3.3.8-1-ba5cdb2523b4fc7722698b4a7ece6702"
}
- installed_packages[2].properties.should ==
+ )
+ expect(installed_packages[2].properties).to eq(
{
:provider => :opkg,
:name => "uhttpd",
:ensure => "2012-10-30-e57bf6d8bfa465a50eea2c30269acdfe751a46fd"
}
+ )
end
end
it "should return a nil if the package isn't found" do
Puppet::Util::Execution.expects(:execute).returns("")
- provider.query.should be_nil
+ expect(provider.query).to be_nil
end
it "should return a hash indicating that the package is missing on error" do
Puppet::Util::Execution.expects(:execute).raises(Puppet::ExecutionFailure.new("ERROR!"))
- provider.query.should == {
+ expect(provider.query).to eq({
:ensure => :purged,
:status => 'missing',
:name => resource[:name],
:error => 'ok',
- }
+ })
end
end #end when querying
end # end describe provider
diff --git a/spec/unit/provider/package/pacman_spec.rb b/spec/unit/provider/package/pacman_spec.rb
index aca7c5d64..d8ceaa50a 100755
--- a/spec/unit/provider/package/pacman_spec.rb
+++ b/spec/unit/provider/package/pacman_spec.rb
@@ -1,314 +1,314 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'stringio'
describe Puppet::Type.type(:package).provider(:pacman) do
let(:no_extra_options) { { :failonfail => true, :combine => true, :custom_environment => {} } }
let(:executor) { Puppet::Util::Execution }
let(:resolver) { Puppet::Util }
let(:resource) { Puppet::Type.type(:package).new(:name => 'package', :provider => 'pacman') }
let(:provider) { described_class.new(resource) }
before do
resolver.stubs(:which).with('/usr/bin/pacman').returns('/usr/bin/pacman')
described_class.stubs(:which).with('/usr/bin/pacman').returns('/usr/bin/pacman')
resolver.stubs(:which).with('/usr/bin/yaourt').returns('/usr/bin/yaourt')
described_class.stubs(:which).with('/usr/bin/yaourt').returns('/usr/bin/yaourt')
end
describe "when installing" do
before do
provider.stubs(:query).returns({
:ensure => '1.0'
})
end
it "should call pacman to install the right package quietly when yaourt is not installed" do
provider.stubs(:yaourt?).returns(false)
args = ['--noconfirm', '--noprogressbar', '-Sy', resource[:name]]
provider.expects(:pacman).at_least_once.with(*args).returns ''
provider.install
end
it "should call yaourt to install the right package quietly when yaourt is installed" do
provider.stubs(:yaourt?).returns(true)
args = ['--noconfirm', '-S', resource[:name]]
provider.expects(:yaourt).at_least_once.with(*args).returns ''
provider.install
end
it "should raise an ExecutionFailure if the installation failed" do
executor.stubs(:execute).returns("")
provider.expects(:query).returns(nil)
- lambda { provider.install }.should raise_exception(Puppet::ExecutionFailure)
+ expect { provider.install }.to raise_exception(Puppet::ExecutionFailure)
end
describe "and install_options are given" do
before do
resource[:install_options] = ['-x', {'--arg' => 'value'}]
end
it "should call pacman to install the right package quietly when yaourt is not installed" do
provider.stubs(:yaourt?).returns(false)
args = ['--noconfirm', '--noprogressbar', '-x', '--arg=value', '-Sy', resource[:name]]
provider.expects(:pacman).at_least_once.with(*args).returns ''
provider.install
end
it "should call yaourt to install the right package quietly when yaourt is installed" do
provider.stubs(:yaourt?).returns(true)
args = ['--noconfirm', '-x', '--arg=value', '-S', resource[:name]]
provider.expects(:yaourt).at_least_once.with(*args).returns ''
provider.install
end
end
context "when :source is specified" do
let(:install_seq) { sequence("install") }
context "recognizable by pacman" do
%w{
/some/package/file
http://some.package.in/the/air
ftp://some.package.in/the/air
}.each do |source|
it "should install #{source} directly" do
resource[:source] = source
executor.expects(:execute).
with(all_of(includes("-Sy"), includes("--noprogressbar")), no_extra_options).
in_sequence(install_seq).
returns("")
executor.expects(:execute).
with(all_of(includes("-U"), includes(source)), no_extra_options).
in_sequence(install_seq).
returns("")
provider.install
end
end
end
context "as a file:// URL" do
let(:actual_file_path) { "/some/package/file" }
before do
resource[:source] = "file:///some/package/file"
end
it "should install from the path segment of the URL" do
executor.expects(:execute).
with(all_of(includes("-Sy"),
includes("--noprogressbar"),
includes("--noconfirm")),
no_extra_options).
in_sequence(install_seq).
returns("")
executor.expects(:execute).
with(all_of(includes("-U"), includes(actual_file_path)), no_extra_options).
in_sequence(install_seq).
returns("")
provider.install
end
end
context "as a puppet URL" do
before do
resource[:source] = "puppet://server/whatever"
end
it "should fail" do
- lambda { provider.install }.should raise_error(Puppet::Error)
+ expect { provider.install }.to raise_error(Puppet::Error)
end
end
context "as a malformed URL" do
before do
resource[:source] = "blah://"
end
it "should fail" do
- lambda { provider.install }.should raise_error(Puppet::Error)
+ expect { provider.install }.to raise_error(Puppet::Error)
end
end
end
end
describe "when updating" do
it "should call install" do
provider.expects(:install).returns("install return value")
- provider.update.should == "install return value"
+ expect(provider.update).to eq("install return value")
end
end
describe "when uninstalling" do
it "should call pacman to remove the right package quietly" do
args = ["/usr/bin/pacman", "--noconfirm", "--noprogressbar", "-R", resource[:name]]
executor.expects(:execute).with(args, no_extra_options).returns ""
provider.uninstall
end
it "adds any uninstall_options" do
resource[:uninstall_options] = ['-x', {'--arg' => 'value'}]
args = ["/usr/bin/pacman", "--noconfirm", "--noprogressbar", "-x", "--arg=value", "-R", resource[:name]]
executor.expects(:execute).with(args, no_extra_options).returns ""
provider.uninstall
end
end
describe "when querying" do
it "should query pacman" do
executor.
expects(:execute).
with(["/usr/bin/pacman", "-Qi", resource[:name]], no_extra_options)
provider.query
end
it "should return the version" do
query_output = <<EOF
Name : package
Version : 1.01.3-2
URL : http://www.archlinux.org/pacman/
Licenses : GPL
Groups : base
Provides : None
Depends On : bash libarchive>=2.7.1 libfetch>=2.25 pacman-mirrorlist
Optional Deps : fakeroot: for makepkg usage as normal user
curl: for rankmirrors usage
Required By : None
Conflicts With : None
Replaces : None
Installed Size : 2352.00 K
Packager : Dan McGee <dan@archlinux.org>
Architecture : i686
Build Date : Sat 22 Jan 2011 03:56:41 PM EST
Install Date : Thu 27 Jan 2011 06:45:49 AM EST
Install Reason : Explicitly installed
Install Script : Yes
Description : A library-based package manager with dependency support
EOF
executor.expects(:execute).returns(query_output)
- provider.query.should == {:ensure => "1.01.3-2"}
+ expect(provider.query).to eq({:ensure => "1.01.3-2"})
end
it "should return a nil if the package isn't found" do
executor.expects(:execute).returns("")
- provider.query.should be_nil
+ expect(provider.query).to be_nil
end
it "should return a hash indicating that the package is missing on error" do
executor.expects(:execute).raises(Puppet::ExecutionFailure.new("ERROR!"))
- provider.query.should == {
+ expect(provider.query).to eq({
:ensure => :purged,
:status => 'missing',
:name => resource[:name],
:error => 'ok',
- }
+ })
end
end
describe "when fetching a package list" do
it "should retrieve installed packages" do
described_class.expects(:execpipe).with(["/usr/bin/pacman", '-Q'])
described_class.installedpkgs
end
it "should retrieve installed package groups" do
described_class.expects(:execpipe).with(["/usr/bin/pacman", '-Qg'])
described_class.installedgroups
end
it "should return installed packages with their versions" do
described_class.expects(:execpipe).yields(StringIO.new("package1 1.23-4\npackage2 2.00\n"))
packages = described_class.installedpkgs
- packages.length.should == 2
+ expect(packages.length).to eq(2)
- packages[0].properties.should == {
+ expect(packages[0].properties).to eq({
:provider => :pacman,
:ensure => '1.23-4',
:name => 'package1'
- }
+ })
- packages[1].properties.should == {
+ expect(packages[1].properties).to eq({
:provider => :pacman,
:ensure => '2.00',
:name => 'package2'
- }
+ })
end
it "should return installed groups with a dummy version" do
described_class.expects(:execpipe).yields(StringIO.new("group1 pkg1\ngroup1 pkg2"))
groups = described_class.installedgroups
- groups.length.should == 1
+ expect(groups.length).to eq(1)
- groups[0].properties.should == {
+ expect(groups[0].properties).to eq({
:provider => :pacman,
:ensure => '1',
:name => 'group1'
- }
+ })
end
it "should return nil on error" do
described_class.expects(:execpipe).twice.raises(Puppet::ExecutionFailure.new("ERROR!"))
- described_class.instances.should be_nil
+ expect(described_class.instances).to be_nil
end
it "should warn on invalid input" do
described_class.expects(:execpipe).yields(StringIO.new("blah"))
described_class.expects(:warning).with("Failed to match line blah")
described_class.installedpkgs == []
end
end
describe "when determining the latest version" do
it "should refresh package list" do
get_latest_version = sequence("get_latest_version")
executor.
expects(:execute).
in_sequence(get_latest_version).
with(['/usr/bin/pacman', '-Sy'], no_extra_options)
executor.
stubs(:execute).
in_sequence(get_latest_version).
returns("")
provider.latest
end
it "should get query pacman for the latest version" do
get_latest_version = sequence("get_latest_version")
executor.
stubs(:execute).
in_sequence(get_latest_version)
executor.
expects(:execute).
in_sequence(get_latest_version).
with(['/usr/bin/pacman', '-Sp', '--print-format', '%v', resource[:name]], no_extra_options).
returns("")
provider.latest
end
it "should return the version number from pacman" do
executor.
expects(:execute).
at_least_once().
returns("1.00.2-3\n")
- provider.latest.should == "1.00.2-3"
+ expect(provider.latest).to eq("1.00.2-3")
end
end
end
diff --git a/spec/unit/provider/package/pip_spec.rb b/spec/unit/provider/package/pip_spec.rb
index 397d8d05f..f12ca4678 100755
--- a/spec/unit/provider/package/pip_spec.rb
+++ b/spec/unit/provider/package/pip_spec.rb
@@ -1,259 +1,259 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:package).provider(:pip)
osfamilies = { ['RedHat', '6'] => 'pip-python', ['RedHat', '7'] => 'pip', ['Not RedHat', nil] => 'pip' }
describe provider_class do
before do
@resource = Puppet::Resource.new(:package, "fake_package")
@provider = provider_class.new(@resource)
@client = stub_everything('client')
@client.stubs(:call).with('package_releases', 'real_package').returns(["1.3", "1.2.5", "1.2.4"])
@client.stubs(:call).with('package_releases', 'fake_package').returns([])
XMLRPC::Client.stubs(:new2).returns(@client)
end
describe "parse" do
it "should return a hash on valid input" do
- provider_class.parse("real_package==1.2.5").should == {
+ expect(provider_class.parse("real_package==1.2.5")).to eq({
:ensure => "1.2.5",
:name => "real_package",
:provider => :pip,
- }
+ })
end
it "should return nil on invalid input" do
- provider_class.parse("foo").should == nil
+ expect(provider_class.parse("foo")).to eq(nil)
end
end
describe "cmd" do
it "should return pip-python on RedHat < 7 systems" do
Facter.stubs(:value).with(:osfamily).returns("RedHat")
Facter.stubs(:value).with(:operatingsystemmajrelease).returns("6")
- provider_class.cmd.should == 'pip-python'
+ expect(provider_class.cmd).to eq('pip-python')
end
it "should return pip on RedHat >= 7 systems" do
Facter.stubs(:value).with(:osfamily).returns("RedHat")
Facter.stubs(:value).with(:operatingsystemmajrelease).returns("7")
- provider_class.cmd.should == 'pip'
+ expect(provider_class.cmd).to eq('pip')
end
it "should return pip by default" do
Facter.stubs(:value).with(:osfamily).returns("Not RedHat")
- provider_class.cmd.should == 'pip'
+ expect(provider_class.cmd).to eq('pip')
end
end
describe "instances" do
osfamilies.each do |osfamily, pip_cmd|
it "should return an array on #{osfamily} when #{pip_cmd} is present" do
Facter.stubs(:value).with(:osfamily).returns(osfamily.first)
Facter.stubs(:value).with(:operatingsystemmajrelease).returns(osfamily.last)
provider_class.expects(:which).with(pip_cmd).returns("/fake/bin/pip")
p = stub("process")
p.expects(:collect).yields("real_package==1.2.5")
provider_class.expects(:execpipe).with("/fake/bin/pip freeze").yields(p)
provider_class.instances
end
it "should return an empty array on #{osfamily} when #{pip_cmd} is missing" do
Facter.stubs(:value).with(:osfamily).returns(osfamily.first)
Facter.stubs(:value).with(:operatingsystemmajrelease).returns(osfamily.last)
provider_class.expects(:which).with(pip_cmd).returns nil
- provider_class.instances.should == []
+ expect(provider_class.instances).to eq([])
end
end
end
describe "query" do
before do
@resource[:name] = "real_package"
end
it "should return a hash when pip and the package are present" do
provider_class.expects(:instances).returns [provider_class.new({
:ensure => "1.2.5",
:name => "real_package",
:provider => :pip,
})]
- @provider.query.should == {
+ expect(@provider.query).to eq({
:ensure => "1.2.5",
:name => "real_package",
:provider => :pip,
- }
+ })
end
it "should return nil when the package is missing" do
provider_class.expects(:instances).returns []
- @provider.query.should == nil
+ expect(@provider.query).to eq(nil)
end
it "should be case insensitive" do
@resource[:name] = "Real_Package"
provider_class.expects(:instances).returns [provider_class.new({
:ensure => "1.2.5",
:name => "real_package",
:provider => :pip,
})]
- @provider.query.should == {
+ expect(@provider.query).to eq({
:ensure => "1.2.5",
:name => "real_package",
:provider => :pip,
- }
+ })
end
end
describe "latest" do
it "should find a version number for real_package" do
@resource[:name] = "real_package"
- @provider.latest.should_not == nil
+ expect(@provider.latest).not_to eq(nil)
end
it "should not find a version number for fake_package" do
@resource[:name] = "fake_package"
- @provider.latest.should == nil
+ expect(@provider.latest).to eq(nil)
end
it "should handle a timeout gracefully" do
@resource[:name] = "fake_package"
@client.stubs(:call).raises(Timeout::Error)
- lambda { @provider.latest }.should raise_error(Puppet::Error)
+ expect { @provider.latest }.to raise_error(Puppet::Error)
end
end
describe "install" do
before do
@resource[:name] = "fake_package"
@url = "git+https://example.com/fake_package.git"
end
it "should install" do
@resource[:ensure] = :installed
@resource[:source] = nil
@provider.expects(:lazy_pip).
with("install", '-q', "fake_package")
@provider.install
end
it "omits the -e flag (GH-1256)" do
# The -e flag makes the provider non-idempotent
@resource[:ensure] = :installed
@resource[:source] = @url
@provider.expects(:lazy_pip).with() do |*args|
not args.include?("-e")
end
@provider.install
end
it "should install from SCM" do
@resource[:ensure] = :installed
@resource[:source] = @url
@provider.expects(:lazy_pip).
with("install", '-q', "#{@url}#egg=fake_package")
@provider.install
end
it "should install a particular SCM revision" do
@resource[:ensure] = "0123456"
@resource[:source] = @url
@provider.expects(:lazy_pip).
with("install", "-q", "#{@url}@0123456#egg=fake_package")
@provider.install
end
it "should install a particular version" do
@resource[:ensure] = "0.0.0"
@resource[:source] = nil
@provider.expects(:lazy_pip).with("install", "-q", "fake_package==0.0.0")
@provider.install
end
it "should upgrade" do
@resource[:ensure] = :latest
@resource[:source] = nil
@provider.expects(:lazy_pip).
with("install", "-q", "--upgrade", "fake_package")
@provider.install
end
end
describe "uninstall" do
it "should uninstall" do
@resource[:name] = "fake_package"
@provider.expects(:lazy_pip).
with('uninstall', '-y', '-q', 'fake_package')
@provider.uninstall
end
end
describe "update" do
it "should just call install" do
@provider.expects(:install).returns(nil)
@provider.update
end
end
describe "lazy_pip" do
after(:each) do
Puppet::Type::Package::ProviderPip.instance_variable_set(:@confine_collection, nil)
end
it "should succeed if pip is present" do
@provider.stubs(:pip).returns(nil)
@provider.method(:lazy_pip).call "freeze"
end
osfamilies.each do |osfamily, pip_cmd|
it "should retry on #{osfamily} if #{pip_cmd} has not yet been found" do
Facter.stubs(:value).with(:osfamily).returns(osfamily.first)
Facter.stubs(:value).with(:operatingsystemmajrelease).returns(osfamily.last)
@provider.expects(:pip).twice.with('freeze').raises(NoMethodError).then.returns(nil)
@provider.expects(:which).with(pip_cmd).returns("/fake/bin/pip")
@provider.method(:lazy_pip).call "freeze"
end
it "should fail on #{osfamily} if #{pip_cmd} is missing" do
Facter.stubs(:value).with(:osfamily).returns(osfamily.first)
Facter.stubs(:value).with(:operatingsystemmajrelease).returns(osfamily.last)
@provider.expects(:pip).with('freeze').raises(NoMethodError)
@provider.expects(:which).with(pip_cmd).returns(nil)
expect { @provider.method(:lazy_pip).call("freeze") }.to raise_error(NoMethodError)
end
it "should output a useful error message on #{osfamily} if #{pip_cmd} is missing" do
Facter.stubs(:value).with(:osfamily).returns(osfamily.first)
Facter.stubs(:value).with(:operatingsystemmajrelease).returns(osfamily.last)
@provider.expects(:pip).with('freeze').raises(NoMethodError)
@provider.expects(:which).with(pip_cmd).returns(nil)
expect { @provider.method(:lazy_pip).call("freeze") }.
to raise_error(NoMethodError, 'Could not locate the pip command.')
end
end
end
end
diff --git a/spec/unit/provider/package/pkg_spec.rb b/spec/unit/provider/package/pkg_spec.rb
index 865e50c2e..9c8bcbb15 100755
--- a/spec/unit/provider/package/pkg_spec.rb
+++ b/spec/unit/provider/package/pkg_spec.rb
@@ -1,333 +1,333 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:package).provider(:pkg) do
let (:resource) { Puppet::Resource.new(:package, 'dummy', :parameters => {:name => 'dummy', :ensure => :latest}) }
let (:provider) { described_class.new(resource) }
before :each do
described_class.stubs(:command).with(:pkg).returns('/bin/pkg')
end
def self.it_should_respond_to(*actions)
actions.each do |action|
it "should respond to :#{action}" do
- provider.should respond_to(action)
+ expect(provider).to respond_to(action)
end
end
end
it_should_respond_to :install, :uninstall, :update, :query, :latest
it "should be versionable" do
- described_class.should be_versionable
+ expect(described_class).to be_versionable
end
describe "#methods" do
context ":pkg_state" do
it "should raise error on unknown values" do
expect {
- described_class.pkg_state('extra').should
+ expect(described_class.pkg_state('extra')).to
}.to raise_error(ArgumentError, /Unknown format/)
end
['known', 'installed'].each do |k|
it "should return known values" do
- described_class.pkg_state(k).should == {:status => k}
+ expect(described_class.pkg_state(k)).to eq({:status => k})
end
end
end
context ":ifo_flag" do
it "should raise error on unknown values" do
expect {
- described_class.ifo_flag('x--').should
+ expect(described_class.ifo_flag('x--')).to
}.to raise_error(ArgumentError, /Unknown format/)
end
{'i--' => 'installed', '---'=> 'known'}.each do |k, v|
it "should return known values" do
- described_class.ifo_flag(k).should == {:status => v}
+ expect(described_class.ifo_flag(k)).to eq({:status => v})
end
end
end
context ":parse_line" do
it "should raise error on unknown values" do
expect {
- described_class.parse_line('pkg (mypkg) 1.2.3.4 i-- zzz').should
+ expect(described_class.parse_line('pkg (mypkg) 1.2.3.4 i-- zzz')).to
}.to raise_error(ArgumentError, /Unknown line format/)
end
{
'pkg://omnios/SUNWcs@0.5.11,5.11-0.151006:20130506T161045Z i--' => {:name => 'SUNWcs', :ensure => '0.5.11,5.11-0.151006:20130506T161045Z', :status => 'installed', :provider => :pkg, :publisher => 'omnios'},
'pkg://omnios/incorporation/jeos/illumos-gate@11,5.11-0.151006:20130506T183443Z if-' => {:name => 'incorporation/jeos/illumos-gate', :ensure => 'held', :status => 'installed', :provider => :pkg, :publisher => 'omnios'},
'pkg://solaris/SUNWcs@0.5.11,5.11-0.151.0.1:20101105T001108Z installed -----' => {:name => 'SUNWcs', :ensure => '0.5.11,5.11-0.151.0.1:20101105T001108Z', :status => 'installed', :provider => :pkg, :publisher => 'solaris'},
}.each do |k, v|
it "[#{k}] should correctly parse" do
- described_class.parse_line(k).should == v
+ expect(described_class.parse_line(k)).to eq(v)
end
end
end
context ":latest" do
it "should work correctly for ensure latest on solaris 11 (UFOXI) when there are no further packages to install" do
described_class.expects(:pkg).with(:list,'-Hvn','dummy').returns File.read(my_fixture('dummy_solaris11.installed'))
- provider.latest.should == '1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z'
+ expect(provider.latest).to eq('1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z')
end
it "should work correctly for ensure latest on solaris 11 in the presence of a certificate expiration warning" do
described_class.expects(:pkg).with(:list,'-Hvn','dummy').returns File.read(my_fixture('dummy_solaris11.certificate_warning'))
- provider.latest.should == "1.0.6-0.175.0.0.0.2.537"
+ expect(provider.latest).to eq("1.0.6-0.175.0.0.0.2.537")
end
it "should work correctly for ensure latest on solaris 11(known UFOXI)" do
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'update', '-n', 'dummy'], {:failonfail => false, :combine => true}).returns ''
$CHILD_STATUS.stubs(:exitstatus).returns 0
described_class.expects(:pkg).with(:list,'-Hvn','dummy').returns File.read(my_fixture('dummy_solaris11.known'))
- provider.latest.should == '1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z'
+ expect(provider.latest).to eq('1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z')
end
it "should work correctly for ensure latest on solaris 11 (IFO)" do
described_class.expects(:pkg).with(:list,'-Hvn','dummy').returns File.read(my_fixture('dummy_solaris11.ifo.installed'))
- provider.latest.should == '1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z'
+ expect(provider.latest).to eq('1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z')
end
it "should work correctly for ensure latest on solaris 11(known IFO)" do
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'update', '-n', 'dummy'], {:failonfail => false, :combine => true}).returns ''
$CHILD_STATUS.stubs(:exitstatus).returns 0
described_class.expects(:pkg).with(:list,'-Hvn','dummy').returns File.read(my_fixture('dummy_solaris11.ifo.known'))
- provider.latest.should == '1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z'
+ expect(provider.latest).to eq('1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z')
end
it "issues a warning when the certificate has expired" do
warning = "Certificate '/var/pkg/ssl/871b4ed0ade09926e6adf95f86bf17535f987684' for publisher 'solarisstudio', needed to access 'https://pkg.oracle.com/solarisstudio/release/', will expire in '29' days."
Puppet.expects(:warning).with("pkg warning: #{warning}")
described_class.expects(:pkg).with(:list,'-Hvn','dummy').returns File.read(my_fixture('dummy_solaris11.certificate_warning'))
provider.latest
end
it "doesn't issue a warning when the certificate hasn't expired" do
Puppet.expects(:warning).with(/pkg warning/).never
described_class.expects(:pkg).with(:list,'-Hvn','dummy').returns File.read(my_fixture('dummy_solaris11.installed'))
provider.latest
end
end
context ":instances" do
it "should correctly parse lines on solaris 11" do
described_class.expects(:pkg).with(:list, '-Hv').returns File.read(my_fixture('solaris11'))
described_class.expects(:warning).never
instances = described_class.instances.map { |p| {:name => p.get(:name), :ensure => p.get(:ensure) }}
- instances.size.should == 2
- instances[0].should == {:name => 'dummy/dummy', :ensure => '3.0,5.11-0.175.0.0.0.2.537:20131230T130000Z'}
- instances[1].should == {:name => 'dummy/dummy2', :ensure => '1.8.1.2-0.175.0.0.0.2.537:20131230T130000Z'}
+ expect(instances.size).to eq(2)
+ expect(instances[0]).to eq({:name => 'dummy/dummy', :ensure => '3.0,5.11-0.175.0.0.0.2.537:20131230T130000Z'})
+ expect(instances[1]).to eq({:name => 'dummy/dummy2', :ensure => '1.8.1.2-0.175.0.0.0.2.537:20131230T130000Z'})
end
it "should fail on incorrect lines" do
fake_output = File.read(my_fixture('incomplete'))
described_class.expects(:pkg).with(:list,'-Hv').returns fake_output
expect {
described_class.instances
}.to raise_error(ArgumentError, /Unknown line format pkg/)
end
it "should fail on unknown package status" do
described_class.expects(:pkg).with(:list,'-Hv').returns File.read(my_fixture('unknown_status'))
expect {
described_class.instances
}.to raise_error(ArgumentError, /Unknown format pkg/)
end
end
context ":query" do
context "on solaris 10" do
it "should find the package" do
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}).returns File.read(my_fixture('dummy_solaris10'))
$CHILD_STATUS.stubs(:exitstatus).returns 0
- provider.query.should == {
+ expect(provider.query).to eq({
:name => 'dummy',
:ensure => '2.5.5,5.10-0.111:20131230T130000Z',
:publisher => 'solaris',
:status => 'installed',
:provider => :pkg,
- }
+ })
end
it "should return :absent when the package is not found" do
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}).returns ''
$CHILD_STATUS.stubs(:exitstatus).returns 1
- provider.query.should == {:ensure => :absent, :name => "dummy"}
+ expect(provider.query).to eq({:ensure => :absent, :name => "dummy"})
end
end
context "on solaris 11" do
it "should find the package" do
$CHILD_STATUS.stubs(:exitstatus).returns 0
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}).returns File.read(my_fixture('dummy_solaris11.installed'))
- provider.query.should == {
+ expect(provider.query).to eq({
:name => 'dummy',
:status => 'installed',
:ensure => '1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z',
:publisher => 'solaris',
:provider => :pkg,
- }
+ })
end
it "should return :absent when the package is not found" do
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}).returns ''
$CHILD_STATUS.stubs(:exitstatus).returns 1
- provider.query.should == {:ensure => :absent, :name => "dummy"}
+ expect(provider.query).to eq({:ensure => :absent, :name => "dummy"})
end
end
it "should return fail when the packageline cannot be parsed" do
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}).returns(File.read(my_fixture('incomplete')))
$CHILD_STATUS.stubs(:exitstatus).returns 0
expect {
provider.query
}.to raise_error(ArgumentError, /Unknown line format/)
end
end
context ":install" do
it "should accept all licenses" do
provider.expects(:query).with().returns({:ensure => :absent})
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'install', '--accept', 'dummy'], {:failonfail => false, :combine => true}).returns ''
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true}).returns ''
$CHILD_STATUS.stubs(:exitstatus).returns 0
provider.install
end
it "should install specific version(1)" do
# Should install also check if the version installed is the same version we are asked to install? or should we rely on puppet for that?
resource[:ensure] = '0.0.7,5.11-0.151006:20131230T130000Z'
$CHILD_STATUS.stubs(:exitstatus).returns 0
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true})
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}).returns 'pkg://foo/dummy@0.0.6,5.11-0.151006:20131230T130000Z installed -----'
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'update', '--accept', 'dummy@0.0.7,5.11-0.151006:20131230T130000Z'], {:failonfail => false, :combine => true}).returns ''
provider.install
end
it "should install specific version(2)" do
resource[:ensure] = '0.0.8'
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true})
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}).returns 'pkg://foo/dummy@0.0.7,5.11-0.151006:20131230T130000Z installed -----'
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'update', '--accept', 'dummy@0.0.8'], {:failonfail => false, :combine => true}).returns ''
$CHILD_STATUS.stubs(:exitstatus).returns 0
provider.install
end
it "should downgrade to specific version" do
resource[:ensure] = '0.0.7'
provider.expects(:query).with().returns({:ensure => '0.0.8,5.11-0.151106:20131230T130000Z'})
$CHILD_STATUS.stubs(:exitstatus).returns 0
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true})
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'update', '--accept', 'dummy@0.0.7'], {:failonfail => false, :combine => true}).returns ''
provider.install
end
it "should install any if version is not specified" do
resource[:ensure] = :present
provider.expects(:query).with().returns({:ensure => :absent})
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'install', '--accept', 'dummy'], {:failonfail => false, :combine => true}).returns ''
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true})
$CHILD_STATUS.stubs(:exitstatus).returns 0
provider.install
end
it "should install if no version was previously installed, and a specific version was requested" do
resource[:ensure] = '0.0.7'
provider.expects(:query).with().returns({:ensure => :absent})
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true})
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'install', '--accept', 'dummy@0.0.7'], {:failonfail => false, :combine => true}).returns ''
$CHILD_STATUS.stubs(:exitstatus).returns 0
provider.install
end
it "installs the latest matching version when given implicit version, and none are installed" do
resource[:ensure] = '1.0-0.151006'
is = :absent
provider.expects(:query).with().returns({:ensure => is})
described_class.expects(:pkg).with(:list, '-Hvfa', 'dummy@1.0-0.151006').returns File.read(my_fixture('dummy_implicit_version'))
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'install', '-n', 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true})
provider.expects(:unhold).with()
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'install', '--accept', 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true})
$CHILD_STATUS.stubs(:exitstatus).returns 0
provider.insync?(is)
provider.install
end
it "updates to the latest matching version when given implicit version" do
resource[:ensure] = '1.0-0.151006'
is = '1.0,5.11-0.151006:20140219T191204Z'
provider.expects(:query).with().returns({:ensure => is})
described_class.expects(:pkg).with(:list, '-Hvfa', 'dummy@1.0-0.151006').returns File.read(my_fixture('dummy_implicit_version'))
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'update', '-n', 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true})
provider.expects(:unhold).with()
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'update', '--accept', 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true})
$CHILD_STATUS.stubs(:exitstatus).returns 0
provider.insync?(is)
provider.install
end
it "issues a warning when an implicit version number is used, and in sync" do
resource[:ensure] = '1.0-0.151006'
is = '1.0,5.11-0.151006:20140220T084443Z'
provider.expects(:warning).with("Implicit version 1.0-0.151006 has 3 possible matches")
described_class.expects(:pkg).with(:list, '-Hvfa', 'dummy@1.0-0.151006').returns File.read(my_fixture('dummy_implicit_version'))
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'update', '-n', 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true})
$CHILD_STATUS.stubs(:exitstatus).returns 4
provider.insync?(is)
end
it "issues a warning when choosing a version number for an implicit match" do
resource[:ensure] = '1.0-0.151006'
is = :absent
provider.expects(:warning).with("Implicit version 1.0-0.151006 has 3 possible matches")
provider.expects(:warning).with("Selecting version '1.0,5.11-0.151006:20140220T084443Z' for implicit '1.0-0.151006'")
described_class.expects(:pkg).with(:list, '-Hvfa', 'dummy@1.0-0.151006').returns File.read(my_fixture('dummy_implicit_version'))
Puppet::Util::Execution.expects(:execute).with(['/bin/pkg', 'install', '-n', 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true})
$CHILD_STATUS.stubs(:exitstatus).returns 0
provider.insync?(is)
end
end
context ":update" do
it "should not raise error if not necessary" do
provider.expects(:install).with(true).returns({:exit => 0})
provider.update
end
it "should not raise error if not necessary (2)" do
provider.expects(:install).with(true).returns({:exit => 4})
provider.update
end
it "should raise error if necessary" do
provider.expects(:install).with(true).returns({:exit => 1})
expect {
provider.update
}.to raise_error(Puppet::Error, /Unable to update/)
end
end
context ":uninstall" do
it "should support current pkg version" do
described_class.expects(:pkg).with(:version).returns('630e1ffc7a19')
described_class.expects(:pkg).with([:uninstall, resource[:name]])
provider.uninstall
end
it "should support original pkg commands" do
described_class.expects(:pkg).with(:version).returns('052adf36c3f4')
described_class.expects(:pkg).with([:uninstall, '-r', resource[:name]])
provider.uninstall
end
end
end
end
diff --git a/spec/unit/provider/package/pkgdmg_spec.rb b/spec/unit/provider/package/pkgdmg_spec.rb
index deafc5e20..bbc05493c 100644
--- a/spec/unit/provider/package/pkgdmg_spec.rb
+++ b/spec/unit/provider/package/pkgdmg_spec.rb
@@ -1,144 +1,144 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:package).provider(:pkgdmg) do
let(:resource) { Puppet::Type.type(:package).new(:name => 'foo', :provider => :pkgdmg) }
let(:provider) { described_class.new(resource) }
- it { should_not be_versionable }
- it { should_not be_uninstallable }
+ it { is_expected.not_to be_versionable }
+ it { is_expected.not_to be_uninstallable }
describe "when installing it should fail when" do
before :each do
Puppet::Util.expects(:execute).never
end
it "no source is specified" do
expect { provider.install }.to raise_error(Puppet::Error, /must specify a package source/)
end
it "the source does not end in .dmg or .pkg" do
resource[:source] = "bar"
expect { provider.install }.to raise_error(Puppet::Error, /must specify a source string ending in .*dmg.*pkg/)
end
end
# These tests shouldn't be this messy. The pkgdmg provider needs work...
describe "when installing a pkgdmg" do
let(:fake_mountpoint) { "/tmp/dmg.foo" }
let(:empty_hdiutil_plist) { Plist::Emit.dump({}) }
let(:fake_hdiutil_plist) { Plist::Emit.dump({"system-entities" => [{"mount-point" => fake_mountpoint}]}) }
before do
fh = mock 'filehandle'
fh.stubs(:path).yields "/tmp/foo"
resource[:source] = "foo.dmg"
File.stubs(:open).yields fh
Dir.stubs(:mktmpdir).returns "/tmp/testtmp123"
FileUtils.stubs(:remove_entry_secure)
end
it "should fail when a disk image with no system entities is mounted" do
described_class.stubs(:hdiutil).returns(empty_hdiutil_plist)
expect { provider.install }.to raise_error(Puppet::Error, /No disk entities/)
end
it "should call hdiutil to mount and eject the disk image" do
Dir.stubs(:entries).returns []
provider.class.expects(:hdiutil).with("eject", fake_mountpoint).returns 0
provider.class.expects(:hdiutil).with("mount", "-plist", "-nobrowse", "-readonly", "-noidme", "-mountrandom", "/tmp", nil).returns fake_hdiutil_plist
provider.install
end
it "should call installpkg if a pkg/mpkg is found on the dmg" do
Dir.stubs(:entries).returns ["foo.pkg"]
provider.class.stubs(:hdiutil).returns fake_hdiutil_plist
provider.class.expects(:installpkg).with("#{fake_mountpoint}/foo.pkg", resource[:name], "foo.dmg").returns ""
provider.install
end
describe "from a remote source" do
let(:tmpdir) { "/tmp/good123" }
before :each do
resource[:source] = "http://fake.puppetlabs.com/foo.dmg"
end
it "should call tmpdir and then call curl with that directory" do
Dir.expects(:mktmpdir).returns tmpdir
Dir.stubs(:entries).returns ["foo.pkg"]
described_class.expects(:curl).with do |*args|
args[0] == "-o" && args[1].include?(tmpdir) && args.include?("--fail") && ! args.include?("-k")
end
described_class.stubs(:hdiutil).returns fake_hdiutil_plist
described_class.expects(:installpkg)
provider.install
end
it "should use an http proxy host and port if specified" do
Puppet::Util::HttpProxy.expects(:http_proxy_host).returns 'some_host'
Puppet::Util::HttpProxy.expects(:http_proxy_port).returns 'some_port'
Dir.expects(:mktmpdir).returns tmpdir
Dir.stubs(:entries).returns ["foo.pkg"]
described_class.expects(:curl).with do |*args|
- args.should be_include 'some_host:some_port'
- args.should be_include '--proxy'
+ expect(args).to be_include 'some_host:some_port'
+ expect(args).to be_include '--proxy'
end
described_class.stubs(:hdiutil).returns fake_hdiutil_plist
described_class.expects(:installpkg)
provider.install
end
it "should use an http proxy host only if specified" do
Puppet::Util::HttpProxy.expects(:http_proxy_host).returns 'some_host'
Puppet::Util::HttpProxy.expects(:http_proxy_port).returns nil
Dir.expects(:mktmpdir).returns tmpdir
Dir.stubs(:entries).returns ["foo.pkg"]
described_class.expects(:curl).with do |*args|
- args.should be_include 'some_host'
- args.should be_include '--proxy'
+ expect(args).to be_include 'some_host'
+ expect(args).to be_include '--proxy'
end
described_class.stubs(:hdiutil).returns fake_hdiutil_plist
described_class.expects(:installpkg)
provider.install
end
end
end
describe "when installing flat pkg file" do
describe "with a local source" do
it "should call installpkg if a flat pkg file is found instead of a .dmg image" do
resource[:source] = "/tmp/test.pkg"
resource[:name] = "testpkg"
provider.class.expects(:installpkgdmg).with("/tmp/test.pkg", "testpkg").returns ""
provider.install
end
end
describe "with a remote source" do
let(:remote_source) { 'http://fake.puppetlabs.com/test.pkg' }
let(:tmpdir) { '/path/to/tmpdir' }
let(:tmpfile) { File.join(tmpdir, 'testpkg.pkg') }
before do
resource[:name] = 'testpkg'
resource[:source] = remote_source
Dir.stubs(:mktmpdir).returns tmpdir
end
it "should call installpkg if a flat pkg file is found instead of a .dmg image" do
described_class.expects(:curl).with do |*args|
- args.should be_include tmpfile
- args.should be_include remote_source
+ expect(args).to be_include tmpfile
+ expect(args).to be_include remote_source
end
provider.class.expects(:installpkg).with(tmpfile, 'testpkg', remote_source)
provider.install
end
end
end
end
diff --git a/spec/unit/provider/package/pkgin_spec.rb b/spec/unit/provider/package/pkgin_spec.rb
index 8b6d4e51d..43bfa2667 100644
--- a/spec/unit/provider/package/pkgin_spec.rb
+++ b/spec/unit/provider/package/pkgin_spec.rb
@@ -1,178 +1,178 @@
require "spec_helper"
provider_class = Puppet::Type.type(:package).provider(:pkgin)
describe provider_class do
let(:resource) { Puppet::Type.type(:package).new(:name => "vim", :provider => :pkgin) }
subject { resource.provider }
describe "Puppet provider interface" do
it "can return the list of all packages" do
- provider_class.should respond_to(:instances)
+ expect(provider_class).to respond_to(:instances)
end
end
describe "#install" do
describe "a package not installed" do
before { resource[:ensure] = :absent }
it "uses pkgin install to install" do
subject.expects(:pkgin).with("-y", :install, "vim").once()
subject.install
end
end
describe "a package with a fixed version" do
before { resource[:ensure] = '7.2.446' }
it "uses pkgin install to install a fixed version" do
subject.expects(:pkgin).with("-y", :install, "vim-7.2.446").once()
subject.install
end
end
end
describe "#uninstall" do
it "uses pkgin remove to uninstall" do
subject.expects(:pkgin).with("-y", :remove, "vim").once()
subject.uninstall
end
end
describe "#instances" do
let(:pkgin_ls_output) do
"zlib-1.2.3 General purpose data compression library\nzziplib-0.13.59 Library for ZIP archive handling\n"
end
before do
provider_class.stubs(:pkgin).with(:list).returns(pkgin_ls_output)
end
it "returns an array of providers for each package" do
instances = provider_class.instances
- instances.should have(2).items
+ expect(instances).to have(2).items
instances.each do |instance|
- instance.should be_a(provider_class)
+ expect(instance).to be_a(provider_class)
end
end
it "populates each provider with an installed package" do
zlib_provider, zziplib_provider = provider_class.instances
- zlib_provider.get(:name).should == "zlib"
- zlib_provider.get(:ensure).should == "1.2.3"
- zziplib_provider.get(:name).should == "zziplib"
- zziplib_provider.get(:ensure).should == "0.13.59"
+ expect(zlib_provider.get(:name)).to eq("zlib")
+ expect(zlib_provider.get(:ensure)).to eq("1.2.3")
+ expect(zziplib_provider.get(:name)).to eq("zziplib")
+ expect(zziplib_provider.get(:ensure)).to eq("0.13.59")
end
end
describe "#latest" do
before do
provider_class.stubs(:pkgin).with(:search, "vim").returns(pkgin_search_output)
end
context "when the package is installed" do
let(:pkgin_search_output) do
"vim-7.2.446 = Vim editor (vi clone) without GUI\nvim-share-7.2.446 = Data files for the vim editor (vi clone)\n\n=: package is installed and up-to-date\n<: package is installed but newer version is available\n>: installed package has a greater version than available package\n"
end
it "returns installed version" do
subject.expects(:properties).returns( { :ensure => "7.2.446" } )
- subject.latest.should == "7.2.446"
+ expect(subject.latest).to eq("7.2.446")
end
end
context "when the package is out of date" do
let(:pkgin_search_output) do
"vim-7.2.447 < Vim editor (vi clone) without GUI\nvim-share-7.2.447 < Data files for the vim editor (vi clone)\n\n=: package is installed and up-to-date\n<: package is installed but newer version is available\n>: installed package has a greater version than available package\n"
end
it "returns the version to be installed" do
- subject.latest.should == "7.2.447"
+ expect(subject.latest).to eq("7.2.447")
end
end
context "when the package is ahead of date" do
let(:pkgin_search_output) do
"vim-7.2.446 > Vim editor (vi clone) without GUI\nvim-share-7.2.446 > Data files for the vim editor (vi clone)\n\n=: package is installed and up-to-date\n<: package is installed but newer version is available\n>: installed package has a greater version than available package\n"
end
it "returns current version" do
subject.expects(:properties).returns( { :ensure => "7.2.446" } )
- subject.latest.should == "7.2.446"
+ expect(subject.latest).to eq("7.2.446")
end
end
context "when multiple candidates do exists" do
let(:pkgin_search_output) do
<<-SEARCH
vim-7.1 > Vim editor (vi clone) without GUI
vim-share-7.1 > Data files for the vim editor (vi clone)
vim-7.2.446 = Vim editor (vi clone) without GUI
vim-share-7.2.446 = Data files for the vim editor (vi clone)
vim-7.3 < Vim editor (vi clone) without GUI
vim-share-7.3 < Data files for the vim editor (vi clone)
=: package is installed and up-to-date
<: package is installed but newer version is available
>: installed package has a greater version than available package
SEARCH
end
it "returns the newest available version" do
provider_class.stubs(:pkgin).with(:search, "vim").returns(pkgin_search_output)
- subject.latest.should == "7.3"
+ expect(subject.latest).to eq("7.3")
end
end
context "when the package cannot be found" do
let(:pkgin_search_output) do
"No results found for is-puppet"
end
it "returns nil" do
expect { subject.latest }.to raise_error(Puppet::Error, "No candidate to be installed")
end
end
end
describe "#parse_pkgin_line" do
context "with an installed package" do
let(:package) { "vim-7.2.446 = Vim editor (vi clone) without GUI" }
it "extracts the name and status" do
- provider_class.parse_pkgin_line(package).should == { :name => "vim" ,
+ expect(provider_class.parse_pkgin_line(package)).to eq({ :name => "vim" ,
:status => "=" ,
- :ensure => "7.2.446" }
+ :ensure => "7.2.446" })
end
end
context "with an installed package with a hyphen in the name" do
let(:package) { "ruby18-puppet-0.25.5nb1 > Configuration management framework written in Ruby" }
it "extracts the name and status" do
- provider_class.parse_pkgin_line(package).should == { :name => "ruby18-puppet",
+ expect(provider_class.parse_pkgin_line(package)).to eq({ :name => "ruby18-puppet",
:status => ">" ,
- :ensure => "0.25.5nb1" }
+ :ensure => "0.25.5nb1" })
end
end
context "with a package not yet installed" do
let(:package) { "vim-7.2.446 Vim editor (vi clone) without GUI" }
it "extracts the name and status" do
- provider_class.parse_pkgin_line(package).should == { :name => "vim" ,
+ expect(provider_class.parse_pkgin_line(package)).to eq({ :name => "vim" ,
:status => nil ,
- :ensure => "7.2.446" }
+ :ensure => "7.2.446" })
end
end
context "with an invalid package" do
let(:package) { "" }
it "returns nil" do
- provider_class.parse_pkgin_line(package).should be_nil
+ expect(provider_class.parse_pkgin_line(package)).to be_nil
end
end
end
end
diff --git a/spec/unit/provider/package/pkgutil_spec.rb b/spec/unit/provider/package/pkgutil_spec.rb
index a89630b76..3660631ab 100755
--- a/spec/unit/provider/package/pkgutil_spec.rb
+++ b/spec/unit/provider/package/pkgutil_spec.rb
@@ -1,235 +1,235 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider = Puppet::Type.type(:package).provider(:pkgutil)
describe provider do
before(:each) do
@resource = Puppet::Type.type(:package).new(
:name => "TESTpkg",
:ensure => :present,
:provider => :pkgutil
)
@provider = provider.new(@resource)
# Stub all file and config tests
provider.stubs(:healthcheck)
end
it "should have an install method" do
- @provider.should respond_to(:install)
+ expect(@provider).to respond_to(:install)
end
it "should have a latest method" do
- @provider.should respond_to(:uninstall)
+ expect(@provider).to respond_to(:uninstall)
end
it "should have an update method" do
- @provider.should respond_to(:update)
+ expect(@provider).to respond_to(:update)
end
it "should have a latest method" do
- @provider.should respond_to(:latest)
+ expect(@provider).to respond_to(:latest)
end
describe "when installing" do
it "should use a command without versioned package" do
@resource[:ensure] = :latest
@provider.expects(:pkguti).with('-y', '-i', 'TESTpkg')
@provider.install
end
it "should support a single temp repo URL" do
@resource[:ensure] = :latest
@resource[:source] = "http://example.net/repo"
@provider.expects(:pkguti).with('-t', 'http://example.net/repo', '-y', '-i', 'TESTpkg')
@provider.install
end
it "should support multiple temp repo URLs as array" do
@resource[:ensure] = :latest
@resource[:source] = [ 'http://example.net/repo', 'http://example.net/foo' ]
@provider.expects(:pkguti).with('-t', 'http://example.net/repo', '-t', 'http://example.net/foo', '-y', '-i', 'TESTpkg')
@provider.install
end
end
describe "when updating" do
it "should use a command without versioned package" do
@provider.expects(:pkguti).with('-y', '-u', 'TESTpkg')
@provider.update
end
it "should support a single temp repo URL" do
@resource[:source] = "http://example.net/repo"
@provider.expects(:pkguti).with('-t', 'http://example.net/repo', '-y', '-u', 'TESTpkg')
@provider.update
end
it "should support multiple temp repo URLs as array" do
@resource[:source] = [ 'http://example.net/repo', 'http://example.net/foo' ]
@provider.expects(:pkguti).with('-t', 'http://example.net/repo', '-t', 'http://example.net/foo', '-y', '-u', 'TESTpkg')
@provider.update
end
end
describe "when uninstalling" do
it "should call the remove operation" do
@provider.expects(:pkguti).with('-y', '-r', 'TESTpkg')
@provider.uninstall
end
it "should support a single temp repo URL" do
@resource[:source] = "http://example.net/repo"
@provider.expects(:pkguti).with('-t', 'http://example.net/repo', '-y', '-r', 'TESTpkg')
@provider.uninstall
end
it "should support multiple temp repo URLs as array" do
@resource[:source] = [ 'http://example.net/repo', 'http://example.net/foo' ]
@provider.expects(:pkguti).with('-t', 'http://example.net/repo', '-t', 'http://example.net/foo', '-y', '-r', 'TESTpkg')
@provider.uninstall
end
end
describe "when getting latest version" do
it "should return TESTpkg's version string" do
fake_data = "
noisy output here
TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
provider.expects(:pkguti).with('-c', '--single', 'TESTpkg').returns fake_data
- @provider.latest.should == "1.4.5,REV=2007.11.20"
+ expect(@provider.latest).to eq("1.4.5,REV=2007.11.20")
end
it "should support a temp repo URL" do
@resource[:source] = "http://example.net/repo"
fake_data = "
noisy output here
TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
provider.expects(:pkguti).with('-t', 'http://example.net/repo', '-c', '--single', 'TESTpkg').returns fake_data
- @provider.latest.should == "1.4.5,REV=2007.11.20"
+ expect(@provider.latest).to eq("1.4.5,REV=2007.11.20")
end
it "should handle TESTpkg's 'SAME' version string" do
fake_data = "
noisy output here
TESTpkg 1.4.5,REV=2007.11.18 SAME"
provider.expects(:pkguti).with('-c', '--single', 'TESTpkg').returns fake_data
- @provider.latest.should == "1.4.5,REV=2007.11.18"
+ expect(@provider.latest).to eq("1.4.5,REV=2007.11.18")
end
it "should handle a non-existent package" do
fake_data = "noisy output here
Not in catalog"
provider.expects(:pkguti).with('-c', '--single', 'TESTpkg').returns fake_data
- @provider.latest.should == nil
+ expect(@provider.latest).to eq(nil)
end
it "should warn on unknown pkgutil noise" do
provider.expects(:pkguti).with('-c', '--single', 'TESTpkg').returns("testingnoise")
- @provider.latest.should == nil
+ expect(@provider.latest).to eq(nil)
end
it "should ignore pkgutil noise/headers to find TESTpkg" do
fake_data = "# stuff
=> Fetching new catalog and descriptions (http://mirror.opencsw.org/opencsw/unstable/i386/5.11) if available ...
2011-02-19 23:05:46 URL:http://mirror.opencsw.org/opencsw/unstable/i386/5.11/catalog [534635/534635] -> \"/var/opt/csw/pkgutil/catalog.mirror.opencsw.org_opencsw_unstable_i386_5.11.tmp\" [1]
Checking integrity of /var/opt/csw/pkgutil/catalog.mirror.opencsw.org_opencsw_unstable_i386_5.11 with gpg.
gpg: Signature made February 17, 2011 05:27:53 PM GMT using DSA key ID E12E9D2F
gpg: Good signature from \"Distribution Manager <dm@blastwave.org>\"
==> 2770 packages loaded from /var/opt/csw/pkgutil/catalog.mirror.opencsw.org_opencsw_unstable_i386_5.11
package installed catalog
TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
provider.expects(:pkguti).with('-c', '--single', 'TESTpkg').returns fake_data
- @provider.latest.should == "1.4.5,REV=2007.11.20"
+ expect(@provider.latest).to eq("1.4.5,REV=2007.11.20")
end
it "should find REALpkg via an alias (TESTpkg)" do
fake_data = "
noisy output here
REALpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
provider.expects(:pkguti).with('-c', '--single', 'TESTpkg').returns fake_data
- @provider.query[:name].should == "TESTpkg"
+ expect(@provider.query[:name]).to eq("TESTpkg")
end
end
describe "when querying current version" do
it "should return TESTpkg's version string" do
fake_data = "TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
provider.expects(:pkguti).with('-c', '--single', 'TESTpkg').returns fake_data
- @provider.query[:ensure].should == "1.4.5,REV=2007.11.18"
+ expect(@provider.query[:ensure]).to eq("1.4.5,REV=2007.11.18")
end
it "should handle a package that isn't installed" do
fake_data = "TESTpkg notinst 1.4.5,REV=2007.11.20"
provider.expects(:pkguti).with('-c', '--single', 'TESTpkg').returns fake_data
- @provider.query[:ensure].should == :absent
+ expect(@provider.query[:ensure]).to eq(:absent)
end
it "should handle a non-existent package" do
fake_data = "noisy output here
Not in catalog"
provider.expects(:pkguti).with('-c', '--single', 'TESTpkg').returns fake_data
- @provider.query[:ensure].should == :absent
+ expect(@provider.query[:ensure]).to eq(:absent)
end
it "should support a temp repo URL" do
@resource[:source] = "http://example.net/repo"
fake_data = "TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
provider.expects(:pkguti).with('-t', 'http://example.net/repo', '-c', '--single', 'TESTpkg').returns fake_data
- @provider.query[:ensure].should == "1.4.5,REV=2007.11.18"
+ expect(@provider.query[:ensure]).to eq("1.4.5,REV=2007.11.18")
end
end
describe "when querying current instances" do
it "should warn on unknown pkgutil noise" do
provider.expects(:pkguti).with(['-a']).returns("testingnoise")
provider.expects(:pkguti).with(['-c']).returns("testingnoise")
Puppet.expects(:warning).times(2)
provider.expects(:new).never
- provider.instances.should == []
+ expect(provider.instances).to eq([])
end
it "should return TESTpkg's version string" do
fake_data = "TESTpkg TESTpkg 1.4.5,REV=2007.11.20"
provider.expects(:pkguti).with(['-a']).returns fake_data
fake_data = "TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
provider.expects(:pkguti).with(['-c']).returns fake_data
testpkg = mock 'pkg1'
provider.expects(:new).with(:ensure => "1.4.5,REV=2007.11.18", :name => "TESTpkg", :provider => :pkgutil).returns testpkg
- provider.instances.should == [testpkg]
+ expect(provider.instances).to eq([testpkg])
end
it "should also return both TESTpkg and mypkg alias instances" do
fake_data = "mypkg TESTpkg 1.4.5,REV=2007.11.20"
provider.expects(:pkguti).with(['-a']).returns fake_data
fake_data = "TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
provider.expects(:pkguti).with(['-c']).returns fake_data
testpkg = mock 'pkg1'
provider.expects(:new).with(:ensure => "1.4.5,REV=2007.11.18", :name => "TESTpkg", :provider => :pkgutil).returns testpkg
aliaspkg = mock 'pkg2'
provider.expects(:new).with(:ensure => "1.4.5,REV=2007.11.18", :name => "mypkg", :provider => :pkgutil).returns aliaspkg
- provider.instances.should == [testpkg,aliaspkg]
+ expect(provider.instances).to eq([testpkg,aliaspkg])
end
it "shouldn't mind noise in the -a output" do
fake_data = "noisy output here"
provider.expects(:pkguti).with(['-a']).returns fake_data
fake_data = "TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
provider.expects(:pkguti).with(['-c']).returns fake_data
testpkg = mock 'pkg1'
provider.expects(:new).with(:ensure => "1.4.5,REV=2007.11.18", :name => "TESTpkg", :provider => :pkgutil).returns testpkg
- provider.instances.should == [testpkg]
+ expect(provider.instances).to eq([testpkg])
end
end
end
diff --git a/spec/unit/provider/package/portage_spec.rb b/spec/unit/provider/package/portage_spec.rb
index 773e9011b..03d9ec5b0 100644
--- a/spec/unit/provider/package/portage_spec.rb
+++ b/spec/unit/provider/package/portage_spec.rb
@@ -1,69 +1,69 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider = Puppet::Type.type(:package).provider(:portage)
describe provider do
before do
packagename="sl"
@resource = stub('resource', :[] => packagename,:should => true)
@provider = provider.new(@resource)
portage = stub(:executable => "foo",:execute => true)
Puppet::Provider::CommandDefiner.stubs(:define).returns(portage)
@nomatch_result = ""
@match_result = "app-misc sl [] [] http://www.tkl.iis.u-tokyo.ac.jp/~toyoda/index_e.html http://www.izumix.org.uk/sl/ sophisticated graphical program which corrects your miss typing\n"
end
it "is versionable" do
- provider.should be_versionable
+ expect(provider).to be_versionable
end
it "is reinstallable" do
- provider.should be_reinstallable
+ expect(provider).to be_reinstallable
end
it "uses :emerge to install packages" do
@provider.expects(:emerge)
@provider.install
end
it "uses query to find the latest package" do
@provider.expects(:query).returns({:versions_available => "myversion"})
@provider.latest
end
it "uses eix to search the lastest version of a package" do
@provider.stubs(:update_eix)
@provider.expects(:eix).returns(StringIO.new(@match_result))
@provider.query
end
it "eix arguments must not include --stable" do
- @provider.class.eix_search_arguments.should_not include("--stable")
+ expect(@provider.class.eix_search_arguments).not_to include("--stable")
end
it "eix arguments must not include --exact" do
- @provider.class.eix_search_arguments.should_not include("--exact")
+ expect(@provider.class.eix_search_arguments).not_to include("--exact")
end
it "query uses default arguments" do
@provider.stubs(:update_eix)
@provider.expects(:eix).returns(StringIO.new(@match_result))
@provider.class.expects(:eix_search_arguments).returns([])
@provider.query
end
it "can handle search output with empty square brackets" do
@provider.stubs(:update_eix)
@provider.expects(:eix).returns(StringIO.new(@match_result))
- @provider.query[:name].should eq("sl")
+ expect(@provider.query[:name]).to eq("sl")
end
end
diff --git a/spec/unit/provider/package/rpm_spec.rb b/spec/unit/provider/package/rpm_spec.rb
index dd1983d32..307f08a5b 100755
--- a/spec/unit/provider/package/rpm_spec.rb
+++ b/spec/unit/provider/package/rpm_spec.rb
@@ -1,484 +1,484 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:package).provider(:rpm)
describe provider_class do
let (:packages) do
<<-RPM_OUTPUT
cracklib-dicts 0 2.8.9 3.3 x86_64
basesystem 0 8.0 5.1.1.el5.centos noarch
chkconfig 0 1.3.30.2 2.el5 x86_64
myresource 0 1.2.3.4 5.el4 noarch
mysummaryless 0 1.2.3.4 5.el4 noarch
RPM_OUTPUT
end
let(:resource_name) { 'myresource' }
let(:resource) do
Puppet::Type.type(:package).new(
:name => resource_name,
:ensure => :installed,
:provider => 'rpm'
)
end
let(:provider) do
provider = provider_class.new
provider.resource = resource
provider
end
let(:nevra_format) { %Q{%{NAME} %|EPOCH?{%{EPOCH}}:{0}| %{VERSION} %{RELEASE} %{ARCH}\\n} }
let(:execute_options) do
{:failonfail => true, :combine => true, :custom_environment => {}}
end
let(:rpm_version) { "RPM version 5.0.0\n" }
before(:each) do
Puppet::Util.stubs(:which).with("rpm").returns("/bin/rpm")
provider_class.stubs(:which).with("rpm").returns("/bin/rpm")
provider_class.instance_variable_set("@current_version", nil)
Puppet::Type::Package::ProviderRpm.expects(:execute).with(["/bin/rpm", "--version"]).returns(rpm_version).at_most_once
Puppet::Util::Execution.expects(:execute).with(["/bin/rpm", "--version"], execute_options).returns(rpm_version).at_most_once
end
describe 'provider features' do
- it { should be_versionable }
- it { should be_install_options }
- it { should be_uninstall_options }
- it { should be_virtual_packages }
+ it { is_expected.to be_versionable }
+ it { is_expected.to be_install_options }
+ it { is_expected.to be_uninstall_options }
+ it { is_expected.to be_virtual_packages }
end
describe "self.instances" do
describe "with a modern version of RPM" do
it "includes all the modern flags" do
Puppet::Util::Execution.expects(:execpipe).with("/bin/rpm -qa --nosignature --nodigest --qf '#{nevra_format}'").yields(packages)
installed_packages = provider_class.instances
end
end
describe "with a version of RPM < 4.1" do
let(:rpm_version) { "RPM version 4.0.2\n" }
it "excludes the --nosignature flag" do
Puppet::Util::Execution.expects(:execpipe).with("/bin/rpm -qa --nodigest --qf '#{nevra_format}'").yields(packages)
installed_packages = provider_class.instances
end
end
describe "with a version of RPM < 4.0.2" do
let(:rpm_version) { "RPM version 3.0.5\n" }
it "excludes the --nodigest flag" do
Puppet::Util::Execution.expects(:execpipe).with("/bin/rpm -qa --qf '#{nevra_format}'").yields(packages)
installed_packages = provider_class.instances
end
end
it "returns an array of packages" do
Puppet::Util::Execution.expects(:execpipe).with("/bin/rpm -qa --nosignature --nodigest --qf '#{nevra_format}'").yields(packages)
installed_packages = provider_class.instances
expect(installed_packages[0].properties).to eq(
{
:provider => :rpm,
:name => "cracklib-dicts",
:epoch => "0",
:version => "2.8.9",
:release => "3.3",
:arch => "x86_64",
:ensure => "2.8.9-3.3",
}
)
expect(installed_packages[1].properties).to eq(
{
:provider => :rpm,
:name => "basesystem",
:epoch => "0",
:version => "8.0",
:release => "5.1.1.el5.centos",
:arch => "noarch",
:ensure => "8.0-5.1.1.el5.centos",
}
)
expect(installed_packages[2].properties).to eq(
{
:provider => :rpm,
:name => "chkconfig",
:epoch => "0",
:version => "1.3.30.2",
:release => "2.el5",
:arch => "x86_64",
:ensure => "1.3.30.2-2.el5",
}
)
expect(installed_packages.last.properties).to eq(
{
:provider => :rpm,
:name => "mysummaryless",
:epoch => "0",
:version => "1.2.3.4",
:release => "5.el4",
:arch => "noarch",
:ensure => "1.2.3.4-5.el4",
}
)
end
end
describe "#install" do
let(:resource) do
Puppet::Type.type(:package).new(
:name => 'myresource',
:ensure => :installed,
:source => '/path/to/package'
)
end
describe "when not already installed" do
it "only includes the '-i' flag" do
Puppet::Util::Execution.expects(:execute).with(["/bin/rpm", ["-i"], '/path/to/package'], execute_options)
provider.install
end
end
describe "when installed with options" do
let(:resource) do
Puppet::Type.type(:package).new(
:name => resource_name,
:ensure => :installed,
:provider => 'rpm',
:source => '/path/to/package',
:install_options => ['-D', {'--test' => 'value'}, '-Q']
)
end
it "includes the options" do
Puppet::Util::Execution.expects(:execute).with(["/bin/rpm", ["-i", "-D", "--test=value", "-Q"], '/path/to/package'], execute_options)
provider.install
end
end
describe "when an older version is installed" do
before(:each) do
# Force the provider to think a version of the package is already installed
# This is real hacky. I'm sorry. --jeffweiss 25 Jan 2013
provider.instance_variable_get('@property_hash')[:ensure] = '1.2.3.3'
end
it "includes the '-U --oldpackage' flags" do
Puppet::Util::Execution.expects(:execute).with(["/bin/rpm", ["-U", "--oldpackage"], '/path/to/package'], execute_options)
provider.install
end
end
end
describe "#latest" do
it "retrieves version string after querying rpm for version from source file" do
resource.expects(:[]).with(:source).returns('source-string')
Puppet::Util::Execution.expects(:execfail).with(["/bin/rpm", "-q", "--qf", nevra_format, "-p", "source-string"], Puppet::Error).returns("myresource 0 1.2.3.4 5.el4 noarch\n")
expect(provider.latest).to eq("1.2.3.4-5.el4")
end
end
describe "#uninstall" do
let(:resource) do
Puppet::Type.type(:package).new(
:name => 'myresource',
:ensure => :installed
)
end
describe "on a modern RPM" do
before(:each) do
Puppet::Util::Execution.expects(:execute).with(["/bin/rpm", "-q", "myresource", '--nosignature', '--nodigest', "--qf", nevra_format], execute_options).returns("myresource 0 1.2.3.4 5.el4 noarch\n")
end
let(:rpm_version) { "RPM version 4.10.0\n" }
it "includes the architecture in the package name" do
Puppet::Util::Execution.expects(:execute).with(["/bin/rpm", ["-e"], 'myresource-1.2.3.4-5.el4.noarch'], execute_options).returns('').at_most_once
provider.uninstall
end
end
describe "on an ancient RPM" do
before(:each) do
Puppet::Util::Execution.expects(:execute).with(["/bin/rpm", "-q", "myresource", '', '', '--qf', nevra_format], execute_options).returns("myresource 0 1.2.3.4 5.el4 noarch\n")
end
let(:rpm_version) { "RPM version 3.0.6\n" }
it "excludes the architecture from the package name" do
Puppet::Util::Execution.expects(:execute).with(["/bin/rpm", ["-e"], 'myresource-1.2.3.4-5.el4'], execute_options).returns('').at_most_once
provider.uninstall
end
end
describe "when uninstalled with options" do
before(:each) do
Puppet::Util::Execution.expects(:execute).with(["/bin/rpm", "-q", "myresource", '--nosignature', '--nodigest', "--qf", nevra_format], execute_options).returns("myresource 0 1.2.3.4 5.el4 noarch\n")
end
let(:resource) do
Puppet::Type.type(:package).new(
:name => resource_name,
:ensure => :absent,
:provider => 'rpm',
:uninstall_options => ['--nodeps']
)
end
it "includes the options" do
Puppet::Util::Execution.expects(:execute).with(["/bin/rpm", ["-e", "--nodeps"], 'myresource-1.2.3.4-5.el4.noarch'], execute_options)
provider.uninstall
end
end
end
describe "parsing" do
def parser_test(rpm_output_string, gold_hash, number_of_debug_logs = 0)
Puppet.expects(:debug).times(number_of_debug_logs)
Puppet::Util::Execution.expects(:execute).with(["/bin/rpm", "-q", resource_name, "--nosignature", "--nodigest", "--qf", nevra_format], execute_options).returns(rpm_output_string)
expect(provider.query).to eq(gold_hash)
end
let(:resource_name) { 'name' }
let('delimiter') { ':DESC:' }
let(:package_hash) do
{
:name => 'name',
:epoch => 'epoch',
:version => 'version',
:release => 'release',
:arch => 'arch',
:provider => :rpm,
:ensure => 'version-release',
}
end
let(:line) { 'name epoch version release arch' }
['name', 'epoch', 'version', 'release', 'arch'].each do |field|
it "still parses if #{field} is replaced by delimiter" do
parser_test(
line.gsub(field, delimiter),
package_hash.merge(
field.to_sym => delimiter,
:ensure => 'version-release'.gsub(field, delimiter)
)
)
end
end
it "does not fail if line is unparseable, but issues a debug log" do
parser_test('bad data', {}, 1)
end
describe "when the package is not found" do
before do
Puppet.expects(:debug).never
expected_args = ["/bin/rpm", "-q", resource_name, "--nosignature", "--nodigest", "--qf", nevra_format]
Puppet::Util::Execution.expects(:execute).with(expected_args, execute_options).raises Puppet::ExecutionFailure.new("package #{resource_name} is not installed")
end
it "does not log or fail if allow_virtual is false" do
resource[:allow_virtual] = false
expect(provider.query).to be_nil
end
it "does not log or fail if allow_virtual is true" do
resource[:allow_virtual] = true
expected_args = ['/bin/rpm', '-q', resource_name, '--nosignature', '--nodigest', '--qf', nevra_format, '--whatprovides']
Puppet::Util::Execution.expects(:execute).with(expected_args, execute_options).raises Puppet::ExecutionFailure.new("package #{resource_name} is not provided")
expect(provider.query).to be_nil
end
end
it "parses virtual package" do
provider.resource[:allow_virtual] = true
expected_args = ["/bin/rpm", "-q", resource_name, "--nosignature", "--nodigest", "--qf", nevra_format]
Puppet::Util::Execution.expects(:execute).with(expected_args, execute_options).raises Puppet::ExecutionFailure.new("package #{resource_name} is not installed")
Puppet::Util::Execution.expects(:execute).with(expected_args + ["--whatprovides"], execute_options).returns "myresource 0 1.2.3.4 5.el4 noarch\n"
expect(provider.query).to eq({
:name => "myresource",
:epoch => "0",
:version => "1.2.3.4",
:release => "5.el4",
:arch => "noarch",
:provider => :rpm,
:ensure => "1.2.3.4-5.el4"
})
end
end
describe "#install_options" do
it "returns nil by default" do
expect(provider.install_options).to eq(nil)
end
it "returns install_options when set" do
provider.resource[:install_options] = ['-n']
expect(provider.install_options).to eq(['-n'])
end
it "returns multiple install_options when set" do
provider.resource[:install_options] = ['-L', '/opt/puppet']
expect(provider.install_options).to eq(['-L', '/opt/puppet'])
end
it 'returns install_options when set as hash' do
provider.resource[:install_options] = [{ '-Darch' => 'vax' }]
expect(provider.install_options).to eq(['-Darch=vax'])
end
it 'returns install_options when an array with hashes' do
provider.resource[:install_options] = [ '-L', { '-Darch' => 'vax' }]
expect(provider.install_options).to eq(['-L', '-Darch=vax'])
end
end
describe "#uninstall_options" do
it "returns nil by default" do
expect(provider.uninstall_options).to eq(nil)
end
it "returns uninstall_options when set" do
provider.resource[:uninstall_options] = ['-n']
expect(provider.uninstall_options).to eq(['-n'])
end
it "returns multiple uninstall_options when set" do
provider.resource[:uninstall_options] = ['-L', '/opt/puppet']
expect(provider.uninstall_options).to eq(['-L', '/opt/puppet'])
end
it 'returns uninstall_options when set as hash' do
provider.resource[:uninstall_options] = [{ '-Darch' => 'vax' }]
expect(provider.uninstall_options).to eq(['-Darch=vax'])
end
it 'returns uninstall_options when an array with hashes' do
provider.resource[:uninstall_options] = [ '-L', { '-Darch' => 'vax' }]
expect(provider.uninstall_options).to eq(['-L', '-Darch=vax'])
end
end
describe ".nodigest" do
{ '4.0' => nil,
'4.0.1' => nil,
'4.0.2' => '--nodigest',
'4.0.3' => '--nodigest',
'4.1' => '--nodigest',
'5' => '--nodigest',
}.each do |version, expected|
describe "when current version is #{version}" do
it "returns #{expected.inspect}" do
provider_class.stubs(:current_version).returns(version)
expect(provider_class.nodigest).to eq(expected)
end
end
end
end
describe ".nosignature" do
{ '4.0.3' => nil,
'4.1' => '--nosignature',
'4.1.1' => '--nosignature',
'4.2' => '--nosignature',
'5' => '--nosignature',
}.each do |version, expected|
describe "when current version is #{version}" do
it "returns #{expected.inspect}" do
provider_class.stubs(:current_version).returns(version)
expect(provider_class.nosignature).to eq(expected)
end
end
end
end
describe 'version comparison' do
# test cases munged directly from rpm's own
# tests/rpmvercmp.at
- it { provider.rpmvercmp("1.0", "1.0").should == 0 }
- it { provider.rpmvercmp("1.0", "2.0").should == -1 }
- it { provider.rpmvercmp("2.0", "1.0").should == 1 }
- it { provider.rpmvercmp("2.0.1", "2.0.1").should == 0 }
- it { provider.rpmvercmp("2.0", "2.0.1").should == -1 }
- it { provider.rpmvercmp("2.0.1", "2.0").should == 1 }
- it { provider.rpmvercmp("2.0.1a", "2.0.1a").should == 0 }
- it { provider.rpmvercmp("2.0.1a", "2.0.1").should == 1 }
- it { provider.rpmvercmp("2.0.1", "2.0.1a").should == -1 }
- it { provider.rpmvercmp("5.5p1", "5.5p1").should == 0 }
- it { provider.rpmvercmp("5.5p1", "5.5p2").should == -1 }
- it { provider.rpmvercmp("5.5p2", "5.5p1").should == 1 }
- it { provider.rpmvercmp("5.5p10", "5.5p10").should == 0 }
- it { provider.rpmvercmp("5.5p1", "5.5p10").should == -1 }
- it { provider.rpmvercmp("5.5p10", "5.5p1").should == 1 }
- it { provider.rpmvercmp("10xyz", "10.1xyz").should == -1 }
- it { provider.rpmvercmp("10.1xyz", "10xyz").should == 1 }
- it { provider.rpmvercmp("xyz10", "xyz10").should == 0 }
- it { provider.rpmvercmp("xyz10", "xyz10.1").should == -1 }
- it { provider.rpmvercmp("xyz10.1", "xyz10").should == 1 }
- it { provider.rpmvercmp("xyz.4", "xyz.4").should == 0 }
- it { provider.rpmvercmp("xyz.4", "8").should == -1 }
- it { provider.rpmvercmp("8", "xyz.4").should == 1 }
- it { provider.rpmvercmp("xyz.4", "2").should == -1 }
- it { provider.rpmvercmp("2", "xyz.4").should == 1 }
- it { provider.rpmvercmp("5.5p2", "5.6p1").should == -1 }
- it { provider.rpmvercmp("5.6p1", "5.5p2").should == 1 }
- it { provider.rpmvercmp("5.6p1", "6.5p1").should == -1 }
- it { provider.rpmvercmp("6.5p1", "5.6p1").should == 1 }
- it { provider.rpmvercmp("6.0.rc1", "6.0").should == 1 }
- it { provider.rpmvercmp("6.0", "6.0.rc1").should == -1 }
- it { provider.rpmvercmp("10b2", "10a1").should == 1 }
- it { provider.rpmvercmp("10a2", "10b2").should == -1 }
- it { provider.rpmvercmp("1.0aa", "1.0aa").should == 0 }
- it { provider.rpmvercmp("1.0a", "1.0aa").should == -1 }
- it { provider.rpmvercmp("1.0aa", "1.0a").should == 1 }
- it { provider.rpmvercmp("10.0001", "10.0001").should == 0 }
- it { provider.rpmvercmp("10.0001", "10.1").should == 0 }
- it { provider.rpmvercmp("10.1", "10.0001").should == 0 }
- it { provider.rpmvercmp("10.0001", "10.0039").should == -1 }
- it { provider.rpmvercmp("10.0039", "10.0001").should == 1 }
- it { provider.rpmvercmp("4.999.9", "5.0").should == -1 }
- it { provider.rpmvercmp("5.0", "4.999.9").should == 1 }
- it { provider.rpmvercmp("20101121", "20101121").should == 0 }
- it { provider.rpmvercmp("20101121", "20101122").should == -1 }
- it { provider.rpmvercmp("20101122", "20101121").should == 1 }
- it { provider.rpmvercmp("2_0", "2_0").should == 0 }
- it { provider.rpmvercmp("2.0", "2_0").should == 0 }
- it { provider.rpmvercmp("2_0", "2.0").should == 0 }
- it { provider.rpmvercmp("a", "a").should == 0 }
- it { provider.rpmvercmp("a+", "a+").should == 0 }
- it { provider.rpmvercmp("a+", "a_").should == 0 }
- it { provider.rpmvercmp("a_", "a+").should == 0 }
- it { provider.rpmvercmp("+a", "+a").should == 0 }
- it { provider.rpmvercmp("+a", "_a").should == 0 }
- it { provider.rpmvercmp("_a", "+a").should == 0 }
- it { provider.rpmvercmp("+_", "+_").should == 0 }
- it { provider.rpmvercmp("_+", "+_").should == 0 }
- it { provider.rpmvercmp("_+", "_+").should == 0 }
- it { provider.rpmvercmp("+", "_").should == 0 }
- it { provider.rpmvercmp("_", "+").should == 0 }
- it { provider.rpmvercmp("1.0~rc1", "1.0~rc1").should == 0 }
- it { provider.rpmvercmp("1.0~rc1", "1.0").should == -1 }
- it { provider.rpmvercmp("1.0", "1.0~rc1").should == 1 }
- it { provider.rpmvercmp("1.0~rc1", "1.0~rc2").should == -1 }
- it { provider.rpmvercmp("1.0~rc2", "1.0~rc1").should == 1 }
- it { provider.rpmvercmp("1.0~rc1~git123", "1.0~rc1~git123").should == 0 }
- it { provider.rpmvercmp("1.0~rc1~git123", "1.0~rc1").should == -1 }
- it { provider.rpmvercmp("1.0~rc1", "1.0~rc1~git123").should == 1 }
- it { provider.rpmvercmp("1.0~rc1", "1.0arc1").should == -1 }
+ it { expect(provider.rpmvercmp("1.0", "1.0")).to eq(0) }
+ it { expect(provider.rpmvercmp("1.0", "2.0")).to eq(-1) }
+ it { expect(provider.rpmvercmp("2.0", "1.0")).to eq(1) }
+ it { expect(provider.rpmvercmp("2.0.1", "2.0.1")).to eq(0) }
+ it { expect(provider.rpmvercmp("2.0", "2.0.1")).to eq(-1) }
+ it { expect(provider.rpmvercmp("2.0.1", "2.0")).to eq(1) }
+ it { expect(provider.rpmvercmp("2.0.1a", "2.0.1a")).to eq(0) }
+ it { expect(provider.rpmvercmp("2.0.1a", "2.0.1")).to eq(1) }
+ it { expect(provider.rpmvercmp("2.0.1", "2.0.1a")).to eq(-1) }
+ it { expect(provider.rpmvercmp("5.5p1", "5.5p1")).to eq(0) }
+ it { expect(provider.rpmvercmp("5.5p1", "5.5p2")).to eq(-1) }
+ it { expect(provider.rpmvercmp("5.5p2", "5.5p1")).to eq(1) }
+ it { expect(provider.rpmvercmp("5.5p10", "5.5p10")).to eq(0) }
+ it { expect(provider.rpmvercmp("5.5p1", "5.5p10")).to eq(-1) }
+ it { expect(provider.rpmvercmp("5.5p10", "5.5p1")).to eq(1) }
+ it { expect(provider.rpmvercmp("10xyz", "10.1xyz")).to eq(-1) }
+ it { expect(provider.rpmvercmp("10.1xyz", "10xyz")).to eq(1) }
+ it { expect(provider.rpmvercmp("xyz10", "xyz10")).to eq(0) }
+ it { expect(provider.rpmvercmp("xyz10", "xyz10.1")).to eq(-1) }
+ it { expect(provider.rpmvercmp("xyz10.1", "xyz10")).to eq(1) }
+ it { expect(provider.rpmvercmp("xyz.4", "xyz.4")).to eq(0) }
+ it { expect(provider.rpmvercmp("xyz.4", "8")).to eq(-1) }
+ it { expect(provider.rpmvercmp("8", "xyz.4")).to eq(1) }
+ it { expect(provider.rpmvercmp("xyz.4", "2")).to eq(-1) }
+ it { expect(provider.rpmvercmp("2", "xyz.4")).to eq(1) }
+ it { expect(provider.rpmvercmp("5.5p2", "5.6p1")).to eq(-1) }
+ it { expect(provider.rpmvercmp("5.6p1", "5.5p2")).to eq(1) }
+ it { expect(provider.rpmvercmp("5.6p1", "6.5p1")).to eq(-1) }
+ it { expect(provider.rpmvercmp("6.5p1", "5.6p1")).to eq(1) }
+ it { expect(provider.rpmvercmp("6.0.rc1", "6.0")).to eq(1) }
+ it { expect(provider.rpmvercmp("6.0", "6.0.rc1")).to eq(-1) }
+ it { expect(provider.rpmvercmp("10b2", "10a1")).to eq(1) }
+ it { expect(provider.rpmvercmp("10a2", "10b2")).to eq(-1) }
+ it { expect(provider.rpmvercmp("1.0aa", "1.0aa")).to eq(0) }
+ it { expect(provider.rpmvercmp("1.0a", "1.0aa")).to eq(-1) }
+ it { expect(provider.rpmvercmp("1.0aa", "1.0a")).to eq(1) }
+ it { expect(provider.rpmvercmp("10.0001", "10.0001")).to eq(0) }
+ it { expect(provider.rpmvercmp("10.0001", "10.1")).to eq(0) }
+ it { expect(provider.rpmvercmp("10.1", "10.0001")).to eq(0) }
+ it { expect(provider.rpmvercmp("10.0001", "10.0039")).to eq(-1) }
+ it { expect(provider.rpmvercmp("10.0039", "10.0001")).to eq(1) }
+ it { expect(provider.rpmvercmp("4.999.9", "5.0")).to eq(-1) }
+ it { expect(provider.rpmvercmp("5.0", "4.999.9")).to eq(1) }
+ it { expect(provider.rpmvercmp("20101121", "20101121")).to eq(0) }
+ it { expect(provider.rpmvercmp("20101121", "20101122")).to eq(-1) }
+ it { expect(provider.rpmvercmp("20101122", "20101121")).to eq(1) }
+ it { expect(provider.rpmvercmp("2_0", "2_0")).to eq(0) }
+ it { expect(provider.rpmvercmp("2.0", "2_0")).to eq(0) }
+ it { expect(provider.rpmvercmp("2_0", "2.0")).to eq(0) }
+ it { expect(provider.rpmvercmp("a", "a")).to eq(0) }
+ it { expect(provider.rpmvercmp("a+", "a+")).to eq(0) }
+ it { expect(provider.rpmvercmp("a+", "a_")).to eq(0) }
+ it { expect(provider.rpmvercmp("a_", "a+")).to eq(0) }
+ it { expect(provider.rpmvercmp("+a", "+a")).to eq(0) }
+ it { expect(provider.rpmvercmp("+a", "_a")).to eq(0) }
+ it { expect(provider.rpmvercmp("_a", "+a")).to eq(0) }
+ it { expect(provider.rpmvercmp("+_", "+_")).to eq(0) }
+ it { expect(provider.rpmvercmp("_+", "+_")).to eq(0) }
+ it { expect(provider.rpmvercmp("_+", "_+")).to eq(0) }
+ it { expect(provider.rpmvercmp("+", "_")).to eq(0) }
+ it { expect(provider.rpmvercmp("_", "+")).to eq(0) }
+ it { expect(provider.rpmvercmp("1.0~rc1", "1.0~rc1")).to eq(0) }
+ it { expect(provider.rpmvercmp("1.0~rc1", "1.0")).to eq(-1) }
+ it { expect(provider.rpmvercmp("1.0", "1.0~rc1")).to eq(1) }
+ it { expect(provider.rpmvercmp("1.0~rc1", "1.0~rc2")).to eq(-1) }
+ it { expect(provider.rpmvercmp("1.0~rc2", "1.0~rc1")).to eq(1) }
+ it { expect(provider.rpmvercmp("1.0~rc1~git123", "1.0~rc1~git123")).to eq(0) }
+ it { expect(provider.rpmvercmp("1.0~rc1~git123", "1.0~rc1")).to eq(-1) }
+ it { expect(provider.rpmvercmp("1.0~rc1", "1.0~rc1~git123")).to eq(1) }
+ it { expect(provider.rpmvercmp("1.0~rc1", "1.0arc1")).to eq(-1) }
# non-upstream test cases
- it { provider.rpmvercmp("405", "406").should == -1 }
- it { provider.rpmvercmp("1", "0").should == 1 }
+ it { expect(provider.rpmvercmp("405", "406")).to eq(-1) }
+ it { expect(provider.rpmvercmp("1", "0")).to eq(1) }
end
end
diff --git a/spec/unit/provider/package/sun_spec.rb b/spec/unit/provider/package/sun_spec.rb
index c6cb7304f..8a9569835 100755
--- a/spec/unit/provider/package/sun_spec.rb
+++ b/spec/unit/provider/package/sun_spec.rb
@@ -1,114 +1,114 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:package).provider(:sun) do
let(:resource) { Puppet::Type.type(:package).new(:name => 'dummy', :ensure => :installed, :provider => :sun) }
let(:provider) { resource.provider }
describe 'provider features' do
- it { should be_installable }
- it { should be_uninstallable }
- it { should be_upgradeable }
- it { should_not be_versionable }
+ it { is_expected.to be_installable }
+ it { is_expected.to be_uninstallable }
+ it { is_expected.to be_upgradeable }
+ it { is_expected.not_to be_versionable }
end
[:install, :uninstall, :latest, :query, :update].each do |method|
it "should have a #{method} method" do
- provider.should respond_to(method)
+ expect(provider).to respond_to(method)
end
end
context '#install' do
it "should install a package" do
resource[:ensure] = :installed
resource[:source] = '/cdrom'
provider.expects(:pkgadd).with(['-d', '/cdrom', '-n', 'dummy'])
provider.install
end
it "should install a package if it is not present on update" do
provider.expects(:pkginfo).with('-l', 'dummy').returns File.read(my_fixture('dummy.server'))
provider.expects(:pkgrm).with(['-n', 'dummy'])
provider.expects(:install)
provider.update
end
it "should install a package on global zone if -G specified" do
resource[:ensure] = :installed
resource[:source] = '/cdrom'
resource[:install_options] = '-G'
provider.expects(:pkgadd).with(['-d', '/cdrom', '-G', '-n', 'dummy'])
provider.install
end
end
context '#uninstall' do
it "should uninstall a package" do
provider.expects(:pkgrm).with(['-n','dummy'])
provider.uninstall
end
end
context '#update' do
it "should call uninstall if not :absent on info2hash" do
provider.stubs(:info2hash).returns({:name => 'SUNWdummy', :ensure => "11.11.0,REV=2010.10.12.04.23"})
provider.expects(:uninstall)
provider.expects(:install)
provider.update
end
it "should not call uninstall if :absent on info2hash" do
provider.stubs(:info2hash).returns({:name => 'SUNWdummy', :ensure => :absent})
provider.expects(:install)
provider.update
end
end
context '#query' do
it "should find the package on query" do
provider.expects(:pkginfo).with('-l', 'dummy').returns File.read(my_fixture('dummy.server'))
- provider.query.should == {
+ expect(provider.query).to eq({
:name => 'SUNWdummy',
:category=>"system",
:platform=>"i386",
:ensure => "11.11.0,REV=2010.10.12.04.23",
:root=>"/",
:description=>"Dummy server (9.6.1-P3)",
:vendor => "Oracle Corporation",
- }
+ })
end
it "shouldn't find the package on query if it is not present" do
provider.expects(:pkginfo).with('-l', 'dummy').raises Puppet::ExecutionFailure, "Execution of 'pkginfo -l dummy' returned 3: ERROR: information for \"dummy\" not found."
- provider.query.should == {:ensure => :absent}
+ expect(provider.query).to eq({:ensure => :absent})
end
it "unknown message should raise error." do
provider.expects(:pkginfo).with('-l', 'dummy').returns 'RANDOM'
expect { provider.query }.to raise_error Puppet::Error
end
end
context '#instance' do
it "should list instances when there are packages in the system" do
described_class.expects(:pkginfo).with('-l').returns File.read(my_fixture('simple'))
instances = provider.class.instances.map { |p| {:name => p.get(:name), :ensure => p.get(:ensure)} }
- instances.size.should == 2
- instances[0].should == {
+ expect(instances.size).to eq(2)
+ expect(instances[0]).to eq({
:name => 'SUNWdummy',
:ensure => "11.11.0,REV=2010.10.12.04.23",
- }
- instances[1].should == {
+ })
+ expect(instances[1]).to eq({
:name => 'SUNWdummyc',
:ensure => "11.11.0,REV=2010.10.12.04.24",
- }
+ })
end
it "should return empty if there were no packages" do
described_class.expects(:pkginfo).with('-l').returns ''
instances = provider.class.instances
- instances.size.should == 0
+ expect(instances.size).to eq(0)
end
end
end
diff --git a/spec/unit/provider/package/up2date_spec.rb b/spec/unit/provider/package/up2date_spec.rb
index 01c19d4a2..9eb622aed 100644
--- a/spec/unit/provider/package/up2date_spec.rb
+++ b/spec/unit/provider/package/up2date_spec.rb
@@ -1,24 +1,24 @@
# spec/unit/provider/package/up2date_spec.rb
require 'spec_helper'
describe 'up2date package provider' do
# This sets the class itself as the subject rather than
# an instance of the class.
subject do
Puppet::Type.type(:package).provider(:up2date)
end
osfamilies = [ 'redhat' ]
releases = [ '2.1', '3', '4' ]
osfamilies.each do |osfamily|
releases.each do |release|
it "should be the default provider on #{osfamily} #{release}" do
Facter.expects(:value).with(:osfamily).returns(osfamily)
Facter.expects(:value).with(:lsbdistrelease).returns(release)
- subject.default?.should be_true
+ expect(subject.default?).to be_truthy
end
end
end
end
diff --git a/spec/unit/provider/package/urpmi_spec.rb b/spec/unit/provider/package/urpmi_spec.rb
index beb4397cc..aef456145 100644
--- a/spec/unit/provider/package/urpmi_spec.rb
+++ b/spec/unit/provider/package/urpmi_spec.rb
@@ -1,80 +1,80 @@
require 'spec_helper'
describe Puppet::Type.type(:package).provider(:urpmi) do
before do
Puppet::Util::Execution.expects(:execute).never
%w[rpm urpmi urpme urpmq].each do |executable|
Puppet::Util.stubs(:which).with(executable).returns(executable)
end
Puppet::Util::Execution.stubs(:execute).with(['rpm', '--version'], anything).returns 'RPM version 4.9.1.3'
end
let(:resource) do
Puppet::Type.type(:package).new(:name => 'foopkg', :provider => :urpmi)
end
before do
subject.resource = resource
Puppet::Type.type(:package).stubs(:defaultprovider).returns described_class
end
describe '#install' do
before do
subject.stubs(:rpm).with('-q', 'foopkg', any_parameters).returns "foopkg 0 1.2.3.4 5 noarch :DESC:\n"
end
describe 'without a version' do
it 'installs the unversioned package' do
resource[:ensure] = :present
Puppet::Util::Execution.expects(:execute).with(['urpmi', '--auto', 'foopkg'], anything)
subject.install
end
end
describe 'with a version' do
it 'installs the versioned package' do
resource[:ensure] = '4.5.6'
Puppet::Util::Execution.expects(:execute).with(['urpmi', '--auto', 'foopkg-4.5.6'], anything)
subject.install
end
end
describe "and the package install fails" do
it "raises an error" do
Puppet::Util::Execution.stubs(:execute).with(['urpmi', '--auto', 'foopkg'], anything)
subject.stubs(:query)
expect { subject.install }.to raise_error Puppet::Error, /Package \S+ was not present after trying to install it/
end
end
end
describe '#latest' do
let(:urpmq_output) { 'foopkg : Lorem ipsum dolor sit amet, consectetur adipisicing elit ( 7.8.9-1.mga2 )' }
it "uses urpmq to determine the latest package" do
Puppet::Util::Execution.expects(:execute).with(['urpmq', '-S', 'foopkg'], anything).returns urpmq_output
- subject.latest.should == '7.8.9-1.mga2'
+ expect(subject.latest).to eq('7.8.9-1.mga2')
end
it "falls back to the current version" do
resource[:ensure] = '5.4.3'
Puppet::Util::Execution.expects(:execute).with(['urpmq', '-S', 'foopkg'], anything).returns ''
- subject.latest.should == '5.4.3'
+ expect(subject.latest).to eq('5.4.3')
end
end
describe '#update' do
it 'delegates to #install' do
subject.expects(:install)
subject.update
end
end
describe '#purge' do
it 'uses urpme to purge packages' do
Puppet::Util::Execution.expects(:execute).with(['urpme', '--auto', 'foopkg'], anything)
subject.purge
end
end
end
diff --git a/spec/unit/provider/package/windows/exe_package_spec.rb b/spec/unit/provider/package/windows/exe_package_spec.rb
index 89e101ccd..31f59c551 100644
--- a/spec/unit/provider/package/windows/exe_package_spec.rb
+++ b/spec/unit/provider/package/windows/exe_package_spec.rb
@@ -1,99 +1,101 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/provider/package/windows/exe_package'
describe Puppet::Provider::Package::Windows::ExePackage do
subject { described_class }
let (:name) { 'Git version 1.7.11' }
let (:version) { '1.7.11' }
let (:source) { 'E:\Git-1.7.11.exe' }
let (:uninstall) { '"C:\Program Files (x86)\Git\unins000.exe" /SP-' }
context '::from_registry' do
it 'should return an instance of ExePackage' do
subject.expects(:valid?).returns(true)
pkg = subject.from_registry('', {'DisplayName' => name, 'DisplayVersion' => version, 'UninstallString' => uninstall})
- pkg.name.should == name
- pkg.version.should == version
- pkg.uninstall_string.should == uninstall
+ expect(pkg.name).to eq(name)
+ expect(pkg.version).to eq(version)
+ expect(pkg.uninstall_string).to eq(uninstall)
end
it 'should return nil if it is not a valid executable' do
subject.expects(:valid?).returns(false)
- subject.from_registry('', {}).should be_nil
+ expect(subject.from_registry('', {})).to be_nil
end
end
context '::valid?' do
let(:name) { 'myproduct' }
let(:values) do { 'DisplayName' => name, 'UninstallString' => uninstall } end
{
'DisplayName' => ['My App', ''],
'UninstallString' => ['E:\uninstall.exe', ''],
'SystemComponent' => [nil, 1],
'WindowsInstaller' => [nil, 1],
'ParentKeyName' => [nil, 'Uber Product'],
'Security Update' => [nil, 'KB890830'],
'Update Rollup' => [nil, 'Service Pack 42'],
'Hotfix' => [nil, 'QFE 42']
}.each_pair do |k, arr|
it "should accept '#{k}' with value '#{arr[0]}'" do
values[k] = arr[0]
- subject.valid?(name, values).should be_true
+ expect(subject.valid?(name, values)).to be_truthy
end
it "should reject '#{k}' with value '#{arr[1]}'" do
values[k] = arr[1]
- subject.valid?(name, values).should be_false
+ expect(subject.valid?(name, values)).to be_falsey
end
end
it 'should reject packages whose name starts with "KBXXXXXX"' do
- subject.valid?('KB890830', values).should be_false
+ expect(subject.valid?('KB890830', values)).to be_falsey
end
it 'should accept packages whose name does not start with "KBXXXXXX"' do
- subject.valid?('My Update (KB890830)', values).should be_true
+ expect(subject.valid?('My Update (KB890830)', values)).to be_truthy
end
end
context '#match?' do
let(:pkg) { subject.new(name, version, uninstall) }
it 'should match product name' do
- pkg.match?({:name => name}).should be_true
+ expect(pkg.match?({:name => name})).to be_truthy
end
it 'should return false otherwise' do
- pkg.match?({:name => 'not going to find it'}).should be_false
+ expect(pkg.match?({:name => 'not going to find it'})).to be_falsey
end
end
context '#install_command' do
it 'should install using the source' do
cmd = subject.install_command({:source => source})
- cmd.should == ['cmd.exe', '/c', 'start', '"puppet-install"', '/w', source]
+ expect(cmd).to eq(['cmd.exe', '/c', 'start', '"puppet-install"', '/w', source])
end
end
context '#uninstall_command' do
['C:\uninstall.exe', 'C:\Program Files\uninstall.exe'].each do |exe|
it "should quote #{exe}" do
- subject.new(name, version, exe).uninstall_command.should ==
+ expect(subject.new(name, version, exe).uninstall_command).to eq(
['cmd.exe', '/c', 'start', '"puppet-uninstall"', '/w', "\"#{exe}\""]
+ )
end
end
['"C:\Program Files\uninstall.exe"', '"C:\Program Files (x86)\Git\unins000.exe" /SILENT"'].each do |exe|
it "should not quote #{exe}" do
- subject.new(name, version, exe).uninstall_command.should ==
+ expect(subject.new(name, version, exe).uninstall_command).to eq(
['cmd.exe', '/c', 'start', '"puppet-uninstall"', '/w', exe]
+ )
end
end
end
end
diff --git a/spec/unit/provider/package/windows/msi_package_spec.rb b/spec/unit/provider/package/windows/msi_package_spec.rb
index 40a323ace..90dd44db2 100644
--- a/spec/unit/provider/package/windows/msi_package_spec.rb
+++ b/spec/unit/provider/package/windows/msi_package_spec.rb
@@ -1,115 +1,115 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/provider/package/windows/msi_package'
describe Puppet::Provider::Package::Windows::MsiPackage do
subject { described_class }
let (:name) { 'mysql-5.1.58-win-x64' }
let (:version) { '5.1.58' }
let (:source) { 'E:\mysql-5.1.58-win-x64.msi' }
let (:productcode) { '{E437FFB6-5C49-4DAC-ABAE-33FF065FE7CC}' }
let (:packagecode) { '{5A6FD560-763A-4BC1-9E03-B18DFFB7C72C}' }
def expect_installer
inst = mock
inst.expects(:ProductState).returns(5)
inst.expects(:ProductInfo).with(productcode, 'PackageCode').returns(packagecode)
subject.expects(:installer).returns(inst)
end
context '::installer', :if => Puppet.features.microsoft_windows? do
it 'should return an instance of the COM interface' do
- subject.installer.should_not be_nil
+ expect(subject.installer).not_to be_nil
end
end
context '::from_registry' do
it 'should return an instance of MsiPackage' do
subject.expects(:valid?).returns(true)
expect_installer
pkg = subject.from_registry(productcode, {'DisplayName' => name, 'DisplayVersion' => version})
- pkg.name.should == name
- pkg.version.should == version
- pkg.productcode.should == productcode
- pkg.packagecode.should == packagecode
+ expect(pkg.name).to eq(name)
+ expect(pkg.version).to eq(version)
+ expect(pkg.productcode).to eq(productcode)
+ expect(pkg.packagecode).to eq(packagecode)
end
it 'should return nil if it is not a valid MSI' do
subject.expects(:valid?).returns(false)
- subject.from_registry(productcode, {}).should be_nil
+ expect(subject.from_registry(productcode, {})).to be_nil
end
end
context '::valid?' do
let(:values) do { 'DisplayName' => name, 'DisplayVersion' => version, 'WindowsInstaller' => 1 } end
{
'DisplayName' => ['My App', ''],
'SystemComponent' => [nil, 1],
'WindowsInstaller' => [1, nil],
}.each_pair do |k, arr|
it "should accept '#{k}' with value '#{arr[0]}'" do
values[k] = arr[0]
- subject.valid?(productcode, values).should be_true
+ expect(subject.valid?(productcode, values)).to be_truthy
end
it "should reject '#{k}' with value '#{arr[1]}'" do
values[k] = arr[1]
- subject.valid?(productcode, values).should be_false
+ expect(subject.valid?(productcode, values)).to be_falsey
end
end
it 'should reject packages whose name is not a productcode' do
- subject.valid?('AddressBook', values).should be_false
+ expect(subject.valid?('AddressBook', values)).to be_falsey
end
it 'should accept packages whose name is a productcode' do
- subject.valid?(productcode, values).should be_true
+ expect(subject.valid?(productcode, values)).to be_truthy
end
end
context '#match?' do
it 'should match package codes case-insensitively' do
pkg = subject.new(name, version, productcode, packagecode.upcase)
- pkg.match?({:name => packagecode.downcase}).should be_true
+ expect(pkg.match?({:name => packagecode.downcase})).to be_truthy
end
it 'should match product codes case-insensitively' do
pkg = subject.new(name, version, productcode.upcase, packagecode)
- pkg.match?({:name => productcode.downcase}).should be_true
+ expect(pkg.match?({:name => productcode.downcase})).to be_truthy
end
it 'should match product name' do
pkg = subject.new(name, version, productcode, packagecode)
- pkg.match?({:name => name}).should be_true
+ expect(pkg.match?({:name => name})).to be_truthy
end
it 'should return false otherwise' do
pkg = subject.new(name, version, productcode, packagecode)
- pkg.match?({:name => 'not going to find it'}).should be_false
+ expect(pkg.match?({:name => 'not going to find it'})).to be_falsey
end
end
context '#install_command' do
it 'should install using the source' do
cmd = subject.install_command({:source => source})
- cmd.should == ['msiexec.exe', '/qn', '/norestart', '/i', source]
+ expect(cmd).to eq(['msiexec.exe', '/qn', '/norestart', '/i', source])
end
end
context '#uninstall_command' do
it 'should uninstall using the productcode' do
pkg = subject.new(name, version, productcode, packagecode)
- pkg.uninstall_command.should == ['msiexec.exe', '/qn', '/norestart', '/x', productcode]
+ expect(pkg.uninstall_command).to eq(['msiexec.exe', '/qn', '/norestart', '/x', productcode])
end
end
end
diff --git a/spec/unit/provider/package/windows/package_spec.rb b/spec/unit/provider/package/windows/package_spec.rb
index 632fa13a6..778901035 100755
--- a/spec/unit/provider/package/windows/package_spec.rb
+++ b/spec/unit/provider/package/windows/package_spec.rb
@@ -1,141 +1,141 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/provider/package/windows/package'
describe Puppet::Provider::Package::Windows::Package do
subject { described_class }
let(:hklm) { 'HKEY_LOCAL_MACHINE' }
let(:hkcu) { 'HKEY_CURRENT_USER' }
let(:path) { 'Software\Microsoft\Windows\CurrentVersion\Uninstall' }
let(:key) { mock('key', :name => "#{hklm}\\#{path}\\Google") }
let(:package) { mock('package') }
context '::each' do
it 'should generate an empty enumeration' do
subject.expects(:with_key)
- subject.to_a.should be_empty
+ expect(subject.to_a).to be_empty
end
it 'should yield each package it finds' do
subject.expects(:with_key).yields(key, {})
Puppet::Provider::Package::Windows::MsiPackage.expects(:from_registry).with('Google', {}).returns(package)
yielded = nil
subject.each do |pkg|
yielded = pkg
end
- yielded.should == package
+ expect(yielded).to eq(package)
end
end
context '::with_key', :if => Puppet.features.microsoft_windows? do
it 'should search HKLM (64 & 32) and HKCU (64 & 32)' do
seq = sequence('reg')
subject.expects(:open).with(hklm, path, subject::KEY64 | subject::KEY_READ).in_sequence(seq)
subject.expects(:open).with(hklm, path, subject::KEY32 | subject::KEY_READ).in_sequence(seq)
subject.expects(:open).with(hkcu, path, subject::KEY64 | subject::KEY_READ).in_sequence(seq)
subject.expects(:open).with(hkcu, path, subject::KEY32 | subject::KEY_READ).in_sequence(seq)
subject.with_key { |key, values| }
end
it 'should ignore file not found exceptions' do
ex = Puppet::Util::Windows::Error.new('Failed to open registry key', Puppet::Util::Windows::Error::ERROR_FILE_NOT_FOUND)
# make sure we don't stop after the first exception
subject.expects(:open).times(4).raises(ex)
keys = []
subject.with_key { |key, values| keys << key }
- keys.should be_empty
+ expect(keys).to be_empty
end
it 'should raise other types of exceptions' do
ex = Puppet::Util::Windows::Error.new('Failed to open registry key', Puppet::Util::Windows::Error::ERROR_ACCESS_DENIED)
subject.expects(:open).raises(ex)
expect {
subject.with_key{ |key, values| }
}.to raise_error(Puppet::Util::Windows::Error, /Access is denied/)
end
end
context '::installer_class' do
it 'should require the source parameter' do
expect {
subject.installer_class({})
}.to raise_error(Puppet::Error, /The source parameter is required when using the Windows provider./)
end
context 'MSI' do
let (:klass) { Puppet::Provider::Package::Windows::MsiPackage }
it 'should accept source ending in .msi' do
- subject.installer_class({:source => 'foo.msi'}).should == klass
+ expect(subject.installer_class({:source => 'foo.msi'})).to eq(klass)
end
it 'should accept quoted source ending in .msi' do
- subject.installer_class({:source => '"foo.msi"'}).should == klass
+ expect(subject.installer_class({:source => '"foo.msi"'})).to eq(klass)
end
it 'should accept source case insensitively' do
- subject.installer_class({:source => '"foo.MSI"'}).should == klass
+ expect(subject.installer_class({:source => '"foo.MSI"'})).to eq(klass)
end
it 'should reject source containing msi in the name' do
expect {
subject.installer_class({:source => 'mymsi.txt'})
}.to raise_error(Puppet::Error, /Don't know how to install 'mymsi.txt'/)
end
end
context 'Unknown' do
it 'should reject packages it does not know about' do
expect {
subject.installer_class({:source => 'basram'})
}.to raise_error(Puppet::Error, /Don't know how to install 'basram'/)
end
end
end
context '::munge' do
it 'should shell quote strings with spaces and fix forward slashes' do
- subject.munge('c:/windows/the thing').should == '"c:\windows\the thing"'
+ expect(subject.munge('c:/windows/the thing')).to eq('"c:\windows\the thing"')
end
it 'should leave properly formatted paths alone' do
- subject.munge('c:\windows\thething').should == 'c:\windows\thething'
+ expect(subject.munge('c:\windows\thething')).to eq('c:\windows\thething')
end
end
context '::replace_forward_slashes' do
it 'should replace forward with back slashes' do
- subject.replace_forward_slashes('c:/windows/thing/stuff').should == 'c:\windows\thing\stuff'
+ expect(subject.replace_forward_slashes('c:/windows/thing/stuff')).to eq('c:\windows\thing\stuff')
end
end
context '::quote' do
it 'should shell quote strings with spaces' do
- subject.quote('foo bar').should == '"foo bar"'
+ expect(subject.quote('foo bar')).to eq('"foo bar"')
end
it 'should shell quote strings with spaces and quotes' do
- subject.quote('"foo bar" baz').should == '"\"foo bar\" baz"'
+ expect(subject.quote('"foo bar" baz')).to eq('"\"foo bar\" baz"')
end
it 'should not shell quote strings without spaces' do
- subject.quote('"foobar"').should == '"foobar"'
+ expect(subject.quote('"foobar"')).to eq('"foobar"')
end
end
it 'should implement instance methods' do
pkg = subject.new('orca', '5.0')
- pkg.name.should == 'orca'
- pkg.version.should == '5.0'
+ expect(pkg.name).to eq('orca')
+ expect(pkg.version).to eq('5.0')
end
end
diff --git a/spec/unit/provider/package/windows_spec.rb b/spec/unit/provider/package/windows_spec.rb
index 0766f2790..e54b7318e 100755
--- a/spec/unit/provider/package/windows_spec.rb
+++ b/spec/unit/provider/package/windows_spec.rb
@@ -1,251 +1,251 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:package).provider(:windows) do
let (:name) { 'mysql-5.1.58-win-x64' }
let (:source) { 'E:\mysql-5.1.58-win-x64.msi' }
let (:resource) { Puppet::Type.type(:package).new(:name => name, :provider => :windows, :source => source) }
let (:provider) { resource.provider }
let (:execute_options) do {:failonfail => false, :combine => true} end
before :each do
# make sure we never try to execute anything
provider.expects(:execute).never
end
def expect_execute(command, status)
provider.expects(:execute).with(command, execute_options).returns(Puppet::Util::Execution::ProcessOutput.new('',status))
end
describe 'provider features' do
- it { should be_installable }
- it { should be_uninstallable }
- it { should be_install_options }
- it { should be_uninstall_options }
- it { should be_versionable }
+ it { is_expected.to be_installable }
+ it { is_expected.to be_uninstallable }
+ it { is_expected.to be_install_options }
+ it { is_expected.to be_uninstall_options }
+ it { is_expected.to be_versionable }
end
describe 'on Windows', :if => Puppet.features.microsoft_windows? do
it 'should be the default provider' do
- Puppet::Type.type(:package).defaultprovider.should == subject.class
+ expect(Puppet::Type.type(:package).defaultprovider).to eq(subject.class)
end
end
context '::instances' do
it 'should return an array of provider instances' do
pkg1 = stub('pkg1')
pkg2 = stub('pkg2')
prov1 = stub('prov1', :name => 'pkg1', :version => '1.0.0', :package => pkg1)
prov2 = stub('prov2', :name => 'pkg2', :version => nil, :package => pkg2)
Puppet::Provider::Package::Windows::Package.expects(:map).multiple_yields([prov1], [prov2]).returns([prov1, prov2])
providers = provider.class.instances
- providers.count.should == 2
- providers[0].name.should == 'pkg1'
- providers[0].version.should == '1.0.0'
- providers[0].package.should == pkg1
+ expect(providers.count).to eq(2)
+ expect(providers[0].name).to eq('pkg1')
+ expect(providers[0].version).to eq('1.0.0')
+ expect(providers[0].package).to eq(pkg1)
- providers[1].name.should == 'pkg2'
- providers[1].version.should be_nil
- providers[1].package.should == pkg2
+ expect(providers[1].name).to eq('pkg2')
+ expect(providers[1].version).to be_nil
+ expect(providers[1].package).to eq(pkg2)
end
it 'should return an empty array if none found' do
Puppet::Provider::Package::Windows::Package.expects(:map).returns([])
- provider.class.instances.should == []
+ expect(provider.class.instances).to eq([])
end
end
context '#query' do
it 'should return the hash of the matched packaged' do
pkg = mock(:name => 'pkg1', :version => nil)
pkg.expects(:match?).returns(true)
Puppet::Provider::Package::Windows::Package.expects(:find).yields(pkg)
- provider.query.should == { :name => 'pkg1', :ensure => :installed, :provider => :windows }
+ expect(provider.query).to eq({ :name => 'pkg1', :ensure => :installed, :provider => :windows })
end
it 'should include the version string when present' do
pkg = mock(:name => 'pkg1', :version => '1.0.0')
pkg.expects(:match?).returns(true)
Puppet::Provider::Package::Windows::Package.expects(:find).yields(pkg)
- provider.query.should == { :name => 'pkg1', :ensure => '1.0.0', :provider => :windows }
+ expect(provider.query).to eq({ :name => 'pkg1', :ensure => '1.0.0', :provider => :windows })
end
it 'should return nil if no package was found' do
Puppet::Provider::Package::Windows::Package.expects(:find)
- provider.query.should be_nil
+ expect(provider.query).to be_nil
end
end
context '#install' do
let(:command) { 'blarg.exe /S' }
let(:klass) { mock('installer', :install_command => ['blarg.exe', '/S'] ) }
before :each do
Puppet::Provider::Package::Windows::Package.expects(:installer_class).returns(klass)
end
it 'should join the install command and options' do
resource[:install_options] = { 'INSTALLDIR' => 'C:\mysql-5.1' }
expect_execute("#{command} INSTALLDIR=C:\\mysql-5.1", 0)
provider.install
end
it 'should compact nil install options' do
expect_execute(command, 0)
provider.install
end
it 'should not warn if the package install succeeds' do
expect_execute(command, 0)
provider.expects(:warning).never
provider.install
end
it 'should warn if reboot initiated' do
expect_execute(command, 1641)
provider.expects(:warning).with('The package installed successfully and the system is rebooting now.')
provider.install
end
it 'should warn if reboot required' do
expect_execute(command, 3010)
provider.expects(:warning).with('The package installed successfully, but the system must be rebooted.')
provider.install
end
it 'should fail otherwise', :if => Puppet.features.microsoft_windows? do
expect_execute(command, 5)
expect do
provider.install
end.to raise_error(Puppet::Util::Windows::Error, /Access is denied/)
end
end
context '#uninstall' do
let(:command) { 'unblarg.exe /Q' }
let(:package) { mock('package', :uninstall_command => ['unblarg.exe', '/Q'] ) }
before :each do
resource[:ensure] = :absent
provider.package = package
end
it 'should join the uninstall command and options' do
resource[:uninstall_options] = { 'INSTALLDIR' => 'C:\mysql-5.1' }
expect_execute("#{command} INSTALLDIR=C:\\mysql-5.1", 0)
provider.uninstall
end
it 'should compact nil install options' do
expect_execute(command, 0)
provider.uninstall
end
it 'should not warn if the package install succeeds' do
expect_execute(command, 0)
provider.expects(:warning).never
provider.uninstall
end
it 'should warn if reboot initiated' do
expect_execute(command, 1641)
provider.expects(:warning).with('The package uninstalled successfully and the system is rebooting now.')
provider.uninstall
end
it 'should warn if reboot required' do
expect_execute(command, 3010)
provider.expects(:warning).with('The package uninstalled successfully, but the system must be rebooted.')
provider.uninstall
end
it 'should fail otherwise', :if => Puppet.features.microsoft_windows? do
expect_execute(command, 5)
expect do
provider.uninstall
end.to raise_error(Puppet::Util::Windows::Error, /Failed to uninstall.*Access is denied/)
end
end
context '#validate_source' do
it 'should fail if the source parameter is empty' do
expect do
resource[:source] = ''
end.to raise_error(Puppet::Error, /The source parameter cannot be empty when using the Windows provider/)
end
it 'should accept a source' do
resource[:source] = source
end
end
context '#install_options' do
it 'should return nil by default' do
- provider.install_options.should be_nil
+ expect(provider.install_options).to be_nil
end
it 'should return the options' do
resource[:install_options] = { 'INSTALLDIR' => 'C:\mysql-here' }
- provider.install_options.should == ['INSTALLDIR=C:\mysql-here']
+ expect(provider.install_options).to eq(['INSTALLDIR=C:\mysql-here'])
end
it 'should only quote if needed' do
resource[:install_options] = { 'INSTALLDIR' => 'C:\mysql here' }
- provider.install_options.should == ['INSTALLDIR="C:\mysql here"']
+ expect(provider.install_options).to eq(['INSTALLDIR="C:\mysql here"'])
end
it 'should escape embedded quotes in install_options values with spaces' do
resource[:install_options] = { 'INSTALLDIR' => 'C:\mysql "here"' }
- provider.install_options.should == ['INSTALLDIR="C:\mysql \"here\""']
+ expect(provider.install_options).to eq(['INSTALLDIR="C:\mysql \"here\""'])
end
end
context '#uninstall_options' do
it 'should return nil by default' do
- provider.uninstall_options.should be_nil
+ expect(provider.uninstall_options).to be_nil
end
it 'should return the options' do
resource[:uninstall_options] = { 'INSTALLDIR' => 'C:\mysql-here' }
- provider.uninstall_options.should == ['INSTALLDIR=C:\mysql-here']
+ expect(provider.uninstall_options).to eq(['INSTALLDIR=C:\mysql-here'])
end
end
context '#join_options' do
it 'should return nil if there are no options' do
- provider.join_options(nil).should be_nil
+ expect(provider.join_options(nil)).to be_nil
end
it 'should sort hash keys' do
- provider.join_options([{'b' => '2', 'a' => '1', 'c' => '3'}]).should == ['a=1', 'b=2', 'c=3']
+ expect(provider.join_options([{'b' => '2', 'a' => '1', 'c' => '3'}])).to eq(['a=1', 'b=2', 'c=3'])
end
it 'should return strings and hashes' do
- provider.join_options([{'a' => '1'}, 'b']).should == ['a=1', 'b']
+ expect(provider.join_options([{'a' => '1'}, 'b'])).to eq(['a=1', 'b'])
end
end
end
diff --git a/spec/unit/provider/package/yum_spec.rb b/spec/unit/provider/package/yum_spec.rb
index 6e3ec7213..2a4545cbe 100755
--- a/spec/unit/provider/package/yum_spec.rb
+++ b/spec/unit/provider/package/yum_spec.rb
@@ -1,505 +1,505 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:package).provider(:yum)
describe provider_class do
let(:name) { 'mypackage' }
let(:resource) do
Puppet::Type.type(:package).new(
:name => name,
:ensure => :installed,
:provider => 'yum'
)
end
let(:provider) do
provider = provider_class.new
provider.resource = resource
provider
end
before do
provider.stubs(:yum).returns 'yum'
provider.stubs(:rpm).returns 'rpm'
provider.stubs(:get).with(:version).returns '1'
provider.stubs(:get).with(:release).returns '1'
provider.stubs(:get).with(:arch).returns 'i386'
end
describe 'provider features' do
- it { should be_versionable }
- it { should be_install_options }
- it { should be_virtual_packages }
+ it { is_expected.to be_versionable }
+ it { is_expected.to be_install_options }
+ it { is_expected.to be_virtual_packages }
end
# provider should repond to the following methods
[:install, :latest, :update, :purge, :install_options].each do |method|
it "should have a(n) #{method}" do
- provider.should respond_to(method)
+ expect(provider).to respond_to(method)
end
end
describe 'package evr parsing' do
it 'should parse full simple evr' do
v = provider.yum_parse_evr('0:1.2.3-4.el5')
- v[:epoch].should == '0'
- v[:version].should == '1.2.3'
- v[:release].should == '4.el5'
+ expect(v[:epoch]).to eq('0')
+ expect(v[:version]).to eq('1.2.3')
+ expect(v[:release]).to eq('4.el5')
end
it 'should parse version only' do
v = provider.yum_parse_evr('1.2.3')
- v[:epoch].should == '0'
- v[:version].should == '1.2.3'
- v[:release].should == nil
+ expect(v[:epoch]).to eq('0')
+ expect(v[:version]).to eq('1.2.3')
+ expect(v[:release]).to eq(nil)
end
it 'should parse version-release' do
v = provider.yum_parse_evr('1.2.3-4.5.el6')
- v[:epoch].should == '0'
- v[:version].should == '1.2.3'
- v[:release].should == '4.5.el6'
+ expect(v[:epoch]).to eq('0')
+ expect(v[:version]).to eq('1.2.3')
+ expect(v[:release]).to eq('4.5.el6')
end
it 'should parse release with git hash' do
v = provider.yum_parse_evr('1.2.3-4.1234aefd')
- v[:epoch].should == '0'
- v[:version].should == '1.2.3'
- v[:release].should == '4.1234aefd'
+ expect(v[:epoch]).to eq('0')
+ expect(v[:version]).to eq('1.2.3')
+ expect(v[:release]).to eq('4.1234aefd')
end
it 'should parse single integer versions' do
v = provider.yum_parse_evr('12345')
- v[:epoch].should == '0'
- v[:version].should == '12345'
- v[:release].should == nil
+ expect(v[:epoch]).to eq('0')
+ expect(v[:version]).to eq('12345')
+ expect(v[:release]).to eq(nil)
end
it 'should parse text in the epoch to 0' do
v = provider.yum_parse_evr('foo0:1.2.3-4')
- v[:epoch].should == '0'
- v[:version].should == '1.2.3'
- v[:release].should == '4'
+ expect(v[:epoch]).to eq('0')
+ expect(v[:version]).to eq('1.2.3')
+ expect(v[:release]).to eq('4')
end
it 'should parse revisions with text' do
v = provider.yum_parse_evr('1.2.3-SNAPSHOT20140107')
- v[:epoch].should == '0'
- v[:version].should == '1.2.3'
- v[:release].should == 'SNAPSHOT20140107'
+ expect(v[:epoch]).to eq('0')
+ expect(v[:version]).to eq('1.2.3')
+ expect(v[:release]).to eq('SNAPSHOT20140107')
end
# test cases for PUP-682
it 'should parse revisions with text and numbers' do
v = provider.yum_parse_evr('2.2-SNAPSHOT20121119105647')
- v[:epoch].should == '0'
- v[:version].should == '2.2'
- v[:release].should == 'SNAPSHOT20121119105647'
+ expect(v[:epoch]).to eq('0')
+ expect(v[:version]).to eq('2.2')
+ expect(v[:release]).to eq('SNAPSHOT20121119105647')
end
end
describe 'yum evr comparison' do
# currently passing tests
it 'should evaluate identical version-release as equal' do
v = provider.yum_compareEVR({:epoch => '0', :version => '1.2.3', :release => '1.el5'},
{:epoch => '0', :version => '1.2.3', :release => '1.el5'})
- v.should == 0
+ expect(v).to eq(0)
end
it 'should evaluate identical version as equal' do
v = provider.yum_compareEVR({:epoch => '0', :version => '1.2.3', :release => nil},
{:epoch => '0', :version => '1.2.3', :release => nil})
- v.should == 0
+ expect(v).to eq(0)
end
it 'should evaluate identical version but older release as less' do
v = provider.yum_compareEVR({:epoch => '0', :version => '1.2.3', :release => '1.el5'},
{:epoch => '0', :version => '1.2.3', :release => '2.el5'})
- v.should == -1
+ expect(v).to eq(-1)
end
it 'should evaluate identical version but newer release as greater' do
v = provider.yum_compareEVR({:epoch => '0', :version => '1.2.3', :release => '3.el5'},
{:epoch => '0', :version => '1.2.3', :release => '2.el5'})
- v.should == 1
+ expect(v).to eq(1)
end
it 'should evaluate a newer epoch as greater' do
v = provider.yum_compareEVR({:epoch => '1', :version => '1.2.3', :release => '4.5'},
{:epoch => '0', :version => '1.2.3', :release => '4.5'})
- v.should == 1
+ expect(v).to eq(1)
end
# these tests describe PUP-1244 logic yet to be implemented
it 'should evaluate any version as equal to the same version followed by release' do
v = provider.yum_compareEVR({:epoch => '0', :version => '1.2.3', :release => nil},
{:epoch => '0', :version => '1.2.3', :release => '2.el5'})
- v.should == 0
+ expect(v).to eq(0)
end
# test cases for PUP-682
it 'should evaluate same-length numeric revisions numerically' do
- provider.yum_compareEVR({:epoch => '0', :version => '2.2', :release => '405'},
- {:epoch => '0', :version => '2.2', :release => '406'}).should == -1
+ expect(provider.yum_compareEVR({:epoch => '0', :version => '2.2', :release => '405'},
+ {:epoch => '0', :version => '2.2', :release => '406'})).to eq(-1)
end
end
describe 'yum version segment comparison' do
it 'should treat two nil values as equal' do
v = provider.compare_values(nil, nil)
- v.should == 0
+ expect(v).to eq(0)
end
it 'should treat a nil value as less than a non-nil value' do
v = provider.compare_values(nil, '0')
- v.should == -1
+ expect(v).to eq(-1)
end
it 'should treat a non-nil value as greater than a nil value' do
v = provider.compare_values('0', nil)
- v.should == 1
+ expect(v).to eq(1)
end
it 'should pass two non-nil values on to rpmvercmp' do
provider.stubs(:rpmvercmp) { 0 }
provider.expects(:rpmvercmp).with('s1', 's2')
provider.compare_values('s1', 's2')
end
end
describe 'when installing' do
before(:each) do
Puppet::Util.stubs(:which).with("rpm").returns("/bin/rpm")
provider.stubs(:which).with("rpm").returns("/bin/rpm")
Puppet::Util::Execution.expects(:execute).with(["/bin/rpm", "--version"], {:combine => true, :custom_environment => {}, :failonfail => true}).returns("4.10.1\n").at_most_once
end
it 'should call yum install for :installed' do
resource.stubs(:should).with(:ensure).returns :installed
provider.expects(:yum).with('-d', '0', '-e', '0', '-y', :install, name)
provider.install
end
it 'should use :install to update' do
provider.expects(:install)
provider.update
end
it 'should be able to set version' do
version = '1.2'
resource[:ensure] = version
provider.expects(:yum).with('-d', '0', '-e', '0', '-y', :install, "#{name}-#{version}")
provider.stubs(:query).returns :ensure => version
provider.install
end
it 'should handle partial versions specified' do
version = '1.3.4'
resource[:ensure] = version
provider.stubs(:query).returns :ensure => '1.3.4-1.el6'
provider.install
end
it 'should be able to downgrade' do
current_version = '1.2'
version = '1.0'
resource[:ensure] = '1.0'
provider.expects(:yum).with('-d', '0', '-e', '0', '-y', :downgrade, "#{name}-#{version}")
provider.stubs(:query).returns(:ensure => current_version).then.returns(:ensure => version)
provider.install
end
it 'should accept install options' do
resource[:ensure] = :installed
resource[:install_options] = ['-t', {'-x' => 'expackage'}]
provider.expects(:yum).with('-d', '0', '-e', '0', '-y', ['-t', '-x=expackage'], :install, name)
provider.install
end
it 'allow virtual packages' do
resource[:ensure] = :installed
resource[:allow_virtual] = true
provider.expects(:yum).with('-d', '0', '-e', '0', '-y', :list, name).never
provider.expects(:yum).with('-d', '0', '-e', '0', '-y', :install, name)
provider.install
end
end
describe 'when uninstalling' do
it 'should use erase to purge' do
provider.expects(:yum).with('-y', :erase, name)
provider.purge
end
end
it 'should be versionable' do
- provider.should be_versionable
+ expect(provider).to be_versionable
end
describe 'determining the latest version available for a package' do
it "passes the value of enablerepo install_options when querying" do
resource[:install_options] = [
{'--enablerepo' => 'contrib'},
{'--enablerepo' => 'centosplus'},
]
provider.stubs(:properties).returns({:ensure => '3.4.5'})
described_class.expects(:latest_package_version).with(name, ['contrib', 'centosplus'], [], [])
provider.latest
end
it "passes the value of disablerepo install_options when querying" do
resource[:install_options] = [
{'--disablerepo' => 'updates'},
{'--disablerepo' => 'centosplus'},
]
provider.stubs(:properties).returns({:ensure => '3.4.5'})
described_class.expects(:latest_package_version).with(name, [], ['updates', 'centosplus'], [])
provider.latest
end
it "passes the value of disableexcludes install_options when querying" do
resource[:install_options] = [
{'--disableexcludes' => 'main'},
{'--disableexcludes' => 'centosplus'},
]
provider.stubs(:properties).returns({:ensure => '3.4.5'})
described_class.expects(:latest_package_version).with(name, [], [], ['main', 'centosplus'])
provider.latest
end
describe 'and a newer version is not available' do
before :each do
described_class.stubs(:latest_package_version).with(name, [], [], []).returns nil
end
it 'raises an error the package is not installed' do
provider.stubs(:properties).returns({:ensure => :absent})
expect {
provider.latest
}.to raise_error(Puppet::DevError, 'Tried to get latest on a missing package')
end
it 'returns version of the currently installed package' do
provider.stubs(:properties).returns({:ensure => '3.4.5'})
- provider.latest.should == '3.4.5'
+ expect(provider.latest).to eq('3.4.5')
end
end
describe 'and a newer version is available' do
let(:latest_version) do
{
:name => name,
:epoch => '1',
:version => '2.3.4',
:release => '5',
:arch => 'i686',
}
end
it 'includes the epoch in the version string' do
described_class.stubs(:latest_package_version).with(name, [], [], []).returns(latest_version)
- provider.latest.should == '1:2.3.4-5'
+ expect(provider.latest).to eq('1:2.3.4-5')
end
end
end
describe "lazy loading of latest package versions" do
before { described_class.clear }
after { described_class.clear }
let(:mypackage_version) do
{
:name => name,
:epoch => '1',
:version => '2.3.4',
:release => '5',
:arch => 'i686',
}
end
let(:mypackage_newerversion) do
{
:name => name,
:epoch => '1',
:version => '4.5.6',
:release => '7',
:arch => 'i686',
}
end
let(:latest_versions) { {name => [mypackage_version]} }
let(:enabled_versions) { {name => [mypackage_newerversion]} }
it "returns the version hash if the package was found" do
described_class.expects(:check_updates).with([], [], []).once.returns(latest_versions)
version = described_class.latest_package_version(name, [], [], [])
expect(version).to eq(mypackage_version)
end
it "is nil if the package was not found in the query" do
described_class.expects(:check_updates).with([], [], []).once.returns(latest_versions)
version = described_class.latest_package_version('nopackage', [], [], [])
expect(version).to be_nil
end
it "caches the package list and reuses that for subsequent queries" do
described_class.expects(:check_updates).with([], [], []).once.returns(latest_versions)
2.times {
version = described_class.latest_package_version(name, [], [], [])
expect(version).to eq mypackage_version
}
end
it "caches separate lists for each combination of 'enablerepo' and 'disablerepo' and 'disableexcludes'" do
described_class.expects(:check_updates).with([], [], []).once.returns(latest_versions)
described_class.expects(:check_updates).with(['enabled'], ['disabled'], ['disableexcludes']).once.returns(enabled_versions)
2.times {
version = described_class.latest_package_version(name, [], [], [])
expect(version).to eq mypackage_version
}
2.times {
version = described_class.latest_package_version(name, ['enabled'], ['disabled'], ['disableexcludes'])
expect(version).to eq(mypackage_newerversion)
}
end
end
describe "executing yum check-update" do
before do
described_class.stubs(:command).with(:yum).returns '/usr/bin/yum'
end
it "passes repos to enable to 'yum check-update'" do
Puppet::Util::Execution.expects(:execute).with do |args, *rest|
expect(args).to eq %w[/usr/bin/yum check-update --enablerepo=updates --enablerepo=centosplus]
end.returns(stub(:exitstatus => 0))
described_class.check_updates(%w[updates centosplus], [], [])
end
it "passes repos to disable to 'yum check-update'" do
Puppet::Util::Execution.expects(:execute).with do |args, *rest|
expect(args).to eq %w[/usr/bin/yum check-update --disablerepo=updates --disablerepo=centosplus]
end.returns(stub(:exitstatus => 0))
described_class.check_updates([],%w[updates centosplus], [])
end
it "passes a combination of repos to enable and disable to 'yum check-update'" do
Puppet::Util::Execution.expects(:execute).with do |args, *rest|
expect(args).to eq %w[/usr/bin/yum check-update --enablerepo=os --enablerepo=contrib --disablerepo=updates --disablerepo=centosplus]
end.returns(stub(:exitstatus => 0))
described_class.check_updates(%w[os contrib], %w[updates centosplus], [])
end
it "passes disableexcludes to 'yum check-update'" do
Puppet::Util::Execution.expects(:execute).with do |args, *rest|
expect(args).to eq %w[/usr/bin/yum check-update --disableexcludes=main --disableexcludes=centosplus]
end.returns(stub(:exitstatus => 0))
described_class.check_updates([], [], %w[main centosplus])
end
it "passes all options to 'yum check-update'" do
Puppet::Util::Execution.expects(:execute).with do |args, *rest|
expect(args).to eq %w[/usr/bin/yum check-update --enablerepo=a --enablerepo=b --disablerepo=c
--disablerepo=d --disableexcludes=e --disableexcludes=f]
end.returns(stub(:exitstatus => 0))
described_class.check_updates(%w[a b], %w[c d], %w[e f])
end
it "returns an empty hash if 'yum check-update' returned 0" do
Puppet::Util::Execution.expects(:execute).returns(stub :exitstatus => 0)
expect(described_class.check_updates([], [], [])).to be_empty
end
it "returns a populated hash if 'yum check-update returned 100'" do
output = stub(:exitstatus => 100)
Puppet::Util::Execution.expects(:execute).returns(output)
described_class.expects(:parse_updates).with(output).returns({:has => :updates})
expect(described_class.check_updates([], [], [])).to eq({:has => :updates})
end
it "returns an empty hash if 'yum check-update' returned an exit code that was not 0 or 100" do
Puppet::Util::Execution.expects(:execute).returns(stub(:exitstatus => 1))
described_class.expects(:warn)
expect(described_class.check_updates([], [], [])).to eq({})
end
end
describe "parsing the output of check-update" do
let(:check_update) do
# Trailing whitespace is intentional
<<-EOD
Loaded plugins: fastestmirror
Determining fastest mirrors
* base: centos.sonn.com
* epel: ftp.osuosl.org
* extras: mirror.web-ster.com
* updates: centos.sonn.com
curl.i686 7.32.0-10.fc20 updates
curl.x86_64 7.32.0-10.fc20 updates
gawk.i686 4.1.0-3.fc20 updates
dhclient.i686 12:4.1.1-38.P1.fc20 updates
selinux-policy.noarch 3.12.1-163.fc20 updates-testing
EOD
end
it 'creates an entry for each package keyed on the package name' do
output = described_class.parse_updates(check_update)
expect(output['curl']).to eq([{:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'i686'}, {:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'x86_64'}])
expect(output['gawk']).to eq([{:name => 'gawk', :epoch => '0', :version => '4.1.0', :release => '3.fc20', :arch => 'i686'}])
expect(output['dhclient']).to eq([{:name => 'dhclient', :epoch => '12', :version => '4.1.1', :release => '38.P1.fc20', :arch => 'i686'}])
expect(output['selinux-policy']).to eq([{:name => 'selinux-policy', :epoch => '0', :version => '3.12.1', :release => '163.fc20', :arch => 'noarch'}])
end
it 'creates an entry for each package keyed on the package name and package architecture' do
output = described_class.parse_updates(check_update)
expect(output['curl.i686']).to eq([{:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'i686'}])
expect(output['curl.x86_64']).to eq([{:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'x86_64'}])
expect(output['gawk.i686']).to eq([{:name => 'gawk', :epoch => '0', :version => '4.1.0', :release => '3.fc20', :arch => 'i686'}])
expect(output['dhclient.i686']).to eq([{:name => 'dhclient', :epoch => '12', :version => '4.1.1', :release => '38.P1.fc20', :arch => 'i686'}])
expect(output['selinux-policy.noarch']).to eq([{:name => 'selinux-policy', :epoch => '0', :version => '3.12.1', :release => '163.fc20', :arch => 'noarch'}])
end
end
describe "parsing a line from yum check-update" do
it "splits up the package name and architecture fields" do
checkupdate = "curl.i686 7.32.0-10.fc20 updates"
parsed = described_class.update_to_hash(checkupdate)
expect(parsed[:name]).to eq 'curl'
expect(parsed[:arch]).to eq 'i686'
end
it "splits up the epoch, version, and release fields" do
checkupdate = "dhclient.i686 12:4.1.1-38.P1.el6.centos base"
parsed = described_class.update_to_hash(checkupdate)
expect(parsed[:epoch]).to eq '12'
expect(parsed[:version]).to eq '4.1.1'
expect(parsed[:release]).to eq '38.P1.el6.centos'
end
it "sets the epoch to 0 when an epoch is not specified" do
checkupdate = "curl.i686 7.32.0-10.fc20 updates"
parsed = described_class.update_to_hash(checkupdate)
expect(parsed[:epoch]).to eq '0'
expect(parsed[:version]).to eq '7.32.0'
expect(parsed[:release]).to eq '10.fc20'
end
end
end
diff --git a/spec/unit/provider/package/zypper_spec.rb b/spec/unit/provider/package/zypper_spec.rb
index 2c5fff50b..3265858b7 100755
--- a/spec/unit/provider/package/zypper_spec.rb
+++ b/spec/unit/provider/package/zypper_spec.rb
@@ -1,186 +1,186 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:package).provider(:zypper)
describe provider_class do
before(:each) do
# Create a mock resource
@resource = stub 'resource'
# A catch all; no parameters set
@resource.stubs(:[]).returns(nil)
# But set name and source
@resource.stubs(:[]).with(:name).returns "mypackage"
@resource.stubs(:[]).with(:ensure).returns :installed
@resource.stubs(:command).with(:zypper).returns "/usr/bin/zypper"
@provider = provider_class.new(@resource)
end
it "should have an install method" do
@provider = provider_class.new
- @provider.should respond_to(:install)
+ expect(@provider).to respond_to(:install)
end
it "should have an uninstall method" do
@provider = provider_class.new
- @provider.should respond_to(:uninstall)
+ expect(@provider).to respond_to(:uninstall)
end
it "should have an update method" do
@provider = provider_class.new
- @provider.should respond_to(:update)
+ expect(@provider).to respond_to(:update)
end
it "should have a latest method" do
@provider = provider_class.new
- @provider.should respond_to(:latest)
+ expect(@provider).to respond_to(:latest)
end
it "should have a install_options method" do
@provider = provider_class.new
- @provider.should respond_to(:install_options)
+ expect(@provider).to respond_to(:install_options)
end
describe "when installing with zypper version >= 1.0" do
it "should use a command-line with versioned package'" do
@resource.stubs(:should).with(:ensure).returns "1.2.3-4.5.6"
@resource.stubs(:allow_virtual?).returns false
@provider.stubs(:zypper_version).returns "1.2.8"
@provider.expects(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', 'mypackage-1.2.3-4.5.6')
@provider.expects(:query).returns "mypackage 0 1.2.3 4.5.6 x86_64"
@provider.install
end
it "should use a command-line without versioned package" do
@resource.stubs(:should).with(:ensure).returns :latest
@resource.stubs(:allow_virtual?).returns false
@provider.stubs(:zypper_version).returns "1.2.8"
@provider.expects(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', '--name', 'mypackage')
@provider.expects(:query).returns "mypackage 0 1.2.3 4.5.6 x86_64"
@provider.install
end
end
describe "when installing with zypper version = 0.6.104" do
it "should use a command-line with versioned package'" do
@resource.stubs(:should).with(:ensure).returns "1.2.3-4.5.6"
@resource.stubs(:allow_virtual?).returns false
@provider.stubs(:zypper_version).returns "0.6.104"
@provider.expects(:zypper).with('--terse', :install, '--auto-agree-with-licenses', '--no-confirm', 'mypackage-1.2.3-4.5.6')
@provider.expects(:query).returns "mypackage 0 1.2.3 4.5.6 x86_64"
@provider.install
end
it "should use a command-line without versioned package" do
@resource.stubs(:should).with(:ensure).returns :latest
@resource.stubs(:allow_virtual?).returns false
@provider.stubs(:zypper_version).returns "0.6.104"
@provider.expects(:zypper).with('--terse', :install, '--auto-agree-with-licenses', '--no-confirm', '--name', 'mypackage')
@provider.expects(:query).returns "mypackage 0 1.2.3 4.5.6 x86_64"
@provider.install
end
end
describe "when installing with zypper version = 0.6.13" do
it "should use a command-line with versioned package'" do
@resource.stubs(:should).with(:ensure).returns "1.2.3-4.5.6"
@resource.stubs(:allow_virtual?).returns false
@provider.stubs(:zypper_version).returns "0.6.13"
@provider.expects(:zypper).with('--terse', :install, '--no-confirm', 'mypackage-1.2.3-4.5.6')
@provider.expects(:query).returns "mypackage 0 1.2.3 4.5.6 x86_64"
@provider.install
end
it "should use a command-line without versioned package" do
@resource.stubs(:should).with(:ensure).returns :latest
@resource.stubs(:allow_virtual?).returns false
@provider.stubs(:zypper_version).returns "0.6.13"
@provider.expects(:zypper).with('--terse', :install, '--no-confirm', '--name', 'mypackage')
@provider.expects(:query).returns "mypackage 0 1.2.3 4.5.6 x86_64"
@provider.install
end
end
describe "when updating" do
it "should call install method of instance" do
@provider.expects(:install)
@provider.update
end
end
describe "when getting latest version" do
it "should return a version string with valid list-updates data from SLES11sp1" do
fake_data = File.read(my_fixture('zypper-list-updates-SLES11sp1.out'))
@resource.stubs(:[]).with(:name).returns "at"
@provider.expects(:zypper).with("list-updates").returns fake_data
- @provider.latest.should == "3.1.8-1069.18.2"
+ expect(@provider.latest).to eq("3.1.8-1069.18.2")
end
end
it "should install a virtual package" do
@resource.stubs(:should).with(:ensure).returns :installed
@resource.stubs(:allow_virtual?).returns true
@provider.stubs(:zypper_version).returns "0.6.13"
@provider.expects(:zypper).with('--terse', :install, '--no-confirm', 'mypackage')
@provider.expects(:query).returns "mypackage 0 1.2.3 4.5.6 x86_64"
@provider.install
end
describe "when installing with zypper install options" do
it "should install the package without checking keys" do
@resource.stubs(:[]).with(:name).returns "php5"
@resource.stubs(:[]).with(:install_options).returns ['--no-gpg-check', {'-p' => '/vagrant/files/localrepo/'}]
@resource.stubs(:should).with(:ensure).returns "5.4.10-4.5.6"
@resource.stubs(:allow_virtual?).returns false
@provider.stubs(:zypper_version).returns "1.2.8"
@provider.expects(:zypper).with('--quiet', :install,
'--auto-agree-with-licenses', '--no-confirm', '--no-gpg-check', '-p=/vagrant/files/localrepo/', 'php5-5.4.10-4.5.6')
@provider.expects(:query).returns "php5 0 5.4.10 4.5.6 x86_64"
@provider.install
end
it "should install package with hash install options" do
@resource.stubs(:[]).with(:name).returns 'vim'
@resource.stubs(:[]).with(:install_options).returns([{ '--a' => 'foo', '--b' => '"quoted bar"' }])
@resource.stubs(:should).with(:ensure).returns :present
@resource.stubs(:allow_virtual?).returns false
@provider.stubs(:zypper_version).returns '1.2.8'
@provider.expects(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', '--name', '--a=foo', '--b="quoted bar"', 'vim')
@provider.expects(:query).returns 'package vim is not installed'
@provider.install
end
it "should install package with array install options" do
@resource.stubs(:[]).with(:name).returns 'vim'
@resource.stubs(:[]).with(:install_options).returns([['--a', '--b', '--c']])
@resource.stubs(:should).with(:ensure).returns :present
@resource.stubs(:allow_virtual?).returns false
@provider.stubs(:zypper_version).returns '1.2.8'
@provider.expects(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', '--name', '--a', '--b', '--c', 'vim')
@provider.expects(:query).returns 'package vim is not installed'
@provider.install
end
it "should install package with string install options" do
@resource.stubs(:[]).with(:name).returns 'vim'
@resource.stubs(:[]).with(:install_options).returns(['--a --b --c'])
@resource.stubs(:should).with(:ensure).returns :present
@resource.stubs(:allow_virtual?).returns false
@provider.stubs(:zypper_version).returns '1.2.8'
@provider.expects(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', '--name', '--a --b --c', 'vim')
@provider.expects(:query).returns 'package vim is not installed'
@provider.install
end
end
end
diff --git a/spec/unit/provider/parsedfile_spec.rb b/spec/unit/provider/parsedfile_spec.rb
index b814bc7ee..da4dde24d 100755
--- a/spec/unit/provider/parsedfile_spec.rb
+++ b/spec/unit/provider/parsedfile_spec.rb
@@ -1,228 +1,228 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
require 'puppet'
require 'puppet/provider/parsedfile'
Puppet::Type.newtype(:parsedfile_type) do
newparam(:name)
newproperty(:target)
end
# Most of the tests for this are still in test/ral/provider/parsedfile.rb.
describe Puppet::Provider::ParsedFile do
# The ParsedFile provider class is meant to be used as an abstract base class
# but also stores a lot of state within the singleton class. To avoid
# sharing data between classes we construct an anonymous class that inherits
# the ParsedFile provider instead of directly working with the ParsedFile
# provider itself.
let(:parsed_type) do
Puppet::Type.type(:parsedfile_type)
end
let!(:provider) { parsed_type.provide(:parsedfile_provider, :parent => described_class) }
describe "when looking up records loaded from disk" do
it "should return nil if no records have been loaded" do
- provider.record?("foo").should be_nil
+ expect(provider.record?("foo")).to be_nil
end
end
describe "when generating a list of instances" do
it "should return an instance for each record parsed from all of the registered targets" do
provider.expects(:targets).returns %w{/one /two}
provider.stubs(:skip_record?).returns false
one = [:uno1, :uno2]
two = [:dos1, :dos2]
provider.expects(:prefetch_target).with("/one").returns one
provider.expects(:prefetch_target).with("/two").returns two
results = []
(one + two).each do |inst|
results << inst.to_s + "_instance"
provider.expects(:new).with(inst).returns(results[-1])
end
- provider.instances.should == results
+ expect(provider.instances).to eq(results)
end
it "should ignore target when retrieve fails" do
provider.expects(:targets).returns %w{/one /two /three}
provider.stubs(:skip_record?).returns false
provider.expects(:retrieve).with("/one").returns [
{:name => 'target1_record1'},
{:name => 'target1_record2'}
]
provider.expects(:retrieve).with("/two").raises Puppet::Util::FileType::FileReadError, "some error"
provider.expects(:retrieve).with("/three").returns [
{:name => 'target3_record1'},
{:name => 'target3_record2'}
]
Puppet.expects(:err).with('Could not prefetch parsedfile_type provider \'parsedfile_provider\' target \'/two\': some error. Treating as empty')
provider.expects(:new).with(:name => 'target1_record1', :on_disk => true, :target => '/one', :ensure => :present).returns 'r1'
provider.expects(:new).with(:name => 'target1_record2', :on_disk => true, :target => '/one', :ensure => :present).returns 'r2'
provider.expects(:new).with(:name => 'target3_record1', :on_disk => true, :target => '/three', :ensure => :present).returns 'r3'
provider.expects(:new).with(:name => 'target3_record2', :on_disk => true, :target => '/three', :ensure => :present).returns 'r4'
- provider.instances.should == %w{r1 r2 r3 r4}
+ expect(provider.instances).to eq(%w{r1 r2 r3 r4})
end
it "should skip specified records" do
provider.expects(:targets).returns %w{/one}
provider.expects(:skip_record?).with(:uno).returns false
provider.expects(:skip_record?).with(:dos).returns true
one = [:uno, :dos]
provider.expects(:prefetch_target).returns one
provider.expects(:new).with(:uno).returns "eh"
provider.expects(:new).with(:dos).never
provider.instances
end
end
describe "when matching resources to existing records" do
let(:first_resource) { stub(:one, :name => :one) }
let(:second_resource) { stub(:two, :name => :two) }
let(:resources) {{:one => first_resource, :two => second_resource}}
it "returns a resource if the record name matches the resource name" do
record = {:name => :one}
- provider.resource_for_record(record, resources).should be first_resource
+ expect(provider.resource_for_record(record, resources)).to be first_resource
end
it "doesn't return a resource if the record name doesn't match any resource names" do
record = {:name => :three}
- provider.resource_for_record(record, resources).should be_nil
+ expect(provider.resource_for_record(record, resources)).to be_nil
end
end
describe "when flushing a file's records to disk" do
before do
# This way we start with some @records, like we would in real life.
provider.stubs(:retrieve).returns []
provider.default_target = "/foo/bar"
provider.initvars
provider.prefetch
@filetype = Puppet::Util::FileType.filetype(:flat).new("/my/file")
Puppet::Util::FileType.filetype(:flat).stubs(:new).with("/my/file",nil).returns @filetype
@filetype.stubs(:write)
end
it "should back up the file being written if the filetype can be backed up" do
@filetype.expects(:backup)
provider.flush_target("/my/file")
end
it "should not try to back up the file if the filetype cannot be backed up" do
@filetype = Puppet::Util::FileType.filetype(:ram).new("/my/file")
Puppet::Util::FileType.filetype(:flat).expects(:new).returns @filetype
@filetype.stubs(:write)
provider.flush_target("/my/file")
end
it "should not back up the file more than once between calls to 'prefetch'" do
@filetype.expects(:backup).once
provider.flush_target("/my/file")
provider.flush_target("/my/file")
end
it "should back the file up again once the file has been reread" do
@filetype.expects(:backup).times(2)
provider.flush_target("/my/file")
provider.prefetch
provider.flush_target("/my/file")
end
end
describe "when flushing multiple files" do
describe "and an error is encountered" do
it "the other file does not fail" do
provider.stubs(:backup_target)
bad_file = 'broken'
good_file = 'writable'
bad_writer = mock 'bad'
bad_writer.expects(:write).raises(Exception, "Failed to write to bad file")
good_writer = mock 'good'
good_writer.expects(:write).returns(nil)
provider.stubs(:target_object).with(bad_file).returns(bad_writer)
provider.stubs(:target_object).with(good_file).returns(good_writer)
bad_resource = parsed_type.new(:name => 'one', :target => bad_file)
good_resource = parsed_type.new(:name => 'two', :target => good_file)
expect {
bad_resource.flush
}.to raise_error(Exception, "Failed to write to bad file")
good_resource.flush
end
end
end
end
describe "A very basic provider based on ParsedFile" do
include PuppetSpec::Files
let(:input_text) { File.read(my_fixture('simple.txt')) }
let(:target) { tmpfile('parsedfile_spec') }
let(:provider) do
example_provider_class = Class.new(Puppet::Provider::ParsedFile)
example_provider_class.default_target = target
# Setup some record rules
example_provider_class.instance_eval do
text_line :text, :match => %r{.}
end
example_provider_class.initvars
example_provider_class.prefetch
# evade a race between multiple invocations of the header method
example_provider_class.stubs(:header).
returns("# HEADER As added by puppet.\n")
example_provider_class
end
context "writing file contents back to disk" do
it "should not change anything except from adding a header" do
input_records = provider.parse(input_text)
- provider.to_file(input_records).
- should match provider.header + input_text
+ expect(provider.to_file(input_records)).
+ to match provider.header + input_text
end
end
context "rewriting a file containing a native header" do
let(:regex) { %r/^# HEADER.*third party\.\n/ }
let(:input_records) { provider.parse(input_text) }
before :each do
provider.stubs(:native_header_regex).returns(regex)
end
it "should move the native header to the top" do
- provider.to_file(input_records).should_not match /\A#{provider.header}/
+ expect(provider.to_file(input_records)).not_to match /\A#{provider.header}/
end
context "and dropping native headers found in input" do
before :each do
provider.stubs(:drop_native_header).returns(true)
end
it "should not include the native header in the output" do
- provider.to_file(input_records).should_not match regex
+ expect(provider.to_file(input_records)).not_to match regex
end
end
end
end
diff --git a/spec/unit/provider/scheduled_task/win32_taskscheduler_spec.rb b/spec/unit/provider/scheduled_task/win32_taskscheduler_spec.rb
index 9aabb469b..50911b135 100644
--- a/spec/unit/provider/scheduled_task/win32_taskscheduler_spec.rb
+++ b/spec/unit/provider/scheduled_task/win32_taskscheduler_spec.rb
@@ -1,1607 +1,1607 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/windows/taskscheduler' if Puppet.features.microsoft_windows?
shared_examples_for "a trigger that handles start_date and start_time" do
let(:trigger) do
described_class.new(
:name => 'Shared Test Task',
:command => 'C:\Windows\System32\notepad.exe'
).translate_hash_to_trigger(trigger_hash)
end
before :each do
Win32::TaskScheduler.any_instance.stubs(:save)
end
describe 'the given start_date' do
before :each do
trigger_hash['start_time'] = '00:00'
end
def date_component
{
'start_year' => trigger['start_year'],
'start_month' => trigger['start_month'],
'start_day' => trigger['start_day']
}
end
it 'should be able to be specified in ISO 8601 calendar date format' do
trigger_hash['start_date'] = '2011-12-31'
- date_component.should == {
+ expect(date_component).to eq({
'start_year' => 2011,
'start_month' => 12,
'start_day' => 31
- }
+ })
end
it 'should fail if before 1753-01-01' do
trigger_hash['start_date'] = '1752-12-31'
expect { date_component }.to raise_error(
Puppet::Error,
'start_date must be on or after 1753-01-01'
)
end
it 'should succeed if on 1753-01-01' do
trigger_hash['start_date'] = '1753-01-01'
- date_component.should == {
+ expect(date_component).to eq({
'start_year' => 1753,
'start_month' => 1,
'start_day' => 1
- }
+ })
end
it 'should succeed if after 1753-01-01' do
trigger_hash['start_date'] = '1753-01-02'
- date_component.should == {
+ expect(date_component).to eq({
'start_year' => 1753,
'start_month' => 1,
'start_day' => 2
- }
+ })
end
end
describe 'the given start_time' do
before :each do
trigger_hash['start_date'] = '2011-12-31'
end
def time_component
{
'start_hour' => trigger['start_hour'],
'start_minute' => trigger['start_minute']
}
end
it 'should be able to be specified as a 24-hour "hh:mm"' do
trigger_hash['start_time'] = '17:13'
- time_component.should == {
+ expect(time_component).to eq({
'start_hour' => 17,
'start_minute' => 13
- }
+ })
end
it 'should be able to be specified as a 12-hour "hh:mm am"' do
trigger_hash['start_time'] = '3:13 am'
- time_component.should == {
+ expect(time_component).to eq({
'start_hour' => 3,
'start_minute' => 13
- }
+ })
end
it 'should be able to be specified as a 12-hour "hh:mm pm"' do
trigger_hash['start_time'] = '3:13 pm'
- time_component.should == {
+ expect(time_component).to eq({
'start_hour' => 15,
'start_minute' => 13
- }
+ })
end
end
end
describe Puppet::Type.type(:scheduled_task).provider(:win32_taskscheduler), :if => Puppet.features.microsoft_windows? do
before :each do
Puppet::Type.type(:scheduled_task).stubs(:defaultprovider).returns(described_class)
end
describe 'when retrieving' do
before :each do
- @mock_task = mock
+ @mock_task = stub
@mock_task.responds_like(Win32::TaskScheduler.new)
described_class.any_instance.stubs(:task).returns(@mock_task)
Win32::TaskScheduler.stubs(:new).returns(@mock_task)
end
let(:resource) { Puppet::Type.type(:scheduled_task).new(:name => 'Test Task', :command => 'C:\Windows\System32\notepad.exe') }
describe 'the triggers for a task' do
describe 'with only one trigger' do
before :each do
@mock_task.expects(:trigger_count).returns(1)
end
it 'should handle a single daily trigger' do
@mock_task.expects(:trigger).with(0).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_DAILY,
'start_year' => 2011,
'start_month' => 9,
'start_day' => 12,
'start_hour' => 13,
'start_minute' => 20,
'flags' => 0,
'type' => { 'days_interval' => 2 },
})
- resource.provider.trigger.should == [{
+ expect(resource.provider.trigger).to eq([{
'start_date' => '2011-9-12',
'start_time' => '13:20',
'schedule' => 'daily',
'every' => '2',
'enabled' => true,
'index' => 0,
- }]
+ }])
end
it 'should handle a single weekly trigger' do
scheduled_days_of_week = Win32::TaskScheduler::MONDAY |
Win32::TaskScheduler::WEDNESDAY |
Win32::TaskScheduler::FRIDAY |
Win32::TaskScheduler::SUNDAY
@mock_task.expects(:trigger).with(0).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_WEEKLY,
'start_year' => 2011,
'start_month' => 9,
'start_day' => 12,
'start_hour' => 13,
'start_minute' => 20,
'flags' => 0,
'type' => {
'weeks_interval' => 2,
'days_of_week' => scheduled_days_of_week
}
})
- resource.provider.trigger.should == [{
+ expect(resource.provider.trigger).to eq([{
'start_date' => '2011-9-12',
'start_time' => '13:20',
'schedule' => 'weekly',
'every' => '2',
'day_of_week' => ['sun', 'mon', 'wed', 'fri'],
'enabled' => true,
'index' => 0,
- }]
+ }])
end
it 'should handle a single monthly date-based trigger' do
scheduled_months = Win32::TaskScheduler::JANUARY |
Win32::TaskScheduler::FEBRUARY |
Win32::TaskScheduler::AUGUST |
Win32::TaskScheduler::SEPTEMBER |
Win32::TaskScheduler::DECEMBER
# 1 3 5 15 'last'
scheduled_days = 1 | 1 << 2 | 1 << 4 | 1 << 14 | 1 << 31
@mock_task.expects(:trigger).with(0).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_MONTHLYDATE,
'start_year' => 2011,
'start_month' => 9,
'start_day' => 12,
'start_hour' => 13,
'start_minute' => 20,
'flags' => 0,
'type' => {
'months' => scheduled_months,
'days' => scheduled_days
}
})
- resource.provider.trigger.should == [{
+ expect(resource.provider.trigger).to eq([{
'start_date' => '2011-9-12',
'start_time' => '13:20',
'schedule' => 'monthly',
'months' => [1, 2, 8, 9, 12],
'on' => [1, 3, 5, 15, 'last'],
'enabled' => true,
'index' => 0,
- }]
+ }])
end
it 'should handle a single monthly day-of-week-based trigger' do
scheduled_months = Win32::TaskScheduler::JANUARY |
Win32::TaskScheduler::FEBRUARY |
Win32::TaskScheduler::AUGUST |
Win32::TaskScheduler::SEPTEMBER |
Win32::TaskScheduler::DECEMBER
scheduled_days_of_week = Win32::TaskScheduler::MONDAY |
Win32::TaskScheduler::WEDNESDAY |
Win32::TaskScheduler::FRIDAY |
Win32::TaskScheduler::SUNDAY
@mock_task.expects(:trigger).with(0).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_MONTHLYDOW,
'start_year' => 2011,
'start_month' => 9,
'start_day' => 12,
'start_hour' => 13,
'start_minute' => 20,
'flags' => 0,
'type' => {
'months' => scheduled_months,
'weeks' => Win32::TaskScheduler::FIRST_WEEK,
'days_of_week' => scheduled_days_of_week
}
})
- resource.provider.trigger.should == [{
+ expect(resource.provider.trigger).to eq([{
'start_date' => '2011-9-12',
'start_time' => '13:20',
'schedule' => 'monthly',
'months' => [1, 2, 8, 9, 12],
'which_occurrence' => 'first',
'day_of_week' => ['sun', 'mon', 'wed', 'fri'],
'enabled' => true,
'index' => 0,
- }]
+ }])
end
it 'should handle a single one-time trigger' do
@mock_task.expects(:trigger).with(0).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_ONCE,
'start_year' => 2011,
'start_month' => 9,
'start_day' => 12,
'start_hour' => 13,
'start_minute' => 20,
'flags' => 0,
})
- resource.provider.trigger.should == [{
+ expect(resource.provider.trigger).to eq([{
'start_date' => '2011-9-12',
'start_time' => '13:20',
'schedule' => 'once',
'enabled' => true,
'index' => 0,
- }]
+ }])
end
end
it 'should handle multiple triggers' do
@mock_task.expects(:trigger_count).returns(3)
@mock_task.expects(:trigger).with(0).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_ONCE,
'start_year' => 2011,
'start_month' => 10,
'start_day' => 13,
'start_hour' => 14,
'start_minute' => 21,
'flags' => 0,
})
@mock_task.expects(:trigger).with(1).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_ONCE,
'start_year' => 2012,
'start_month' => 11,
'start_day' => 14,
'start_hour' => 15,
'start_minute' => 22,
'flags' => 0,
})
@mock_task.expects(:trigger).with(2).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_ONCE,
'start_year' => 2013,
'start_month' => 12,
'start_day' => 15,
'start_hour' => 16,
'start_minute' => 23,
'flags' => 0,
})
- resource.provider.trigger.should =~ [
+ expect(resource.provider.trigger).to match_array([
{
'start_date' => '2011-10-13',
'start_time' => '14:21',
'schedule' => 'once',
'enabled' => true,
'index' => 0,
},
{
'start_date' => '2012-11-14',
'start_time' => '15:22',
'schedule' => 'once',
'enabled' => true,
'index' => 1,
},
{
'start_date' => '2013-12-15',
'start_time' => '16:23',
'schedule' => 'once',
'enabled' => true,
'index' => 2,
}
- ]
+ ])
end
it 'should skip triggers Win32::TaskScheduler cannot handle' do
@mock_task.expects(:trigger_count).returns(3)
@mock_task.expects(:trigger).with(0).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_ONCE,
'start_year' => 2011,
'start_month' => 10,
'start_day' => 13,
'start_hour' => 14,
'start_minute' => 21,
'flags' => 0,
})
@mock_task.expects(:trigger).with(1).raises(
Win32::TaskScheduler::Error.new('Unhandled trigger type!')
)
@mock_task.expects(:trigger).with(2).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_ONCE,
'start_year' => 2013,
'start_month' => 12,
'start_day' => 15,
'start_hour' => 16,
'start_minute' => 23,
'flags' => 0,
})
- resource.provider.trigger.should =~ [
+ expect(resource.provider.trigger).to match_array([
{
'start_date' => '2011-10-13',
'start_time' => '14:21',
'schedule' => 'once',
'enabled' => true,
'index' => 0,
},
{
'start_date' => '2013-12-15',
'start_time' => '16:23',
'schedule' => 'once',
'enabled' => true,
'index' => 2,
}
- ]
+ ])
end
it 'should skip trigger types Puppet does not handle' do
@mock_task.expects(:trigger_count).returns(3)
@mock_task.expects(:trigger).with(0).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_ONCE,
'start_year' => 2011,
'start_month' => 10,
'start_day' => 13,
'start_hour' => 14,
'start_minute' => 21,
'flags' => 0,
})
@mock_task.expects(:trigger).with(1).returns({
'trigger_type' => Win32::TaskScheduler::TASK_EVENT_TRIGGER_AT_LOGON,
})
@mock_task.expects(:trigger).with(2).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_ONCE,
'start_year' => 2013,
'start_month' => 12,
'start_day' => 15,
'start_hour' => 16,
'start_minute' => 23,
'flags' => 0,
})
- resource.provider.trigger.should =~ [
+ expect(resource.provider.trigger).to match_array([
{
'start_date' => '2011-10-13',
'start_time' => '14:21',
'schedule' => 'once',
'enabled' => true,
'index' => 0,
},
{
'start_date' => '2013-12-15',
'start_time' => '16:23',
'schedule' => 'once',
'enabled' => true,
'index' => 2,
}
- ]
+ ])
end
end
it 'should get the working directory from the working_directory on the task' do
@mock_task.expects(:working_directory).returns('C:\Windows\System32')
- resource.provider.working_dir.should == 'C:\Windows\System32'
+ expect(resource.provider.working_dir).to eq('C:\Windows\System32')
end
it 'should get the command from the application_name on the task' do
@mock_task.expects(:application_name).returns('C:\Windows\System32\notepad.exe')
- resource.provider.command.should == 'C:\Windows\System32\notepad.exe'
+ expect(resource.provider.command).to eq('C:\Windows\System32\notepad.exe')
end
it 'should get the command arguments from the parameters on the task' do
@mock_task.expects(:parameters).returns('these are my arguments')
- resource.provider.arguments.should == 'these are my arguments'
+ expect(resource.provider.arguments).to eq('these are my arguments')
end
it 'should get the user from the account_information on the task' do
@mock_task.expects(:account_information).returns('this is my user')
- resource.provider.user.should == 'this is my user'
+ expect(resource.provider.user).to eq('this is my user')
end
describe 'whether the task is enabled' do
it 'should report tasks with the disabled bit set as disabled' do
@mock_task.stubs(:flags).returns(Win32::TaskScheduler::DISABLED)
- resource.provider.enabled.should == :false
+ expect(resource.provider.enabled).to eq(:false)
end
it 'should report tasks without the disabled bit set as enabled' do
@mock_task.stubs(:flags).returns(~Win32::TaskScheduler::DISABLED)
- resource.provider.enabled.should == :true
+ expect(resource.provider.enabled).to eq(:true)
end
it 'should not consider triggers for determining if the task is enabled' do
@mock_task.stubs(:flags).returns(~Win32::TaskScheduler::DISABLED)
@mock_task.stubs(:trigger_count).returns(1)
@mock_task.stubs(:trigger).with(0).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_ONCE,
'start_year' => 2011,
'start_month' => 10,
'start_day' => 13,
'start_hour' => 14,
'start_minute' => 21,
'flags' => Win32::TaskScheduler::TASK_TRIGGER_FLAG_DISABLED,
})
- resource.provider.enabled.should == :true
+ expect(resource.provider.enabled).to eq(:true)
end
end
end
describe '#exists?' do
before :each do
- @mock_task = mock
+ @mock_task = stub
@mock_task.responds_like(Win32::TaskScheduler.new)
described_class.any_instance.stubs(:task).returns(@mock_task)
Win32::TaskScheduler.stubs(:new).returns(@mock_task)
end
let(:resource) { Puppet::Type.type(:scheduled_task).new(:name => 'Test Task', :command => 'C:\Windows\System32\notepad.exe') }
it "should delegate to Win32::TaskScheduler using the resource's name" do
@mock_task.expects(:exists?).with('Test Task').returns(true)
- resource.provider.exists?.should == true
+ expect(resource.provider.exists?).to eq(true)
end
end
describe '#clear_task' do
before :each do
- @mock_task = mock
- @new_mock_task = mock
+ @mock_task = stub
+ @new_mock_task = stub
@mock_task.responds_like(Win32::TaskScheduler.new)
@new_mock_task.responds_like(Win32::TaskScheduler.new)
Win32::TaskScheduler.stubs(:new).returns(@mock_task, @new_mock_task)
described_class.any_instance.stubs(:exists?).returns(false)
end
let(:resource) { Puppet::Type.type(:scheduled_task).new(:name => 'Test Task', :command => 'C:\Windows\System32\notepad.exe') }
it 'should clear the cached task object' do
- resource.provider.task.should == @mock_task
- resource.provider.task.should == @mock_task
+ expect(resource.provider.task).to eq(@mock_task)
+ expect(resource.provider.task).to eq(@mock_task)
resource.provider.clear_task
- resource.provider.task.should == @new_mock_task
+ expect(resource.provider.task).to eq(@new_mock_task)
end
it 'should clear the cached list of triggers for the task' do
@mock_task.stubs(:trigger_count).returns(1)
@mock_task.stubs(:trigger).with(0).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_ONCE,
'start_year' => 2011,
'start_month' => 10,
'start_day' => 13,
'start_hour' => 14,
'start_minute' => 21,
'flags' => 0,
})
@new_mock_task.stubs(:trigger_count).returns(1)
@new_mock_task.stubs(:trigger).with(0).returns({
'trigger_type' => Win32::TaskScheduler::TASK_TIME_TRIGGER_ONCE,
'start_year' => 2012,
'start_month' => 11,
'start_day' => 14,
'start_hour' => 15,
'start_minute' => 22,
'flags' => 0,
})
mock_task_trigger = {
'start_date' => '2011-10-13',
'start_time' => '14:21',
'schedule' => 'once',
'enabled' => true,
'index' => 0,
}
- resource.provider.trigger.should == [mock_task_trigger]
- resource.provider.trigger.should == [mock_task_trigger]
+ expect(resource.provider.trigger).to eq([mock_task_trigger])
+ expect(resource.provider.trigger).to eq([mock_task_trigger])
resource.provider.clear_task
- resource.provider.trigger.should == [{
+ expect(resource.provider.trigger).to eq([{
'start_date' => '2012-11-14',
'start_time' => '15:22',
'schedule' => 'once',
'enabled' => true,
'index' => 0,
- }]
+ }])
end
end
describe '.instances' do
it 'should use the list of .job files to construct the list of scheduled_tasks' do
job_files = ['foo.job', 'bar.job', 'baz.job']
Win32::TaskScheduler.any_instance.stubs(:tasks).returns(job_files)
job_files.each do |job|
job = File.basename(job, '.job')
described_class.expects(:new).with(:provider => :win32_taskscheduler, :name => job)
end
described_class.instances
end
end
describe '#user_insync?', :if => Puppet.features.microsoft_windows? do
let(:resource) { described_class.new(:name => 'foobar', :command => 'C:\Windows\System32\notepad.exe') }
it 'should consider the user as in sync if the name matches' do
Puppet::Util::Windows::SID.expects(:name_to_sid).with('joe').twice.returns('SID A')
- resource.should be_user_insync('joe', ['joe'])
+ expect(resource).to be_user_insync('joe', ['joe'])
end
it 'should consider the user as in sync if the current user is fully qualified' do
Puppet::Util::Windows::SID.expects(:name_to_sid).with('joe').returns('SID A')
Puppet::Util::Windows::SID.expects(:name_to_sid).with('MACHINE\joe').returns('SID A')
- resource.should be_user_insync('MACHINE\joe', ['joe'])
+ expect(resource).to be_user_insync('MACHINE\joe', ['joe'])
end
it 'should consider a current user of the empty string to be the same as the system user' do
Puppet::Util::Windows::SID.expects(:name_to_sid).with('system').twice.returns('SYSTEM SID')
- resource.should be_user_insync('', ['system'])
+ expect(resource).to be_user_insync('', ['system'])
end
it 'should consider different users as being different' do
Puppet::Util::Windows::SID.expects(:name_to_sid).with('joe').returns('SID A')
Puppet::Util::Windows::SID.expects(:name_to_sid).with('bob').returns('SID B')
- resource.should_not be_user_insync('joe', ['bob'])
+ expect(resource).not_to be_user_insync('joe', ['bob'])
end
end
describe '#trigger_insync?' do
let(:resource) { described_class.new(:name => 'foobar', :command => 'C:\Windows\System32\notepad.exe') }
it 'should not consider any extra current triggers as in sync' do
current = [
{'start_date' => '2011-09-12', 'start_time' => '15:15', 'schedule' => 'once'},
{'start_date' => '2012-10-13', 'start_time' => '16:16', 'schedule' => 'once'}
]
desired = {'start_date' => '2011-09-12', 'start_time' => '15:15', 'schedule' => 'once'}
- resource.should_not be_trigger_insync(current, desired)
+ expect(resource).not_to be_trigger_insync(current, desired)
end
it 'should not consider any extra desired triggers as in sync' do
current = {'start_date' => '2011-09-12', 'start_time' => '15:15', 'schedule' => 'once'}
desired = [
{'start_date' => '2011-09-12', 'start_time' => '15:15', 'schedule' => 'once'},
{'start_date' => '2012-10-13', 'start_time' => '16:16', 'schedule' => 'once'}
]
- resource.should_not be_trigger_insync(current, desired)
+ expect(resource).not_to be_trigger_insync(current, desired)
end
it 'should consider triggers to be in sync if the sets of current and desired triggers are equal' do
current = [
{'start_date' => '2011-09-12', 'start_time' => '15:15', 'schedule' => 'once'},
{'start_date' => '2012-10-13', 'start_time' => '16:16', 'schedule' => 'once'}
]
desired = [
{'start_date' => '2011-09-12', 'start_time' => '15:15', 'schedule' => 'once'},
{'start_date' => '2012-10-13', 'start_time' => '16:16', 'schedule' => 'once'}
]
- resource.should be_trigger_insync(current, desired)
+ expect(resource).to be_trigger_insync(current, desired)
end
end
describe '#triggers_same?' do
let(:provider) { described_class.new(:name => 'foobar', :command => 'C:\Windows\System32\notepad.exe') }
it "should not mutate triggers" do
current = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3}
current.freeze
desired = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30'}
desired.freeze
expect(provider).to be_triggers_same(current, desired)
end
it "ignores 'index' in current trigger" do
current = {'index' => 0, 'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3}
desired = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3}
expect(provider).to be_triggers_same(current, desired)
end
it "ignores 'enabled' in current triggger" do
current = {'enabled' => true, 'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3}
desired = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3}
expect(provider).to be_triggers_same(current, desired)
end
it "should not consider a disabled 'current' trigger to be the same" do
current = {'schedule' => 'once', 'enabled' => false}
desired = {'schedule' => 'once'}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it 'should not consider triggers with different schedules to be the same' do
current = {'schedule' => 'once'}
desired = {'schedule' => 'weekly'}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
describe 'start_date' do
it "considers triggers to be equal when start_date is not specified in the 'desired' trigger" do
current = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3}
desired = {'schedule' => 'daily', 'start_time' => '15:30', 'every' => 3}
- provider.should be_triggers_same(current, desired)
+ expect(provider).to be_triggers_same(current, desired)
end
end
describe 'comparing daily triggers' do
it "should consider 'desired' triggers not specifying 'every' to have the same value as the 'current' trigger" do
current = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3}
desired = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30'}
- provider.should be_triggers_same(current, desired)
+ expect(provider).to be_triggers_same(current, desired)
end
it "should consider different 'start_dates' as different triggers" do
current = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3}
desired = {'schedule' => 'daily', 'start_date' => '2012-09-12', 'start_time' => '15:30', 'every' => 3}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it "should consider different 'start_times' as different triggers" do
current = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3}
desired = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:31', 'every' => 3}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it 'should not consider differences in date formatting to be different triggers' do
current = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3}
desired = {'schedule' => 'weekly', 'start_date' => '2011-9-12', 'start_time' => '15:30', 'every' => 3}
- provider.should be_triggers_same(current, desired)
+ expect(provider).to be_triggers_same(current, desired)
end
it 'should not consider differences in time formatting to be different triggers' do
current = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '5:30', 'every' => 3}
desired = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '05:30', 'every' => 3}
- provider.should be_triggers_same(current, desired)
+ expect(provider).to be_triggers_same(current, desired)
end
it "should consider different 'every' as different triggers" do
current = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3}
desired = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 1}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it 'should consider triggers that are the same as being the same' do
trigger = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '01:30', 'every' => 1}
- provider.should be_triggers_same(trigger, trigger)
+ expect(provider).to be_triggers_same(trigger, trigger)
end
end
describe 'comparing one-time triggers' do
it "should consider different 'start_dates' as different triggers" do
current = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30'}
desired = {'schedule' => 'daily', 'start_date' => '2012-09-12', 'start_time' => '15:30'}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it "should consider different 'start_times' as different triggers" do
current = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:30'}
desired = {'schedule' => 'daily', 'start_date' => '2011-09-12', 'start_time' => '15:31'}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it 'should not consider differences in date formatting to be different triggers' do
current = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '15:30'}
desired = {'schedule' => 'weekly', 'start_date' => '2011-9-12', 'start_time' => '15:30'}
- provider.should be_triggers_same(current, desired)
+ expect(provider).to be_triggers_same(current, desired)
end
it 'should not consider differences in time formatting to be different triggers' do
current = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '1:30'}
desired = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '01:30'}
- provider.should be_triggers_same(current, desired)
+ expect(provider).to be_triggers_same(current, desired)
end
it 'should consider triggers that are the same as being the same' do
trigger = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '01:30'}
- provider.should be_triggers_same(trigger, trigger)
+ expect(provider).to be_triggers_same(trigger, trigger)
end
end
describe 'comparing monthly date-based triggers' do
it "should consider 'desired' triggers not specifying 'months' to have the same value as the 'current' trigger" do
current = {'schedule' => 'monthly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'months' => [3], 'on' => [1,'last']}
desired = {'schedule' => 'monthly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'on' => [1, 'last']}
- provider.should be_triggers_same(current, desired)
+ expect(provider).to be_triggers_same(current, desired)
end
it "should consider different 'start_dates' as different triggers" do
current = {'schedule' => 'monthly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'months' => [1, 2], 'on' => [1, 3, 5, 7]}
desired = {'schedule' => 'monthly', 'start_date' => '2011-10-12', 'start_time' => '15:30', 'months' => [1, 2], 'on' => [1, 3, 5, 7]}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it "should consider different 'start_times' as different triggers" do
current = {'schedule' => 'monthly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'months' => [1, 2], 'on' => [1, 3, 5, 7]}
desired = {'schedule' => 'monthly', 'start_date' => '2011-09-12', 'start_time' => '22:30', 'months' => [1, 2], 'on' => [1, 3, 5, 7]}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it 'should not consider differences in date formatting to be different triggers' do
current = {'schedule' => 'monthly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'months' => [1, 2], 'on' => [1, 3, 5, 7]}
desired = {'schedule' => 'monthly', 'start_date' => '2011-9-12', 'start_time' => '15:30', 'months' => [1, 2], 'on' => [1, 3, 5, 7]}
- provider.should be_triggers_same(current, desired)
+ expect(provider).to be_triggers_same(current, desired)
end
it 'should not consider differences in time formatting to be different triggers' do
current = {'schedule' => 'monthly', 'start_date' => '2011-09-12', 'start_time' => '5:30', 'months' => [1, 2], 'on' => [1, 3, 5, 7]}
desired = {'schedule' => 'monthly', 'start_date' => '2011-09-12', 'start_time' => '05:30', 'months' => [1, 2], 'on' => [1, 3, 5, 7]}
- provider.should be_triggers_same(current, desired)
+ expect(provider).to be_triggers_same(current, desired)
end
it "should consider different 'months' as different triggers" do
current = {'schedule' => 'monthly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'months' => [1, 2], 'on' => [1, 3, 5, 7]}
desired = {'schedule' => 'monthly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'months' => [1], 'on' => [1, 3, 5, 7]}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it "should consider different 'on' as different triggers" do
current = {'schedule' => 'monthly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'months' => [1, 2], 'on' => [1, 3, 5, 7]}
desired = {'schedule' => 'monthly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'months' => [1, 2], 'on' => [1, 5, 7]}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it 'should consider triggers that are the same as being the same' do
trigger = {'schedule' => 'monthly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'months' => [1, 2], 'on' => [1, 3, 5, 7]}
- provider.should be_triggers_same(trigger, trigger)
+ expect(provider).to be_triggers_same(trigger, trigger)
end
end
describe 'comparing monthly day-of-week-based triggers' do
it "should consider 'desired' triggers not specifying 'months' to have the same value as the 'current' trigger" do
current = {
'schedule' => 'monthly',
'start_date' => '2011-09-12',
'start_time' => '15:30',
'months' => [3],
'which_occurrence' => 'first',
'day_of_week' => ['mon', 'tues', 'sat']
}
desired = {
'schedule' => 'monthly',
'start_date' => '2011-09-12',
'start_time' => '15:30',
'which_occurrence' => 'first',
'day_of_week' => ['mon', 'tues', 'sat']
}
- provider.should be_triggers_same(current, desired)
+ expect(provider).to be_triggers_same(current, desired)
end
it "should consider different 'start_dates' as different triggers" do
current = {
'schedule' => 'monthly',
'start_date' => '2011-09-12',
'start_time' => '15:30',
'months' => [3],
'which_occurrence' => 'first',
'day_of_week' => ['mon', 'tues', 'sat']
}
desired = {
'schedule' => 'monthly',
'start_date' => '2011-10-12',
'start_time' => '15:30',
'months' => [3],
'which_occurrence' => 'first',
'day_of_week' => ['mon', 'tues', 'sat']
}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it "should consider different 'start_times' as different triggers" do
current = {
'schedule' => 'monthly',
'start_date' => '2011-09-12',
'start_time' => '15:30',
'months' => [3],
'which_occurrence' => 'first',
'day_of_week' => ['mon', 'tues', 'sat']
}
desired = {
'schedule' => 'monthly',
'start_date' => '2011-09-12',
'start_time' => '22:30',
'months' => [3],
'which_occurrence' => 'first',
'day_of_week' => ['mon', 'tues', 'sat']
}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it "should consider different 'months' as different triggers" do
current = {
'schedule' => 'monthly',
'start_date' => '2011-09-12',
'start_time' => '15:30',
'months' => [3],
'which_occurrence' => 'first',
'day_of_week' => ['mon', 'tues', 'sat']
}
desired = {
'schedule' => 'monthly',
'start_date' => '2011-09-12',
'start_time' => '15:30',
'months' => [3, 5, 7, 9],
'which_occurrence' => 'first',
'day_of_week' => ['mon', 'tues', 'sat']
}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it "should consider different 'which_occurrence' as different triggers" do
current = {
'schedule' => 'monthly',
'start_date' => '2011-09-12',
'start_time' => '15:30',
'months' => [3],
'which_occurrence' => 'first',
'day_of_week' => ['mon', 'tues', 'sat']
}
desired = {
'schedule' => 'monthly',
'start_date' => '2011-09-12',
'start_time' => '15:30',
'months' => [3],
'which_occurrence' => 'last',
'day_of_week' => ['mon', 'tues', 'sat']
}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it "should consider different 'day_of_week' as different triggers" do
current = {
'schedule' => 'monthly',
'start_date' => '2011-09-12',
'start_time' => '15:30',
'months' => [3],
'which_occurrence' => 'first',
'day_of_week' => ['mon', 'tues', 'sat']
}
desired = {
'schedule' => 'monthly',
'start_date' => '2011-09-12',
'start_time' => '15:30',
'months' => [3],
'which_occurrence' => 'first',
'day_of_week' => ['fri']
}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it 'should consider triggers that are the same as being the same' do
trigger = {
'schedule' => 'monthly',
'start_date' => '2011-09-12',
'start_time' => '15:30',
'months' => [3],
'which_occurrence' => 'first',
'day_of_week' => ['mon', 'tues', 'sat']
}
- provider.should be_triggers_same(trigger, trigger)
+ expect(provider).to be_triggers_same(trigger, trigger)
end
end
describe 'comparing weekly triggers' do
it "should consider 'desired' triggers not specifying 'day_of_week' to have the same value as the 'current' trigger" do
current = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3, 'day_of_week' => ['mon', 'wed', 'fri']}
desired = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3}
- provider.should be_triggers_same(current, desired)
+ expect(provider).to be_triggers_same(current, desired)
end
it "should consider different 'start_dates' as different triggers" do
current = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3, 'day_of_week' => ['mon', 'wed', 'fri']}
desired = {'schedule' => 'weekly', 'start_date' => '2011-10-12', 'start_time' => '15:30', 'every' => 3, 'day_of_week' => ['mon', 'wed', 'fri']}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it "should consider different 'start_times' as different triggers" do
current = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3, 'day_of_week' => ['mon', 'wed', 'fri']}
desired = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '22:30', 'every' => 3, 'day_of_week' => ['mon', 'wed', 'fri']}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it 'should not consider differences in date formatting to be different triggers' do
current = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3, 'day_of_week' => ['mon', 'wed', 'fri']}
desired = {'schedule' => 'weekly', 'start_date' => '2011-9-12', 'start_time' => '15:30', 'every' => 3, 'day_of_week' => ['mon', 'wed', 'fri']}
- provider.should be_triggers_same(current, desired)
+ expect(provider).to be_triggers_same(current, desired)
end
it 'should not consider differences in time formatting to be different triggers' do
current = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '1:30', 'every' => 3, 'day_of_week' => ['mon', 'wed', 'fri']}
desired = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '01:30', 'every' => 3, 'day_of_week' => ['mon', 'wed', 'fri']}
- provider.should be_triggers_same(current, desired)
+ expect(provider).to be_triggers_same(current, desired)
end
it "should consider different 'every' as different triggers" do
current = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 1, 'day_of_week' => ['mon', 'wed', 'fri']}
desired = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3, 'day_of_week' => ['mon', 'wed', 'fri']}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it "should consider different 'day_of_week' as different triggers" do
current = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3, 'day_of_week' => ['mon', 'wed', 'fri']}
desired = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3, 'day_of_week' => ['fri']}
- provider.should_not be_triggers_same(current, desired)
+ expect(provider).not_to be_triggers_same(current, desired)
end
it 'should consider triggers that are the same as being the same' do
trigger = {'schedule' => 'weekly', 'start_date' => '2011-09-12', 'start_time' => '15:30', 'every' => 3, 'day_of_week' => ['mon', 'wed', 'fri']}
- provider.should be_triggers_same(trigger, trigger)
+ expect(provider).to be_triggers_same(trigger, trigger)
end
end
end
describe '#normalized_date' do
it 'should format the date without leading zeros' do
- described_class.normalized_date('2011-01-01').should == '2011-1-1'
+ expect(described_class.normalized_date('2011-01-01')).to eq('2011-1-1')
end
end
describe '#normalized_time' do
it 'should format the time as {24h}:{minutes}' do
- described_class.normalized_time('8:37 PM').should == '20:37'
+ expect(described_class.normalized_time('8:37 PM')).to eq('20:37')
end
end
describe '#translate_hash_to_trigger' do
before :each do
@puppet_trigger = {
'start_date' => '2011-1-1',
'start_time' => '01:10'
}
end
let(:provider) { described_class.new(:name => 'Test Task', :command => 'C:\Windows\System32\notepad.exe') }
let(:trigger) { provider.translate_hash_to_trigger(@puppet_trigger) }
describe 'when given a one-time trigger' do
before :each do
@puppet_trigger['schedule'] = 'once'
end
it 'should set the trigger_type to Win32::TaskScheduler::ONCE' do
- trigger['trigger_type'].should == Win32::TaskScheduler::ONCE
+ expect(trigger['trigger_type']).to eq(Win32::TaskScheduler::ONCE)
end
it 'should not set a type' do
- trigger.should_not be_has_key('type')
+ expect(trigger).not_to be_has_key('type')
end
it "should require 'start_date'" do
@puppet_trigger.delete('start_date')
expect { trigger }.to raise_error(
Puppet::Error,
/Must specify 'start_date' when defining a one-time trigger/
)
end
it "should require 'start_time'" do
@puppet_trigger.delete('start_time')
expect { trigger }.to raise_error(
Puppet::Error,
/Must specify 'start_time' when defining a trigger/
)
end
it_behaves_like "a trigger that handles start_date and start_time" do
let(:trigger_hash) {{'schedule' => 'once' }}
end
end
describe 'when given a daily trigger' do
before :each do
@puppet_trigger['schedule'] = 'daily'
end
it "should default 'every' to 1" do
- trigger['type']['days_interval'].should == 1
+ expect(trigger['type']['days_interval']).to eq(1)
end
it "should use the specified value for 'every'" do
@puppet_trigger['every'] = 5
- trigger['type']['days_interval'].should == 5
+ expect(trigger['type']['days_interval']).to eq(5)
end
it "should default 'start_date' to 'today'" do
@puppet_trigger.delete('start_date')
today = Time.now
- trigger['start_year'].should == today.year
- trigger['start_month'].should == today.month
- trigger['start_day'].should == today.day
+ expect(trigger['start_year']).to eq(today.year)
+ expect(trigger['start_month']).to eq(today.month)
+ expect(trigger['start_day']).to eq(today.day)
end
it_behaves_like "a trigger that handles start_date and start_time" do
let(:trigger_hash) {{'schedule' => 'daily', 'every' => 1}}
end
end
describe 'when given a weekly trigger' do
before :each do
@puppet_trigger['schedule'] = 'weekly'
end
it "should default 'every' to 1" do
- trigger['type']['weeks_interval'].should == 1
+ expect(trigger['type']['weeks_interval']).to eq(1)
end
it "should use the specified value for 'every'" do
@puppet_trigger['every'] = 4
- trigger['type']['weeks_interval'].should == 4
+ expect(trigger['type']['weeks_interval']).to eq(4)
end
it "should default 'day_of_week' to be every day of the week" do
- trigger['type']['days_of_week'].should == Win32::TaskScheduler::MONDAY |
+ expect(trigger['type']['days_of_week']).to eq(Win32::TaskScheduler::MONDAY |
Win32::TaskScheduler::TUESDAY |
Win32::TaskScheduler::WEDNESDAY |
Win32::TaskScheduler::THURSDAY |
Win32::TaskScheduler::FRIDAY |
Win32::TaskScheduler::SATURDAY |
- Win32::TaskScheduler::SUNDAY
+ Win32::TaskScheduler::SUNDAY)
end
it "should use the specified value for 'day_of_week'" do
@puppet_trigger['day_of_week'] = ['mon', 'wed', 'fri']
- trigger['type']['days_of_week'].should == Win32::TaskScheduler::MONDAY |
+ expect(trigger['type']['days_of_week']).to eq(Win32::TaskScheduler::MONDAY |
Win32::TaskScheduler::WEDNESDAY |
- Win32::TaskScheduler::FRIDAY
+ Win32::TaskScheduler::FRIDAY)
end
it "should default 'start_date' to 'today'" do
@puppet_trigger.delete('start_date')
today = Time.now
- trigger['start_year'].should == today.year
- trigger['start_month'].should == today.month
- trigger['start_day'].should == today.day
+ expect(trigger['start_year']).to eq(today.year)
+ expect(trigger['start_month']).to eq(today.month)
+ expect(trigger['start_day']).to eq(today.day)
end
it_behaves_like "a trigger that handles start_date and start_time" do
let(:trigger_hash) {{'schedule' => 'weekly', 'every' => 1, 'day_of_week' => 'mon'}}
end
end
shared_examples_for 'a monthly schedule' do
it "should default 'months' to be every month" do
- trigger['type']['months'].should == Win32::TaskScheduler::JANUARY |
+ expect(trigger['type']['months']).to eq(Win32::TaskScheduler::JANUARY |
Win32::TaskScheduler::FEBRUARY |
Win32::TaskScheduler::MARCH |
Win32::TaskScheduler::APRIL |
Win32::TaskScheduler::MAY |
Win32::TaskScheduler::JUNE |
Win32::TaskScheduler::JULY |
Win32::TaskScheduler::AUGUST |
Win32::TaskScheduler::SEPTEMBER |
Win32::TaskScheduler::OCTOBER |
Win32::TaskScheduler::NOVEMBER |
- Win32::TaskScheduler::DECEMBER
+ Win32::TaskScheduler::DECEMBER)
end
it "should use the specified value for 'months'" do
@puppet_trigger['months'] = [2, 8]
- trigger['type']['months'].should == Win32::TaskScheduler::FEBRUARY |
- Win32::TaskScheduler::AUGUST
+ expect(trigger['type']['months']).to eq(Win32::TaskScheduler::FEBRUARY |
+ Win32::TaskScheduler::AUGUST)
end
end
describe 'when given a monthly date-based trigger' do
before :each do
@puppet_trigger['schedule'] = 'monthly'
@puppet_trigger['on'] = [7, 14]
end
it_behaves_like 'a monthly schedule'
it "should not allow 'which_occurrence' to be specified" do
@puppet_trigger['which_occurrence'] = 'first'
expect {trigger}.to raise_error(
Puppet::Error,
/Neither 'day_of_week' nor 'which_occurrence' can be specified when creating a monthly date-based trigger/
)
end
it "should not allow 'day_of_week' to be specified" do
@puppet_trigger['day_of_week'] = 'mon'
expect {trigger}.to raise_error(
Puppet::Error,
/Neither 'day_of_week' nor 'which_occurrence' can be specified when creating a monthly date-based trigger/
)
end
it "should require 'on'" do
@puppet_trigger.delete('on')
expect {trigger}.to raise_error(
Puppet::Error,
/Don't know how to create a 'monthly' schedule with the options: schedule, start_date, start_time/
)
end
it "should default 'start_date' to 'today'" do
@puppet_trigger.delete('start_date')
today = Time.now
- trigger['start_year'].should == today.year
- trigger['start_month'].should == today.month
- trigger['start_day'].should == today.day
+ expect(trigger['start_year']).to eq(today.year)
+ expect(trigger['start_month']).to eq(today.month)
+ expect(trigger['start_day']).to eq(today.day)
end
it_behaves_like "a trigger that handles start_date and start_time" do
let(:trigger_hash) {{'schedule' => 'monthly', 'months' => 1, 'on' => 1}}
end
end
describe 'when given a monthly day-of-week-based trigger' do
before :each do
@puppet_trigger['schedule'] = 'monthly'
@puppet_trigger['which_occurrence'] = 'first'
@puppet_trigger['day_of_week'] = 'mon'
end
it_behaves_like 'a monthly schedule'
it "should not allow 'on' to be specified" do
@puppet_trigger['on'] = 15
expect {trigger}.to raise_error(
Puppet::Error,
/Neither 'day_of_week' nor 'which_occurrence' can be specified when creating a monthly date-based trigger/
)
end
it "should require 'which_occurrence'" do
@puppet_trigger.delete('which_occurrence')
expect {trigger}.to raise_error(
Puppet::Error,
/which_occurrence must be specified when creating a monthly day-of-week based trigger/
)
end
it "should require 'day_of_week'" do
@puppet_trigger.delete('day_of_week')
expect {trigger}.to raise_error(
Puppet::Error,
/day_of_week must be specified when creating a monthly day-of-week based trigger/
)
end
it "should default 'start_date' to 'today'" do
@puppet_trigger.delete('start_date')
today = Time.now
- trigger['start_year'].should == today.year
- trigger['start_month'].should == today.month
- trigger['start_day'].should == today.day
+ expect(trigger['start_year']).to eq(today.year)
+ expect(trigger['start_month']).to eq(today.month)
+ expect(trigger['start_day']).to eq(today.day)
end
it_behaves_like "a trigger that handles start_date and start_time" do
let(:trigger_hash) {{'schedule' => 'monthly', 'months' => 1, 'which_occurrence' => 'first', 'day_of_week' => 'mon'}}
end
end
end
describe '#validate_trigger' do
let(:provider) { described_class.new(:name => 'Test Task', :command => 'C:\Windows\System32\notepad.exe') }
it 'should succeed if all passed triggers translate from hashes to triggers' do
triggers_to_validate = [
{'schedule' => 'once', 'start_date' => '2011-09-13', 'start_time' => '13:50'},
{'schedule' => 'weekly', 'start_date' => '2011-09-13', 'start_time' => '13:50', 'day_of_week' => 'mon'}
]
- provider.validate_trigger(triggers_to_validate).should == true
+ expect(provider.validate_trigger(triggers_to_validate)).to eq(true)
end
it 'should use the exception from translate_hash_to_trigger when it fails' do
triggers_to_validate = [
{'schedule' => 'once', 'start_date' => '2011-09-13', 'start_time' => '13:50'},
{'schedule' => 'monthly', 'this is invalid' => true}
]
expect {provider.validate_trigger(triggers_to_validate)}.to raise_error(
Puppet::Error,
/#{Regexp.escape("Unknown trigger option(s): ['this is invalid']")}/
)
end
end
describe '#flush' do
let(:resource) do
Puppet::Type.type(:scheduled_task).new(
:name => 'Test Task',
:command => 'C:\Windows\System32\notepad.exe',
:ensure => @ensure
)
end
before :each do
- @mock_task = mock
+ @mock_task = stub
@mock_task.responds_like(Win32::TaskScheduler.new)
@mock_task.stubs(:exists?).returns(true)
@mock_task.stubs(:activate)
Win32::TaskScheduler.stubs(:new).returns(@mock_task)
@command = 'C:\Windows\System32\notepad.exe'
end
describe 'when :ensure is :present' do
before :each do
@ensure = :present
end
it 'should save the task' do
@mock_task.expects(:save)
resource.provider.flush
end
it 'should fail if the command is not specified' do
resource = Puppet::Type.type(:scheduled_task).new(
:name => 'Test Task',
:ensure => @ensure
)
expect { resource.provider.flush }.to raise_error(
Puppet::Error,
'Parameter command is required.'
)
end
end
describe 'when :ensure is :absent' do
before :each do
@ensure = :absent
@mock_task.stubs(:activate)
end
it 'should not save the task if :ensure is :absent' do
@mock_task.expects(:save).never
resource.provider.flush
end
it 'should not fail if the command is not specified' do
@mock_task.stubs(:save)
resource = Puppet::Type.type(:scheduled_task).new(
:name => 'Test Task',
:ensure => @ensure
)
resource.provider.flush
end
end
end
describe 'property setter methods' do
let(:resource) do
Puppet::Type.type(:scheduled_task).new(
:name => 'Test Task',
:command => 'C:\dummy_task.exe'
)
end
before :each do
- @mock_task = mock
+ @mock_task = stub
@mock_task.responds_like(Win32::TaskScheduler.new)
@mock_task.stubs(:exists?).returns(true)
@mock_task.stubs(:activate)
Win32::TaskScheduler.stubs(:new).returns(@mock_task)
end
describe '#command=' do
it 'should set the application_name on the task' do
@mock_task.expects(:application_name=).with('C:\Windows\System32\notepad.exe')
resource.provider.command = 'C:\Windows\System32\notepad.exe'
end
end
describe '#arguments=' do
it 'should set the parameters on the task' do
@mock_task.expects(:parameters=).with(['/some /arguments /here'])
resource.provider.arguments = ['/some /arguments /here']
end
end
describe '#working_dir=' do
it 'should set the working_directory on the task' do
@mock_task.expects(:working_directory=).with('C:\Windows\System32')
resource.provider.working_dir = 'C:\Windows\System32'
end
end
describe '#enabled=' do
it 'should set the disabled flag if the task should be disabled' do
@mock_task.stubs(:flags).returns(0)
@mock_task.expects(:flags=).with(Win32::TaskScheduler::DISABLED)
resource.provider.enabled = :false
end
it 'should clear the disabled flag if the task should be enabled' do
@mock_task.stubs(:flags).returns(Win32::TaskScheduler::DISABLED)
@mock_task.expects(:flags=).with(0)
resource.provider.enabled = :true
end
end
describe '#trigger=' do
let(:resource) do
Puppet::Type.type(:scheduled_task).new(
:name => 'Test Task',
:command => 'C:\Windows\System32\notepad.exe',
:trigger => @trigger
)
end
before :each do
- @mock_task = mock
+ @mock_task = stub
@mock_task.responds_like(Win32::TaskScheduler.new)
@mock_task.stubs(:exists?).returns(true)
@mock_task.stubs(:activate)
Win32::TaskScheduler.stubs(:new).returns(@mock_task)
end
it 'should not consider all duplicate current triggers in sync with a single desired trigger' do
@trigger = {'schedule' => 'once', 'start_date' => '2011-09-15', 'start_time' => '15:10'}
current_triggers = [
{'schedule' => 'once', 'start_date' => '2011-09-15', 'start_time' => '15:10', 'index' => 0},
{'schedule' => 'once', 'start_date' => '2011-09-15', 'start_time' => '15:10', 'index' => 1},
{'schedule' => 'once', 'start_date' => '2011-09-15', 'start_time' => '15:10', 'index' => 2},
]
resource.provider.stubs(:trigger).returns(current_triggers)
@mock_task.expects(:delete_trigger).with(1)
@mock_task.expects(:delete_trigger).with(2)
resource.provider.trigger = @trigger
end
it 'should remove triggers not defined in the resource' do
@trigger = {'schedule' => 'once', 'start_date' => '2011-09-15', 'start_time' => '15:10'}
current_triggers = [
{'schedule' => 'once', 'start_date' => '2011-09-15', 'start_time' => '15:10', 'index' => 0},
{'schedule' => 'once', 'start_date' => '2012-09-15', 'start_time' => '15:10', 'index' => 1},
{'schedule' => 'once', 'start_date' => '2013-09-15', 'start_time' => '15:10', 'index' => 2},
]
resource.provider.stubs(:trigger).returns(current_triggers)
@mock_task.expects(:delete_trigger).with(1)
@mock_task.expects(:delete_trigger).with(2)
resource.provider.trigger = @trigger
end
it 'should add triggers defined in the resource, but not found on the system' do
@trigger = [
{'schedule' => 'once', 'start_date' => '2011-09-15', 'start_time' => '15:10'},
{'schedule' => 'once', 'start_date' => '2012-09-15', 'start_time' => '15:10'},
{'schedule' => 'once', 'start_date' => '2013-09-15', 'start_time' => '15:10'},
]
current_triggers = [
{'schedule' => 'once', 'start_date' => '2011-09-15', 'start_time' => '15:10', 'index' => 0},
]
resource.provider.stubs(:trigger).returns(current_triggers)
@mock_task.expects(:trigger=).with(resource.provider.translate_hash_to_trigger(@trigger[1]))
@mock_task.expects(:trigger=).with(resource.provider.translate_hash_to_trigger(@trigger[2]))
resource.provider.trigger = @trigger
end
end
describe '#user=', :if => Puppet.features.microsoft_windows? do
before :each do
- @mock_task = mock
+ @mock_task = stub
@mock_task.responds_like(Win32::TaskScheduler.new)
@mock_task.stubs(:exists?).returns(true)
@mock_task.stubs(:activate)
Win32::TaskScheduler.stubs(:new).returns(@mock_task)
end
it 'should use nil for user and password when setting the user to the SYSTEM account' do
Puppet::Util::Windows::SID.stubs(:name_to_sid).with('system').returns('SYSTEM SID')
resource = Puppet::Type.type(:scheduled_task).new(
:name => 'Test Task',
:command => 'C:\dummy_task.exe',
:user => 'system'
)
@mock_task.expects(:set_account_information).with(nil, nil)
resource.provider.user = 'system'
end
it 'should use the specified user and password when setting the user to anything other than SYSTEM' do
Puppet::Util::Windows::SID.stubs(:name_to_sid).with('my_user_name').returns('SID A')
resource = Puppet::Type.type(:scheduled_task).new(
:name => 'Test Task',
:command => 'C:\dummy_task.exe',
:user => 'my_user_name',
:password => 'my password'
)
@mock_task.expects(:set_account_information).with('my_user_name', 'my password')
resource.provider.user = 'my_user_name'
end
end
end
describe '#create' do
let(:resource) do
Puppet::Type.type(:scheduled_task).new(
:name => 'Test Task',
:enabled => @enabled,
:command => @command,
:arguments => @arguments,
:working_dir => @working_dir,
:trigger => { 'schedule' => 'once', 'start_date' => '2011-09-27', 'start_time' => '17:00' }
)
end
before :each do
@enabled = :true
@command = 'C:\Windows\System32\notepad.exe'
@arguments = '/a /list /of /arguments'
@working_dir = 'C:\Windows\Some\Directory'
- @mock_task = mock
+ @mock_task = stub
@mock_task.responds_like(Win32::TaskScheduler.new)
@mock_task.stubs(:exists?).returns(true)
@mock_task.stubs(:activate)
@mock_task.stubs(:application_name=)
@mock_task.stubs(:parameters=)
@mock_task.stubs(:working_directory=)
@mock_task.stubs(:set_account_information)
@mock_task.stubs(:flags)
@mock_task.stubs(:flags=)
@mock_task.stubs(:trigger_count).returns(0)
@mock_task.stubs(:trigger=)
@mock_task.stubs(:save)
Win32::TaskScheduler.stubs(:new).returns(@mock_task)
described_class.any_instance.stubs(:sync_triggers)
end
it 'should set the command' do
resource.provider.expects(:command=).with(@command)
resource.provider.create
end
it 'should set the arguments' do
resource.provider.expects(:arguments=).with(@arguments)
resource.provider.create
end
it 'should set the working_dir' do
resource.provider.expects(:working_dir=).with(@working_dir)
resource.provider.create
end
it "should set the user" do
resource.provider.expects(:user=).with(:system)
resource.provider.create
end
it 'should set the enabled property' do
resource.provider.expects(:enabled=)
resource.provider.create
end
it 'should sync triggers' do
resource.provider.expects(:trigger=)
resource.provider.create
end
end
end
diff --git a/spec/unit/provider/selboolean_spec.rb b/spec/unit/provider/selboolean_spec.rb
index 3b203c1df..6c12ed0d5 100755
--- a/spec/unit/provider/selboolean_spec.rb
+++ b/spec/unit/provider/selboolean_spec.rb
@@ -1,36 +1,36 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:selboolean).provider(:getsetsebool)
describe provider_class do
before :each do
@resource = stub("resource", :name => "foo")
@resource.stubs(:[]).returns "foo"
@provider = provider_class.new(@resource)
end
it "should return :on when getsebool returns on" do
@provider.expects(:getsebool).with("foo").returns "foo --> on\n"
- @provider.value.should == :on
+ expect(@provider.value).to eq(:on)
end
it "should return :off when getsebool returns on" do
@provider.expects(:getsebool).with("foo").returns "foo --> off\n"
- @provider.value.should == :off
+ expect(@provider.value).to eq(:off)
end
it "should call execpipe when updating boolean setting" do
@provider.expects(:command).with(:setsebool).returns "/usr/sbin/setsebool"
@provider.expects(:execpipe).with("/usr/sbin/setsebool foo off")
@provider.value = :off
end
it "should call execpipe with -P when updating persistent boolean setting" do
@resource.stubs(:[]).with(:persistent).returns :true
@provider.expects(:command).with(:setsebool).returns "/usr/sbin/setsebool"
@provider.expects(:execpipe).with("/usr/sbin/setsebool -P foo off")
@provider.value = :off
end
end
diff --git a/spec/unit/provider/selmodule_spec.rb b/spec/unit/provider/selmodule_spec.rb
index 2b89b6590..de50f7a22 100755
--- a/spec/unit/provider/selmodule_spec.rb
+++ b/spec/unit/provider/selmodule_spec.rb
@@ -1,73 +1,73 @@
#! /usr/bin/env ruby
# Note: This unit test depends on having a sample SELinux policy file
# in the same directory as this test called selmodule-example.pp
# with version 1.5.0. The provided selmodule-example.pp is the first
# 256 bytes taken from /usr/share/selinux/targeted/nagios.pp on Fedora 9
require 'spec_helper'
require 'stringio'
provider_class = Puppet::Type.type(:selmodule).provider(:semodule)
describe provider_class do
before :each do
@resource = stub("resource", :name => "foo")
@resource.stubs(:[]).returns "foo"
@provider = provider_class.new(@resource)
end
describe "exists? method" do
it "should find a module if it is already loaded" do
@provider.expects(:command).with(:semodule).returns "/usr/sbin/semodule"
@provider.expects(:execpipe).with("/usr/sbin/semodule --list").yields StringIO.new("bar\t1.2.3\nfoo\t4.4.4\nbang\t1.0.0\n")
- @provider.exists?.should == :true
+ expect(@provider.exists?).to eq(:true)
end
it "should return nil if not loaded" do
@provider.expects(:command).with(:semodule).returns "/usr/sbin/semodule"
@provider.expects(:execpipe).with("/usr/sbin/semodule --list").yields StringIO.new("bar\t1.2.3\nbang\t1.0.0\n")
- @provider.exists?.should be_nil
+ expect(@provider.exists?).to be_nil
end
it "should return nil if no modules are loaded" do
@provider.expects(:command).with(:semodule).returns "/usr/sbin/semodule"
@provider.expects(:execpipe).with("/usr/sbin/semodule --list").yields StringIO.new("")
- @provider.exists?.should be_nil
+ expect(@provider.exists?).to be_nil
end
end
describe "selmodversion_file" do
it "should return 1.5.0 for the example policy file" do
@provider.expects(:selmod_name_to_filename).returns "#{File.dirname(__FILE__)}/selmodule-example.pp"
- @provider.selmodversion_file.should == "1.5.0"
+ expect(@provider.selmodversion_file).to eq("1.5.0")
end
end
describe "syncversion" do
it "should return :true if loaded and file modules are in sync" do
@provider.expects(:selmodversion_loaded).returns "1.5.0"
@provider.expects(:selmodversion_file).returns "1.5.0"
- @provider.syncversion.should == :true
+ expect(@provider.syncversion).to eq(:true)
end
it "should return :false if loaded and file modules are not in sync" do
@provider.expects(:selmodversion_loaded).returns "1.4.0"
@provider.expects(:selmodversion_file).returns "1.5.0"
- @provider.syncversion.should == :false
+ expect(@provider.syncversion).to eq(:false)
end
it "should return before checking file version if no loaded policy" do
@provider.expects(:selmodversion_loaded).returns nil
- @provider.syncversion.should == :false
+ expect(@provider.syncversion).to eq(:false)
end
end
describe "selmodversion_loaded" do
it "should return the version of a loaded module" do
@provider.expects(:command).with(:semodule).returns "/usr/sbin/semodule"
@provider.expects(:execpipe).with("/usr/sbin/semodule --list").yields StringIO.new("bar\t1.2.3\nfoo\t4.4.4\nbang\t1.0.0\n")
- @provider.selmodversion_loaded.should == "4.4.4"
+ expect(@provider.selmodversion_loaded).to eq("4.4.4")
end
end
end
diff --git a/spec/unit/provider/service/base_spec.rb b/spec/unit/provider/service/base_spec.rb
index eb8c65034..90613df7c 100755
--- a/spec/unit/provider/service/base_spec.rb
+++ b/spec/unit/provider/service/base_spec.rb
@@ -1,77 +1,77 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'rbconfig'
require 'fileutils'
provider_class = Puppet::Type.type(:service).provider(:init)
describe "base service provider" do
include PuppetSpec::Files
let :type do Puppet::Type.type(:service) end
let :provider do type.provider(:base) end
subject { provider }
context "basic operations" do
# Cross-platform file interactions. Fun times.
Ruby = File.join(RbConfig::CONFIG["bindir"],
RbConfig::CONFIG["RUBY_INSTALL_NAME"] +
RbConfig::CONFIG["EXEEXT"])
Start = [Ruby, '-rfileutils', '-e', 'FileUtils.touch(ARGV[0])']
Status = [Ruby, '-e' 'exit File.file?(ARGV[0])']
Stop = [Ruby, '-e', 'File.exist?(ARGV[0]) and File.unlink(ARGV[0])']
let :flag do tmpfile('base-service-test') end
subject do
type.new(:name => "test", :provider => :base,
:start => Start + [flag],
:status => Status + [flag],
:stop => Stop + [flag]
).provider
end
before :each do
Puppet::FileSystem.unlink(flag) if Puppet::FileSystem.exist?(flag)
end
- it { should be }
+ it { is_expected.to be }
it "should invoke the start command if not running" do
- File.should_not be_file(flag)
+ expect(File).not_to be_file(flag)
subject.start
- File.should be_file(flag)
+ expect(File).to be_file(flag)
end
it "should be stopped before being started" do
- subject.status.should == :stopped
+ expect(subject.status).to eq(:stopped)
end
it "should be running after being started" do
subject.start
- subject.status.should == :running
+ expect(subject.status).to eq(:running)
end
it "should invoke the stop command when asked" do
subject.start
- subject.status.should == :running
+ expect(subject.status).to eq(:running)
subject.stop
- subject.status.should == :stopped
- File.should_not be_file(flag)
+ expect(subject.status).to eq(:stopped)
+ expect(File).not_to be_file(flag)
end
it "should start again even if already running" do
subject.start
subject.expects(:ucommand).with(:start)
subject.start
end
it "should stop again even if already stopped" do
subject.stop
subject.expects(:ucommand).with(:stop)
subject.stop
end
end
end
diff --git a/spec/unit/provider/service/daemontools_spec.rb b/spec/unit/provider/service/daemontools_spec.rb
index 57bf632c2..3be1ec956 100755
--- a/spec/unit/provider/service/daemontools_spec.rb
+++ b/spec/unit/provider/service/daemontools_spec.rb
@@ -1,171 +1,171 @@
#! /usr/bin/env ruby
#
# Unit testing for the Daemontools service Provider
#
# author Brice Figureau
#
require 'spec_helper'
provider_class = Puppet::Type.type(:service).provider(:daemontools)
describe provider_class do
before(:each) do
# Create a mock resource
@resource = stub 'resource'
@provider = provider_class.new
@servicedir = "/etc/service"
@provider.servicedir=@servicedir
@daemondir = "/var/lib/service"
@provider.class.defpath=@daemondir
# A catch all; no parameters set
@resource.stubs(:[]).returns(nil)
# But set name, source and path (because we won't run
# the thing that will fetch the resource path from the provider)
@resource.stubs(:[]).with(:name).returns "myservice"
@resource.stubs(:[]).with(:ensure).returns :enabled
@resource.stubs(:[]).with(:path).returns @daemondir
@resource.stubs(:ref).returns "Service[myservice]"
@provider.resource = @resource
@provider.stubs(:command).with(:svc).returns "svc"
@provider.stubs(:command).with(:svstat).returns "svstat"
@provider.stubs(:svc)
@provider.stubs(:svstat)
end
it "should have a restart method" do
- @provider.should respond_to(:restart)
+ expect(@provider).to respond_to(:restart)
end
it "should have a start method" do
- @provider.should respond_to(:start)
+ expect(@provider).to respond_to(:start)
end
it "should have a stop method" do
- @provider.should respond_to(:stop)
+ expect(@provider).to respond_to(:stop)
end
it "should have an enabled? method" do
- @provider.should respond_to(:enabled?)
+ expect(@provider).to respond_to(:enabled?)
end
it "should have an enable method" do
- @provider.should respond_to(:enable)
+ expect(@provider).to respond_to(:enable)
end
it "should have a disable method" do
- @provider.should respond_to(:disable)
+ expect(@provider).to respond_to(:disable)
end
describe "when starting" do
it "should use 'svc' to start the service" do
@provider.stubs(:enabled?).returns :true
@provider.expects(:svc).with("-u", "/etc/service/myservice")
@provider.start
end
it "should enable the service if it is not enabled" do
@provider.stubs(:svc)
@provider.expects(:enabled?).returns :false
@provider.expects(:enable)
@provider.start
end
end
describe "when stopping" do
it "should use 'svc' to stop the service" do
@provider.stubs(:disable)
@provider.expects(:svc).with("-d", "/etc/service/myservice")
@provider.stop
end
end
describe "when restarting" do
it "should use 'svc' to restart the service" do
@provider.expects(:svc).with("-t", "/etc/service/myservice")
@provider.restart
end
end
describe "when enabling" do
it "should create a symlink between daemon dir and service dir", :if => Puppet.features.manages_symlinks? do
daemon_path = File.join(@daemondir, "myservice")
service_path = File.join(@servicedir, "myservice")
Puppet::FileSystem.expects(:symlink?).with(service_path).returns(false)
Puppet::FileSystem.expects(:symlink).with(daemon_path, service_path).returns(0)
@provider.enable
end
end
describe "when disabling" do
it "should remove the symlink between daemon dir and service dir" do
FileTest.stubs(:directory?).returns(false)
path = File.join(@servicedir,"myservice")
Puppet::FileSystem.expects(:symlink?).with(path).returns(true)
Puppet::FileSystem.expects(:unlink).with(path)
@provider.stubs(:texecute).returns("")
@provider.disable
end
it "should stop the service" do
FileTest.stubs(:directory?).returns(false)
Puppet::FileSystem.expects(:symlink?).returns(true)
Puppet::FileSystem.stubs(:unlink)
@provider.expects(:stop)
@provider.disable
end
end
describe "when checking if the service is enabled?" do
it "should return true if it is running" do
@provider.stubs(:status).returns(:running)
- @provider.enabled?.should == :true
+ expect(@provider.enabled?).to eq(:true)
end
[true, false].each do |t|
it "should return #{t} if the symlink exists" do
@provider.stubs(:status).returns(:stopped)
path = File.join(@servicedir,"myservice")
Puppet::FileSystem.expects(:symlink?).with(path).returns(t)
- @provider.enabled?.should == "#{t}".to_sym
+ expect(@provider.enabled?).to eq("#{t}".to_sym)
end
end
end
describe "when checking status" do
it "should call the external command 'svstat /etc/service/myservice'" do
@provider.expects(:svstat).with(File.join(@servicedir,"myservice"))
@provider.status
end
end
describe "when checking status" do
it "and svstat fails, properly raise a Puppet::Error" do
@provider.expects(:svstat).with(File.join(@servicedir,"myservice")).raises(Puppet::ExecutionFailure, "failure")
- lambda { @provider.status }.should raise_error(Puppet::Error, 'Could not get status for service Service[myservice]: failure')
+ expect { @provider.status }.to raise_error(Puppet::Error, 'Could not get status for service Service[myservice]: failure')
end
it "and svstat returns up, then return :running" do
@provider.expects(:svstat).with(File.join(@servicedir,"myservice")).returns("/etc/service/myservice: up (pid 454) 954326 seconds")
- @provider.status.should == :running
+ expect(@provider.status).to eq(:running)
end
it "and svstat returns not running, then return :stopped" do
@provider.expects(:svstat).with(File.join(@servicedir,"myservice")).returns("/etc/service/myservice: supervise not running")
- @provider.status.should == :stopped
+ expect(@provider.status).to eq(:stopped)
end
end
end
diff --git a/spec/unit/provider/service/debian_spec.rb b/spec/unit/provider/service/debian_spec.rb
index 05c0f00f4..a1aa42266 100755
--- a/spec/unit/provider/service/debian_spec.rb
+++ b/spec/unit/provider/service/debian_spec.rb
@@ -1,116 +1,116 @@
#! /usr/bin/env ruby
#
# Unit testing for the debian service provider
#
require 'spec_helper'
provider_class = Puppet::Type.type(:service).provider(:debian)
describe provider_class do
before(:each) do
# Create a mock resource
@resource = stub 'resource'
@provider = provider_class.new
# A catch all; no parameters set
@resource.stubs(:[]).returns(nil)
# But set name, source and path
@resource.stubs(:[]).with(:name).returns "myservice"
@resource.stubs(:[]).with(:ensure).returns :enabled
@resource.stubs(:ref).returns "Service[myservice]"
@provider.resource = @resource
@provider.stubs(:command).with(:update_rc).returns "update_rc"
@provider.stubs(:command).with(:invoke_rc).returns "invoke_rc"
@provider.stubs(:update_rc)
@provider.stubs(:invoke_rc)
end
it "should have an enabled? method" do
- @provider.should respond_to(:enabled?)
+ expect(@provider).to respond_to(:enabled?)
end
it "should have an enable method" do
- @provider.should respond_to(:enable)
+ expect(@provider).to respond_to(:enable)
end
it "should have a disable method" do
- @provider.should respond_to(:disable)
+ expect(@provider).to respond_to(:disable)
end
describe "when enabling" do
it "should call update-rc.d twice" do
@provider.expects(:update_rc).twice
@provider.enable
end
end
describe "when disabling" do
it "should be able to disable services with newer sysv-rc versions" do
@provider.stubs(:`).with("dpkg --compare-versions $(dpkg-query -W --showformat '${Version}' sysv-rc) ge 2.88 ; echo $?").returns "0"
@provider.expects(:update_rc).with(@resource[:name], "disable")
@provider.disable
end
it "should be able to enable services with older sysv-rc versions" do
@provider.stubs(:`).with("dpkg --compare-versions $(dpkg-query -W --showformat '${Version}' sysv-rc) ge 2.88 ; echo $?").returns "1"
@provider.expects(:update_rc).with("-f", @resource[:name], "remove")
@provider.expects(:update_rc).with(@resource[:name], "stop", "00", "1", "2", "3", "4", "5", "6", ".")
@provider.disable
end
end
describe "when checking whether it is enabled" do
it "should call Kernel.system() with the appropriate parameters" do
@provider.expects(:system).with("/usr/sbin/invoke-rc.d", "--quiet", "--query", @resource[:name], "start").once
@provider.enabled?
end
it "should return true when invoke-rc.d exits with 104 status" do
@provider.stubs(:system)
$CHILD_STATUS.stubs(:exitstatus).returns(104)
- @provider.enabled?.should == :true
+ expect(@provider.enabled?).to eq(:true)
end
it "should return true when invoke-rc.d exits with 106 status" do
@provider.stubs(:system)
$CHILD_STATUS.stubs(:exitstatus).returns(106)
- @provider.enabled?.should == :true
+ expect(@provider.enabled?).to eq(:true)
end
context "when invoke-rc.d exits with 105 status" do
it "links count is 4" do
@provider.stubs(:system)
$CHILD_STATUS.stubs(:exitstatus).returns(105)
@provider.stubs(:get_start_link_count).returns(4)
- @provider.enabled?.should == :true
+ expect(@provider.enabled?).to eq(:true)
end
it "links count is less than 4" do
@provider.stubs(:system)
$CHILD_STATUS.stubs(:exitstatus).returns(105)
@provider.stubs(:get_start_link_count).returns(3)
- @provider.enabled?.should == :false
+ expect(@provider.enabled?).to eq(:false)
end
end
# pick a range of non-[104.106] numbers, strings and booleans to test with.
[-100, -1, 0, 1, 100, "foo", "", :true, :false].each do |exitstatus|
it "should return false when invoke-rc.d exits with #{exitstatus} status" do
@provider.stubs(:system)
$CHILD_STATUS.stubs(:exitstatus).returns(exitstatus)
- @provider.enabled?.should == :false
+ expect(@provider.enabled?).to eq(:false)
end
end
end
end
diff --git a/spec/unit/provider/service/freebsd_spec.rb b/spec/unit/provider/service/freebsd_spec.rb
index 8ef5fee78..87229ca2b 100755
--- a/spec/unit/provider/service/freebsd_spec.rb
+++ b/spec/unit/provider/service/freebsd_spec.rb
@@ -1,75 +1,75 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:service).provider(:freebsd)
describe provider_class do
before :each do
@provider = provider_class.new
@provider.stubs(:initscript)
end
it "should correctly parse rcvar for FreeBSD < 7" do
@provider.stubs(:execute).returns <<OUTPUT
# ntpd
$ntpd_enable=YES
OUTPUT
- @provider.rcvar.should == ['# ntpd', 'ntpd_enable=YES']
+ expect(@provider.rcvar).to eq(['# ntpd', 'ntpd_enable=YES'])
end
it "should correctly parse rcvar for FreeBSD 7 to 8" do
@provider.stubs(:execute).returns <<OUTPUT
# ntpd
ntpd_enable=YES
OUTPUT
- @provider.rcvar.should == ['# ntpd', 'ntpd_enable=YES']
+ expect(@provider.rcvar).to eq(['# ntpd', 'ntpd_enable=YES'])
end
it "should correctly parse rcvar for FreeBSD >= 8.1" do
@provider.stubs(:execute).returns <<OUTPUT
# ntpd
#
ntpd_enable="YES"
# (default: "")
OUTPUT
- @provider.rcvar.should == ['# ntpd', 'ntpd_enable="YES"', '# (default: "")']
+ expect(@provider.rcvar).to eq(['# ntpd', 'ntpd_enable="YES"', '# (default: "")'])
end
it "should correctly parse rcvar for DragonFly BSD" do
@provider.stubs(:execute).returns <<OUTPUT
# ntpd
$ntpd=YES
OUTPUT
- @provider.rcvar.should == ['# ntpd', 'ntpd=YES']
+ expect(@provider.rcvar).to eq(['# ntpd', 'ntpd=YES'])
end
it "should find the right rcvar_value for FreeBSD < 7" do
@provider.stubs(:rcvar).returns(['# ntpd', 'ntpd_enable=YES'])
- @provider.rcvar_value.should == "YES"
+ expect(@provider.rcvar_value).to eq("YES")
end
it "should find the right rcvar_value for FreeBSD >= 7" do
@provider.stubs(:rcvar).returns(['# ntpd', 'ntpd_enable="YES"', '# (default: "")'])
- @provider.rcvar_value.should == "YES"
+ expect(@provider.rcvar_value).to eq("YES")
end
it "should find the right rcvar_name" do
@provider.stubs(:rcvar).returns(['# ntpd', 'ntpd_enable="YES"'])
- @provider.rcvar_name.should == "ntpd"
+ expect(@provider.rcvar_name).to eq("ntpd")
end
it "should enable only the selected service" do
Puppet::FileSystem.stubs(:exist?).with('/etc/rc.conf').returns(true)
File.stubs(:read).with('/etc/rc.conf').returns("openntpd_enable=\"NO\"\nntpd_enable=\"NO\"\n")
fh = stub 'fh'
File.stubs(:open).with('/etc/rc.conf', File::WRONLY).yields(fh)
fh.expects(:<<).with("openntpd_enable=\"NO\"\nntpd_enable=\"YES\"\n")
Puppet::FileSystem.stubs(:exist?).with('/etc/rc.conf.local').returns(false)
Puppet::FileSystem.stubs(:exist?).with('/etc/rc.conf.d/ntpd').returns(false)
@provider.rc_replace('ntpd', 'ntpd', 'YES')
end
end
diff --git a/spec/unit/provider/service/gentoo_spec.rb b/spec/unit/provider/service/gentoo_spec.rb
index 2bca67937..ed4440b70 100755
--- a/spec/unit/provider/service/gentoo_spec.rb
+++ b/spec/unit/provider/service/gentoo_spec.rb
@@ -1,241 +1,241 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:service).provider(:gentoo) do
before :each do
Puppet::Type.type(:service).stubs(:defaultprovider).returns described_class
FileTest.stubs(:file?).with('/sbin/rc-update').returns true
FileTest.stubs(:executable?).with('/sbin/rc-update').returns true
Facter.stubs(:value).with(:operatingsystem).returns 'Gentoo'
# The initprovider (parent of the gentoo provider) does a stat call
# before it even tries to execute an initscript. We use sshd in all the
# tests so make sure it is considered present.
sshd_path = '/etc/init.d/sshd'
# stub_file = stub(sshd_path, :stat => stub('stat'))
Puppet::FileSystem.stubs(:stat).with(sshd_path).returns stub('stat')
end
let :initscripts do
[
'alsasound',
'bootmisc',
'functions.sh',
'hwclock',
'reboot.sh',
'rsyncd',
'shutdown.sh',
'sshd',
'vixie-cron',
'wpa_supplicant',
'xdm-setup'
]
end
let :helperscripts do
[
'functions.sh',
'reboot.sh',
'shutdown.sh'
]
end
describe ".instances" do
it "should have an instances method" do
- described_class.should respond_to(:instances)
+ expect(described_class).to respond_to(:instances)
end
it "should get a list of services from /etc/init.d but exclude helper scripts" do
FileTest.expects(:directory?).with('/etc/init.d').returns true
Dir.expects(:entries).with('/etc/init.d').returns initscripts
(initscripts - helperscripts).each do |script|
FileTest.expects(:executable?).with("/etc/init.d/#{script}").returns true
end
helperscripts.each do |script|
FileTest.expects(:executable?).with("/etc/init.d/#{script}").never
end
Puppet::FileSystem.stubs(:symlink?).returns false # stub('file', :symlink? => false)
- described_class.instances.map(&:name).should == [
+ expect(described_class.instances.map(&:name)).to eq([
'alsasound',
'bootmisc',
'hwclock',
'rsyncd',
'sshd',
'vixie-cron',
'wpa_supplicant',
'xdm-setup'
- ]
+ ])
end
end
describe "#start" do
it "should use the supplied start command if specified" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :start => '/bin/foo'))
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.start
end
it "should start the service with <initscript> start otherwise" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
provider.expects(:execute).with(['/etc/init.d/sshd',:start], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.expects(:search).with('sshd').returns('/etc/init.d/sshd')
provider.start
end
end
describe "#stop" do
it "should use the supplied stop command if specified" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :stop => '/bin/foo'))
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.stop
end
it "should stop the service with <initscript> stop otherwise" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
provider.expects(:execute).with(['/etc/init.d/sshd',:stop], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.expects(:search).with('sshd').returns('/etc/init.d/sshd')
provider.stop
end
end
describe "#enabled?" do
before :each do
described_class.any_instance.stubs(:update).with(:show).returns File.read(my_fixture('rc_update_show'))
end
it "should run rc-update show to get a list of enabled services" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
provider.expects(:update).with(:show).returns "\n"
provider.enabled?
end
['hostname', 'net.lo', 'procfs'].each do |service|
it "should consider service #{service} in runlevel boot as enabled" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => service))
- provider.enabled?.should == :true
+ expect(provider.enabled?).to eq(:true)
end
end
['alsasound', 'xdm', 'netmount'].each do |service|
it "should consider service #{service} in runlevel default as enabled" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => service))
- provider.enabled?.should == :true
+ expect(provider.enabled?).to eq(:true)
end
end
['rsyncd', 'lighttpd', 'mysql'].each do |service|
it "should consider unused service #{service} as disabled" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => service))
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
end
end
describe "#enable" do
it "should run rc-update add to enable a service" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
provider.expects(:update).with(:add, 'sshd', :default)
provider.enable
end
end
describe "#disable" do
it "should run rc-update del to disable a service" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
provider.expects(:update).with(:del, 'sshd', :default)
provider.disable
end
end
describe "#status" do
describe "when a special status command is specified" do
it "should use the status command from the resource" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
provider.expects(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
provider.status
end
it "should return :stopped when the status command returns with a non-zero exitcode" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
provider.expects(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 3
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
it "should return :running when the status command returns with a zero exitcode" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
provider.expects(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 0
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
end
describe "when hasstatus is false" do
it "should return running if a pid can be found" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => false))
provider.expects(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:getpid).returns 1000
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
it "should return stopped if no pid can be found" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => false))
provider.expects(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:getpid).returns nil
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
end
describe "when hasstatus is true" do
it "should return running if <initscript> status exits with a zero exitcode" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => true))
provider.expects(:search).with('sshd').returns('/etc/init.d/sshd')
provider.expects(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 0
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
it "should return stopped if <initscript> status exits with a non-zero exitcode" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => true))
provider.expects(:search).with('sshd').returns('/etc/init.d/sshd')
provider.expects(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 3
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
end
end
describe "#restart" do
it "should use the supplied restart command if specified" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :restart => '/bin/foo'))
provider.expects(:execute).with(['/etc/init.d/sshd',:restart], :failonfail => true, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.restart
end
it "should restart the service with <initscript> restart if hasrestart is true" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasrestart => true))
provider.expects(:search).with('sshd').returns('/etc/init.d/sshd')
provider.expects(:execute).with(['/etc/init.d/sshd',:restart], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.restart
end
it "should restart the service with <initscript> stop/start if hasrestart is false" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasrestart => false))
provider.expects(:search).with('sshd').returns('/etc/init.d/sshd')
provider.expects(:execute).with(['/etc/init.d/sshd',:restart], :failonfail => true, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/etc/init.d/sshd',:stop], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.expects(:execute).with(['/etc/init.d/sshd',:start], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.restart
end
end
end
diff --git a/spec/unit/provider/service/init_spec.rb b/spec/unit/provider/service/init_spec.rb
index 63d64cf18..29ab61f3c 100755
--- a/spec/unit/provider/service/init_spec.rb
+++ b/spec/unit/provider/service/init_spec.rb
@@ -1,217 +1,217 @@
#! /usr/bin/env ruby
#
# Unit testing for the Init service Provider
#
require 'spec_helper'
describe Puppet::Type.type(:service).provider(:init) do
before do
Puppet::Type.type(:service).defaultprovider = described_class
end
after do
Puppet::Type.type(:service).defaultprovider = nil
end
let :provider do
resource.provider
end
let :resource do
Puppet::Type.type(:service).new(
:name => 'myservice',
:ensure => :running,
:path => paths
)
end
let :paths do
["/service/path","/alt/service/path"]
end
let :excludes do
# Taken from redhat, gentoo, and debian
%w{functions.sh reboot.sh shutdown.sh functions halt killall single linuxconf reboot boot wait-for-state rcS module-init-tools}
end
describe "when getting all service instances" do
before :each do
described_class.stubs(:defpath).returns('tmp')
@services = ['one', 'two', 'three', 'four']
Dir.stubs(:entries).with('tmp').returns @services
FileTest.expects(:directory?).with('tmp').returns(true)
FileTest.stubs(:executable?).returns(true)
end
it "should return instances for all services" do
- described_class.instances.map(&:name).should == @services
+ expect(described_class.instances.map(&:name)).to eq(@services)
end
it "should omit an array of services from exclude list" do
exclude = ['two', 'four']
- described_class.get_services(described_class.defpath, exclude).map(&:name).should == (@services - exclude)
+ expect(described_class.get_services(described_class.defpath, exclude).map(&:name)).to eq(@services - exclude)
end
it "should omit a single service from the exclude list" do
exclude = 'two'
- described_class.get_services(described_class.defpath, exclude).map(&:name).should == @services - [exclude]
+ expect(described_class.get_services(described_class.defpath, exclude).map(&:name)).to eq(@services - [exclude])
end
it "should use defpath" do
- described_class.instances.should be_all { |provider| provider.get(:path) == described_class.defpath }
+ expect(described_class.instances).to be_all { |provider| provider.get(:path) == described_class.defpath }
end
it "should set hasstatus to true for providers" do
- described_class.instances.should be_all { |provider| provider.get(:hasstatus) == true }
+ expect(described_class.instances).to be_all { |provider| provider.get(:hasstatus) == true }
end
it "should discard upstart jobs", :if => Puppet.features.manages_symlinks? do
not_init_service, *valid_services = @services
path = "tmp/#{not_init_service}"
Puppet::FileSystem.expects(:symlink?).at_least_once.returns false
Puppet::FileSystem.expects(:symlink?).with(Puppet::FileSystem.pathname(path)).returns(true)
Puppet::FileSystem.expects(:readlink).with(Puppet::FileSystem.pathname(path)).returns("/lib/init/upstart-job")
- described_class.instances.map(&:name).should == valid_services
+ expect(described_class.instances.map(&:name)).to eq(valid_services)
end
it "should discard non-initscript scripts" do
valid_services = @services
all_services = valid_services + excludes
Dir.expects(:entries).with('tmp').returns all_services
- described_class.instances.map(&:name).should =~ valid_services
+ expect(described_class.instances.map(&:name)).to match_array(valid_services)
end
end
describe "when checking valid paths" do
it "should discard paths that do not exist" do
File.expects(:directory?).with(paths[0]).returns false
Puppet::FileSystem.expects(:exist?).with(paths[0]).returns false
File.expects(:directory?).with(paths[1]).returns true
- provider.paths.should == [paths[1]]
+ expect(provider.paths).to eq([paths[1]])
end
it "should discard paths that are not directories" do
paths.each do |path|
Puppet::FileSystem.expects(:exist?).with(path).returns true
File.expects(:directory?).with(path).returns false
end
- provider.paths.should be_empty
+ expect(provider.paths).to be_empty
end
end
describe "when searching for the init script" do
before :each do
paths.each {|path| File.expects(:directory?).with(path).returns true }
end
it "should be able to find the init script in the service path" do
Puppet::FileSystem.expects(:exist?).with("#{paths[0]}/myservice").returns true
Puppet::FileSystem.expects(:exist?).with("#{paths[1]}/myservice").never # first one wins
- provider.initscript.should == "/service/path/myservice"
+ expect(provider.initscript).to eq("/service/path/myservice")
end
it "should be able to find the init script in an alternate service path" do
Puppet::FileSystem.expects(:exist?).with("#{paths[0]}/myservice").returns false
Puppet::FileSystem.expects(:exist?).with("#{paths[1]}/myservice").returns true
- provider.initscript.should == "/alt/service/path/myservice"
+ expect(provider.initscript).to eq("/alt/service/path/myservice")
end
it "should be able to find the init script if it ends with .sh" do
Puppet::FileSystem.expects(:exist?).with("#{paths[0]}/myservice").returns false
Puppet::FileSystem.expects(:exist?).with("#{paths[1]}/myservice").returns false
Puppet::FileSystem.expects(:exist?).with("#{paths[0]}/myservice.sh").returns true
- provider.initscript.should == "/service/path/myservice.sh"
+ expect(provider.initscript).to eq("/service/path/myservice.sh")
end
it "should fail if the service isn't there" do
paths.each do |path|
Puppet::FileSystem.expects(:exist?).with("#{path}/myservice").returns false
Puppet::FileSystem.expects(:exist?).with("#{path}/myservice.sh").returns false
end
expect { provider.initscript }.to raise_error(Puppet::Error, "Could not find init script for 'myservice'")
end
end
describe "if the init script is present" do
before :each do
File.stubs(:directory?).with("/service/path").returns true
File.stubs(:directory?).with("/alt/service/path").returns true
Puppet::FileSystem.stubs(:exist?).with("/service/path/myservice").returns true
end
[:start, :stop, :status, :restart].each do |method|
it "should have a #{method} method" do
- provider.should respond_to(method)
+ expect(provider).to respond_to(method)
end
describe "when running #{method}" do
it "should use any provided explicit command" do
resource[method] = "/user/specified/command"
provider.expects(:execute).with { |command, *args| command == ["/user/specified/command"] }
provider.send(method)
end
it "should pass #{method} to the init script when no explicit command is provided" do
resource[:hasrestart] = :true
resource[:hasstatus] = :true
provider.expects(:execute).with { |command, *args| command == ["/service/path/myservice",method]}
provider.send(method)
end
end
end
describe "when checking status" do
describe "when hasstatus is :true" do
before :each do
resource[:hasstatus] = :true
end
it "should execute the command" do
provider.expects(:texecute).with(:status, ['/service/path/myservice', :status], false).returns("")
provider.status
end
it "should consider the process running if the command returns 0" do
provider.expects(:texecute).with(:status, ['/service/path/myservice', :status], false).returns("")
$CHILD_STATUS.stubs(:exitstatus).returns(0)
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
[-10,-1,1,10].each { |ec|
it "should consider the process stopped if the command returns something non-0" do
provider.expects(:texecute).with(:status, ['/service/path/myservice', :status], false).returns("")
$CHILD_STATUS.stubs(:exitstatus).returns(ec)
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
}
end
describe "when hasstatus is not :true" do
before :each do
resource[:hasstatus] = :false
end
it "should consider the service :running if it has a pid" do
provider.expects(:getpid).returns "1234"
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
it "should consider the service :stopped if it doesn't have a pid" do
provider.expects(:getpid).returns nil
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
end
end
describe "when restarting and hasrestart is not :true" do
before :each do
resource[:hasrestart] = :false
end
it "should stop and restart the process" do
provider.expects(:texecute).with(:stop, ['/service/path/myservice', :stop ], true).returns("")
provider.expects(:texecute).with(:start,['/service/path/myservice', :start], true).returns("")
$CHILD_STATUS.stubs(:exitstatus).returns(0)
provider.restart
end
end
end
end
diff --git a/spec/unit/provider/service/launchd_spec.rb b/spec/unit/provider/service/launchd_spec.rb
index 50b87c462..b42921ef3 100755
--- a/spec/unit/provider/service/launchd_spec.rb
+++ b/spec/unit/provider/service/launchd_spec.rb
@@ -1,246 +1,246 @@
# Spec Tests for the Launchd provider
#
require 'spec_helper'
describe Puppet::Type.type(:service).provider(:launchd) do
let (:joblabel) { "com.foo.food" }
let (:provider) { subject.class }
let (:launchd_overrides) { '/var/db/launchd.db/com.apple.launchd/overrides.plist' }
let(:resource) { Puppet::Type.type(:service).new(:name => joblabel, :provider => :launchd) }
subject { resource.provider }
describe "the type interface" do
%w{ start stop enabled? enable disable status}.each do |method|
- it { should respond_to method.to_sym }
+ it { is_expected.to respond_to method.to_sym }
end
end
describe 'the status of the services' do
it "should call the external command 'launchctl list' once" do
provider.expects(:launchctl).with(:list).returns(joblabel)
provider.expects(:jobsearch).with(nil).returns({joblabel => "/Library/LaunchDaemons/#{joblabel}"})
provider.prefetch({})
end
it "should return stopped if not listed in launchctl list output" do
provider.expects(:launchctl).with(:list).returns('com.bar.is_running')
provider.expects(:jobsearch).with(nil).returns({'com.bar.is_not_running' => "/Library/LaunchDaemons/com.bar.is_not_running"})
- provider.prefetch({}).last.status.should eq :stopped
+ expect(provider.prefetch({}).last.status).to eq :stopped
end
it "should return running if listed in launchctl list output" do
provider.expects(:launchctl).with(:list).returns('com.bar.is_running')
provider.expects(:jobsearch).with(nil).returns({'com.bar.is_running' => "/Library/LaunchDaemons/com.bar.is_running"})
- provider.prefetch({}).last.status.should eq :running
+ expect(provider.prefetch({}).last.status).to eq :running
end
after :each do
provider.instance_variable_set(:@job_list, nil)
end
end
describe "when starting the service" do
it "should call any explicit 'start' command" do
resource[:start] = "/bin/false"
subject.expects(:texecute).with(:start, ["/bin/false"], true)
subject.start
end
it "should look for the relevant plist once" do
subject.expects(:plist_from_label).returns([joblabel, {}]).once
subject.expects(:enabled?).returns :true
subject.expects(:execute).with([:launchctl, :load, joblabel])
subject.start
end
it "should execute 'launchctl load' once without writing to the plist if the job is enabled" do
subject.expects(:plist_from_label).returns([joblabel, {}])
subject.expects(:enabled?).returns :true
subject.expects(:execute).with([:launchctl, :load, joblabel]).once
subject.start
end
it "should execute 'launchctl load' with writing to the plist once if the job is disabled" do
subject.expects(:plist_from_label).returns([joblabel, {}])
subject.expects(:enabled?).returns(:false)
subject.expects(:execute).with([:launchctl, :load, "-w", joblabel]).once
subject.start
end
it "should disable the job once if the job is disabled and should be disabled at boot" do
resource[:enable] = false
subject.expects(:plist_from_label).returns([joblabel, {"Disabled" => true}])
subject.expects(:enabled?).returns :false
subject.expects(:execute).with([:launchctl, :load, "-w", joblabel])
subject.expects(:disable).once
subject.start
end
it "(#2773) should execute 'launchctl load -w' if the job is enabled but stopped" do
subject.expects(:plist_from_label).returns([joblabel, {}])
subject.expects(:enabled?).returns(:true)
subject.expects(:status).returns(:stopped)
subject.expects(:execute).with([:launchctl, :load, '-w', joblabel])
subject.start
end
it "(#16271) Should stop and start the service when a restart is called" do
subject.expects(:stop)
subject.expects(:start)
subject.restart
end
end
describe "when stopping the service" do
it "should call any explicit 'stop' command" do
resource[:stop] = "/bin/false"
subject.expects(:texecute).with(:stop, ["/bin/false"], true)
subject.stop
end
it "should look for the relevant plist once" do
subject.expects(:plist_from_label).returns([joblabel, {}]).once
subject.expects(:enabled?).returns :true
subject.expects(:execute).with([:launchctl, :unload, '-w', joblabel])
subject.stop
end
it "should execute 'launchctl unload' once without writing to the plist if the job is disabled" do
subject.expects(:plist_from_label).returns([joblabel, {}])
subject.expects(:enabled?).returns :false
subject.expects(:execute).with([:launchctl, :unload, joblabel]).once
subject.stop
end
it "should execute 'launchctl unload' with writing to the plist once if the job is enabled" do
subject.expects(:plist_from_label).returns([joblabel, {}])
subject.expects(:enabled?).returns :true
subject.expects(:execute).with([:launchctl, :unload, '-w', joblabel]).once
subject.stop
end
it "should enable the job once if the job is enabled and should be enabled at boot" do
resource[:enable] = true
subject.expects(:plist_from_label).returns([joblabel, {"Disabled" => false}])
subject.expects(:enabled?).returns :true
subject.expects(:execute).with([:launchctl, :unload, "-w", joblabel])
subject.expects(:enable).once
subject.stop
end
end
describe "when enabling the service" do
it "should look for the relevant plist once" do ### Do we need this test? Differentiating it?
resource[:enable] = true
subject.expects(:plist_from_label).returns([joblabel, {}]).once
subject.expects(:enabled?).returns :false
subject.expects(:execute).with([:launchctl, :unload, joblabel])
subject.stop
end
it "should check if the job is enabled once" do
resource[:enable] = true
subject.expects(:plist_from_label).returns([joblabel, {}]).once
subject.expects(:enabled?).once
subject.expects(:execute).with([:launchctl, :unload, joblabel])
subject.stop
end
end
describe "when disabling the service" do
it "should look for the relevant plist once" do
resource[:enable] = false
subject.expects(:plist_from_label).returns([joblabel, {}]).once
subject.expects(:enabled?).returns :true
subject.expects(:execute).with([:launchctl, :unload, '-w', joblabel])
subject.stop
end
end
describe "when enabling the service" do
it "should write to the global launchd overrides file once" do
resource[:enable] = true
provider.expects(:read_plist).returns({})
Plist::Emit.expects(:save_plist).once
subject.enable
end
end
describe "when disabling the service" do
it "should write to the global launchd overrides file once" do
resource[:enable] = false
provider.stubs(:read_plist).returns({})
Plist::Emit.expects(:save_plist).once
subject.enable
end
end
describe "make_label_to_path_map" do
before do
# clear out this class variable between runs
if provider.instance_variable_defined? :@label_to_path_map
provider.send(:remove_instance_variable, :@label_to_path_map)
end
end
describe "when encountering malformed plists" do
let(:plist_without_label) do
{
'LimitLoadToSessionType' => 'Aqua'
}
end
let(:busted_plist_path) { '/Library/LaunchAgents/org.busted.plist' }
it "[17624] should warn that the plist in question is being skipped" do
provider.expects(:launchd_paths).returns(['/Library/LaunchAgents'])
provider.expects(:return_globbed_list_of_file_paths).with('/Library/LaunchAgents').returns([busted_plist_path])
provider.expects(:read_plist).with(busted_plist_path).returns(plist_without_label)
Puppet.expects(:warning).with("The #{busted_plist_path} plist does not contain a 'label' key; Puppet is skipping it")
provider.make_label_to_path_map
end
it "[15929] should skip plists that plutil cannot read" do
provider.expects(:plutil).with('-convert', 'xml1', '-o', '/dev/stdout',
busted_plist_path).raises(Puppet::ExecutionFailure, 'boom')
Puppet.expects(:warning).with("Cannot read file #{busted_plist_path}; " +
"Puppet is skipping it. \n" +
"Details: boom")
provider.read_plist(busted_plist_path)
end
end
it "should return the cached value when available" do
provider.instance_variable_set(:@label_to_path_map, {'xx'=>'yy'})
- provider.make_label_to_path_map.should eq({'xx'=>'yy'})
+ expect(provider.make_label_to_path_map).to eq({'xx'=>'yy'})
end
describe "when successful" do
let(:launchd_dir) { '/Library/LaunchAgents' }
let(:plist) { launchd_dir + '/foo.bar.service.plist' }
let(:label) { 'foo.bar.service' }
before do
provider.instance_variable_set(:@label_to_path_map, nil)
provider.expects(:launchd_paths).returns([launchd_dir])
provider.expects(:return_globbed_list_of_file_paths).with(launchd_dir).returns([plist])
provider.expects(:read_plist).with(plist).returns({'Label'=>'foo.bar.service'})
end
it "should read the plists and return their contents" do
- provider.make_label_to_path_map.should eq({label=>plist})
+ expect(provider.make_label_to_path_map).to eq({label=>plist})
end
it "should re-read the plists and return their contents when refreshed" do
provider.instance_variable_set(:@label_to_path_map, {'xx'=>'yy'})
- provider.make_label_to_path_map(true).should eq({label=>plist})
+ expect(provider.make_label_to_path_map(true)).to eq({label=>plist})
end
end
end
describe "jobsearch" do
let(:map) { {"org.mozilla.puppet" => "/path/to/puppet.plist",
"org.mozilla.python" => "/path/to/python.plist"} }
it "returns the entire map with no args" do
provider.expects(:make_label_to_path_map).returns(map)
- provider.jobsearch.should == map
+ expect(provider.jobsearch).to eq(map)
end
it "returns a singleton hash when given a label" do
provider.expects(:make_label_to_path_map).returns(map)
- provider.jobsearch("org.mozilla.puppet").should == { "org.mozilla.puppet" => "/path/to/puppet.plist" }
+ expect(provider.jobsearch("org.mozilla.puppet")).to eq({ "org.mozilla.puppet" => "/path/to/puppet.plist" })
end
it "refreshes the label_to_path_map when label is not found" do
provider.expects(:make_label_to_path_map).with().returns({})
provider.expects(:make_label_to_path_map).with(true).returns(map)
- provider.jobsearch("org.mozilla.puppet").should == { "org.mozilla.puppet" => "/path/to/puppet.plist" }
+ expect(provider.jobsearch("org.mozilla.puppet")).to eq({ "org.mozilla.puppet" => "/path/to/puppet.plist" })
end
it "raises Puppet::Error when the label is still not found" do
provider.expects(:make_label_to_path_map).with().returns(map)
provider.expects(:make_label_to_path_map).with(true).returns(map)
expect { provider.jobsearch("NOSUCH") }.to raise_error(Puppet::Error)
end
end
end
diff --git a/spec/unit/provider/service/openbsd_spec.rb b/spec/unit/provider/service/openbsd_spec.rb
index 777c348a7..bf81d15f0 100755
--- a/spec/unit/provider/service/openbsd_spec.rb
+++ b/spec/unit/provider/service/openbsd_spec.rb
@@ -1,201 +1,201 @@
#!/usr/bin/env ruby
#
# Unit testing for the OpenBSD service provider
require 'spec_helper'
provider_class = Puppet::Type.type(:service).provider(:openbsd)
describe provider_class, :unless => Puppet.features.microsoft_windows? do
before :each do
Puppet::Type.type(:service).stubs(:defaultprovider).returns described_class
Facter.stubs(:value).with(:operatingsystem).returns :openbsd
FileTest.stubs(:file?).with('/usr/sbin/rcctl').returns true
FileTest.stubs(:executable?).with('/usr/sbin/rcctl').returns true
end
describe "#instances" do
it "should have an instances method" do
- described_class.should respond_to :instances
+ expect(described_class).to respond_to :instances
end
it "should list all available services" do
described_class.stubs(:execpipe).with(['/usr/sbin/rcctl', :status]).yields File.read(my_fixture('rcctl_status'))
- described_class.instances.map(&:name).should == [
+ expect(described_class.instances.map(&:name)).to eq([
'accounting', 'pf', 'postgresql', 'tftpd', 'wsmoused', 'xdm',
- ]
+ ])
end
end
describe "#start" do
it "should use the supplied start command if specified" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :start => '/bin/foo'))
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.start
end
it "should start the service otherwise" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
provider.expects(:texecute).with(:start, ['/usr/sbin/rcctl', '-f', :start, 'sshd'], true)
provider.start
end
end
describe "#stop" do
it "should use the supplied stop command if specified" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :stop => '/bin/foo'))
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.stop
end
it "should stop the service otherwise" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
provider.expects(:texecute).with(:stop, ['/usr/sbin/rcctl', :stop, 'sshd'], true)
provider.stop
end
end
describe "#status" do
it "should use the status command from the resource" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
provider.expects(:execute).with(['/usr/sbin/rcctl', :status, 'sshd'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
provider.status
end
it "should return :stopped when status command returns with a non-zero exitcode" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
provider.expects(:execute).with(['/usr/sbin/rcctl', :status, 'sshd'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 3
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
it "should return :running when status command returns with a zero exitcode" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
provider.expects(:execute).with(['/usr/sbin/rcctl', :status, 'sshd'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 0
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
end
describe "#restart" do
it "should use the supplied restart command if specified" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :restart => '/bin/foo'))
provider.expects(:execute).with(['/usr/sbin/rcctl', '-f', :restart, 'sshd'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.restart
end
it "should restart the service with rcctl restart if hasrestart is true" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasrestart => true))
provider.expects(:texecute).with(:restart, ['/usr/sbin/rcctl', '-f', :restart, 'sshd'], true)
provider.restart
end
it "should restart the service with rcctl stop/start if hasrestart is false" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasrestart => false))
provider.expects(:texecute).with(:restart, ['/usr/sbin/rcctl', '-f', :restart, 'sshd'], true).never
provider.expects(:texecute).with(:stop, ['/usr/sbin/rcctl', :stop, 'sshd'], true)
provider.expects(:texecute).with(:start, ['/usr/sbin/rcctl', '-f', :start, 'sshd'], true)
provider.restart
end
end
describe "#enabled?" do
it "should return :true if the service is enabled" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
described_class.stubs(:rcctl).with('status', 'sshd').returns('-6')
provider.expects(:execute).with(['/usr/sbin/rcctl', 'status', 'sshd'], :failonfail => false, :combine => false, :squelch => false).returns('-6')
- provider.enabled?.should == :true
+ expect(provider.enabled?).to eq(:true)
end
it "should return :false if the service is disabled" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
described_class.stubs(:rcctl).with('status', 'sshd').returns('NO')
provider.expects(:execute).with(['/usr/sbin/rcctl', 'status', 'sshd'], :failonfail => false, :combine => false, :squelch => false).returns('NO')
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
end
describe "#enable" do
it "should run rcctl enable to enable the service" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
described_class.stubs(:rcctl).with(:enable, 'sshd').returns('')
provider.expects(:rcctl).with(:enable, 'sshd')
provider.enable
end
it "should run rcctl enable with flags if provided" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :flags => '-6'))
described_class.stubs(:rcctl).with(:enable, 'sshd', :flags, '-6').returns('')
provider.expects(:rcctl).with(:enable, 'sshd', :flags, '-6')
provider.enable
end
end
describe "#disable" do
it "should run rcctl disable to disable the service" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
described_class.stubs(:rcctl).with(:disable, 'sshd').returns('')
provider.expects(:rcctl).with(:disable, 'sshd')
provider.disable
end
end
describe "#running?" do
it "should run rcctl check to check the service" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
described_class.stubs(:rcctl).with(:check, 'sshd').returns('sshd(ok)')
provider.expects(:execute).with(['/usr/sbin/rcctl', 'check', 'sshd'], :failonfail => false, :combine => false, :squelch => false).returns('sshd(ok)')
- provider.running?.should be_true
+ expect(provider.running?).to be_truthy
end
it "should return true if the service is running" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
described_class.stubs(:rcctl).with(:check, 'sshd').returns('sshd(ok)')
provider.expects(:execute).with(['/usr/sbin/rcctl', 'check', 'sshd'], :failonfail => false, :combine => false, :squelch => false).returns('sshd(ok)')
- provider.running?.should be_true
+ expect(provider.running?).to be_truthy
end
it "should return nil if the service is not running" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
described_class.stubs(:rcctl).with(:check, 'sshd').returns('sshd(failed)')
provider.expects(:execute).with(['/usr/sbin/rcctl', 'check', 'sshd'], :failonfail => false, :combine => false, :squelch => false).returns('sshd(failed)')
- provider.running?.should be_nil
+ expect(provider.running?).to be_nil
end
end
describe "#flags" do
it "should return flags when set" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :flags => '-6'))
described_class.stubs(:rcctl).with(:status, 'sshd').returns('-6')
provider.expects(:execute).with(['/usr/sbin/rcctl', 'status', 'sshd'], :failonfail => false, :combine => false, :squelch => false).returns('-6')
provider.flags
end
it "should return empty flags" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
described_class.stubs(:rcctl).with(:status, 'sshd').returns('')
provider.expects(:execute).with(['/usr/sbin/rcctl', 'status', 'sshd'], :failonfail => false, :combine => false, :squelch => false).returns('')
provider.flags
end
it "should return flags for special services" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'pf'))
described_class.stubs(:rcctl).with(:status, 'pf').returns('YES')
provider.expects(:execute).with(['/usr/sbin/rcctl', 'status', 'pf'], :failonfail => false, :combine => false, :squelch => false).returns('YES')
provider.flags
end
end
describe "#flags=" do
it "should run rcctl to set flags" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
described_class.stubs(:rcctl).with(:enable, 'sshd', :flags, '-4').returns('')
provider.expects(:rcctl).with(:enable, 'sshd', :flags, '-4')
provider.flags = '-4'
end
end
end
diff --git a/spec/unit/provider/service/openrc_spec.rb b/spec/unit/provider/service/openrc_spec.rb
index 038340ed6..95950379b 100755
--- a/spec/unit/provider/service/openrc_spec.rb
+++ b/spec/unit/provider/service/openrc_spec.rb
@@ -1,225 +1,225 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:service).provider(:openrc) do
before :each do
Puppet::Type.type(:service).stubs(:defaultprovider).returns described_class
['/sbin/rc-service', '/bin/rc-status', '/sbin/rc-update'].each do |command|
# Puppet::Util is both mixed in to providers and is also invoked directly
# by Puppet::Provider::CommandDefiner, so we have to stub both out.
described_class.stubs(:which).with(command).returns(command)
Puppet::Util.stubs(:which).with(command).returns(command)
end
end
describe ".instances" do
it "should have an instances method" do
- described_class.should respond_to :instances
+ expect(described_class).to respond_to :instances
end
it "should get a list of services from rc-service --list" do
described_class.expects(:rcservice).with('-C','--list').returns File.read(my_fixture('rcservice_list'))
- described_class.instances.map(&:name).should == [
+ expect(described_class.instances.map(&:name)).to eq([
'alsasound',
'consolefont',
'lvm-monitoring',
'pydoc-2.7',
'pydoc-3.2',
'wpa_supplicant',
'xdm',
'xdm-setup'
- ]
+ ])
end
end
describe "#start" do
it "should use the supplied start command if specified" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :start => '/bin/foo'))
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.start
end
it "should start the service with rc-service start otherwise" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
provider.expects(:execute).with(['/sbin/rc-service','sshd',:start], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.start
end
end
describe "#stop" do
it "should use the supplied stop command if specified" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :stop => '/bin/foo'))
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.stop
end
it "should stop the service with rc-service stop otherwise" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
provider.expects(:execute).with(['/sbin/rc-service','sshd',:stop], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.stop
end
end
describe 'when invoking `rc-status`' do
subject { described_class.new(Puppet::Type.type(:service).new(:name => 'urandom')) }
it "clears the RC_SVCNAME environment variable" do
Puppet::Util.withenv(:RC_SVCNAME => 'puppet') do
Puppet::Util::Execution.expects(:execute).with(
includes('/bin/rc-status'),
has_entry(:custom_environment, {:RC_SVCNAME => nil})
).returns ''
subject.enabled?
end
end
end
describe "#enabled?" do
before :each do
described_class.any_instance.stubs(:rcstatus).with('-C','-a').returns File.read(my_fixture('rcstatus'))
end
it "should run rc-status to get a list of enabled services" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
provider.expects(:rcstatus).with('-C','-a').returns "\n"
provider.enabled?
end
['hwclock', 'modules', 'urandom'].each do |service|
it "should consider service #{service} in runlevel boot as enabled" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => service))
- provider.enabled?.should == :true
+ expect(provider.enabled?).to eq(:true)
end
end
['netmount', 'xdm', 'local', 'foo_with_very_very_long_servicename_no_still_not_the_end_wait_for_it_almost_there_almost_there_now_finally_the_end'].each do |service|
it "should consider service #{service} in runlevel default as enabled" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => service))
- provider.enabled?.should == :true
+ expect(provider.enabled?).to eq(:true)
end
end
['net.eth0', 'pcscd'].each do |service|
it "should consider service #{service} in dynamic runlevel: hotplugged as disabled" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => service))
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
end
['sysfs', 'udev-mount'].each do |service|
it "should consider service #{service} in dynamic runlevel: needed as disabled" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => service))
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
end
['sshd'].each do |service|
it "should consider service #{service} in dynamic runlevel: manual as disabled" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => service))
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
end
end
describe "#enable" do
it "should run rc-update add to enable a service" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
provider.expects(:rcupdate).with('-C', :add, 'sshd')
provider.enable
end
end
describe "#disable" do
it "should run rc-update del to disable a service" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
provider.expects(:rcupdate).with('-C', :del, 'sshd')
provider.disable
end
end
describe "#status" do
describe "when a special status command if specified" do
it "should use the status command from the resource" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
provider.expects(:execute).with(['/sbin/rc-service','sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
provider.status
end
it "should return :stopped when status command returns with a non-zero exitcode" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
provider.expects(:execute).with(['/sbin/rc-service','sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 3
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
it "should return :running when status command returns with a zero exitcode" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
provider.expects(:execute).with(['/sbin/rc-service','sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 0
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
end
describe "when hasstatus is false" do
it "should return running if a pid can be found" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => false))
provider.expects(:execute).with(['/sbin/rc-service','sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:getpid).returns 1000
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
it "should return stopped if no pid can be found" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => false))
provider.expects(:execute).with(['/sbin/rc-service','sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:getpid).returns nil
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
end
describe "when hasstatus is true" do
it "should return running if rc-service status exits with a zero exitcode" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => true))
provider.expects(:execute).with(['/sbin/rc-service','sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 0
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
it "should return stopped if rc-service status exits with a non-zero exitcode" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => true))
provider.expects(:execute).with(['/sbin/rc-service','sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 3
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
end
end
describe "#restart" do
it "should use the supplied restart command if specified" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :restart => '/bin/foo'))
provider.expects(:execute).with(['/sbin/rc-service','sshd',:restart], :failonfail => true, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.restart
end
it "should restart the service with rc-service restart if hasrestart is true" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasrestart => true))
provider.expects(:execute).with(['/sbin/rc-service','sshd',:restart], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.restart
end
it "should restart the service with rc-service stop/start if hasrestart is false" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasrestart => false))
provider.expects(:execute).with(['/sbin/rc-service','sshd',:restart], :failonfail => true, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/sbin/rc-service','sshd',:stop], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.expects(:execute).with(['/sbin/rc-service','sshd',:start], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.restart
end
end
end
diff --git a/spec/unit/provider/service/openwrt_spec.rb b/spec/unit/provider/service/openwrt_spec.rb
index 4550d6623..da21dea83 100755
--- a/spec/unit/provider/service/openwrt_spec.rb
+++ b/spec/unit/provider/service/openwrt_spec.rb
@@ -1,109 +1,109 @@
#! /usr/bin/env ruby
#
# Unit testing for the OpenWrt service Provider
#
require 'spec_helper'
describe Puppet::Type.type(:service).provider(:openwrt), :if => Puppet.features.posix? do
let(:resource) do
resource = stub 'resource'
resource.stubs(:[]).returns(nil)
resource.stubs(:[]).with(:name).returns "myservice"
resource.stubs(:[]).with(:path).returns ["/etc/init.d"]
resource
end
let(:provider) do
provider = described_class.new
provider.stubs(:get).with(:hasstatus).returns false
provider
end
before :each do
resource.stubs(:provider).returns provider
provider.resource = resource
FileTest.stubs(:file?).with('/etc/rc.common').returns true
FileTest.stubs(:executable?).with('/etc/rc.common').returns true
# All OpenWrt tests operate on the init script directly. It must exist.
File.stubs(:directory?).with('/etc/init.d').returns true
Puppet::FileSystem.stubs(:exist?).with('/etc/init.d/myservice').returns true
FileTest.stubs(:file?).with('/etc/init.d/myservice').returns true
FileTest.stubs(:executable?).with('/etc/init.d/myservice').returns true
end
operatingsystem = 'openwrt'
it "should be the default provider on #{operatingsystem}" do
Facter.expects(:value).with(:operatingsystem).returns(operatingsystem)
- described_class.default?.should be_true
+ expect(described_class.default?).to be_truthy
end
# test self.instances
describe "when getting all service instances" do
let(:services) {['dnsmasq', 'dropbear', 'firewall', 'led', 'puppet', 'uhttpd' ]}
before :each do
Dir.stubs(:entries).returns services
FileTest.stubs(:directory?).returns(true)
FileTest.stubs(:executable?).returns(true)
end
it "should return instances for all services" do
services.each do |inst|
described_class.expects(:new).with{|hash| hash[:name] == inst && hash[:path] == '/etc/init.d'}.returns("#{inst}_instance")
end
results = services.collect {|x| "#{x}_instance"}
- described_class.instances.should == results
+ expect(described_class.instances).to eq(results)
end
end
it "should have an enabled? method" do
- provider.should respond_to(:enabled?)
+ expect(provider).to respond_to(:enabled?)
end
it "should have an enable method" do
- provider.should respond_to(:enable)
+ expect(provider).to respond_to(:enable)
end
it "should have a disable method" do
- provider.should respond_to(:disable)
+ expect(provider).to respond_to(:disable)
end
[:start, :stop, :restart].each do |method|
it "should have a #{method} method" do
- provider.should respond_to(method)
+ expect(provider).to respond_to(method)
end
describe "when running #{method}" do
it "should use any provided explicit command" do
resource.stubs(:[]).with(method).returns "/user/specified/command"
provider.expects(:execute).with { |command, *args| command == ["/user/specified/command"] }
provider.send(method)
end
it "should execute the init script with #{method} when no explicit command is provided" do
resource.stubs(:[]).with("has#{method}".intern).returns :true
provider.expects(:execute).with { |command, *args| command == ['/etc/init.d/myservice', method ]}
provider.send(method)
end
end
end
describe "when checking status" do
it "should consider the service :running if it has a pid" do
provider.expects(:getpid).returns "1234"
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
it "should consider the service :stopped if it doesn't have a pid" do
provider.expects(:getpid).returns nil
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
end
end
diff --git a/spec/unit/provider/service/redhat_spec.rb b/spec/unit/provider/service/redhat_spec.rb
index 9478cd83b..2ff4acf36 100755
--- a/spec/unit/provider/service/redhat_spec.rb
+++ b/spec/unit/provider/service/redhat_spec.rb
@@ -1,163 +1,163 @@
#! /usr/bin/env ruby
#
# Unit testing for the RedHat service Provider
#
require 'spec_helper'
provider_class = Puppet::Type.type(:service).provider(:redhat)
describe provider_class, :if => Puppet.features.posix? do
before :each do
@class = Puppet::Type.type(:service).provider(:redhat)
@resource = stub 'resource'
@resource.stubs(:[]).returns(nil)
@resource.stubs(:[]).with(:name).returns "myservice"
@provider = provider_class.new
@resource.stubs(:provider).returns @provider
@provider.resource = @resource
@provider.stubs(:get).with(:hasstatus).returns false
FileTest.stubs(:file?).with('/sbin/service').returns true
FileTest.stubs(:executable?).with('/sbin/service').returns true
Facter.stubs(:value).with(:operatingsystem).returns('CentOS')
end
osfamily = [ 'RedHat', 'Suse' ]
osfamily.each do |osfamily|
it "should be the default provider on #{osfamily}" do
Facter.expects(:value).with(:osfamily).returns(osfamily)
- provider_class.default?.should be_true
+ expect(provider_class.default?).to be_truthy
end
end
# test self.instances
describe "when getting all service instances" do
before :each do
@services = ['one', 'two', 'three', 'four', 'kudzu', 'functions', 'halt', 'killall', 'single', 'linuxconf', 'boot', 'reboot']
@not_services = ['functions', 'halt', 'killall', 'single', 'linuxconf', 'reboot', 'boot']
Dir.stubs(:entries).returns @services
FileTest.stubs(:directory?).returns(true)
FileTest.stubs(:executable?).returns(true)
end
it "should return instances for all services" do
(@services-@not_services).each do |inst|
@class.expects(:new).with{|hash| hash[:name] == inst && hash[:path] == '/etc/init.d'}.returns("#{inst}_instance")
end
results = (@services-@not_services).collect {|x| "#{x}_instance"}
- @class.instances.should == results
+ expect(@class.instances).to eq(results)
end
it "should call service status when initialized from provider" do
@resource.stubs(:[]).with(:status).returns nil
@provider.stubs(:get).with(:hasstatus).returns true
@provider.expects(:execute).with{|command, *args| command == ['/sbin/service', 'myservice', 'status']}
@provider.send(:status)
end
end
it "should use '--add' and 'on' when calling enable" do
provider_class.expects(:chkconfig).with("--add", @resource[:name])
provider_class.expects(:chkconfig).with(@resource[:name], :on)
@provider.enable
end
it "(#15797) should explicitly turn off the service in all run levels" do
provider_class.expects(:chkconfig).with("--level", "0123456", @resource[:name], :off)
@provider.disable
end
it "should have an enabled? method" do
- @provider.should respond_to(:enabled?)
+ expect(@provider).to respond_to(:enabled?)
end
describe "when checking enabled? on Suse" do
before :each do
Facter.expects(:value).with(:osfamily).returns 'Suse'
end
it "should check for on" do
provider_class.stubs(:chkconfig).with(@resource[:name]).returns "#{@resource[:name]} on"
- @provider.enabled?.should == :true
+ expect(@provider.enabled?).to eq(:true)
end
it "should check for off" do
provider_class.stubs(:chkconfig).with(@resource[:name]).returns "#{@resource[:name]} off"
- @provider.enabled?.should == :false
+ expect(@provider.enabled?).to eq(:false)
end
it "should check for unknown service" do
provider_class.stubs(:chkconfig).with(@resource[:name]).returns "#{@resource[:name]}: unknown service"
- @provider.enabled?.should == :false
+ expect(@provider.enabled?).to eq(:false)
end
end
it "should have an enable method" do
- @provider.should respond_to(:enable)
+ expect(@provider).to respond_to(:enable)
end
it "should have a disable method" do
- @provider.should respond_to(:disable)
+ expect(@provider).to respond_to(:disable)
end
[:start, :stop, :status, :restart].each do |method|
it "should have a #{method} method" do
- @provider.should respond_to(method)
+ expect(@provider).to respond_to(method)
end
describe "when running #{method}" do
it "should use any provided explicit command" do
@resource.stubs(:[]).with(method).returns "/user/specified/command"
@provider.expects(:execute).with { |command, *args| command == ["/user/specified/command"] }
@provider.send(method)
end
it "should execute the service script with #{method} when no explicit command is provided" do
@resource.stubs(:[]).with("has#{method}".intern).returns :true
@provider.expects(:execute).with { |command, *args| command == ['/sbin/service', 'myservice', method.to_s]}
@provider.send(method)
end
end
end
describe "when checking status" do
describe "when hasstatus is :true" do
before :each do
@resource.stubs(:[]).with(:hasstatus).returns :true
end
it "should execute the service script with fail_on_failure false" do
@provider.expects(:texecute).with(:status, ['/sbin/service', 'myservice', 'status'], false)
@provider.status
end
it "should consider the process running if the command returns 0" do
@provider.expects(:texecute).with(:status, ['/sbin/service', 'myservice', 'status'], false)
$CHILD_STATUS.stubs(:exitstatus).returns(0)
- @provider.status.should == :running
+ expect(@provider.status).to eq(:running)
end
[-10,-1,1,10].each { |ec|
it "should consider the process stopped if the command returns something non-0" do
@provider.expects(:texecute).with(:status, ['/sbin/service', 'myservice', 'status'], false)
$CHILD_STATUS.stubs(:exitstatus).returns(ec)
- @provider.status.should == :stopped
+ expect(@provider.status).to eq(:stopped)
end
}
end
describe "when hasstatus is not :true" do
it "should consider the service :running if it has a pid" do
@provider.expects(:getpid).returns "1234"
- @provider.status.should == :running
+ expect(@provider.status).to eq(:running)
end
it "should consider the service :stopped if it doesn't have a pid" do
@provider.expects(:getpid).returns nil
- @provider.status.should == :stopped
+ expect(@provider.status).to eq(:stopped)
end
end
end
describe "when restarting and hasrestart is not :true" do
it "should stop and restart the process with the server script" do
@provider.expects(:texecute).with(:stop, ['/sbin/service', 'myservice', 'stop'], true)
@provider.expects(:texecute).with(:start, ['/sbin/service', 'myservice', 'start'], true)
@provider.restart
end
end
end
diff --git a/spec/unit/provider/service/runit_spec.rb b/spec/unit/provider/service/runit_spec.rb
index 58701309f..db6a44c43 100755
--- a/spec/unit/provider/service/runit_spec.rb
+++ b/spec/unit/provider/service/runit_spec.rb
@@ -1,145 +1,145 @@
#! /usr/bin/env ruby
#
# Unit testing for the Runit service Provider
#
# author Brice Figureau
#
require 'spec_helper'
provider_class = Puppet::Type.type(:service).provider(:runit)
describe provider_class do
before(:each) do
# Create a mock resource
@resource = stub 'resource'
@provider = provider_class.new
@servicedir = "/etc/service"
@provider.servicedir=@servicedir
@daemondir = "/etc/sv"
@provider.class.defpath=@daemondir
# A catch all; no parameters set
@resource.stubs(:[]).returns(nil)
# But set name, source and path (because we won't run
# the thing that will fetch the resource path from the provider)
@resource.stubs(:[]).with(:name).returns "myservice"
@resource.stubs(:[]).with(:ensure).returns :enabled
@resource.stubs(:[]).with(:path).returns @daemondir
@resource.stubs(:ref).returns "Service[myservice]"
@provider.stubs(:sv)
@provider.stubs(:resource).returns @resource
end
it "should have a restart method" do
- @provider.should respond_to(:restart)
+ expect(@provider).to respond_to(:restart)
end
it "should have a restartcmd method" do
- @provider.should respond_to(:restartcmd)
+ expect(@provider).to respond_to(:restartcmd)
end
it "should have a start method" do
- @provider.should respond_to(:start)
+ expect(@provider).to respond_to(:start)
end
it "should have a stop method" do
- @provider.should respond_to(:stop)
+ expect(@provider).to respond_to(:stop)
end
it "should have an enabled? method" do
- @provider.should respond_to(:enabled?)
+ expect(@provider).to respond_to(:enabled?)
end
it "should have an enable method" do
- @provider.should respond_to(:enable)
+ expect(@provider).to respond_to(:enable)
end
it "should have a disable method" do
- @provider.should respond_to(:disable)
+ expect(@provider).to respond_to(:disable)
end
describe "when starting" do
it "should enable the service if it is not enabled" do
@provider.stubs(:sv)
@provider.expects(:enabled?).returns :false
@provider.expects(:enable)
@provider.stubs(:sleep)
@provider.start
end
it "should execute external command 'sv start /etc/service/myservice'" do
@provider.stubs(:enabled?).returns :true
@provider.expects(:sv).with("start", "/etc/service/myservice")
@provider.start
end
end
describe "when stopping" do
it "should execute external command 'sv stop /etc/service/myservice'" do
@provider.expects(:sv).with("stop", "/etc/service/myservice")
@provider.stop
end
end
describe "when restarting" do
it "should call 'sv restart /etc/service/myservice'" do
@provider.expects(:sv).with("restart","/etc/service/myservice")
@provider.restart
end
end
describe "when enabling" do
it "should create a symlink between daemon dir and service dir", :if => Puppet.features.manages_symlinks? do
daemon_path = File.join(@daemondir,"myservice")
service_path = File.join(@servicedir,"myservice")
Puppet::FileSystem.expects(:symlink?).with(service_path).returns(false)
Puppet::FileSystem.expects(:symlink).with(daemon_path, File.join(@servicedir,"myservice")).returns(0)
@provider.enable
end
end
describe "when disabling" do
it "should remove the '/etc/service/myservice' symlink" do
path = File.join(@servicedir,"myservice")
# mocked_file = mock(path, :symlink? => true)
FileTest.stubs(:directory?).returns(false)
Puppet::FileSystem.expects(:symlink?).with(path).returns(true) # mocked_file)
Puppet::FileSystem.expects(:unlink).with(path).returns(0)
@provider.disable
end
end
describe "when checking status" do
it "should call the external command 'sv status /etc/sv/myservice'" do
@provider.expects(:sv).with('status',File.join(@daemondir,"myservice"))
@provider.status
end
end
describe "when checking status" do
it "and sv status fails, properly raise a Puppet::Error" do
@provider.expects(:sv).with('status',File.join(@daemondir,"myservice")).raises(Puppet::ExecutionFailure, "fail: /etc/sv/myservice: file not found")
- lambda { @provider.status }.should raise_error(Puppet::Error, 'Could not get status for service Service[myservice]: fail: /etc/sv/myservice: file not found')
+ expect { @provider.status }.to raise_error(Puppet::Error, 'Could not get status for service Service[myservice]: fail: /etc/sv/myservice: file not found')
end
it "and sv status returns up, then return :running" do
@provider.expects(:sv).with('status',File.join(@daemondir,"myservice")).returns("run: /etc/sv/myservice: (pid 9029) 6s")
- @provider.status.should == :running
+ expect(@provider.status).to eq(:running)
end
it "and sv status returns not running, then return :stopped" do
@provider.expects(:sv).with('status',File.join(@daemondir,"myservice")).returns("fail: /etc/sv/myservice: runsv not running")
- @provider.status.should == :stopped
+ expect(@provider.status).to eq(:stopped)
end
it "and sv status returns a warning, then return :stopped" do
@provider.expects(:sv).with('status',File.join(@daemondir,"myservice")).returns("warning: /etc/sv/myservice: unable to open supervise/ok: file does not exist")
- @provider.status.should == :stopped
+ expect(@provider.status).to eq(:stopped)
end
end
end
diff --git a/spec/unit/provider/service/smf_spec.rb b/spec/unit/provider/service/smf_spec.rb
index 99fba15cb..7d8bed7b3 100755
--- a/spec/unit/provider/service/smf_spec.rb
+++ b/spec/unit/provider/service/smf_spec.rb
@@ -1,153 +1,153 @@
#! /usr/bin/env ruby
#
# Unit testing for the SMF service Provider
#
# author Dominic Cleal
#
require 'spec_helper'
provider_class = Puppet::Type.type(:service).provider(:smf)
describe provider_class, :if => Puppet.features.posix? do
before(:each) do
# Create a mock resource
@resource = Puppet::Type.type(:service).new(
:name => "/system/myservice", :ensure => :running, :enable => :true)
@provider = provider_class.new(@resource)
FileTest.stubs(:file?).with('/usr/sbin/svcadm').returns true
FileTest.stubs(:executable?).with('/usr/sbin/svcadm').returns true
FileTest.stubs(:file?).with('/usr/bin/svcs').returns true
FileTest.stubs(:executable?).with('/usr/bin/svcs').returns true
end
describe ".instances" do
it "should have an instances method" do
- provider_class.should respond_to :instances
+ expect(provider_class).to respond_to :instances
end
it "should get a list of services (excluding legacy)" do
provider_class.expects(:svcs).with().returns File.read(my_fixture('svcs.out'))
instances = provider_class.instances.map { |p| {:name => p.get(:name), :ensure => p.get(:ensure)} }
# we dont manage legacy
- instances.size.should == 2
- instances[0].should == {:name => 'svc:/system/svc/restarter:default', :ensure => :running }
- instances[1].should == {:name => 'svc:/network/cswrsyncd:default', :ensure => :maintenance }
+ expect(instances.size).to eq(2)
+ expect(instances[0]).to eq({:name => 'svc:/system/svc/restarter:default', :ensure => :running })
+ expect(instances[1]).to eq({:name => 'svc:/network/cswrsyncd:default', :ensure => :maintenance })
end
end
it "should have a restart method" do
- @provider.should respond_to(:restart)
+ expect(@provider).to respond_to(:restart)
end
it "should have a restartcmd method" do
- @provider.should respond_to(:restartcmd)
+ expect(@provider).to respond_to(:restartcmd)
end
it "should have a start method" do
- @provider.should respond_to(:start)
+ expect(@provider).to respond_to(:start)
end
it "should have a stop method" do
- @provider.should respond_to(:stop)
+ expect(@provider).to respond_to(:stop)
end
it "should have an enabled? method" do
- @provider.should respond_to(:enabled?)
+ expect(@provider).to respond_to(:enabled?)
end
it "should have an enable method" do
- @provider.should respond_to(:enable)
+ expect(@provider).to respond_to(:enable)
end
it "should have a disable method" do
- @provider.should respond_to(:disable)
+ expect(@provider).to respond_to(:disable)
end
describe "when checking status" do
it "should call the external command 'svcs /system/myservice' once" do
@provider.expects(:svcs).with('-H', '-o', 'state,nstate', "/system/myservice").returns("online\t-")
@provider.status
end
it "should return stopped if svcs can't find the service" do
@provider.stubs(:svcs).raises(Puppet::ExecutionFailure.new("no svc found"))
- @provider.status.should == :stopped
+ expect(@provider.status).to eq(:stopped)
end
it "should return running if online in svcs output" do
@provider.stubs(:svcs).returns("online\t-")
- @provider.status.should == :running
+ expect(@provider.status).to eq(:running)
end
it "should return stopped if disabled in svcs output" do
@provider.stubs(:svcs).returns("disabled\t-")
- @provider.status.should == :stopped
+ expect(@provider.status).to eq(:stopped)
end
it "should return maintenance if in maintenance in svcs output" do
@provider.stubs(:svcs).returns("maintenance\t-")
- @provider.status.should == :maintenance
+ expect(@provider.status).to eq(:maintenance)
end
it "should return target state if transitioning in svcs output" do
@provider.stubs(:svcs).returns("online\tdisabled")
- @provider.status.should == :stopped
+ expect(@provider.status).to eq(:stopped)
end
it "should throw error if it's a legacy service in svcs output" do
@provider.stubs(:svcs).returns("legacy_run\t-")
- lambda { @provider.status }.should raise_error(Puppet::Error, "Cannot manage legacy services through SMF")
+ expect { @provider.status }.to raise_error(Puppet::Error, "Cannot manage legacy services through SMF")
end
end
describe "when starting" do
it "should enable the service if it is not enabled" do
@provider.expects(:status).returns :stopped
@provider.expects(:texecute)
@provider.start
end
it "should always execute external command 'svcadm enable /system/myservice'" do
@provider.stubs(:status).returns :running
@provider.expects(:texecute).with(:start, ["/usr/sbin/svcadm", :enable, "-s", "/system/myservice"], true)
@provider.start
end
it "should execute external command 'svcadm clear /system/myservice' if in maintenance" do
@provider.stubs(:status).returns :maintenance
@provider.expects(:texecute).with(:start, ["/usr/sbin/svcadm", :clear, "/system/myservice"], true)
@provider.start
end
end
describe "when starting a service with a manifest" do
before(:each) do
@resource = Puppet::Type.type(:service).new(:name => "/system/myservice", :ensure => :running, :enable => :true, :manifest => "/tmp/myservice.xml")
@provider = provider_class.new(@resource)
$CHILD_STATUS.stubs(:exitstatus).returns(1)
end
it "should import the manifest if service is missing" do
@provider.expects(:svccfg).with(:import, "/tmp/myservice.xml")
@provider.expects(:texecute).with(:start, ["/usr/sbin/svcadm", :enable, "-s", "/system/myservice"], true)
@provider.expects(:svcs).with('-H', '-o', 'state,nstate', "/system/myservice").returns("online\t-")
@provider.start
end
it "should handle failures if importing a manifest" do
@provider.expects(:svccfg).raises(Puppet::ExecutionFailure.new("can't svccfg import"))
- lambda { @provider.start }.should raise_error(Puppet::Error, "Cannot config /system/myservice to enable it: can't svccfg import")
+ expect { @provider.start }.to raise_error(Puppet::Error, "Cannot config /system/myservice to enable it: can't svccfg import")
end
end
describe "when stopping" do
it "should execute external command 'svcadm disable /system/myservice'" do
@provider.expects(:texecute).with(:stop, ["/usr/sbin/svcadm", :disable, "-s", "/system/myservice"], true)
@provider.stop
end
end
describe "when restarting" do
it "should call 'svcadm restart /system/myservice'" do
@provider.expects(:texecute).with(:restart, ["/usr/sbin/svcadm", :restart, "/system/myservice"], true)
@provider.restart
end
end
end
diff --git a/spec/unit/provider/service/src_spec.rb b/spec/unit/provider/service/src_spec.rb
index f168e3844..1749de4c8 100755
--- a/spec/unit/provider/service/src_spec.rb
+++ b/spec/unit/provider/service/src_spec.rb
@@ -1,173 +1,173 @@
#! /usr/bin/env ruby
#
# Unit testing for the AIX System Resource Controller (src) provider
#
require 'spec_helper'
provider_class = Puppet::Type.type(:service).provider(:src)
describe provider_class do
before :each do
@resource = stub 'resource'
@resource.stubs(:[]).returns(nil)
@resource.stubs(:[]).with(:name).returns "myservice"
@provider = provider_class.new
@provider.resource = @resource
@provider.stubs(:command).with(:stopsrc).returns "/usr/bin/stopsrc"
@provider.stubs(:command).with(:startsrc).returns "/usr/bin/startsrc"
@provider.stubs(:command).with(:lssrc).returns "/usr/bin/lssrc"
@provider.stubs(:command).with(:refresh).returns "/usr/bin/refresh"
@provider.stubs(:command).with(:lsitab).returns "/usr/sbin/lsitab"
@provider.stubs(:command).with(:mkitab).returns "/usr/sbin/mkitab"
@provider.stubs(:command).with(:rmitab).returns "/usr/sbin/rmitab"
@provider.stubs(:command).with(:chitab).returns "/usr/sbin/chitab"
@provider.stubs(:stopsrc)
@provider.stubs(:startsrc)
@provider.stubs(:lssrc)
@provider.stubs(:refresh)
@provider.stubs(:lsitab)
@provider.stubs(:mkitab)
@provider.stubs(:rmitab)
@provider.stubs(:chitab)
end
describe ".instances" do
it "should has a .instances method" do
- provider_class.should respond_to :instances
+ expect(provider_class).to respond_to :instances
end
it "should get a list of running services" do
sample_output = <<_EOF_
#subsysname:synonym:cmdargs:path:uid:auditid:standin:standout:standerr:action:multi:contact:svrkey:svrmtype:priority:signorm:sigforce:display:waittime:grpname:
myservice.1:::/usr/sbin/inetd:0:0:/dev/console:/dev/console:/dev/console:-O:-Q:-K:0:0:20:0:0:-d:20:tcpip:
myservice.2:::/usr/sbin/inetd:0:0:/dev/console:/dev/console:/dev/console:-O:-Q:-K:0:0:20:0:0:-d:20:tcpip:
myservice.3:::/usr/sbin/inetd:0:0:/dev/console:/dev/console:/dev/console:-O:-Q:-K:0:0:20:0:0:-d:20:tcpip:
myservice.4:::/usr/sbin/inetd:0:0:/dev/console:/dev/console:/dev/console:-O:-Q:-K:0:0:20:0:0:-d:20:tcpip:
_EOF_
provider_class.stubs(:lssrc).returns sample_output
- provider_class.instances.map(&:name).should == [
+ expect(provider_class.instances.map(&:name)).to eq([
'myservice.1',
'myservice.2',
'myservice.3',
'myservice.4'
- ]
+ ])
end
end
describe "when starting a service" do
it "should execute the startsrc command" do
@provider.expects(:execute).with(['/usr/bin/startsrc', '-s', "myservice"], {:override_locale => false, :squelch => false, :combine => true, :failonfail => true})
@provider.start
end
end
describe "when stopping a service" do
it "should execute the stopsrc command" do
@provider.expects(:execute).with(['/usr/bin/stopsrc', '-s', "myservice"], {:override_locale => false, :squelch => false, :combine => true, :failonfail => true})
@provider.stop
end
end
describe "should have a set of methods" do
[:enabled?, :enable, :disable, :start, :stop, :status, :restart].each do |method|
it "should have a #{method} method" do
- @provider.should respond_to(method)
+ expect(@provider).to respond_to(method)
end
end
end
describe "when enabling" do
it "should execute the mkitab command" do
@provider.expects(:mkitab).with("myservice:2:once:/usr/bin/startsrc -s myservice").once
@provider.enable
end
end
describe "when disabling" do
it "should execute the rmitab command" do
@provider.expects(:rmitab).with("myservice")
@provider.disable
end
end
describe "when checking if it is enabled" do
it "should execute the lsitab command" do
@provider.expects(:execute).with(['/usr/sbin/lsitab', 'myservice'], {:combine => true, :failonfail => false})
@provider.enabled?
end
it "should return false when lsitab returns non-zero" do
@provider.stubs(:execute)
$CHILD_STATUS.stubs(:exitstatus).returns(1)
- @provider.enabled?.should == :false
+ expect(@provider.enabled?).to eq(:false)
end
it "should return true when lsitab returns zero" do
@provider.stubs(:execute)
$CHILD_STATUS.stubs(:exitstatus).returns(0)
- @provider.enabled?.should == :true
+ expect(@provider.enabled?).to eq(:true)
end
end
describe "when checking a subsystem's status" do
it "should execute status and return running if the subsystem is active" do
sample_output = <<_EOF_
Subsystem Group PID Status
myservice tcpip 1234 active
_EOF_
@provider.expects(:execute).with(['/usr/bin/lssrc', '-s', "myservice"]).returns sample_output
- @provider.status.should == :running
+ expect(@provider.status).to eq(:running)
end
it "should execute status and return stopped if the subsystem is inoperative" do
sample_output = <<_EOF_
Subsystem Group PID Status
myservice tcpip inoperative
_EOF_
@provider.expects(:execute).with(['/usr/bin/lssrc', '-s', "myservice"]).returns sample_output
- @provider.status.should == :stopped
+ expect(@provider.status).to eq(:stopped)
end
it "should execute status and return nil if the status is not known" do
sample_output = <<_EOF_
Subsystem Group PID Status
myservice tcpip randomdata
_EOF_
@provider.expects(:execute).with(['/usr/bin/lssrc', '-s', "myservice"]).returns sample_output
- @provider.status.should == nil
+ expect(@provider.status).to eq(nil)
end
end
describe "when restarting a service" do
it "should execute restart which runs refresh" do
sample_output = <<_EOF_
#subsysname:synonym:cmdargs:path:uid:auditid:standin:standout:standerr:action:multi:contact:svrkey:svrmtype:priority:signorm:sigforce:display:waittime:grpname:
myservice:::/usr/sbin/inetd:0:0:/dev/console:/dev/console:/dev/console:-O:-Q:-K:0:0:20:0:0:-d:20:tcpip:
_EOF_
@provider.expects(:execute).with(['/usr/bin/lssrc', '-Ss', "myservice"]).returns sample_output
@provider.expects(:execute).with(['/usr/bin/refresh', '-s', "myservice"])
@provider.restart
end
it "should execute restart which runs stopsrc then startsrc" do
sample_output = <<_EOF_
#subsysname:synonym:cmdargs:path:uid:auditid:standin:standout:standerr:action:multi:contact:svrkey:svrmtype:priority:signorm:sigforce:display:waittime:grpname:
myservice::--no-daemonize:/usr/sbin/puppetd:0:0:/dev/null:/var/log/puppet.log:/var/log/puppet.log:-O:-Q:-S:0:0:20:15:9:-d:20::"
_EOF_
@provider.expects(:execute).with(['/usr/bin/lssrc', '-Ss', "myservice"]).returns sample_output
@provider.expects(:execute).with(['/usr/bin/stopsrc', '-s', "myservice"], {:override_locale => false, :squelch => false, :combine => true, :failonfail => true})
@provider.expects(:execute).with(['/usr/bin/startsrc', '-s', "myservice"], {:override_locale => false, :squelch => false, :combine => true, :failonfail => true})
@provider.restart
end
end
end
diff --git a/spec/unit/provider/service/systemd_spec.rb b/spec/unit/provider/service/systemd_spec.rb
index f2b95cdfd..02874a9b0 100755
--- a/spec/unit/provider/service/systemd_spec.rb
+++ b/spec/unit/provider/service/systemd_spec.rb
@@ -1,176 +1,176 @@
#! /usr/bin/env ruby
#
# Unit testing for the systemd service Provider
#
require 'spec_helper'
describe Puppet::Type.type(:service).provider(:systemd) do
before :each do
Puppet::Type.type(:service).stubs(:defaultprovider).returns described_class
described_class.stubs(:which).with('systemctl').returns '/bin/systemctl'
end
let :provider do
described_class.new(:name => 'sshd.service')
end
osfamily = [ 'archlinux' ]
osfamily.each do |osfamily|
it "should be the default provider on #{osfamily}" do
Facter.expects(:value).with(:osfamily).returns(osfamily)
- described_class.default?.should be_true
+ expect(described_class.default?).to be_truthy
end
end
it "should be the default provider on rhel7" do
Facter.expects(:value).with(:osfamily).at_least_once.returns(:redhat)
Facter.expects(:value).with(:operatingsystemmajrelease).at_least_once.returns("7")
- described_class.default?.should be_true
+ expect(described_class.default?).to be_truthy
end
it "should not be the default provider on rhel6" do
Facter.expects(:value).with(:osfamily).at_least_once.returns(:redhat)
Facter.expects(:value).with(:operatingsystemmajrelease).at_least_once.returns("6")
- described_class.default?.should_not be_true
+ expect(described_class.default?).not_to be_truthy
end
it "should be the default provider on sles12" do
Facter.expects(:value).with(:osfamily).at_least_once.returns(:suse)
Facter.expects(:value).with(:operatingsystemmajrelease).at_least_once.returns("12")
- described_class.default?.should be_true
+ expect(described_class.default?).to be_truthy
end
it "should be the default provider on opensuse13" do
Facter.expects(:value).with(:osfamily).at_least_once.returns(:suse)
Facter.expects(:value).with(:operatingsystemmajrelease).at_least_once.returns("13")
- described_class.default?.should be_true
+ expect(described_class.default?).to be_truthy
end
it "should not be the default provider on sles11" do
Facter.expects(:value).with(:osfamily).at_least_once.returns(:suse)
Facter.expects(:value).with(:operatingsystemmajrelease).at_least_once.returns("11")
- described_class.default?.should_not be_true
+ expect(described_class.default?).not_to be_truthy
end
[:enabled?, :enable, :disable, :start, :stop, :status, :restart].each do |method|
it "should have a #{method} method" do
- provider.should respond_to(method)
+ expect(provider).to respond_to(method)
end
end
describe ".instances" do
it "should have an instances method" do
- described_class.should respond_to :instances
+ expect(described_class).to respond_to :instances
end
it "should return only services" do
described_class.expects(:systemctl).with('list-unit-files', '--type', 'service', '--full', '--all', '--no-pager').returns File.read(my_fixture('list_unit_files_services'))
- described_class.instances.map(&:name).should =~ %w{
+ expect(described_class.instances.map(&:name)).to match_array(%w{
arp-ethers.service
auditd.service
autovt@.service
avahi-daemon.service
blk-availability.service
- }
+ })
end
end
describe "#start" do
it "should use the supplied start command if specified" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service', :start => '/bin/foo'))
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.start
end
it "should start the service with systemctl start otherwise" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
provider.expects(:execute).with(['/bin/systemctl','start','sshd.service'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.start
end
end
describe "#stop" do
it "should use the supplied stop command if specified" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service', :stop => '/bin/foo'))
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.stop
end
it "should stop the service with systemctl stop otherwise" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
provider.expects(:execute).with(['/bin/systemctl','stop','sshd.service'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.stop
end
end
describe "#enabled?" do
it "should return :true if the service is enabled" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
provider.expects(:systemctl).with('is-enabled', 'sshd.service').returns 'enabled'
- provider.enabled?.should == :true
+ expect(provider.enabled?).to eq(:true)
end
it "should return :false if the service is disabled" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
provider.expects(:systemctl).with('is-enabled', 'sshd.service').raises Puppet::ExecutionFailure, "Execution of '/bin/systemctl is-enabled sshd.service' returned 1: disabled"
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
end
describe "#enable" do
it "should run systemctl enable to enable a service" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
provider.expects(:systemctl).with('enable', 'sshd.service')
provider.enable
end
end
describe "#disable" do
it "should run systemctl disable to disable a service" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
provider.expects(:systemctl).with(:disable, 'sshd.service')
provider.disable
end
end
# Note: systemd provider does not care about hasstatus or a custom status
# command. I just assume that it does not make sense for systemd.
describe "#status" do
it "should return running if active" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
provider.expects(:systemctl).with('is-active', 'sshd.service').returns 'active'
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
it "should return stopped if inactive" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
provider.expects(:systemctl).with('is-active', 'sshd.service').raises Puppet::ExecutionFailure, "Execution of '/bin/systemctl is-active sshd.service' returned 3: inactive"
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
end
# Note: systemd provider does not care about hasrestart. I just assume it
# does not make sense for systemd
describe "#restart" do
it "should use the supplied restart command if specified" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :restart => '/bin/foo'))
provider.expects(:execute).with(['/bin/systemctl','restart','sshd.service'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.restart
end
it "should restart the service with systemctl restart" do
provider = described_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
provider.expects(:execute).with(['/bin/systemctl','restart','sshd.service'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.restart
end
end
it "(#16451) has command systemctl without being fully qualified" do
- described_class.instance_variable_get(:@commands).
- should include(:systemctl => 'systemctl')
+ expect(described_class.instance_variable_get(:@commands)).
+ to include(:systemctl => 'systemctl')
end
end
diff --git a/spec/unit/provider/service/upstart_spec.rb b/spec/unit/provider/service/upstart_spec.rb
index ba55cb846..9d7c4714b 100755
--- a/spec/unit/provider/service/upstart_spec.rb
+++ b/spec/unit/provider/service/upstart_spec.rb
@@ -1,590 +1,590 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:service).provider(:upstart) do
let(:manual) { "\nmanual" }
let(:start_on_default_runlevels) { "\nstart on runlevel [2,3,4,5]" }
let(:provider_class) { Puppet::Type.type(:service).provider(:upstart) }
def given_contents_of(file, content)
File.open(file, 'w') do |file|
file.write(content)
end
end
def then_contents_of(file)
File.open(file).read
end
def lists_processes_as(output)
Puppet::Util::Execution.stubs(:execpipe).with("/sbin/initctl list").yields(output)
provider_class.stubs(:which).with("/sbin/initctl").returns("/sbin/initctl")
end
it "should be the default provider on Ubuntu" do
Facter.expects(:value).with(:operatingsystem).returns("Ubuntu")
- described_class.default?.should be_true
+ expect(described_class.default?).to be_truthy
end
describe "excluding services" do
it "ignores tty and serial on Redhat systems" do
Facter.stubs(:value).with(:osfamily).returns('RedHat')
expect(described_class.excludes).to include 'serial'
expect(described_class.excludes).to include 'tty'
end
end
describe "#instances" do
it "should be able to find all instances" do
lists_processes_as("rc stop/waiting\nssh start/running, process 712")
- provider_class.instances.map {|provider| provider.name}.should =~ ["rc","ssh"]
+ expect(provider_class.instances.map {|provider| provider.name}).to match_array(["rc","ssh"])
end
it "should attach the interface name for network interfaces" do
lists_processes_as("network-interface (eth0)")
- provider_class.instances.first.name.should == "network-interface INTERFACE=eth0"
+ expect(provider_class.instances.first.name).to eq("network-interface INTERFACE=eth0")
end
it "should attach the job name for network interface security" do
processes = "network-interface-security (network-interface/eth0)"
provider_class.stubs(:execpipe).yields(processes)
- provider_class.instances.first.name.should == "network-interface-security JOB=network-interface/eth0"
+ expect(provider_class.instances.first.name).to eq("network-interface-security JOB=network-interface/eth0")
end
it "should not find excluded services" do
processes = "wait-for-state stop/waiting"
processes += "\nportmap-wait start/running"
processes += "\nidmapd-mounting stop/waiting"
processes += "\nstartpar-bridge start/running"
processes += "\ncryptdisks-udev stop/waiting"
processes += "\nstatd-mounting stop/waiting"
processes += "\ngssd-mounting stop/waiting"
provider_class.stubs(:execpipe).yields(processes)
- provider_class.instances.should be_empty
+ expect(provider_class.instances).to be_empty
end
end
describe "#search" do
it "searches through paths to find a matching conf file" do
File.stubs(:directory?).returns(true)
Puppet::FileSystem.stubs(:exist?).returns(false)
Puppet::FileSystem.expects(:exist?).with("/etc/init/foo-bar.conf").returns(true)
resource = Puppet::Type.type(:service).new(:name => "foo-bar", :provider => :upstart)
provider = provider_class.new(resource)
- provider.initscript.should == "/etc/init/foo-bar.conf"
+ expect(provider.initscript).to eq("/etc/init/foo-bar.conf")
end
it "searches for just the name of a compound named service" do
File.stubs(:directory?).returns(true)
Puppet::FileSystem.stubs(:exist?).returns(false)
Puppet::FileSystem.expects(:exist?).with("/etc/init/network-interface.conf").returns(true)
resource = Puppet::Type.type(:service).new(:name => "network-interface INTERFACE=lo", :provider => :upstart)
provider = provider_class.new(resource)
- provider.initscript.should == "/etc/init/network-interface.conf"
+ expect(provider.initscript).to eq("/etc/init/network-interface.conf")
end
end
describe "#status" do
it "should use the default status command if none is specified" do
resource = Puppet::Type.type(:service).new(:name => "foo", :provider => :upstart)
provider = provider_class.new(resource)
provider.stubs(:is_upstart?).returns(true)
provider.expects(:status_exec).with(["foo"]).returns("foo start/running, process 1000")
Process::Status.any_instance.stubs(:exitstatus).returns(0)
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
describe "when a special status command is specifed" do
it "should use the provided status command" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :provider => :upstart, :status => '/bin/foo')
provider = provider_class.new(resource)
provider.stubs(:is_upstart?).returns(true)
provider.expects(:status_exec).with(['foo']).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
Process::Status.any_instance.stubs(:exitstatus).returns(0)
provider.status
end
it "should return :stopped when the provided status command return non-zero" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :provider => :upstart, :status => '/bin/foo')
provider = provider_class.new(resource)
provider.stubs(:is_upstart?).returns(true)
provider.expects(:status_exec).with(['foo']).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 1
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
it "should return :running when the provided status command return zero" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :provider => :upstart, :status => '/bin/foo')
provider = provider_class.new(resource)
provider.stubs(:is_upstart?).returns(true)
provider.expects(:status_exec).with(['foo']).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 0
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
end
describe "when :hasstatus is set to false" do
it "should return :stopped if the pid can not be found" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :hasstatus => false, :provider => :upstart)
provider = provider_class.new(resource)
provider.stubs(:is_upstart?).returns(true)
provider.expects(:status_exec).with(['foo']).never
provider.expects(:getpid).returns nil
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
it "should return :running if the pid can be found" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :hasstatus => false, :provider => :upstart)
provider = provider_class.new(resource)
provider.stubs(:is_upstart?).returns(true)
provider.expects(:status_exec).with(['foo']).never
provider.expects(:getpid).returns 2706
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
end
it "should properly handle services with 'start' in their name" do
resource = Puppet::Type.type(:service).new(:name => "foostartbar", :provider => :upstart)
provider = provider_class.new(resource)
provider.stubs(:is_upstart?).returns(true)
provider.expects(:status_exec).with(["foostartbar"]).returns("foostartbar stop/waiting")
Process::Status.any_instance.stubs(:exitstatus).returns(0)
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
end
describe "inheritance" do
let :resource do
resource = Puppet::Type.type(:service).new(:name => "foo", :provider => :upstart)
end
let :provider do
provider = provider_class.new(resource)
end
describe "when upstart job" do
before(:each) do
provider.stubs(:is_upstart?).returns(true)
end
["start", "stop"].each do |command|
it "should return the #{command}cmd of its parent provider" do
- provider.send("#{command}cmd".to_sym).should == [provider.command(command.to_sym), resource.name]
+ expect(provider.send("#{command}cmd".to_sym)).to eq([provider.command(command.to_sym), resource.name])
end
end
it "should return nil for the statuscmd" do
- provider.statuscmd.should be_nil
+ expect(provider.statuscmd).to be_nil
end
end
end
describe "should be enableable" do
let :resource do
Puppet::Type.type(:service).new(:name => "foo", :provider => :upstart)
end
let :provider do
provider_class.new(resource)
end
let :init_script do
PuppetSpec::Files.tmpfile("foo.conf")
end
let :over_script do
PuppetSpec::Files.tmpfile("foo.override")
end
let :disabled_content do
"\t # \t start on\nother file stuff"
end
let :multiline_disabled do
"# \t start on other file stuff (\n" +
"# more stuff ( # )))))inline comment\n" +
"# finishing up )\n" +
"# and done )\n" +
"this line shouldn't be touched\n"
end
let :multiline_disabled_bad do
"# \t start on other file stuff (\n" +
"# more stuff ( # )))))inline comment\n" +
"# finishing up )\n" +
"# and done )\n" +
"# this is a comment i want to be a comment\n" +
"this line shouldn't be touched\n"
end
let :multiline_enabled_bad do
" \t start on other file stuff (\n" +
" more stuff ( # )))))inline comment\n" +
" finishing up )\n" +
" and done )\n" +
"# this is a comment i want to be a comment\n" +
"this line shouldn't be touched\n"
end
let :multiline_enabled do
" \t start on other file stuff (\n" +
" more stuff ( # )))))inline comment\n" +
" finishing up )\n" +
" and done )\n" +
"this line shouldn't be touched\n"
end
let :multiline_enabled_standalone do
" \t start on other file stuff (\n" +
" more stuff ( # )))))inline comment\n" +
" finishing up )\n" +
" and done )\n"
end
let :enabled_content do
"\t \t start on\nother file stuff"
end
let :content do
"just some text"
end
describe "Upstart version < 0.6.7" do
before(:each) do
provider.stubs(:is_upstart?).returns(true)
provider.stubs(:upstart_version).returns("0.6.5")
provider.stubs(:search).returns(init_script)
end
[:enabled?,:enable,:disable].each do |enableable|
it "should respond to #{enableable}" do
- provider.should respond_to(enableable)
+ expect(provider).to respond_to(enableable)
end
end
describe "when enabling" do
it "should open and uncomment the '#start on' line" do
given_contents_of(init_script, disabled_content)
provider.enable
- then_contents_of(init_script).should == enabled_content
+ expect(then_contents_of(init_script)).to eq(enabled_content)
end
it "should add a 'start on' line if none exists" do
given_contents_of(init_script, "this is a file")
provider.enable
- then_contents_of(init_script).should == "this is a file" + start_on_default_runlevels
+ expect(then_contents_of(init_script)).to eq("this is a file" + start_on_default_runlevels)
end
it "should handle multiline 'start on' stanzas" do
given_contents_of(init_script, multiline_disabled)
provider.enable
- then_contents_of(init_script).should == multiline_enabled
+ expect(then_contents_of(init_script)).to eq(multiline_enabled)
end
it "should leave not 'start on' comments alone" do
given_contents_of(init_script, multiline_disabled_bad)
provider.enable
- then_contents_of(init_script).should == multiline_enabled_bad
+ expect(then_contents_of(init_script)).to eq(multiline_enabled_bad)
end
end
describe "when disabling" do
it "should open and comment the 'start on' line" do
given_contents_of(init_script, enabled_content)
provider.disable
- then_contents_of(init_script).should == "#" + enabled_content
+ expect(then_contents_of(init_script)).to eq("#" + enabled_content)
end
it "should handle multiline 'start on' stanzas" do
given_contents_of(init_script, multiline_enabled)
provider.disable
- then_contents_of(init_script).should == multiline_disabled
+ expect(then_contents_of(init_script)).to eq(multiline_disabled)
end
end
describe "when checking whether it is enabled" do
it "should consider 'start on ...' to be enabled" do
given_contents_of(init_script, enabled_content)
- provider.enabled?.should == :true
+ expect(provider.enabled?).to eq(:true)
end
it "should consider '#start on ...' to be disabled" do
given_contents_of(init_script, disabled_content)
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
it "should consider no start on line to be disabled" do
given_contents_of(init_script, content)
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
end
end
describe "Upstart version < 0.9.0" do
before(:each) do
provider.stubs(:is_upstart?).returns(true)
provider.stubs(:upstart_version).returns("0.7.0")
provider.stubs(:search).returns(init_script)
end
[:enabled?,:enable,:disable].each do |enableable|
it "should respond to #{enableable}" do
- provider.should respond_to(enableable)
+ expect(provider).to respond_to(enableable)
end
end
describe "when enabling" do
it "should open and uncomment the '#start on' line" do
given_contents_of(init_script, disabled_content)
provider.enable
- then_contents_of(init_script).should == enabled_content
+ expect(then_contents_of(init_script)).to eq(enabled_content)
end
it "should add a 'start on' line if none exists" do
given_contents_of(init_script, "this is a file")
provider.enable
- then_contents_of(init_script).should == "this is a file" + start_on_default_runlevels
+ expect(then_contents_of(init_script)).to eq("this is a file" + start_on_default_runlevels)
end
it "should handle multiline 'start on' stanzas" do
given_contents_of(init_script, multiline_disabled)
provider.enable
- then_contents_of(init_script).should == multiline_enabled
+ expect(then_contents_of(init_script)).to eq(multiline_enabled)
end
it "should remove manual stanzas" do
given_contents_of(init_script, multiline_enabled + manual)
provider.enable
- then_contents_of(init_script).should == multiline_enabled
+ expect(then_contents_of(init_script)).to eq(multiline_enabled)
end
it "should leave not 'start on' comments alone" do
given_contents_of(init_script, multiline_disabled_bad)
provider.enable
- then_contents_of(init_script).should == multiline_enabled_bad
+ expect(then_contents_of(init_script)).to eq(multiline_enabled_bad)
end
end
describe "when disabling" do
it "should add a manual stanza" do
given_contents_of(init_script, enabled_content)
provider.disable
- then_contents_of(init_script).should == enabled_content + manual
+ expect(then_contents_of(init_script)).to eq(enabled_content + manual)
end
it "should remove manual stanzas before adding new ones" do
given_contents_of(init_script, multiline_enabled + manual + "\n" + multiline_enabled)
provider.disable
- then_contents_of(init_script).should == multiline_enabled + "\n" + multiline_enabled + manual
+ expect(then_contents_of(init_script)).to eq(multiline_enabled + "\n" + multiline_enabled + manual)
end
it "should handle multiline 'start on' stanzas" do
given_contents_of(init_script, multiline_enabled)
provider.disable
- then_contents_of(init_script).should == multiline_enabled + manual
+ expect(then_contents_of(init_script)).to eq(multiline_enabled + manual)
end
end
describe "when checking whether it is enabled" do
describe "with no manual stanza" do
it "should consider 'start on ...' to be enabled" do
given_contents_of(init_script, enabled_content)
- provider.enabled?.should == :true
+ expect(provider.enabled?).to eq(:true)
end
it "should consider '#start on ...' to be disabled" do
given_contents_of(init_script, disabled_content)
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
it "should consider no start on line to be disabled" do
given_contents_of(init_script, content)
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
end
describe "with manual stanza" do
it "should consider 'start on ...' to be disabled if there is a trailing manual stanza" do
given_contents_of(init_script, enabled_content + manual + "\nother stuff")
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
it "should consider two start on lines with a manual in the middle to be enabled" do
given_contents_of(init_script, enabled_content + manual + "\n" + enabled_content)
- provider.enabled?.should == :true
+ expect(provider.enabled?).to eq(:true)
end
end
end
end
describe "Upstart version > 0.9.0" do
before(:each) do
provider.stubs(:is_upstart?).returns(true)
provider.stubs(:upstart_version).returns("0.9.5")
provider.stubs(:search).returns(init_script)
provider.stubs(:overscript).returns(over_script)
end
[:enabled?,:enable,:disable].each do |enableable|
it "should respond to #{enableable}" do
- provider.should respond_to(enableable)
+ expect(provider).to respond_to(enableable)
end
end
describe "when enabling" do
it "should add a 'start on' line if none exists" do
given_contents_of(init_script, "this is a file")
provider.enable
- then_contents_of(init_script).should == "this is a file"
- then_contents_of(over_script).should == start_on_default_runlevels
+ expect(then_contents_of(init_script)).to eq("this is a file")
+ expect(then_contents_of(over_script)).to eq(start_on_default_runlevels)
end
it "should handle multiline 'start on' stanzas" do
given_contents_of(init_script, multiline_disabled)
provider.enable
- then_contents_of(init_script).should == multiline_disabled
- then_contents_of(over_script).should == start_on_default_runlevels
+ expect(then_contents_of(init_script)).to eq(multiline_disabled)
+ expect(then_contents_of(over_script)).to eq(start_on_default_runlevels)
end
it "should remove any manual stanzas from the override file" do
given_contents_of(over_script, manual)
given_contents_of(init_script, enabled_content)
provider.enable
- then_contents_of(init_script).should == enabled_content
- then_contents_of(over_script).should == ""
+ expect(then_contents_of(init_script)).to eq(enabled_content)
+ expect(then_contents_of(over_script)).to eq("")
end
it "should copy existing start on from conf file if conf file is disabled" do
given_contents_of(init_script, multiline_enabled_standalone + manual)
provider.enable
- then_contents_of(init_script).should == multiline_enabled_standalone + manual
- then_contents_of(over_script).should == multiline_enabled_standalone
+ expect(then_contents_of(init_script)).to eq(multiline_enabled_standalone + manual)
+ expect(then_contents_of(over_script)).to eq(multiline_enabled_standalone)
end
it "should leave not 'start on' comments alone" do
given_contents_of(init_script, multiline_disabled_bad)
given_contents_of(over_script, "")
provider.enable
- then_contents_of(init_script).should == multiline_disabled_bad
- then_contents_of(over_script).should == start_on_default_runlevels
+ expect(then_contents_of(init_script)).to eq(multiline_disabled_bad)
+ expect(then_contents_of(over_script)).to eq(start_on_default_runlevels)
end
end
describe "when disabling" do
it "should add a manual stanza to the override file" do
given_contents_of(init_script, enabled_content)
provider.disable
- then_contents_of(init_script).should == enabled_content
- then_contents_of(over_script).should == manual
+ expect(then_contents_of(init_script)).to eq(enabled_content)
+ expect(then_contents_of(over_script)).to eq(manual)
end
it "should handle multiline 'start on' stanzas" do
given_contents_of(init_script, multiline_enabled)
provider.disable
- then_contents_of(init_script).should == multiline_enabled
- then_contents_of(over_script).should == manual
+ expect(then_contents_of(init_script)).to eq(multiline_enabled)
+ expect(then_contents_of(over_script)).to eq(manual)
end
end
describe "when checking whether it is enabled" do
describe "with no override file" do
it "should consider 'start on ...' to be enabled" do
given_contents_of(init_script, enabled_content)
- provider.enabled?.should == :true
+ expect(provider.enabled?).to eq(:true)
end
it "should consider '#start on ...' to be disabled" do
given_contents_of(init_script, disabled_content)
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
it "should consider no start on line to be disabled" do
given_contents_of(init_script, content)
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
end
describe "with override file" do
it "should consider 'start on ...' to be disabled if there is manual in override file" do
given_contents_of(init_script, enabled_content)
given_contents_of(over_script, manual + "\nother stuff")
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
it "should consider '#start on ...' to be enabled if there is a start on in the override file" do
given_contents_of(init_script, disabled_content)
given_contents_of(over_script, "start on stuff")
- provider.enabled?.should == :true
+ expect(provider.enabled?).to eq(:true)
end
end
end
end
end
end
diff --git a/spec/unit/provider/service/windows_spec.rb b/spec/unit/provider/service/windows_spec.rb
index 3ecff6aa3..bec454784 100755
--- a/spec/unit/provider/service/windows_spec.rb
+++ b/spec/unit/provider/service/windows_spec.rb
@@ -1,231 +1,231 @@
#! /usr/bin/env ruby
#
# Unit testing for the Windows service Provider
#
require 'spec_helper'
require 'win32/service' if Puppet.features.microsoft_windows?
describe Puppet::Type.type(:service).provider(:windows), :if => Puppet.features.microsoft_windows? do
let(:name) { 'nonexistentservice' }
let(:resource) { Puppet::Type.type(:service).new(:name => name, :provider => :windows) }
let(:provider) { resource.provider }
let(:config) { Struct::ServiceConfigInfo.new }
let(:status) { Struct::ServiceStatus.new }
before :each do
# make sure we never actually execute anything (there are two execute methods)
provider.class.expects(:execute).never
provider.expects(:execute).never
Win32::Service.stubs(:config_info).with(name).returns(config)
Win32::Service.stubs(:status).with(name).returns(status)
end
describe ".instances" do
it "should enumerate all services" do
list_of_services = ['snmptrap', 'svchost', 'sshd'].map { |s| stub('service', :service_name => s) }
Win32::Service.expects(:services).returns(list_of_services)
- described_class.instances.map(&:name).should =~ ['snmptrap', 'svchost', 'sshd']
+ expect(described_class.instances.map(&:name)).to match_array(['snmptrap', 'svchost', 'sshd'])
end
end
describe "#start" do
before :each do
config.start_type = Win32::Service.get_start_type(Win32::Service::SERVICE_AUTO_START)
end
it "should start the service" do
provider.expects(:net).with(:start, name)
provider.start
end
it "should raise an error if the start command fails" do
provider.expects(:net).with(:start, name).raises(Puppet::ExecutionFailure, "The service name is invalid.")
expect {
provider.start
}.to raise_error(Puppet::Error, /Cannot start #{name}, error was: The service name is invalid./)
end
it "raises an error if the service doesn't exist" do
Win32::Service.expects(:config_info).with(name).raises(SystemCallError, 'OpenService')
expect {
provider.start
}.to raise_error(Puppet::Error, /Cannot get start type for #{name}/)
end
describe "when the service is disabled" do
before :each do
config.start_type = Win32::Service.get_start_type(Win32::Service::SERVICE_DISABLED)
end
it "should refuse to start if not managing enable" do
expect { provider.start }.to raise_error(Puppet::Error, /Will not start disabled service/)
end
it "should enable if managing enable and enable is true" do
resource[:enable] = :true
provider.expects(:net).with(:start, name)
Win32::Service.expects(:configure).with('service_name' => name, 'start_type' => Win32::Service::SERVICE_AUTO_START).returns(Win32::Service)
provider.start
end
it "should manual start if managing enable and enable is false" do
resource[:enable] = :false
provider.expects(:net).with(:start, name)
Win32::Service.expects(:configure).with('service_name' => name, 'start_type' => Win32::Service::SERVICE_DEMAND_START).returns(Win32::Service)
provider.start
end
end
end
describe "#stop" do
it "should stop a running service" do
provider.expects(:net).with(:stop, name)
provider.stop
end
it "should raise an error if the stop command fails" do
provider.expects(:net).with(:stop, name).raises(Puppet::ExecutionFailure, 'The service name is invalid.')
expect {
provider.stop
}.to raise_error(Puppet::Error, /Cannot stop #{name}, error was: The service name is invalid./)
end
end
describe "#status" do
['stopped', 'paused', 'stop pending', 'pause pending'].each do |state|
it "should report a #{state} service as stopped" do
status.current_state = state
- provider.status.should == :stopped
+ expect(provider.status).to eq(:stopped)
end
end
["running", "continue pending", "start pending" ].each do |state|
it "should report a #{state} service as running" do
status.current_state = state
- provider.status.should == :running
+ expect(provider.status).to eq(:running)
end
end
it "raises an error if the service doesn't exist" do
Win32::Service.expects(:status).with(name).raises(SystemCallError, 'OpenService')
expect {
provider.status
}.to raise_error(Puppet::Error, /Cannot get status of #{name}/)
end
end
describe "#restart" do
it "should use the supplied restart command if specified" do
resource[:restart] = 'c:/bin/foo'
provider.expects(:execute).never
provider.expects(:execute).with(['c:/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.restart
end
it "should restart the service" do
seq = sequence("restarting")
provider.expects(:stop).in_sequence(seq)
provider.expects(:start).in_sequence(seq)
provider.restart
end
end
describe "#enabled?" do
it "should report a service with a startup type of manual as manual" do
config.start_type = Win32::Service.get_start_type(Win32::Service::SERVICE_DEMAND_START)
- provider.enabled?.should == :manual
+ expect(provider.enabled?).to eq(:manual)
end
it "should report a service with a startup type of disabled as false" do
config.start_type = Win32::Service.get_start_type(Win32::Service::SERVICE_DISABLED)
- provider.enabled?.should == :false
+ expect(provider.enabled?).to eq(:false)
end
it "raises an error if the service doesn't exist" do
Win32::Service.expects(:config_info).with(name).raises(SystemCallError, 'OpenService')
expect {
provider.enabled?
}.to raise_error(Puppet::Error, /Cannot get start type for #{name}/)
end
# We need to guard this section explicitly since rspec will always
# construct all examples, even if it isn't going to run them.
if Puppet.features.microsoft_windows?
[Win32::Service::SERVICE_AUTO_START, Win32::Service::SERVICE_BOOT_START, Win32::Service::SERVICE_SYSTEM_START].each do |start_type_const|
start_type = Win32::Service.get_start_type(start_type_const)
it "should report a service with a startup type of '#{start_type}' as true" do
config.start_type = start_type
- provider.enabled?.should == :true
+ expect(provider.enabled?).to eq(:true)
end
end
end
end
describe "#enable" do
it "should set service start type to Service_Auto_Start when enabled" do
Win32::Service.expects(:configure).with('service_name' => name, 'start_type' => Win32::Service::SERVICE_AUTO_START).returns(Win32::Service)
provider.enable
end
it "raises an error if the service doesn't exist" do
Win32::Service.expects(:configure).with(has_entry('service_name' => name)).raises(SystemCallError, 'OpenService')
expect {
provider.enable
}.to raise_error(Puppet::Error, /Cannot enable #{name}/)
end
end
describe "#disable" do
it "should set service start type to Service_Disabled when disabled" do
Win32::Service.expects(:configure).with('service_name' => name, 'start_type' => Win32::Service::SERVICE_DISABLED).returns(Win32::Service)
provider.disable
end
it "raises an error if the service doesn't exist" do
Win32::Service.expects(:configure).with(has_entry('service_name' => name)).raises(SystemCallError, 'OpenService')
expect {
provider.disable
}.to raise_error(Puppet::Error, /Cannot disable #{name}/)
end
end
describe "#manual_start" do
it "should set service start type to Service_Demand_Start (manual) when manual" do
Win32::Service.expects(:configure).with('service_name' => name, 'start_type' => Win32::Service::SERVICE_DEMAND_START).returns(Win32::Service)
provider.manual_start
end
it "raises an error if the service doesn't exist" do
Win32::Service.expects(:configure).with(has_entry('service_name' => name)).raises(SystemCallError, 'OpenService')
expect {
provider.manual_start
}.to raise_error(Puppet::Error, /Cannot enable #{name}/)
end
end
end
diff --git a/spec/unit/provider/ssh_authorized_key/parsed_spec.rb b/spec/unit/provider/ssh_authorized_key/parsed_spec.rb
index 78abec901..3183a5ca8 100755
--- a/spec/unit/provider/ssh_authorized_key/parsed_spec.rb
+++ b/spec/unit/provider/ssh_authorized_key/parsed_spec.rb
@@ -1,276 +1,276 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'shared_behaviours/all_parsedfile_providers'
require 'puppet_spec/files'
provider_class = Puppet::Type.type(:ssh_authorized_key).provider(:parsed)
describe provider_class, :unless => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
before :each do
@keyfile = tmpfile('authorized_keys')
@provider_class = provider_class
@provider_class.initvars
@provider_class.any_instance.stubs(:target).returns @keyfile
@user = 'random_bob'
Puppet::Util.stubs(:uid).with(@user).returns 12345
end
def mkkey(args)
args[:target] = @keyfile
args[:user] = @user
resource = Puppet::Type.type(:ssh_authorized_key).new(args)
key = @provider_class.new(resource)
args.each do |p,v|
key.send(p.to_s + "=", v)
end
key
end
def genkey(key)
@provider_class.stubs(:filetype).returns(Puppet::Util::FileType::FileTypeRam)
File.stubs(:chown)
File.stubs(:chmod)
Puppet::Util::SUIDManager.stubs(:asuser).yields
key.flush
@provider_class.target_object(@keyfile).read
end
it_should_behave_like "all parsedfile providers", provider_class
it "should be able to generate a basic authorized_keys file" do
key = mkkey(:name => "Just_Testing",
:key => "AAAAfsfddsjldjgksdflgkjsfdlgkj",
:type => "ssh-dss",
:ensure => :present,
:options => [:absent]
)
- genkey(key).should == "ssh-dss AAAAfsfddsjldjgksdflgkjsfdlgkj Just_Testing\n"
+ expect(genkey(key)).to eq("ssh-dss AAAAfsfddsjldjgksdflgkjsfdlgkj Just_Testing\n")
end
it "should be able to generate an authorized_keys file with options" do
key = mkkey(:name => "root@localhost",
:key => "AAAAfsfddsjldjgksdflgkjsfdlgkj",
:type => "ssh-rsa",
:ensure => :present,
:options => ['from="192.168.1.1"', "no-pty", "no-X11-forwarding"]
)
- genkey(key).should == "from=\"192.168.1.1\",no-pty,no-X11-forwarding ssh-rsa AAAAfsfddsjldjgksdflgkjsfdlgkj root@localhost\n"
+ expect(genkey(key)).to eq("from=\"192.168.1.1\",no-pty,no-X11-forwarding ssh-rsa AAAAfsfddsjldjgksdflgkjsfdlgkj root@localhost\n")
end
it "should parse comments" do
result = [{ :record_type => :comment, :line => "# hello" }]
- @provider_class.parse("# hello\n").should == result
+ expect(@provider_class.parse("# hello\n")).to eq(result)
end
it "should parse comments with leading whitespace" do
result = [{ :record_type => :comment, :line => " # hello" }]
- @provider_class.parse(" # hello\n").should == result
+ expect(@provider_class.parse(" # hello\n")).to eq(result)
end
it "should skip over lines with only whitespace" do
result = [{ :record_type => :comment, :line => "#before" },
{ :record_type => :blank, :line => " " },
{ :record_type => :comment, :line => "#after" }]
- @provider_class.parse("#before\n \n#after\n").should == result
+ expect(@provider_class.parse("#before\n \n#after\n")).to eq(result)
end
it "should skip over completely empty lines" do
result = [{ :record_type => :comment, :line => "#before"},
{ :record_type => :blank, :line => ""},
{ :record_type => :comment, :line => "#after"}]
- @provider_class.parse("#before\n\n#after\n").should == result
+ expect(@provider_class.parse("#before\n\n#after\n")).to eq(result)
end
it "should be able to parse name if it includes whitespace" do
- @provider_class.parse_line('ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC7pHZ1XRj3tXbFpPFhMGU1bVwz7jr13zt/wuE+pVIJA8GlmHYuYtIxHPfDHlkixdwLachCpSQUL9NbYkkRFRn9m6PZ7125ohE4E4m96QS6SGSQowTiRn4Lzd9LV38g93EMHjPmEkdSq7MY4uJEd6DUYsLvaDYdIgBiLBIWPA3OrQ== fancy user')[:name].should == 'fancy user'
- @provider_class.parse_line('from="host1.reductlivelabs.com,host.reductivelabs.com",command="/usr/local/bin/run",ssh-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC7pHZ1XRj3tXbFpPFhMGU1bVwz7jr13zt/wuE+pVIJA8GlmHYuYtIxHPfDHlkixdwLachCpSQUL9NbYkkRFRn9m6PZ7125ohE4E4m96QS6SGSQowTiRn4Lzd9LV38g93EMHjPmEkdSq7MY4uJEd6DUYsLvaDYdIgBiLBIWPA3OrQ== fancy user')[:name].should == 'fancy user'
+ expect(@provider_class.parse_line('ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC7pHZ1XRj3tXbFpPFhMGU1bVwz7jr13zt/wuE+pVIJA8GlmHYuYtIxHPfDHlkixdwLachCpSQUL9NbYkkRFRn9m6PZ7125ohE4E4m96QS6SGSQowTiRn4Lzd9LV38g93EMHjPmEkdSq7MY4uJEd6DUYsLvaDYdIgBiLBIWPA3OrQ== fancy user')[:name]).to eq('fancy user')
+ expect(@provider_class.parse_line('from="host1.reductlivelabs.com,host.reductivelabs.com",command="/usr/local/bin/run",ssh-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC7pHZ1XRj3tXbFpPFhMGU1bVwz7jr13zt/wuE+pVIJA8GlmHYuYtIxHPfDHlkixdwLachCpSQUL9NbYkkRFRn9m6PZ7125ohE4E4m96QS6SGSQowTiRn4Lzd9LV38g93EMHjPmEkdSq7MY4uJEd6DUYsLvaDYdIgBiLBIWPA3OrQ== fancy user')[:name]).to eq('fancy user')
end
it "should be able to parse options containing commas via its parse_options method" do
options = %w{from="host1.reductlivelabs.com,host.reductivelabs.com" command="/usr/local/bin/run" ssh-pty}
optionstr = options.join(", ")
- @provider_class.parse_options(optionstr).should == options
+ expect(@provider_class.parse_options(optionstr)).to eq(options)
end
it "should parse quoted options" do
line = 'command="/usr/local/bin/mybin \"$SSH_ORIGINAL_COMMAND\"" ssh-rsa xxx mykey'
- @provider_class.parse(line)[0][:options][0].should == 'command="/usr/local/bin/mybin \"$SSH_ORIGINAL_COMMAND\""'
+ expect(@provider_class.parse(line)[0][:options][0]).to eq('command="/usr/local/bin/mybin \"$SSH_ORIGINAL_COMMAND\""')
end
it "should use '' as name for entries that lack a comment" do
line = "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAut8aOSxenjOqF527dlsdHWV4MNoAsX14l9M297+SQXaQ5Z3BedIxZaoQthkDALlV/25A1COELrg9J2MqJNQc8Xe9XQOIkBQWWinUlD/BXwoOTWEy8C8zSZPHZ3getMMNhGTBO+q/O+qiJx3y5cA4MTbw2zSxukfWC87qWwcZ64UUlegIM056vPsdZWFclS9hsROVEa57YUMrehQ1EGxT4Z5j6zIopufGFiAPjZigq/vqgcAqhAKP6yu4/gwO6S9tatBeEjZ8fafvj1pmvvIplZeMr96gHE7xS3pEEQqnB3nd4RY7AF6j9kFixnsytAUO7STPh/M3pLiVQBN89TvWPQ=="
- @provider_class.parse(line)[0][:name].should == ""
+ expect(@provider_class.parse(line)[0][:name]).to eq("")
end
{
# ssh-keygen -t dsa -b 1024
'ssh-dss' => 'AAAAB3NzaC1kc3MAAACBANGTefWMXS780qLMMgysq3GNMKzg55LXZODif6Tqv1vtTh4Wuk3J5X5u644jTyNdAIn1RiBI9MnwnZMZ6nXKvucMcMQWMibYS9W2MhkRj3oqsLWMMsdGXJL18SWM5A6oC3oIRC4JHJZtkm0OctR2trKxmX+MGhdCd+Xpsh9CNK8XAAAAFQD4olFiwv+QQUFdaZbWUy1CLEG9xQAAAIByCkXKgoriZF8bQ0OX1sKuR69M/6n5ngmQGVBKB7BQkpUjbK/OggB6iJgst5utKkDcaqYRnrTYG9q3jJ/flv7yYePuoSreS0nCMMx9gpEYuq+7Sljg9IecmN/IHrNd9qdYoASy5iuROQMvEZM7KFHA8vBv0tWdBOsp4hZKyiL1DAAAAIEAjkZlOps9L+cD/MTzxDj7toYYypdLOvjlcPBaglkPZoFZ0MAKTI0zXlVX1cWAnkd0Yfo4EpP+6XAjlZkod+QXKXM4Tb4PnR34ASMeU6sEjM61Na24S7JD3gpPKataFU/oH3hzXsBdK2ttKYmoqvf61h32IA/3Z5PjCCD9pPLPpAY',
# ssh-keygen -t rsa -b 2048
'ssh-rsa' => 'AAAAB3NzaC1yc2EAAAADAQABAAABAQDYtEaWa1mlxaAh9vtiz6RCVKDiJHDY15nsqqWU7F7A1+U1498+sWDyRDkZ8vXWQpzyOMBzBSHIxhsprlKhkjomy8BuJP+bHDBIKx4zgSFDrklrPIf467Iuug8J0qqDLxO4rOOjeAiLEyC0t2ZGnsTEea+rmat0bJ2cv3g5L4gH/OFz2pI4ZLp1HGN83ipl5UH8CjXQKwo3Db1E3WJCqKgszVX0Z4/qjnBRxFMoqky/1mGb/mX1eoT9JyQ8OhU9uENZOShkksSpgUqjlrjpj0Yd14hBlnE3M18pE4ivxjzectA/XRKNZaxOL1YREtU8sXusAwmlEY4aJ64aR0JrXfgx',
# ssh-keygen -t ecdsa -b 256
'ecdsa-sha2-nistp256' => 'AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBO5PfBf0c2jAuqD+Lj3j+SuXOXNT2uqESLVOn5jVQfEF9GzllOw+CMOpUvV1CiOOn+F1ET15vcsfmD7z05WUTA=',
# ssh-keygen -t ecdsa -b 384
'ecdsa-sha2-nistp384' => 'AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBJIfxNoVK4FX3RuMlkHOwwxXwAh6Fqx5uAp4ftXrJ+64qYuIzb+/zSAkJV698Sre1b1lb0G4LyDdVAvXwaYK9kN25vy8umV3WdfZeHKXJGCcrplMCbbOERWARlpiPNEblg==',
# ssh-keygen -t ecdsa -b 521
'ecdsa-sha2-nistp521' => 'AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBADLK+u12xwB0JOwpmaxYXv8KnPK4p+SE2405qoo+vpAQ569fMwPMgKzltd770amdeuFogw/MJu17PN9LDdrD3o0uwHMjWee6TpHQDkuEetaxiou6K0WAzgbxx9QsY0MsJgXf1BuMLqdK+xT183wOSXwwumv99G7T32dOJZ5tYrH0y4XMw==',
# ssh-keygen -t ed25519
'ssh-ed25519' => 'AAAAC3NzaC1lZDI1NTE5AAAAIBWvu7D1KHBPaNXQcEuBsp48+JyPelXAq8ds6K5Du9gd',
}.each_pair do |keytype, keydata|
it "should be able to parse a #{keytype} key entry" do
comment = 'sample_key'
record = @provider_class.parse_line("#{keytype} #{keydata} #{comment}")
- record.should_not be_nil
- record[:name].should == comment
- record[:key].should == keydata
- record[:type].should == keytype
+ expect(record).not_to be_nil
+ expect(record[:name]).to eq(comment)
+ expect(record[:key]).to eq(keydata)
+ expect(record[:type]).to eq(keytype)
end
end
describe "prefetch_hook" do
let(:path) { '/path/to/keyfile' }
let(:input) do
{ :type => 'rsa',
:key => 'KEYDATA',
:name => '',
:record_type => :parsed,
:target => path,
}
end
it "adds an indexed name to unnamed resources" do
- @provider_class.prefetch_hook([input])[0][:name].should =~ /^#{path}:unnamed-\d+/
+ expect(@provider_class.prefetch_hook([input])[0][:name]).to match(/^#{path}:unnamed-\d+/)
end
end
end
describe provider_class, :unless => Puppet.features.microsoft_windows? do
before :each do
@resource = Puppet::Type.type(:ssh_authorized_key).new(:name => "foo", :user => "random_bob")
@provider = provider_class.new(@resource)
provider_class.stubs(:filetype).returns(Puppet::Util::FileType::FileTypeRam)
Puppet::Util::SUIDManager.stubs(:asuser).yields
provider_class.initvars
end
describe "when flushing" do
before :each do
# Stub file and directory operations
Dir.stubs(:mkdir)
File.stubs(:chmod)
File.stubs(:chown)
end
describe "and both a user and a target have been specified" do
before :each do
Puppet::Util.stubs(:uid).with("random_bob").returns 12345
@resource[:user] = "random_bob"
target = "/tmp/.ssh_dir/place_to_put_authorized_keys"
@resource[:target] = target
end
it "should create the directory" do
Puppet::FileSystem.stubs(:exist?).with("/tmp/.ssh_dir").returns false
Dir.expects(:mkdir).with("/tmp/.ssh_dir", 0700)
@provider.flush
end
it "should absolutely not chown the directory to the user" do
uid = Puppet::Util.uid("random_bob")
File.expects(:chown).never
@provider.flush
end
it "should absolutely not chown the key file to the user" do
uid = Puppet::Util.uid("random_bob")
File.expects(:chown).never
@provider.flush
end
it "should chmod the key file to 0600" do
File.expects(:chmod).with(0600, "/tmp/.ssh_dir/place_to_put_authorized_keys")
@provider.flush
end
end
describe "and a user has been specified with no target" do
before :each do
@resource[:user] = "nobody"
#
# I'd like to use random_bob here and something like
#
# File.stubs(:expand_path).with("~random_bob/.ssh").returns "/users/r/random_bob/.ssh"
#
# but mocha objects strenuously to stubbing File.expand_path
# so I'm left with using nobody.
@dir = File.expand_path("~nobody/.ssh")
end
it "should create the directory if it doesn't exist" do
Puppet::FileSystem.stubs(:exist?).with(@dir).returns false
Dir.expects(:mkdir).with(@dir,0700)
@provider.flush
end
it "should not create or chown the directory if it already exist" do
Puppet::FileSystem.stubs(:exist?).with(@dir).returns false
Dir.expects(:mkdir).never
@provider.flush
end
it "should absolutely not chown the directory to the user if it creates it" do
Puppet::FileSystem.stubs(:exist?).with(@dir).returns false
Dir.stubs(:mkdir).with(@dir,0700)
uid = Puppet::Util.uid("nobody")
File.expects(:chown).never
@provider.flush
end
it "should not create or chown the directory if it already exist" do
Puppet::FileSystem.stubs(:exist?).with(@dir).returns false
Dir.expects(:mkdir).never
File.expects(:chown).never
@provider.flush
end
it "should absolutely not chown the key file to the user" do
uid = Puppet::Util.uid("nobody")
File.expects(:chown).never
@provider.flush
end
it "should chmod the key file to 0600" do
File.expects(:chmod).with(0600, File.expand_path("~nobody/.ssh/authorized_keys"))
@provider.flush
end
end
describe "and a target has been specified with no user" do
it "should raise an error" do
@resource = Puppet::Type.type(:ssh_authorized_key).new(:name => "foo", :target => "/tmp/.ssh_dir/place_to_put_authorized_keys")
@provider = provider_class.new(@resource)
- proc { @provider.flush }.should raise_error
+ expect { @provider.flush }.to raise_error
end
end
describe "and an invalid user has been specified with no target" do
it "should catch an exception and raise a Puppet error" do
@resource[:user] = "thisusershouldnotexist"
- lambda { @provider.flush }.should raise_error(Puppet::Error)
+ expect { @provider.flush }.to raise_error(Puppet::Error)
end
end
end
end
diff --git a/spec/unit/provider/sshkey/parsed_spec.rb b/spec/unit/provider/sshkey/parsed_spec.rb
index 28b357b9a..e80e75325 100755
--- a/spec/unit/provider/sshkey/parsed_spec.rb
+++ b/spec/unit/provider/sshkey/parsed_spec.rb
@@ -1,71 +1,71 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:sshkey).provider(:parsed)
describe "sshkey parsed provider" do
let :type do Puppet::Type.type(:sshkey) end
let :provider do type.provider(:parsed) end
subject { provider }
after :each do
subject.clear
end
def key
'AAAAB3NzaC1yc2EAAAABIwAAAQEAzwHhxXvIrtfIwrudFqc8yQcIfMudrgpnuh1F3AV6d2BrLgu/yQE7W5UyJMUjfj427sQudRwKW45O0Jsnr33F4mUw+GIMlAAmp9g24/OcrTiB8ZUKIjoPy/cO4coxGi8/NECtRzpD/ZUPFh6OEpyOwJPMb7/EC2Az6Otw4StHdXUYw22zHazBcPFnv6zCgPx1hA7QlQDWTu4YcL0WmTYQCtMUb3FUqrcFtzGDD0ytosgwSd+JyN5vj5UwIABjnNOHPZ62EY1OFixnfqX/+dUwrFSs5tPgBF/KkC6R7tmbUfnBON6RrGEmu+ajOTOLy23qUZB4CQ53V7nyAWhzqSK+hw=='
end
it "should parse the name from the first field" do
- subject.parse_line('test ssh-rsa '+key)[:name].should == "test"
+ expect(subject.parse_line('test ssh-rsa '+key)[:name]).to eq("test")
end
it "should parse the first component of the first field as the name" do
- subject.parse_line('test,alias ssh-rsa '+key)[:name].should == "test"
+ expect(subject.parse_line('test,alias ssh-rsa '+key)[:name]).to eq("test")
end
it "should parse host_aliases from the remaining components of the first field" do
- subject.parse_line('test,alias ssh-rsa '+key)[:host_aliases].should == ["alias"]
+ expect(subject.parse_line('test,alias ssh-rsa '+key)[:host_aliases]).to eq(["alias"])
end
it "should parse multiple host_aliases" do
- subject.parse_line('test,alias1,alias2,alias3 ssh-rsa '+key)[:host_aliases].should == ["alias1","alias2","alias3"]
+ expect(subject.parse_line('test,alias1,alias2,alias3 ssh-rsa '+key)[:host_aliases]).to eq(["alias1","alias2","alias3"])
end
it "should not drop an empty host_alias" do
- subject.parse_line('test,alias, ssh-rsa '+key)[:host_aliases].should == ["alias",""]
+ expect(subject.parse_line('test,alias, ssh-rsa '+key)[:host_aliases]).to eq(["alias",""])
end
it "should recognise when there are no host aliases" do
- subject.parse_line('test ssh-rsa '+key)[:host_aliases].should == []
+ expect(subject.parse_line('test ssh-rsa '+key)[:host_aliases]).to eq([])
end
context "with the sample file" do
let :fixture do my_fixture('sample') end
before :each do subject.stubs(:default_target).returns(fixture) end
it "should parse to records on prefetch" do
- subject.target_records(fixture).should be_empty
+ expect(subject.target_records(fixture)).to be_empty
subject.prefetch
records = subject.target_records(fixture)
- records.should be_an Array
- records.should be_all {|x| x.should be_an Hash }
+ expect(records).to be_an Array
+ expect(records).to be_all {|x| expect(x).to be_an Hash }
end
it "should reconstitute the file from records" do
subject.prefetch
records = subject.target_records(fixture)
text = subject.to_file(records).gsub(/^# HEADER.+\n/, '')
oldlines = File.readlines(fixture).map(&:chomp)
newlines = text.chomp.split("\n")
- oldlines.length.should == newlines.length
+ expect(oldlines.length).to eq(newlines.length)
oldlines.zip(newlines).each do |old, new|
- old.gsub(/\s+/, '').should == new.gsub(/\s+/, '')
+ expect(old.gsub(/\s+/, '')).to eq(new.gsub(/\s+/, ''))
end
end
end
end
diff --git a/spec/unit/provider/user/aix_spec.rb b/spec/unit/provider/user/aix_spec.rb
index b9edaff49..a0c639806 100644
--- a/spec/unit/provider/user/aix_spec.rb
+++ b/spec/unit/provider/user/aix_spec.rb
@@ -1,162 +1,162 @@
require 'spec_helper'
provider_class = Puppet::Type.type(:user).provider(:aix)
describe provider_class do
let(:lsuser_all_example) do
<<-OUTPUT
root id=0 pgrp=system groups=system,bin,sys,security,cron,audit,lp home=/root shell=/usr/bin/bash auditclasses=general login=true su=true rlogin=true daemon=true admin=true sugroups=ALL admgroups=lolt,allstaff tpath=nosak ttys=ALL expires=0 auth1=SYSTEM auth2=NONE umask=22 registry=files SYSTEM=compat logintimes= loginretries=0 pwdwarntime=0 account_locked=false minage=0 maxage=0 maxexpired=-1 minalpha=0 minother=0 mindiff=0 maxrepeats=8 minlen=0 histexpire=0 histsize=0 pwdchecks= dictionlist= default_roles= fsize=2097151 cpu=-1 data=262144 stack=65536 core=2097151 rss=65536 nofiles=2000 time_last_login=1358465855 time_last_unsuccessful_login=1358378454 tty_last_login=ssh tty_last_unsuccessful_login=ssh host_last_login=rpm-builder.puppetlabs.lan host_last_unsuccessful_login=192.168.100.78 unsuccessful_login_count=0 roles=
guest id=100 pgrp=usr groups=usr home=/home/guest login=true su=true rlogin=true daemon=true admin=false sugroups=ALL admgroups= tpath=nosak ttys=ALL expires=0 auth1=SYSTEM auth2=NONE umask=22 registry=files SYSTEM=compat logintimes= loginretries=0 pwdwarntime=0 account_locked=false minage=0 maxage=0 maxexpired=-1 minalpha=0 minother=0 mindiff=0 maxrepeats=8 minlen=0 histexpire=0 histsize=0 pwdchecks= dictionlist= default_roles= fsize=2097151 cpu=-1 data=262144 stack=65536 core=2097151 rss=65536 nofiles=2000 roles=
OUTPUT
end
let(:lsgroup_all_example) do
<<-OUTPUT
root id=0 pgrp=system groups=system,bin,sys,security,cron,audit,lp home=/root shell=/usr/bin/bash
guest id=100 pgrp=usr groups=usr home=/home/guest
OUTPUT
end
before do
@resource = stub('resource')
@provider = provider_class.new(@resource)
end
it "should be able to return a group name based on a group ID" do
@provider.stubs(:lsgroupscmd)
@provider.stubs(:execute).returns(lsgroup_all_example)
- @provider.groupname_by_id(100).should == 'guest'
+ expect(@provider.groupname_by_id(100)).to eq('guest')
end
it "should be able to list all users" do
provider_class.stubs(:command)
provider_class.stubs(:execute).returns(lsuser_all_example)
- provider_class.list_all.should == ['root', 'guest']
+ expect(provider_class.list_all).to eq(['root', 'guest'])
end
describe "#managed_attribute_keys" do
let(:existing_attributes) do
{ :account_locked => 'false',
:admin => 'false',
:login => 'true',
'su' => 'true'
}
end
before(:each) do
original_parameters = { :attributes => attribute_array }
@resource.stubs(:original_parameters).returns(original_parameters)
end
describe "invoked via manifest" do
let(:attribute_array) { ["rlogin=false", "login =true"] }
it "should return only the keys of the attribute key=value pair from manifest" do
keys = @provider.managed_attribute_keys(existing_attributes)
- keys.should be_include(:rlogin)
- keys.should be_include(:login)
- keys.should_not be_include(:su)
+ expect(keys).to be_include(:rlogin)
+ expect(keys).to be_include(:login)
+ expect(keys).not_to be_include(:su)
end
it "should strip spaces from symbols" do
keys = @provider.managed_attribute_keys(existing_attributes)
- keys.should be_include(:login)
- keys.should_not be_include(:"login ")
+ expect(keys).to be_include(:login)
+ expect(keys).not_to be_include(:"login ")
end
it "should have the same count as that from the manifest" do
keys = @provider.managed_attribute_keys(existing_attributes)
- keys.size.should == attribute_array.size
+ expect(keys.size).to eq(attribute_array.size)
end
it "should convert the keys to symbols" do
keys = @provider.managed_attribute_keys(existing_attributes)
all_symbols = keys.all? {|k| k.is_a? Symbol}
- all_symbols.should be_true
+ expect(all_symbols).to be_truthy
end
end
describe "invoked via RAL" do
let(:attribute_array) { nil }
it "should return the keys in supplied hash" do
keys = @provider.managed_attribute_keys(existing_attributes)
- keys.should_not be_include(:rlogin)
- keys.should be_include(:login)
- keys.should be_include(:su)
+ expect(keys).not_to be_include(:rlogin)
+ expect(keys).to be_include(:login)
+ expect(keys).to be_include(:su)
end
it "should convert the keys to symbols" do
keys = @provider.managed_attribute_keys(existing_attributes)
all_symbols = keys.all? {|k| k.is_a? Symbol}
- all_symbols.should be_true
+ expect(all_symbols).to be_truthy
end
end
end
describe "#should_include?" do
it "should exclude keys translated into something else" do
managed_keys = [:rlogin]
@provider.class.attribute_mapping_from.stubs(:include?).with(:rlogin).returns(true)
@provider.class.stubs(:attribute_ignore).returns([])
- @provider.should_include?(:rlogin, managed_keys).should be_false
+ expect(@provider.should_include?(:rlogin, managed_keys)).to be_falsey
end
it "should exclude keys explicitly ignored" do
managed_keys = [:rlogin]
@provider.class.attribute_mapping_from.stubs(:include?).with(:rlogin).returns(false)
@provider.class.stubs(:attribute_ignore).returns([:rlogin])
- @provider.should_include?(:rlogin, managed_keys).should be_false
+ expect(@provider.should_include?(:rlogin, managed_keys)).to be_falsey
end
it "should exclude keys not specified in manifest" do
managed_keys = [:su]
@provider.class.attribute_mapping_from.stubs(:include?).with(:rlogin).returns(false)
@provider.class.stubs(:attribute_ignore).returns([])
- @provider.should_include?(:rlogin, managed_keys).should be_false
+ expect(@provider.should_include?(:rlogin, managed_keys)).to be_falsey
end
it "should include keys specified in manifest if not translated or ignored" do
managed_keys = [:rlogin]
@provider.class.attribute_mapping_from.stubs(:include?).with(:rlogin).returns(false)
@provider.class.stubs(:attribute_ignore).returns([])
- @provider.should_include?(:rlogin, managed_keys).should be_true
+ expect(@provider.should_include?(:rlogin, managed_keys)).to be_truthy
end
end
describe "when handling passwords" do
let(:passwd_without_spaces) do
# from http://pic.dhe.ibm.com/infocenter/aix/v7r1/index.jsp?topic=%2Fcom.ibm.aix.files%2Fdoc%2Faixfiles%2Fpasswd_security.htm
<<-OUTPUT
smith:
password = MGURSj.F056Dj
lastupdate = 623078865
flags = ADMIN,NOCHECK
OUTPUT
end
let(:passwd_with_spaces) do
# add trailing space to the password
passwd_without_spaces.gsub(/password = (.*)/, 'password = \1 ')
end
it "should be able to read the hashed password" do
@provider.stubs(:open_security_passwd).returns(StringIO.new(passwd_without_spaces))
@resource.stubs(:[]).returns('smith')
- @provider.password.should == 'MGURSj.F056Dj'
+ expect(@provider.password).to eq('MGURSj.F056Dj')
end
it "should be able to read the hashed password, even with trailing spaces" do
@provider.stubs(:open_security_passwd).returns(StringIO.new(passwd_with_spaces))
@resource.stubs(:[]).returns('smith')
- @provider.password.should == 'MGURSj.F056Dj'
+ expect(@provider.password).to eq('MGURSj.F056Dj')
end
end
end
diff --git a/spec/unit/provider/user/directoryservice_spec.rb b/spec/unit/provider/user/directoryservice_spec.rb
index 5f4ba3552..a055a738b 100755
--- a/spec/unit/provider/user/directoryservice_spec.rb
+++ b/spec/unit/provider/user/directoryservice_spec.rb
@@ -1,1070 +1,1070 @@
#! /usr/bin/env ruby -S rspec
# encoding: ASCII-8BIT
require 'spec_helper'
require 'facter/util/plist'
describe Puppet::Type.type(:user).provider(:directoryservice) do
let(:username) { 'nonexistent_user' }
let(:user_path) { "/Users/#{username}" }
let(:resource) do
Puppet::Type.type(:user).new(
:name => username,
:provider => :directoryservice
)
end
let(:provider) { resource.provider }
let(:users_plist_dir) { '/var/db/dslocal/nodes/Default/users' }
let(:stringio_object) { StringIO.new('new_stringio_object') }
# This is the output of doing `dscl -plist . read /Users/<username>` which
# will return a hash of keys whose values are all arrays.
let(:user_plist_xml) do
'<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>dsAttrTypeStandard:NFSHomeDirectory</key>
<array>
<string>/Users/nonexistent_user</string>
</array>
<key>dsAttrTypeStandard:RealName</key>
<array>
<string>nonexistent_user</string>
</array>
<key>dsAttrTypeStandard:PrimaryGroupID</key>
<array>
<string>22</string>
</array>
<key>dsAttrTypeStandard:UniqueID</key>
<array>
<string>1000</string>
</array>
<key>dsAttrTypeStandard:RecordName</key>
<array>
<string>nonexistent_user</string>
</array>
</dict>
</plist>'
end
# This is the same as above, however in a native Ruby hash instead
# of XML
let(:user_plist_hash) do
{
"dsAttrTypeStandard:RealName" => [username],
"dsAttrTypeStandard:NFSHomeDirectory" => [user_path],
"dsAttrTypeStandard:PrimaryGroupID" => ["22"],
"dsAttrTypeStandard:UniqueID" => ["1000"],
"dsAttrTypeStandard:RecordName" => [username]
}
end
# The below value is the result of executing
# `dscl -plist . read /Users/<username> ShadowHashData` on a 10.7
# system and converting it to a native Ruby Hash with Plist.parse_xml
let(:sha512_shadowhashdata_hash) do
{
'dsAttrTypeNative:ShadowHashData' => ['62706c69 73743030 d101025d 53414c54 45442d53 48413531 324f1044 7ea7d592 131f57b2 c8f8bdbc ec8d9df1 2128a386 393a4f00 c7619bac 2622a44d 451419d1 1da512d5 915ab98e 39718ac9 4083fe2e fd6bf710 a54d477f 8ff735b1 2587192d 080b1900 00000000 00010100 00000000 00000300 00000000 00000000 00000000 000060']
}
end
# The below is a binary plist that is stored in the ShadowHashData key
# on a 10.7 system.
let(:sha512_embedded_bplist) do
"bplist00\321\001\002]SALTED-SHA512O\020D~\247\325\222\023\037W\262\310\370\275\274\354\215\235\361!(\243\2069:O\000\307a\233\254&\"\244ME\024\031\321\035\245\022\325\221Z\271\2169q\212\311@\203\376.\375k\367\020\245MG\177\217\3675\261%\207\031-\b\v\031\000\000\000\000\000\000\001\001\000\000\000\000\000\000\000\003\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000`"
end
# The below is a Base64 encoded string representing a salted-SHA512 password
# hash.
let(:sha512_pw_string) do
"~\247\325\222\023\037W\262\310\370\275\274\354\215\235\361!(\243\2069:O\000\307a\233\254&\"\244ME\024\031\321\035\245\022\325\221Z\271\2169q\212\311@\203\376.\375k\367\020\245MG\177\217\3675\261%\207\031-"
end
# The below is the result of converting sha512_embedded_bplist to XML and
# parsing it with Plist.parse_xml. It is a Ruby Hash whose value is a
# StringIO object holding a Base64 encoded salted-SHA512 password hash.
let(:sha512_embedded_bplist_hash) do
{ 'SALTED-SHA512' => StringIO.new(sha512_pw_string) }
end
# The value below is the result of converting sha512_pw_string to Hex.
let(:sha512_password_hash) do
'7ea7d592131f57b2c8f8bdbcec8d9df12128a386393a4f00c7619bac2622a44d451419d11da512d5915ab98e39718ac94083fe2efd6bf710a54d477f8ff735b12587192d'
end
# The below value is the result of executing
# `dscl -plist . read /Users/<username> ShadowHashData` on a 10.8
# system and converting it to a native Ruby Hash with Plist.parse_xml
let(:pbkdf2_shadowhashdata_hash) do
{
"dsAttrTypeNative:ShadowHashData"=>["62706c69 73743030 d101025f 10145341 4c544544 2d534841 3531322d 50424b44 4632d303 04050607 0857656e 74726f70 79547361 6c745a69 74657261 74696f6e 734f1080 0590ade1 9e6953c1 35ae872a e7761823 5df7d46c 63de7f9a 0fcdf2cd 9e7d85e4 b7ca8681 01235b61 58e05a30 9805ee48 14b027a4 be9c23ec 2926bc81 72269aff ba5c9a59 85e81091 fa689807 6d297f1f aa75fa61 7551ef16 71d75200 55c4a0d9 7b9b9c58 05aa322b aedbcd8e e9c52381 1653ac2e a9e9c8d8 f1ac519a 0f2b595e 4f102093 77c46908 a1c8ac2c 3e45c0d4 4da8ad0f cd85ec5c 14d9a59f fc40c9da 31f0ec11 60b0080b 22293136 41c4e700 00000000 00010100 00000000 00000900 00000000 00000000 00000000 0000ea"]
}
end
# The below value is the result of converting pbkdf2_embedded_bplist to XML and
# parsing it with Plist.parse_xml.
let(:pbkdf2_embedded_bplist_hash) do
{
'SALTED-SHA512-PBKDF2' => {
'entropy' => StringIO.new(pbkdf2_pw_string),
'salt' => StringIO.new(pbkdf2_salt_string),
'iterations' => pbkdf2_iterations_value
}
}
end
# The value below is the result of converting pbkdf2_pw_string to Hex.
let(:pbkdf2_password_hash) do
'0590ade19e6953c135ae872ae77618235df7d46c63de7f9a0fcdf2cd9e7d85e4b7ca868101235b6158e05a309805ee4814b027a4be9c23ec2926bc8172269affba5c9a5985e81091fa6898076d297f1faa75fa617551ef1671d7520055c4a0d97b9b9c5805aa322baedbcd8ee9c523811653ac2ea9e9c8d8f1ac519a0f2b595e'
end
# The below is a binary plist that is stored in the ShadowHashData key
# of a 10.8 system.
let(:pbkdf2_embedded_plist) do
"bplist00\321\001\002_\020\024SALTED-SHA512-PBKDF2\323\003\004\005\006\a\bWentropyTsaltZiterationsO\020\200\005\220\255\341\236iS\3015\256\207*\347v\030#]\367\324lc\336\177\232\017\315\362\315\236}\205\344\267\312\206\201\001#[aX\340Z0\230\005\356H\024\260'\244\276\234#\354)&\274\201r&\232\377\272\\\232Y\205\350\020\221\372h\230\am)\177\037\252u\372auQ\357\026q\327R\000U\304\240\331{\233\234X\005\2522+\256\333\315\216\351\305#\201\026S\254.\251\351\310\330\361\254Q\232\017+Y^O\020 \223w\304i\b\241\310\254,>E\300\324M\250\255\017\315\205\354\\\024\331\245\237\374@\311\3321\360\354\021`\260\b\v\")16A\304\347\000\000\000\000\000\000\001\001\000\000\000\000\000\000\000\t\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\352"
end
# The below value is a Base64 encoded string representing a PBKDF2 password
# hash.
let(:pbkdf2_pw_string) do
"\005\220\255\341\236iS\3015\256\207*\347v\030#]\367\324lc\336\177\232\017\315\362\315\236}\205\344\267\312\206\201\001#[aX\340Z0\230\005\356H\024\260'\244\276\234#\354)&\274\201r&\232\377\272\\\232Y\205\350\020\221\372h\230\am)\177\037\252u\372auQ\357\026q\327R\000U\304\240\331{\233\234X\005\2522+\256\333\315\216\351\305#\201\026S\254.\251\351\310\330\361\254Q\232\017+Y^"
end
# The below value is a Base64 encoded string representing a PBKDF2 salt
# string.
let(:pbkdf2_salt_string) do
"\223w\304i\b\241\310\254,>E\300\324M\250\255\017\315\205\354\\\024\331\245\237\374@\311\3321\360\354"
end
# The below value represents the Hex value of a PBKDF2 salt string
let(:pbkdf2_salt_value) do
"9377c46908a1c8ac2c3e45c0d44da8ad0fcd85ec5c14d9a59ffc40c9da31f0ec"
end
# The below value is a Fixnum iterations value used in the PBKDF2
# key stretching algorithm
let(:pbkdf2_iterations_value) do
24752
end
# The below represents output of 'dscl -plist . readall /Users' converted to
# a native Ruby hash if only one user were installed on the system.
# This lets us check the behavior of all the methods necessary to return a
# user's groups property by controlling the data provided by dscl
let(:testuser_hash) do
[{"dsAttrTypeStandard:RecordName" =>["nonexistent_user"],
"dsAttrTypeStandard:UniqueID" =>["1000"],
"dsAttrTypeStandard:AuthenticationAuthority"=>
[";Kerberosv5;;testuser@LKDC:SHA1.4383E152D9D394AA32D13AE98F6F6E1FE8D00F81;LKDC:SHA1.4383E152D9D394AA32D13AE98F6F6E1FE8D00F81",
";ShadowHash;HASHLIST:<SALTED-SHA512>"],
"dsAttrTypeStandard:AppleMetaNodeLocation" =>["/Local/Default"],
"dsAttrTypeStandard:NFSHomeDirectory" =>["/Users/nonexistent_user"],
"dsAttrTypeStandard:RecordType" =>["dsRecTypeStandard:Users"],
"dsAttrTypeStandard:RealName" =>["nonexistent_user"],
"dsAttrTypeStandard:Password" =>["********"],
"dsAttrTypeStandard:PrimaryGroupID" =>["22"],
"dsAttrTypeStandard:GeneratedUID" =>["0A7D5B63-3AD4-4CA7-B03E-85876F1D1FB3"],
"dsAttrTypeStandard:AuthenticationHint" =>[""],
"dsAttrTypeNative:KerberosKeys" =>
["30820157 a1030201 02a08201 4e308201 4a3074a1 2b3029a0 03020112 a1220420 54af3992 1c198bf8 94585a6b 2fba445b c8482228 0dcad666 ea62e038 99e59c45 a2453043 a0030201 03a13c04 3a4c4b44 433a5348 41312e34 33383345 31353244 39443339 34414133 32443133 41453938 46364636 45314645 38443030 46383174 65737475 73657230 64a11b30 19a00302 0111a112 04106375 7d97b2ce ca8343a6 3b0f73d5 1001a245 3043a003 020103a1 3c043a4c 4b44433a 53484131 2e343338 33453135 32443944 33393441 41333244 31334145 39384636 46364531 46453844 30304638 31746573 74757365 72306ca1 233021a0 03020110 a11a0418 67b09be3 5131b670 f8e9265e 62459b4c 19435419 fe918519 a2453043 a0030201 03a13c04 3a4c4b44 433a5348 41312e34 33383345 31353244 39443339 34414133 32443133 41453938 46364636 45314645 38443030 46383174 65737475 736572"],
"dsAttrTypeStandard:PasswordPolicyOptions" =>
["<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n <plist version=\"1.0\">\n <dict>\n <key>failedLoginCount</key>\n <integer>0</integer>\n <key>failedLoginTimestamp</key>\n <date>2001-01-01T00:00:00Z</date>\n <key>lastLoginTimestamp</key>\n <date>2001-01-01T00:00:00Z</date>\n <key>passwordTimestamp</key>\n <date>2012-08-10T23:53:50Z</date>\n </dict>\n </plist>\n "],
"dsAttrTypeStandard:UserShell" =>["/bin/bash"],
"dsAttrTypeNative:ShadowHashData" =>
["62706c69 73743030 d101025d 53414c54 45442d53 48413531 324f1044 7ea7d592 131f57b2 c8f8bdbc ec8d9df1 2128a386 393a4f00 c7619bac 2622a44d 451419d1 1da512d5 915ab98e 39718ac9 4083fe2e fd6bf710 a54d477f 8ff735b1 2587192d 080b1900 00000000 00010100 00000000 00000300 00000000 00000000 00000000 000060"]}]
end
# The below represents the result of running Plist.parse_xml on XML
# data returned from the `dscl -plist . readall /Groups` command.
# (AKA: What the get_list_of_groups method returns)
let(:group_plist_hash_guid) do
[{
'dsAttrTypeStandard:RecordName' => ['testgroup'],
'dsAttrTypeStandard:GroupMembership' => [
username,
'jeff',
'zack'
],
'dsAttrTypeStandard:GroupMembers' => [
"guid#{username}",
'guidtestuser',
'guidjeff',
'guidzack'
],
},
{
'dsAttrTypeStandard:RecordName' => ['second'],
'dsAttrTypeStandard:GroupMembership' => [
'jeff',
'zack'
],
'dsAttrTypeStandard:GroupMembers' => [
"guid#{username}",
'guidjeff',
'guidzack'
],
},
{
'dsAttrTypeStandard:RecordName' => ['third'],
'dsAttrTypeStandard:GroupMembership' => [
username,
'jeff',
'zack'
],
'dsAttrTypeStandard:GroupMembers' => [
"guid#{username}",
'guidtestuser',
'guidjeff',
'guidzack'
],
}]
end
describe 'Creating a user that does not exist' do
# These are the defaults that the provider will use if a user does
# not provide a value
let(:defaults) do
{
'UniqueID' => '1000',
'RealName' => resource[:name],
'PrimaryGroupID' => 20,
'UserShell' => '/bin/bash',
'NFSHomeDirectory' => "/Users/#{resource[:name]}"
}
end
before :each do
# Stub out all calls to dscl with default values from above
defaults.each do |key, val|
provider.stubs(:merge_attribute_with_dscl).with('Users', username, key, val)
end
# Mock the rest of the dscl calls. We can't assume that our Linux
# build system will have the dscl binary
provider.stubs(:create_new_user).with(username)
provider.class.stubs(:get_attribute_from_dscl).with('Users', username, 'GeneratedUID').returns({'dsAttrTypeStandard:GeneratedUID' => ['GUID']})
provider.stubs(:next_system_id).returns('1000')
end
it 'should not raise any errors when creating a user with default values' do
provider.create
end
%w{password iterations salt}.each do |value|
it "should call ##{value}= if a #{value} attribute is specified" do
resource[value.intern] = 'somevalue'
setter = (value << '=').intern
provider.expects(setter).with('somevalue')
provider.create
end
end
it 'should merge the GroupMembership and GroupMembers dscl values if a groups attribute is specified' do
resource[:groups] = 'somegroup'
provider.expects(:merge_attribute_with_dscl).with('Groups', 'somegroup', 'GroupMembership', username)
provider.expects(:merge_attribute_with_dscl).with('Groups', 'somegroup', 'GroupMembers', 'GUID')
provider.create
end
it 'should convert group names into integers' do
resource[:gid] = 'somegroup'
Puppet::Util.expects(:gid).with('somegroup').returns(21)
provider.expects(:merge_attribute_with_dscl).with('Users', username, 'PrimaryGroupID', 21)
provider.create
end
end
describe 'self#instances' do
it 'should create an array of provider instances' do
provider.class.expects(:get_all_users).returns(['foo', 'bar'])
['foo', 'bar'].each do |user|
provider.class.expects(:generate_attribute_hash).with(user).returns({})
end
instances = provider.class.instances
- instances.should be_a_kind_of Array
+ expect(instances).to be_a_kind_of Array
instances.each do |instance|
- instance.should be_a_kind_of Puppet::Provider
+ expect(instance).to be_a_kind_of Puppet::Provider
end
end
end
describe 'self#get_all_users' do
let(:empty_plist) do
'<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
</dict>
</plist>'
end
it 'should return a hash of user attributes' do
provider.class.expects(:dscl).with('-plist', '.', 'readall', '/Users').returns(user_plist_xml)
- provider.class.get_all_users.should == user_plist_hash
+ expect(provider.class.get_all_users).to eq(user_plist_hash)
end
it 'should return a hash when passed an empty plist' do
provider.class.expects(:dscl).with('-plist', '.', 'readall', '/Users').returns(empty_plist)
- provider.class.get_all_users.should == {}
+ expect(provider.class.get_all_users).to eq({})
end
end
describe 'self#generate_attribute_hash' do
let(:user_plist_resource) do
{
:ensure => :present,
:provider => :directoryservice,
:groups => 'testgroup,third',
:comment => username,
:password => sha512_password_hash,
:shadowhashdata => sha512_shadowhashdata_hash,
:name => username,
:uid => 1000,
:gid => 22,
:home => user_path
}
end
before :each do
provider.class.stubs(:get_os_version).returns('10.7')
provider.class.stubs(:get_all_users).returns(testuser_hash)
provider.class.stubs(:get_attribute_from_dscl).with('Users', username, 'ShadowHashData').returns(sha512_shadowhashdata_hash)
provider.class.stubs(:get_list_of_groups).returns(group_plist_hash_guid)
provider.class.stubs(:convert_binary_to_xml).with(sha512_embedded_bplist).returns(sha512_embedded_bplist_hash)
provider.class.prefetch({})
end
it 'should return :uid values as a Fixnum' do
- provider.class.generate_attribute_hash(user_plist_hash)[:uid].should be_a_kind_of Fixnum
+ expect(provider.class.generate_attribute_hash(user_plist_hash)[:uid]).to be_a_kind_of Fixnum
end
it 'should return :gid values as a Fixnum' do
- provider.class.generate_attribute_hash(user_plist_hash)[:gid].should be_a_kind_of Fixnum
+ expect(provider.class.generate_attribute_hash(user_plist_hash)[:gid]).to be_a_kind_of Fixnum
end
it 'should return a hash of resource attributes' do
- provider.class.generate_attribute_hash(user_plist_hash).should == user_plist_resource
+ expect(provider.class.generate_attribute_hash(user_plist_hash)).to eq(user_plist_resource)
end
end
describe '#exists?' do
# This test expects an error to be raised
# I'm PROBABLY doing this wrong...
it 'should return false if the dscl command errors out' do
provider.expects(:dscl).with('.', 'read', user_path).raises(Puppet::ExecutionFailure, 'Dscl Fails')
- provider.exists?.should == false
+ expect(provider.exists?).to eq(false)
end
it 'should return true if the dscl command does not error' do
provider.expects(:dscl).with('.', 'read', user_path).returns(user_plist_xml)
- provider.exists?.should == true
+ expect(provider.exists?).to eq(true)
end
end
describe '#delete' do
it 'should call dscl when destroying/deleting a resource' do
provider.expects(:dscl).with('.', '-delete', user_path)
provider.delete
end
end
describe 'the groups property' do
# The below represents the result of running Plist.parse_xml on XML
# data returned from the `dscl -plist . readall /Groups` command.
# (AKA: What the get_list_of_groups method returns)
let(:group_plist_hash) do
[{
'dsAttrTypeStandard:RecordName' => ['testgroup'],
'dsAttrTypeStandard:GroupMembership' => [
'testuser',
username,
'jeff',
'zack'
],
'dsAttrTypeStandard:GroupMembers' => [
'guidtestuser',
'guidjeff',
'guidzack'
],
},
{
'dsAttrTypeStandard:RecordName' => ['second'],
'dsAttrTypeStandard:GroupMembership' => [
username,
'testuser',
'jeff',
],
'dsAttrTypeStandard:GroupMembers' => [
'guidtestuser',
'guidjeff',
],
},
{
'dsAttrTypeStandard:RecordName' => ['third'],
'dsAttrTypeStandard:GroupMembership' => [
'jeff',
'zack'
],
'dsAttrTypeStandard:GroupMembers' => [
'guidjeff',
'guidzack'
],
}]
end
before :each do
provider.class.stubs(:get_all_users).returns(testuser_hash)
provider.class.stubs(:get_attribute_from_dscl).with('Users', username, 'ShadowHashData').returns([])
provider.class.stubs(:get_os_version).returns('10.7')
end
it "should return a list of groups if the user's name matches GroupMembership" do
provider.class.expects(:get_list_of_groups).returns(group_plist_hash)
- provider.class.prefetch({}).first.groups.should == 'second,testgroup'
+ expect(provider.class.prefetch({}).first.groups).to eq('second,testgroup')
end
it "should return a list of groups if the user's GUID matches GroupMembers" do
provider.class.expects(:get_list_of_groups).returns(group_plist_hash_guid)
- provider.class.prefetch({}).first.groups.should == 'testgroup,third'
+ expect(provider.class.prefetch({}).first.groups).to eq('testgroup,third')
end
end
describe '#groups=' do
let(:group_plist_one_two_three) do
[{
'dsAttrTypeStandard:RecordName' => ['one'],
'dsAttrTypeStandard:GroupMembership' => [
'jeff',
'zack'
],
'dsAttrTypeStandard:GroupMembers' => [
'guidjeff',
'guidzack'
],
},
{
'dsAttrTypeStandard:RecordName' => ['two'],
'dsAttrTypeStandard:GroupMembership' => [
'jeff',
'zack',
username
],
'dsAttrTypeStandard:GroupMembers' => [
'guidjeff',
'guidzack'
],
},
{
'dsAttrTypeStandard:RecordName' => ['three'],
'dsAttrTypeStandard:GroupMembership' => [
'jeff',
'zack',
username
],
'dsAttrTypeStandard:GroupMembers' => [
'guidjeff',
'guidzack'
],
}]
end
before :each do
provider.class.stubs(:get_all_users).returns(testuser_hash)
provider.class.stubs(:get_list_of_groups).returns(group_plist_one_two_three)
end
it 'should call dscl to add necessary groups' do
provider.class.expects(:get_attribute_from_dscl).with('Users', username, 'ShadowHashData').returns([])
provider.class.expects(:get_attribute_from_dscl).with('Users', username, 'GeneratedUID').returns({'dsAttrTypeStandard:GeneratedUID' => ['guidnonexistent_user']})
provider.expects(:groups).returns('two,three')
provider.expects(:dscl).with('.', '-merge', '/Groups/one', 'GroupMembership', 'nonexistent_user')
provider.expects(:dscl).with('.', '-merge', '/Groups/one', 'GroupMembers', 'guidnonexistent_user')
provider.class.prefetch({})
provider.groups= 'one,two,three'
end
it 'should call the get_salted_sha512 method on 10.7 and return the correct hash' do
provider.class.expects(:get_attribute_from_dscl).with('Users', username, 'ShadowHashData').returns(sha512_shadowhashdata_hash)
provider.class.expects(:convert_binary_to_xml).with(sha512_embedded_bplist).returns(sha512_embedded_bplist_hash)
- provider.class.prefetch({}).first.password.should == sha512_password_hash
+ expect(provider.class.prefetch({}).first.password).to eq(sha512_password_hash)
end
it 'should call the get_salted_sha512_pbkdf2 method on 10.8 and return the correct hash' do
provider.class.expects(:get_attribute_from_dscl).with('Users', username,'ShadowHashData').returns(pbkdf2_shadowhashdata_hash)
provider.class.expects(:convert_binary_to_xml).with(pbkdf2_embedded_plist).returns(pbkdf2_embedded_bplist_hash)
- provider.class.prefetch({}).first.password.should == pbkdf2_password_hash
+ expect(provider.class.prefetch({}).first.password).to eq(pbkdf2_password_hash)
end
end
describe '#password=' do
before :each do
provider.stubs(:sleep)
provider.stubs(:flush_dscl_cache)
end
it 'should call write_password_to_users_plist when setting the password' do
provider.class.stubs(:get_os_version).returns('10.7')
provider.expects(:write_password_to_users_plist).with(sha512_password_hash)
provider.password = sha512_password_hash
end
it 'should call write_password_to_users_plist when setting the password' do
provider.class.stubs(:get_os_version).returns('10.8')
resource[:salt] = pbkdf2_salt_value
resource[:iterations] = pbkdf2_iterations_value
resource[:password] = pbkdf2_password_hash
provider.expects(:write_password_to_users_plist).with(pbkdf2_password_hash)
provider.password = resource[:password]
end
it "should raise an error on 10.7 if a password hash that doesn't contain 136 characters is passed" do
provider.class.stubs(:get_os_version).returns('10.7')
expect { provider.password = 'password' }.to raise_error Puppet::Error, /OS X 10\.7 requires a Salted SHA512 hash password of 136 characters\. Please check your password and try again/
end
end
describe "passwords on 10.8" do
before :each do
provider.class.stubs(:get_os_version).returns('10.8')
end
it "should raise an error on 10.8 if a password hash that doesn't contain 256 characters is passed" do
expect do
provider.password = 'password'
end.to raise_error(Puppet::Error, /OS X versions > 10\.7 require a Salted SHA512 PBKDF2 password hash of 256 characters\. Please check your password and try again\./)
end
it "fails if a password is given but not salt and iterations" do
resource[:password] = pbkdf2_password_hash
expect do
provider.password = resource[:password]
end.to raise_error(Puppet::Error, /OS X versions > 10\.7 use PBKDF2 password hashes, which requires all three of salt, iterations, and password hash\. This resource is missing: salt, iterations\./)
end
it "fails if salt is given but not password and iterations" do
resource[:salt] = pbkdf2_salt_value
expect do
provider.salt = resource[:salt]
end.to raise_error(Puppet::Error, /OS X versions > 10\.7 use PBKDF2 password hashes, which requires all three of salt, iterations, and password hash\. This resource is missing: password, iterations\./)
end
it "fails if iterations is given but not password and salt" do
resource[:iterations] = pbkdf2_iterations_value
expect do
provider.iterations = resource[:iterations]
end.to raise_error(Puppet::Error, /OS X versions > 10\.7 use PBKDF2 password hashes, which requires all three of salt, iterations, and password hash\. This resource is missing: password, salt\./)
end
end
describe '#get_list_of_groups' do
# The below value is the result of running `dscl -plist . readall /Groups`
# on an OS X system.
let(:groups_xml) do
'<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>dsAttrTypeStandard:AppleMetaNodeLocation</key>
<array>
<string>/Local/Default</string>
</array>
<key>dsAttrTypeStandard:GeneratedUID</key>
<array>
<string>ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000053</string>
</array>
<key>dsAttrTypeStandard:Password</key>
<array>
<string>*</string>
</array>
<key>dsAttrTypeStandard:PrimaryGroupID</key>
<array>
<string>83</string>
</array>
<key>dsAttrTypeStandard:RealName</key>
<array>
<string>SPAM Assassin Group 2</string>
</array>
<key>dsAttrTypeStandard:RecordName</key>
<array>
<string>_amavisd</string>
<string>amavisd</string>
</array>
<key>dsAttrTypeStandard:RecordType</key>
<array>
<string>dsRecTypeStandard:Groups</string>
</array>
</dict>
</array>
</plist>'
end
# The below value is the result of executing Plist.parse_xml on
# groups_xml
let(:groups_hash) do
[{ 'dsAttrTypeStandard:AppleMetaNodeLocation' => ['/Local/Default'],
'dsAttrTypeStandard:GeneratedUID' => ['ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000053'],
'dsAttrTypeStandard:Password' => ['*'],
'dsAttrTypeStandard:PrimaryGroupID' => ['83'],
'dsAttrTypeStandard:RealName' => ['SPAM Assassin Group 2'],
'dsAttrTypeStandard:RecordName' => ['_amavisd', 'amavisd'],
'dsAttrTypeStandard:RecordType' => ['dsRecTypeStandard:Groups']
}]
end
before :each do
# Ensure we don't have a value cached from another spec
provider.class.instance_variable_set(:@groups, nil) if provider.class.instance_variable_defined? :@groups
end
it 'should return an array of hashes containing group data' do
provider.class.expects(:dscl).with('-plist', '.', 'readall', '/Groups').returns(groups_xml)
- provider.class.get_list_of_groups.should == groups_hash
+ expect(provider.class.get_list_of_groups).to eq(groups_hash)
end
end
describe '#get_attribute_from_dscl' do
# The below value is the result of executing
# `dscl -plist . read /Users/<username/ GeneratedUID`
# on an OS X system.
let(:user_guid_xml) do
'<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>dsAttrTypeStandard:GeneratedUID</key>
<array>
<string>DCC660C6-F5A9-446D-B9FF-3C0258AB5BA0</string>
</array>
</dict>
</plist>'
end
# The below value is the result of parsing user_guid_xml with
# Plist.parse_xml
let(:user_guid_hash) do
{ 'dsAttrTypeStandard:GeneratedUID' => ['DCC660C6-F5A9-446D-B9FF-3C0258AB5BA0'] }
end
it 'should return a hash containing a user\'s dscl attribute data' do
provider.class.expects(:dscl).with('-plist', '.', 'read', user_path, 'GeneratedUID').returns(user_guid_xml)
- provider.class.get_attribute_from_dscl('Users', username, 'GeneratedUID').should == user_guid_hash
+ expect(provider.class.get_attribute_from_dscl('Users', username, 'GeneratedUID')).to eq(user_guid_hash)
end
end
describe '#convert_xml_to_binary' do
# Because this method relies on a binary that only exists on OS X, a stub
# object is needed to expect the calls. This makes testing somewhat...uneventful
let(:stub_io_object) { stub('connection') }
it 'should use plutil to successfully convert an xml plist to a binary plist' do
IO.expects(:popen).with('plutil -convert binary1 -o - -', 'r+').yields stub_io_object
Plist::Emit.expects(:dump).with('ruby_hash').returns('xml_plist_data')
stub_io_object.expects(:write).with('xml_plist_data')
stub_io_object.expects(:close_write)
stub_io_object.expects(:read).returns('binary_plist_data')
- provider.class.convert_xml_to_binary('ruby_hash').should == 'binary_plist_data'
+ expect(provider.class.convert_xml_to_binary('ruby_hash')).to eq('binary_plist_data')
end
end
describe '#convert_binary_to_xml' do
let(:stub_io_object) { stub('connection') }
it 'should accept a binary plist and return a ruby hash containing the plist data' do
IO.expects(:popen).with('plutil -convert xml1 -o - -', 'r+').yields stub_io_object
stub_io_object.expects(:write).with('binary_plist_data')
stub_io_object.expects(:close_write)
stub_io_object.expects(:read).returns(user_plist_xml)
- provider.class.convert_binary_to_xml('binary_plist_data').should == user_plist_hash
+ expect(provider.class.convert_binary_to_xml('binary_plist_data')).to eq(user_plist_hash)
end
end
describe '#next_system_id' do
it 'should return the next available UID number that is not in the list obtained from dscl and is greater than the passed integer value' do
provider.expects(:dscl).with('.', '-list', '/Users', 'uid').returns("kathee 312\ngary 11\ntanny 33\njohn 9\nzach 5")
- provider.next_system_id(30).should == 34
+ expect(provider.next_system_id(30)).to eq(34)
end
end
describe '#get_salted_sha512' do
it "should accept a hash whose 'SALTED-SHA512' key contains a StringIO object with a base64 encoded salted-SHA512 password hash and return the hex value of that password hash" do
- provider.class.get_salted_sha512(sha512_embedded_bplist_hash).should == sha512_password_hash
+ expect(provider.class.get_salted_sha512(sha512_embedded_bplist_hash)).to eq(sha512_password_hash)
end
end
describe '#get_salted_sha512_pbkdf2' do
it "should accept a hash containing a PBKDF2 password hash, salt, and iterations value and return the correct password hash" do
- provider.class.get_salted_sha512_pbkdf2('entropy', pbkdf2_embedded_bplist_hash).should == pbkdf2_password_hash
+ expect(provider.class.get_salted_sha512_pbkdf2('entropy', pbkdf2_embedded_bplist_hash)).to eq(pbkdf2_password_hash)
end
it "should accept a hash containing a PBKDF2 password hash, salt, and iterations value and return the correct salt value" do
- provider.class.get_salted_sha512_pbkdf2('salt', pbkdf2_embedded_bplist_hash).should == pbkdf2_salt_value
+ expect(provider.class.get_salted_sha512_pbkdf2('salt', pbkdf2_embedded_bplist_hash)).to eq(pbkdf2_salt_value)
end
it "should accept a hash containing a PBKDF2 password hash, salt, and iterations value and return the correct iterations value" do
- provider.class.get_salted_sha512_pbkdf2('iterations', pbkdf2_embedded_bplist_hash).should == pbkdf2_iterations_value
+ expect(provider.class.get_salted_sha512_pbkdf2('iterations', pbkdf2_embedded_bplist_hash)).to eq(pbkdf2_iterations_value)
end
it "should return a Fixnum value when looking up the PBKDF2 iterations value" do
- provider.class.get_salted_sha512_pbkdf2('iterations', pbkdf2_embedded_bplist_hash).should be_a_kind_of(Fixnum)
+ expect(provider.class.get_salted_sha512_pbkdf2('iterations', pbkdf2_embedded_bplist_hash)).to be_a_kind_of(Fixnum)
end
it "should raise an error if a field other than 'entropy', 'salt', or 'iterations' is passed" do
expect { provider.class.get_salted_sha512_pbkdf2('othervalue', pbkdf2_embedded_bplist_hash) }.to raise_error(Puppet::Error, /Puppet has tried to read an incorrect value from the SALTED-SHA512-PBKDF2 hash. Acceptable fields are 'salt', 'entropy', or 'iterations'/)
end
end
describe '#get_sha1' do
let(:password_hash_file) { '/var/db/shadow/hash/user_guid' }
let(:stub_password_file) { stub('connection') }
it 'should return a sha1 hash read from disk' do
Puppet::FileSystem.expects(:exist?).with(password_hash_file).returns(true)
File.expects(:file?).with(password_hash_file).returns(true)
File.expects(:readable?).with(password_hash_file).returns(true)
File.expects(:new).with(password_hash_file).returns(stub_password_file)
stub_password_file.expects(:read).returns('sha1_password_hash')
stub_password_file.expects(:close)
- provider.class.get_sha1('user_guid').should == 'sha1_password_hash'
+ expect(provider.class.get_sha1('user_guid')).to eq('sha1_password_hash')
end
it 'should return nil if the password_hash_file does not exist' do
Puppet::FileSystem.expects(:exist?).with(password_hash_file).returns(false)
- provider.class.get_sha1('user_guid').should == nil
+ expect(provider.class.get_sha1('user_guid')).to eq(nil)
end
it 'should return nil if the password_hash_file is not a file' do
Puppet::FileSystem.expects(:exist?).with(password_hash_file).returns(true)
File.expects(:file?).with(password_hash_file).returns(false)
- provider.class.get_sha1('user_guid').should == nil
+ expect(provider.class.get_sha1('user_guid')).to eq(nil)
end
it 'should raise an error if the password_hash_file is not readable' do
Puppet::FileSystem.expects(:exist?).with(password_hash_file).returns(true)
File.expects(:file?).with(password_hash_file).returns(true)
File.expects(:readable?).with(password_hash_file).returns(false)
- expect { provider.class.get_sha1('user_guid').should == nil }.to raise_error(Puppet::Error, /Could not read password hash file at #{password_hash_file}/)
+ expect { expect(provider.class.get_sha1('user_guid')).to eq(nil) }.to raise_error(Puppet::Error, /Could not read password hash file at #{password_hash_file}/)
end
end
describe '#write_password_to_users_plist' do
let(:sha512_plist_xml) do
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>KerberosKeys</key>\n\t<array>\n\t\t<data>\n\t\tMIIBS6EDAgEBoIIBQjCCAT4wcKErMCmgAwIBEqEiBCCS/0Im7BAps/YhX/ED\n\t\tKOpDeSMFkUsu3UzEa6gqDu35BKJBMD+gAwIBA6E4BDZMS0RDOlNIQTEuNDM4\n\t\tM0UxNTJEOUQzOTRBQTMyRDEzQUU5OEY2RjZFMUZFOEQwMEY4MWplZmYwYKEb\n\t\tMBmgAwIBEaESBBAk8a3rrFk5mHAdEU5nRgFwokEwP6ADAgEDoTgENkxLREM6\n\t\tU0hBMS40MzgzRTE1MkQ5RDM5NEFBMzJEMTNBRTk4RjZGNkUxRkU4RDAwRjgx\n\t\tamVmZjBooSMwIaADAgEQoRoEGFg71irsV+9ddRNPSn9houo3Q6jZuj55XaJB\n\t\tMD+gAwIBA6E4BDZMS0RDOlNIQTEuNDM4M0UxNTJEOUQzOTRBQTMyRDEzQUU5\n\t\tOEY2RjZFMUZFOEQwMEY4MWplZmY=\n\t\t</data>\n\t</array>\n\t<key>ShadowHashData</key>\n\t<array>\n\t\t<data>\n\t\tYnBsaXN0MDDRAQJdU0FMVEVELVNIQTUxMk8QRFNL0iuruijP6becUWe43GTX\n\t\t5WTgOTi2emx41DMnwnB4vbKieVOE4eNHiyocX5c0GX1LWJ6VlZqZ9EnDLsuA\n\t\tNC5Ga9qlCAsZAAAAAAAAAQEAAAAAAAAAAwAAAAAAAAAAAAAAAAAAAGA=\n\t\t</data>\n\t</array>\n\t<key>authentication_authority</key>\n\t<array>\n\t\t<string>;Kerberosv5;;jeff@LKDC:SHA1.4383E152D9D394AA32D13AE98F6F6E1FE8D00F81;LKDC:SHA1.4383E152D9D394AA32D13AE98F6F6E1FE8D00F81</string>\n\t\t<string>;ShadowHash;HASHLIST:&lt;SALTED-SHA512&gt;</string>\n\t</array>\n\t<key>dsAttrTypeStandard:ShadowHashData</key>\n\t<array>\n\t\t<data>\n\t\tYnBsaXN0MDDRAQJdU0FMVEVELVNIQTUxMk8QRH6n1ZITH1eyyPi9vOyNnfEh\n\t\tKKOGOTpPAMdhm6wmIqRNRRQZ0R2lEtWRWrmOOXGKyUCD/i79a/cQpU1Hf4/3\n\t\tNbElhxktCAsZAAAAAAAAAQEAAAAAAAAAAwAAAAAAAAAAAAAAAAAAAGA=\n\t\t</data>\n\t</array>\n\t<key>generateduid</key>\n\t<array>\n\t\t<string>3AC74939-C14F-45DD-B6A9-D1A82373F0B0</string>\n\t</array>\n\t<key>name</key>\n\t<array>\n\t\t<string>jeff</string>\n\t</array>\n\t<key>passwd</key>\n\t<array>\n\t\t<string>********</string>\n\t</array>\n\t<key>passwordpolicyoptions</key>\n\t<array>\n\t\t<data>\n\t\tPD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NU\n\t\tWVBFIHBsaXN0IFBVQkxJQyAiLS8vQXBwbGUvL0RURCBQTElTVCAxLjAvL0VO\n\t\tIiAiaHR0cDovL3d3dy5hcHBsZS5jb20vRFREcy9Qcm9wZXJ0eUxpc3QtMS4w\n\t\tLmR0ZCI+CjxwbGlzdCB2ZXJzaW9uPSIxLjAiPgo8ZGljdD4KCTxrZXk+ZmFp\n\t\tbGVkTG9naW5Db3VudDwva2V5PgoJPGludGVnZXI+MDwvaW50ZWdlcj4KCTxr\n\t\tZXk+ZmFpbGVkTG9naW5UaW1lc3RhbXA8L2tleT4KCTxkYXRlPjIwMDEtMDEt\n\t\tMDFUMDA6MDA6MDBaPC9kYXRlPgoJPGtleT5sYXN0TG9naW5UaW1lc3RhbXA8\n\t\tL2tleT4KCTxkYXRlPjIwMDEtMDEtMDFUMDA6MDA6MDBaPC9kYXRlPgoJPGtl\n\t\teT5wYXNzd29yZFRpbWVzdGFtcDwva2V5PgoJPGRhdGU+MjAxMi0wOC0xMVQw\n\t\tMDozNTo1MFo8L2RhdGU+CjwvZGljdD4KPC9wbGlzdD4K\n\t\t</data>\n\t</array>\n\t<key>uid</key>\n\t<array>\n\t\t<string>28</string>\n\t</array>\n</dict>\n</plist>"
end
let(:pbkdf2_plist_xml) do
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>KerberosKeys</key>\n\t<array>\n\t\t<data>\n\t\tMIIBS6EDAgEBoIIBQjCCAT4wcKErMCmgAwIBEqEiBCDrboPy0gxu7oTZR/Pc\n\t\tYdCBC9ivXo1k05gt036/aNe5VqJBMD+gAwIBA6E4BDZMS0RDOlNIQTEuNDEz\n\t\tQTMwRjU5MEVFREM3ODdENTMyOTgxODUwQTk3NTI0NUIwQTcyM2plZmYwYKEb\n\t\tMBmgAwIBEaESBBCm02SYYdsxo2fiDP4KuPtmokEwP6ADAgEDoTgENkxLREM6\n\t\tU0hBMS40MTNBMzBGNTkwRUVEQzc4N0Q1MzI5ODE4NTBBOTc1MjQ1QjBBNzIz\n\t\tamVmZjBooSMwIaADAgEQoRoEGHPBc7Dg7zjaE8g+YXObwupiBLMIlCrN5aJB\n\t\tMD+gAwIBA6E4BDZMS0RDOlNIQTEuNDEzQTMwRjU5MEVFREM3ODdENTMyOTgx\n\t\tODUwQTk3NTI0NUIwQTcyM2plZmY=\n\t\t</data>\n\t</array>\n\t<key>ShadowHashData</key>\n\t<array>\n\t\t<data>\n\t\tYnBsaXN0MDDRAQJfEBRTQUxURUQtU0hBNTEyLVBCS0RGMtMDBAUGBwhXZW50\n\t\tcm9weVRzYWx0Wml0ZXJhdGlvbnNPEIAFkK3hnmlTwTWuhyrndhgjXffUbGPe\n\t\tf5oPzfLNnn2F5LfKhoEBI1thWOBaMJgF7kgUsCekvpwj7CkmvIFyJpr/ulya\n\t\tWYXoEJH6aJgHbSl/H6p1+mF1Ue8WcddSAFXEoNl7m5xYBaoyK67bzY7pxSOB\n\t\tFlOsLqnpyNjxrFGaDytZXk8QIJN3xGkIocisLD5FwNRNqK0PzYXsXBTZpZ/8\n\t\tQMnaMfDsEWCwCAsiKTE2QcTnAAAAAAAAAQEAAAAAAAAACQAAAAAAAAAAAAAA\n\t\tAAAAAOo=\n\t\t</data>\n\t</array>\n\t<key>authentication_authority</key>\n\t<array>\n\t\t<string>;Kerberosv5;;jeff@LKDC:SHA1.413A30F590EEDC787D532981850A975245B0A723;LKDC:SHA1.413A30F590EEDC787D532981850A975245B0A723</string>\n\t\t<string>;ShadowHash;HASHLIST:&lt;SALTED-SHA512-PBKDF2&gt;</string>\n\t</array>\n\t<key>generateduid</key>\n\t<array>\n\t\t<string>1CB825D1-2DF7-43CC-B874-DB6BBB76C402</string>\n\t</array>\n\t<key>gid</key>\n\t<array>\n\t\t<string>21</string>\n\t</array>\n\t<key>name</key>\n\t<array>\n\t\t<string>jeff</string>\n\t</array>\n\t<key>passwd</key>\n\t<array>\n\t\t<string>********</string>\n\t</array>\n\t<key>passwordpolicyoptions</key>\n\t<array>\n\t\t<data>\n\t\tPD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NU\n\t\tWVBFIHBsaXN0IFBVQkxJQyAiLS8vQXBwbGUvL0RURCBQTElTVCAxLjAvL0VO\n\t\tIiAiaHR0cDovL3d3dy5hcHBsZS5jb20vRFREcy9Qcm9wZXJ0eUxpc3QtMS4w\n\t\tLmR0ZCI+CjxwbGlzdCB2ZXJzaW9uPSIxLjAiPgo8ZGljdD4KCTxrZXk+ZmFp\n\t\tbGVkTG9naW5Db3VudDwva2V5PgoJPGludGVnZXI+MDwvaW50ZWdlcj4KCTxr\n\t\tZXk+ZmFpbGVkTG9naW5UaW1lc3RhbXA8L2tleT4KCTxkYXRlPjIwMDEtMDEt\n\t\tMDFUMDA6MDA6MDBaPC9kYXRlPgoJPGtleT5sYXN0TG9naW5UaW1lc3RhbXA8\n\t\tL2tleT4KCTxkYXRlPjIwMDEtMDEtMDFUMDA6MDA6MDBaPC9kYXRlPgoJPGtl\n\t\teT5wYXNzd29yZExhc3RTZXRUaW1lPC9rZXk+Cgk8ZGF0ZT4yMDEyLTA3LTI1\n\t\tVDE4OjQ3OjU5WjwvZGF0ZT4KPC9kaWN0Pgo8L3BsaXN0Pgo=\n\t\t</data>\n\t</array>\n\t<key>uid</key>\n\t<array>\n\t\t<string>28</string>\n\t</array>\n</dict>\n</plist>"
end
let(:sha512_shadowhashdata) do
{
'SALTED-SHA512' => StringIO.new('blankvalue')
}
end
let(:pbkdf2_shadowhashdata) do
{
'SALTED-SHA512-PBKDF2' => {
'entropy' => StringIO.new('blank_entropy'),
'salt' => StringIO.new('blank_salt'),
'iterations' => 100
}
}
end
let(:sample_users_plist) do
{
"shell" => ["/bin/zsh"],
"passwd" => ["********"],
"picture" => ["/Library/User Pictures/Animals/Eagle.tif"],
"_writers_LinkedIdentity" => ["puppet"], "name"=>["puppet"],
"home" => ["/Users/puppet"],
"_writers_UserCertificate" => ["puppet"],
"_writers_passwd" => ["puppet"],
"gid" => ["20"],
"generateduid" => ["DA8A0E67-E9BE-4B4F-B34E-8977BAE0D3D4"],
"realname" => ["Puppet"],
"_writers_picture" => ["puppet"],
"uid" => ["501"],
"hint" => [""],
"authentication_authority" => [";ShadowHash;HASHLIST:<SALTED-SHA512>",
";Kerberosv5;;puppet@LKDC:S HA1.35580B1D6366D2890A35D430373FF653297F377D;LKDC:SHA1.35580B1D6366D2890A35D430373FF653297F377D"],
"_writers_realname" => ["puppet"],
"_writers_hint" => ["puppet"],
"ShadowHashData" => [StringIO.new('blank')]
}
end
it 'should call set_salted_sha512 on 10.7 when given a salted-SHA512 password hash' do
provider.expects(:get_users_plist).returns(sample_users_plist)
provider.expects(:get_shadow_hash_data).with(sample_users_plist).returns(sha512_shadowhashdata)
provider.class.expects(:get_os_version).returns('10.7')
provider.expects(:set_salted_sha512).with(sample_users_plist, sha512_shadowhashdata, sha512_password_hash)
provider.write_password_to_users_plist(sha512_password_hash)
end
it 'should call set_salted_pbkdf2 on 10.8 when given a PBKDF2 password hash' do
provider.expects(:get_users_plist).returns(sample_users_plist)
provider.expects(:get_shadow_hash_data).with(sample_users_plist).returns(pbkdf2_shadowhashdata)
provider.class.expects(:get_os_version).returns('10.8')
provider.expects(:set_salted_pbkdf2).with(sample_users_plist, pbkdf2_shadowhashdata, 'entropy', pbkdf2_password_hash)
provider.write_password_to_users_plist(pbkdf2_password_hash)
end
it "should delete the SALTED-SHA512 key in the shadow_hash_data hash if it exists on a 10.8 system and write_password_to_users_plist has been called to set the user's password" do
provider.expects(:get_users_plist).returns('users_plist')
provider.expects(:get_shadow_hash_data).with('users_plist').returns(sha512_shadowhashdata)
provider.class.expects(:get_os_version).returns('10.8')
provider.expects(:set_salted_pbkdf2).with('users_plist', {}, 'entropy', pbkdf2_password_hash)
provider.write_password_to_users_plist(pbkdf2_password_hash)
end
end
describe '#set_salted_sha512' do
let(:users_plist) { {'ShadowHashData' => [StringIO.new('string_data')] } }
let(:sha512_shadow_hash_data) do
{
'SALTED-SHA512' => stringio_object
}
end
it 'should set the SALTED-SHA512 password hash for a user in 10.7 and call the set_shadow_hash_data method to write the plist to disk' do
provider.class.expects(:convert_xml_to_binary).with(sha512_embedded_bplist_hash).returns(sha512_embedded_bplist)
provider.expects(:set_shadow_hash_data).with(users_plist, sha512_embedded_bplist)
provider.set_salted_sha512(users_plist, sha512_embedded_bplist_hash, sha512_password_hash)
end
it 'should set the salted-SHA512 password, even if a blank shadow_hash_data hash is passed' do
provider.expects(:new_stringio_object).returns(stringio_object)
provider.class.expects(:convert_xml_to_binary).with(sha512_shadow_hash_data).returns(sha512_embedded_bplist)
provider.expects(:set_shadow_hash_data).with(users_plist, sha512_embedded_bplist)
provider.set_salted_sha512(users_plist, false, sha512_password_hash)
end
end
describe '#set_salted_pbkdf2' do
let(:users_plist) { {'ShadowHashData' => [StringIO.new('string_data')] } }
let(:entropy_shadow_hash_data) do
{
'SALTED-SHA512-PBKDF2' =>
{
'entropy' => stringio_object
}
}
end
# This will also catch the edge-case where a 10.6-style user exists on
# a 10.8 system and Puppet attempts to set a password
it 'should not fail if shadow_hash_data is not a Hash' do
provider.expects(:new_stringio_object).returns(stringio_object)
provider.expects(:base64_decode_string).with(pbkdf2_password_hash).returns('binary_string')
provider.class.expects(:convert_xml_to_binary).with(entropy_shadow_hash_data).returns('binary_plist')
provider.expects(:set_shadow_hash_data).with({'passwd' => '********'}, 'binary_plist')
provider.set_salted_pbkdf2({}, false, 'entropy', pbkdf2_password_hash)
end
it "should set the PBKDF2 password hash when the 'entropy' field is passed with a valid password hash" do
provider.class.expects(:convert_xml_to_binary).with(pbkdf2_embedded_bplist_hash).returns(pbkdf2_embedded_plist)
provider.expects(:set_shadow_hash_data).with(users_plist, pbkdf2_embedded_plist)
users_plist.expects(:[]=).with('passwd', '********')
provider.set_salted_pbkdf2(users_plist, pbkdf2_embedded_bplist_hash, 'entropy', pbkdf2_password_hash)
end
it "should set the PBKDF2 password hash when the 'salt' field is passed with a valid password hash" do
provider.class.expects(:convert_xml_to_binary).with(pbkdf2_embedded_bplist_hash).returns(pbkdf2_embedded_plist)
provider.expects(:set_shadow_hash_data).with(users_plist, pbkdf2_embedded_plist)
users_plist.expects(:[]=).with('passwd', '********')
provider.set_salted_pbkdf2(users_plist, pbkdf2_embedded_bplist_hash, 'salt', pbkdf2_salt_value)
end
it "should set the PBKDF2 password hash when the 'iterations' field is passed with a valid password hash" do
provider.class.expects(:convert_xml_to_binary).with(pbkdf2_embedded_bplist_hash).returns(pbkdf2_embedded_plist)
provider.expects(:set_shadow_hash_data).with(users_plist, pbkdf2_embedded_plist)
users_plist.expects(:[]=).with('passwd', '********')
provider.set_salted_pbkdf2(users_plist, pbkdf2_embedded_bplist_hash, 'iterations', pbkdf2_iterations_value)
end
end
describe '#write_users_plist_to_disk' do
it 'should save the passed plist to disk and convert it to a binary plist' do
Plist::Emit.expects(:save_plist).with(user_plist_xml, "#{users_plist_dir}/nonexistent_user.plist")
provider.expects(:plutil).with('-convert', 'binary1', "#{users_plist_dir}/nonexistent_user.plist")
provider.write_users_plist_to_disk(user_plist_xml)
end
end
describe '#merge_attribute_with_dscl' do
it 'should raise an error if a dscl command raises an error' do
provider.expects(:dscl).with('.', '-merge', user_path, 'GeneratedUID', 'GUID').raises(Puppet::ExecutionFailure, 'boom')
expect { provider.merge_attribute_with_dscl('Users', username, 'GeneratedUID', 'GUID') }.to raise_error Puppet::Error, /Could not set the dscl GeneratedUID key with value: GUID/
end
end
describe '#get_users_plist' do
let(:test_plist) do
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>shell</key>\n\t<string>/bin/bash</string>\n\t<key>user</key>\n\t<string>puppet</string>\n</dict>\n</plist>\n"
end
let(:test_hash) do
{
'user' => 'puppet',
'shell' => '/bin/bash'
}
end
it 'should convert a plist to a valid Ruby hash' do
provider.expects(:plutil).with('-convert', 'xml1', '-o', '/dev/stdout', "#{users_plist_dir}/#{username}.plist").returns(test_plist)
- provider.get_users_plist(username).should == test_hash
+ expect(provider.get_users_plist(username)).to eq(test_hash)
end
end
describe '#get_shadow_hash_data' do
let(:shadow_hash) do
{
'ShadowHashData' => [StringIO.new('test')]
}
end
let(:no_shadow_hash) do
{
'no' => 'Shadow Hash Data'
}
end
it 'should return false if the passed users_plist does NOT have a ShadowHashData key' do
- provider.get_shadow_hash_data(no_shadow_hash).should == false
+ expect(provider.get_shadow_hash_data(no_shadow_hash)).to eq(false)
end
it 'should call convert_binary_to_xml() with the contents of the StringIO Object ' +
'located in the first element of the array of the ShadowHashData key if the ' +
'passed users_plist contains a ShadowHashData key' do
provider.class.expects(:convert_binary_to_xml).with('test').returns('returnvalue')
- provider.get_shadow_hash_data(shadow_hash).should == 'returnvalue'
+ expect(provider.get_shadow_hash_data(shadow_hash)).to eq('returnvalue')
end
end
describe 'self#get_os_version' do
before :each do
# Ensure we don't have a value cached from another spec
provider.class.instance_variable_set(:@os_version, nil) if provider.class.instance_variable_defined? :@os_version
end
it 'should call Facter.value(:macosx_productversion_major) ONLY ONCE no matter how ' +
'many times get_os_version() is called' do
Facter.expects(:value).with(:macosx_productversion_major).once.returns('10.8')
- provider.class.get_os_version.should == '10.8'
- provider.class.get_os_version.should == '10.8'
- provider.class.get_os_version.should == '10.8'
- provider.class.get_os_version.should == '10.8'
+ expect(provider.class.get_os_version).to eq('10.8')
+ expect(provider.class.get_os_version).to eq('10.8')
+ expect(provider.class.get_os_version).to eq('10.8')
+ expect(provider.class.get_os_version).to eq('10.8')
end
end
describe '#base64_decode_string' do
it 'should return a Base64-decoded string appropriate for use in a user\'s plist' do
- provider.base64_decode_string(sha512_password_hash).should == sha512_pw_string
+ expect(provider.base64_decode_string(sha512_password_hash)).to eq(sha512_pw_string)
end
end
describe '(#12833) 10.6-style users on 10.8' do
# The below represents output of 'dscl -plist . readall /Users'
# converted to a Ruby hash if only one user were installed on the system.
# This lets us check the behavior of all the methods necessary to return
# a user's groups property by controlling the data provided by dscl. The
# differentiating aspect about this plist is that it's from a 10.6-style
# user. There's an edge case whereby a user that was created in 10.6, but
# who hasn't attempted to login to the system until after it's been
# upgraded to 10.8, will experience errors due to assumptions in Puppet
# based solely on operatingsystem.
let(:all_users_hash) do
[
{
"dsAttrTypeNative:_writers_UserCertificate" => ["testuser"],
"dsAttrTypeStandard:RealName" => ["testuser"],
"dsAttrTypeStandard:NFSHomeDirectory" => ["/Users/testuser"],
"dsAttrTypeNative:_writers_realname" => ["testuser"],
"dsAttrTypeNative:_writers_picture" => ["testuser"],
"dsAttrTypeStandard:AppleMetaNodeLocation" => ["/Local/Default"],
"dsAttrTypeStandard:PrimaryGroupID" => ["20"],
"dsAttrTypeNative:_writers_LinkedIdentity" => ["testuser"],
"dsAttrTypeStandard:UserShell" => ["/bin/bash"],
"dsAttrTypeStandard:UniqueID" => ["1234"],
"dsAttrTypeStandard:RecordName" => ["testuser"],
"dsAttrTypeStandard:Password" => ["********"],
"dsAttrTypeNative:_writers_jpegphoto" => ["testuser"],
"dsAttrTypeNative:_writers_hint" => ["testuser"],
"dsAttrTypeNative:_writers_passwd" => ["testuser"],
"dsAttrTypeStandard:RecordType" => ["dsRecTypeStandard:Users"],
"dsAttrTypeStandard:AuthenticationAuthority" => [
";ShadowHash;",
";Kerberosv5;;testuser@LKDC:SHA1.48AC4BCFEFE9 D66847B5E7D813BC4B12C5513A07;LKDC:SHA1.48AC4BCFEFE9D66847B5E7D813BC4B12C5513A07;"
],
"dsAttrTypeStandard:GeneratedUID" => ["D1AC2ECC-F177-4B45-8B18-59CF002F97FF"]
}
]
end
let(:username) { 'testuser' }
let(:user_path) { "/Users/#{username}" }
let(:resource) do
Puppet::Type.type(:user).new(
:name => username,
:provider => :directoryservice
)
end
let(:provider) { resource.provider }
# The below represents the result of get_users_plist on the testuser
# account from the 'all_users_hash' helper method. The get_users_plist
# method calls the `plutil` binary to do its work, so we want to stub
# that out
let(:user_plist_hash) do
{
'realname' => ['testuser'],
'authentication_authority' => [';ShadowHash;', ';Kerberosv5;;testuser@LKDC:SHA1.48AC4BCFEFE9D66847B5E7D813BC4B12C5513A07;LKDC:SHA1.48AC4BCFEFE9D66847B5E7D813BC4B12C5513A07;'],
'home' => ['/Users/testuser'],
'_writers_realname' => ['testuser'],
'passwd' => '********',
'_writers_LinkedIdentity' => ['testuser'],
'_writers_picture' => ['testuser'],
'gid' => ['20'],
'_writers_passwd' => ['testuser'],
'_writers_hint' => ['testuser'],
'_writers_UserCertificate' => ['testuser'],
'_writers_jpegphoto' => ['testuser'],
'shell' => ['/bin/bash'],
'uid' => ['1234'],
'generateduid' => ['D1AC2ECC-F177-4B45-8B18-59CF002F97FF'],
'name' => ['testuser']
}
end
before :each do
provider.class.stubs(:get_all_users).returns(all_users_hash)
provider.class.stubs(:get_list_of_groups).returns(group_plist_hash_guid)
provider.class.stubs(:get_attribute_from_dscl).with('Users', 'testuser', 'ShadowHashData').returns({})
provider.class.prefetch({})
end
it 'should not raise an error if the password=() method is called on ' +
'a user without a ShadowHashData key in their user\'s plist on OS X ' +
'version 10.8' do
resource[:salt] = pbkdf2_salt_value
resource[:iterations] = pbkdf2_iterations_value
resource[:password] = pbkdf2_password_hash
provider.class.stubs(:get_os_version).returns('10.8')
provider.stubs(:sleep)
provider.stubs(:flush_dscl_cache)
provider.expects(:get_users_plist).with('testuser').returns(user_plist_hash)
provider.expects(:set_salted_pbkdf2).with(user_plist_hash, false, 'entropy', pbkdf2_password_hash)
provider.password = resource[:password]
end
end
end
diff --git a/spec/unit/provider/user/hpux_spec.rb b/spec/unit/provider/user/hpux_spec.rb
index b9e9275d6..87e33e16a 100755
--- a/spec/unit/provider/user/hpux_spec.rb
+++ b/spec/unit/provider/user/hpux_spec.rb
@@ -1,73 +1,73 @@
#!/usr/bin/env ruby
require 'spec_helper'
require 'etc'
provider_class = Puppet::Type.type(:user).provider(:hpuxuseradd)
describe provider_class, :unless => Puppet.features.microsoft_windows? do
let :resource do
Puppet::Type.type(:user).new(
:title => 'testuser',
:comment => 'Test J. User',
:provider => :hpuxuseradd
)
end
let(:provider) { resource.provider }
it "should add -F when modifying a user" do
resource.stubs(:allowdupe?).returns true
provider.expects(:execute).with { |args| args.include?("-F") }
provider.uid = 1000
end
it "should add -F when deleting a user" do
provider.stubs(:exists?).returns(true)
provider.expects(:execute).with { |args| args.include?("-F") }
provider.delete
end
context "managing passwords" do
let :pwent do
Struct::Passwd.new("testuser", "foopassword")
end
before :each do
Etc.stubs(:getpwent).returns(pwent)
Etc.stubs(:getpwnam).returns(pwent)
resource.stubs(:command).with(:modify).returns '/usr/sam/lbin/usermod.sam'
end
it "should have feature manages_passwords" do
- provider_class.should be_manages_passwords
+ expect(provider_class).to be_manages_passwords
end
it "should return nil if user does not exist" do
Etc.stubs(:getpwent).returns(nil)
- provider.password.must be_nil
+ expect(provider.password).to be_nil
end
it "should return password entry if exists" do
- provider.password.must == "foopassword"
+ expect(provider.password).to eq("foopassword")
end
end
context "check for trusted computing" do
before :each do
provider.stubs(:command).with(:modify).returns '/usr/sam/lbin/usermod.sam'
end
it "should add modprpw to modifycmd if Trusted System" do
resource.stubs(:allowdupe?).returns true
provider.expects(:exec_getprpw).with('root','-m uid').returns('uid=0')
provider.expects(:execute).with(['/usr/sam/lbin/usermod.sam', '-u', 1000, '-o', 'testuser', '-F', ';', '/usr/lbin/modprpw', '-v', '-l', 'testuser'])
provider.uid = 1000
end
it "should not add modprpw if not Trusted System" do
resource.stubs(:allowdupe?).returns true
provider.expects(:exec_getprpw).with('root','-m uid').returns('System is not trusted')
provider.expects(:execute).with(['/usr/sam/lbin/usermod.sam', '-u', 1000, '-o', 'testuser', '-F'])
provider.uid = 1000
end
end
end
diff --git a/spec/unit/provider/user/ldap_spec.rb b/spec/unit/provider/user/ldap_spec.rb
index cb3019a04..7f89c072a 100755
--- a/spec/unit/provider/user/ldap_spec.rb
+++ b/spec/unit/provider/user/ldap_spec.rb
@@ -1,289 +1,289 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:user).provider(:ldap)
describe provider_class do
it "should have the Ldap provider class as its baseclass" do
- provider_class.superclass.should equal(Puppet::Provider::Ldap)
+ expect(provider_class.superclass).to equal(Puppet::Provider::Ldap)
end
it "should manage :posixAccount and :person objectclasses" do
- provider_class.manager.objectclasses.should == [:posixAccount, :person]
+ expect(provider_class.manager.objectclasses).to eq([:posixAccount, :person])
end
it "should use 'ou=People' as its relative base" do
- provider_class.manager.location.should == "ou=People"
+ expect(provider_class.manager.location).to eq("ou=People")
end
it "should use :uid as its rdn" do
- provider_class.manager.rdn.should == :uid
+ expect(provider_class.manager.rdn).to eq(:uid)
end
it "should be able to manage passwords" do
- provider_class.should be_manages_passwords
+ expect(provider_class).to be_manages_passwords
end
{:name => "uid",
:password => "userPassword",
:comment => "cn",
:uid => "uidNumber",
:gid => "gidNumber",
:home => "homeDirectory",
:shell => "loginShell"
}.each do |puppet, ldap|
it "should map :#{puppet.to_s} to '#{ldap}'" do
- provider_class.manager.ldap_name(puppet).should == ldap
+ expect(provider_class.manager.ldap_name(puppet)).to eq(ldap)
end
end
describe "when being created" do
before do
# So we don't try to actually talk to ldap
@connection = mock 'connection'
provider_class.manager.stubs(:connect).yields @connection
end
it "should generate the sn as the last field of the cn" do
Puppet::Type.type(:group).provider(:ldap).expects(:name2id).with(["whatever"]).returns [123]
resource = stub 'resource', :should => %w{whatever}
resource.stubs(:should).with(:comment).returns ["Luke Kanies"]
resource.stubs(:should).with(:ensure).returns :present
instance = provider_class.new(:name => "luke", :ensure => :absent)
instance.stubs(:resource).returns resource
@connection.expects(:add).with { |dn, attrs| attrs["sn"] == ["Kanies"] }
instance.create
instance.flush
end
it "should translate a group name to the numeric id" do
Puppet::Type.type(:group).provider(:ldap).expects(:name2id).with("bar").returns 101
resource = stub 'resource', :should => %w{whatever}
resource.stubs(:should).with(:gid).returns 'bar'
resource.stubs(:should).with(:ensure).returns :present
instance = provider_class.new(:name => "luke", :ensure => :absent)
instance.stubs(:resource).returns resource
@connection.expects(:add).with { |dn, attrs| attrs["gidNumber"] == ["101"] }
instance.create
instance.flush
end
describe "with no uid specified" do
it "should pick the first available UID after the largest existing UID" do
Puppet::Type.type(:group).provider(:ldap).expects(:name2id).with(["whatever"]).returns [123]
low = {:name=>["luke"], :shell=>:absent, :uid=>["600"], :home=>["/h"], :gid=>["1000"], :password=>["blah"], :comment=>["l k"]}
high = {:name=>["testing"], :shell=>:absent, :uid=>["640"], :home=>["/h"], :gid=>["1000"], :password=>["blah"], :comment=>["t u"]}
provider_class.manager.expects(:search).returns([low, high])
resource = stub 'resource', :should => %w{whatever}
resource.stubs(:should).with(:uid).returns nil
resource.stubs(:should).with(:ensure).returns :present
instance = provider_class.new(:name => "luke", :ensure => :absent)
instance.stubs(:resource).returns resource
@connection.expects(:add).with { |dn, attrs| attrs["uidNumber"] == ["641"] }
instance.create
instance.flush
end
it "should pick 501 of no users exist" do
Puppet::Type.type(:group).provider(:ldap).expects(:name2id).with(["whatever"]).returns [123]
provider_class.manager.expects(:search).returns nil
resource = stub 'resource', :should => %w{whatever}
resource.stubs(:should).with(:uid).returns nil
resource.stubs(:should).with(:ensure).returns :present
instance = provider_class.new(:name => "luke", :ensure => :absent)
instance.stubs(:resource).returns resource
@connection.expects(:add).with { |dn, attrs| attrs["uidNumber"] == ["501"] }
instance.create
instance.flush
end
end
end
describe "when flushing" do
before do
provider_class.stubs(:suitable?).returns true
@instance = provider_class.new(:name => "myname", :groups => %w{whatever}, :uid => "400")
end
it "should remove the :groups value before updating" do
@instance.class.manager.expects(:update).with { |name, ldap, puppet| puppet[:groups].nil? }
@instance.flush
end
it "should empty the property hash" do
@instance.class.manager.stubs(:update)
@instance.flush
- @instance.uid.should == :absent
+ expect(@instance.uid).to eq(:absent)
end
it "should empty the ldap property hash" do
@instance.class.manager.stubs(:update)
@instance.flush
- @instance.ldap_properties[:uid].should be_nil
+ expect(@instance.ldap_properties[:uid]).to be_nil
end
end
describe "when checking group membership" do
before do
@groups = Puppet::Type.type(:group).provider(:ldap)
@group_manager = @groups.manager
provider_class.stubs(:suitable?).returns true
@instance = provider_class.new(:name => "myname")
end
it "should show its group membership as the sorted list of all groups returned by an ldap query of group memberships" do
one = {:name => "one"}
two = {:name => "two"}
@group_manager.expects(:search).with("memberUid=myname").returns([two, one])
- @instance.groups.should == "one,two"
+ expect(@instance.groups).to eq("one,two")
end
it "should show its group membership as :absent if no matching groups are found in ldap" do
@group_manager.expects(:search).with("memberUid=myname").returns(nil)
- @instance.groups.should == :absent
+ expect(@instance.groups).to eq(:absent)
end
it "should cache the group value" do
@group_manager.expects(:search).with("memberUid=myname").once.returns nil
@instance.groups
- @instance.groups.should == :absent
+ expect(@instance.groups).to eq(:absent)
end
end
describe "when modifying group membership" do
before do
@groups = Puppet::Type.type(:group).provider(:ldap)
@group_manager = @groups.manager
provider_class.stubs(:suitable?).returns true
@one = {:name => "one", :gid => "500"}
@group_manager.stubs(:find).with("one").returns(@one)
@two = {:name => "one", :gid => "600"}
@group_manager.stubs(:find).with("two").returns(@two)
@instance = provider_class.new(:name => "myname")
@instance.stubs(:groups).returns :absent
end
it "should fail if the group does not exist" do
@group_manager.expects(:find).with("mygroup").returns nil
- lambda { @instance.groups = "mygroup" }.should raise_error(Puppet::Error)
+ expect { @instance.groups = "mygroup" }.to raise_error(Puppet::Error)
end
it "should only pass the attributes it cares about to the group manager" do
@group_manager.expects(:update).with { |name, attrs| attrs[:gid].nil? }
@instance.groups = "one"
end
it "should always include :ensure => :present in the current values" do
@group_manager.expects(:update).with { |name, is, should| is[:ensure] == :present }
@instance.groups = "one"
end
it "should always include :ensure => :present in the desired values" do
@group_manager.expects(:update).with { |name, is, should| should[:ensure] == :present }
@instance.groups = "one"
end
it "should always pass the group's original member list" do
@one[:members] = %w{yay ness}
@group_manager.expects(:update).with { |name, is, should| is[:members] == %w{yay ness} }
@instance.groups = "one"
end
it "should find the group again when resetting its member list, so it has the full member list" do
@group_manager.expects(:find).with("one").returns(@one)
@group_manager.stubs(:update)
@instance.groups = "one"
end
describe "for groups that have no members" do
it "should create a new members attribute with its value being the user's name" do
@group_manager.expects(:update).with { |name, is, should| should[:members] == %w{myname} }
@instance.groups = "one"
end
end
describe "for groups it is being removed from" do
it "should replace the group's member list with one missing the user's name" do
@one[:members] = %w{myname a}
@two[:members] = %w{myname b}
@group_manager.expects(:update).with { |name, is, should| name == "two" and should[:members] == %w{b} }
@instance.stubs(:groups).returns "one,two"
@instance.groups = "one"
end
it "should mark the member list as empty if there are no remaining members" do
@one[:members] = %w{myname}
@two[:members] = %w{myname b}
@group_manager.expects(:update).with { |name, is, should| name == "one" and should[:members] == :absent }
@instance.stubs(:groups).returns "one,two"
@instance.groups = "two"
end
end
describe "for groups that already have members" do
it "should replace each group's member list with a new list including the user's name" do
@one[:members] = %w{a b}
@group_manager.expects(:update).with { |name, is, should| should[:members] == %w{a b myname} }
@two[:members] = %w{b c}
@group_manager.expects(:update).with { |name, is, should| should[:members] == %w{b c myname} }
@instance.groups = "one,two"
end
end
describe "for groups of which it is a member" do
it "should do nothing" do
@one[:members] = %w{a b}
@group_manager.expects(:update).with { |name, is, should| should[:members] == %w{a b myname} }
@two[:members] = %w{c myname}
@group_manager.expects(:update).with { |name, *other| name == "two" }.never
@instance.stubs(:groups).returns "two"
@instance.groups = "one,two"
end
end
end
end
diff --git a/spec/unit/provider/user/openbsd_spec.rb b/spec/unit/provider/user/openbsd_spec.rb
index 52fe130d9..2baea9d69 100755
--- a/spec/unit/provider/user/openbsd_spec.rb
+++ b/spec/unit/provider/user/openbsd_spec.rb
@@ -1,77 +1,77 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:user).provider(:openbsd) do
before :each do
described_class.stubs(:command).with(:password).returns '/usr/sbin/passwd'
described_class.stubs(:command).with(:add).returns '/usr/sbin/useradd'
described_class.stubs(:command).with(:modify).returns '/usr/sbin/usermod'
described_class.stubs(:command).with(:delete).returns '/usr/sbin/userdel'
end
let(:resource) do
Puppet::Type.type(:user).new(
:name => 'myuser',
:managehome => :false,
:system => :false,
:loginclass => 'staff',
:provider => provider
)
end
let(:provider) { described_class.new(:name => 'myuser') }
let(:shadow_entry) {
return unless Puppet.features.libshadow?
entry = Struct::PasswdEntry.new
entry[:sp_namp] = 'myuser' # login name
entry[:sp_loginclass] = 'staff' # login class
entry
}
describe "#expiry=" do
it "should pass expiry to usermod as MM/DD/YY" do
resource[:expiry] = '2014-11-05'
provider.expects(:execute).with(['/usr/sbin/usermod', '-e', 'November 05 2014', 'myuser'])
provider.expiry = '2014-11-05'
end
it "should use -e with an empty string when the expiry property is removed" do
resource[:expiry] = :absent
provider.expects(:execute).with(['/usr/sbin/usermod', '-e', '', 'myuser'])
provider.expiry = :absent
end
end
describe "#addcmd" do
it "should return an array with the full command and expiry as MM/DD/YY" do
Facter.stubs(:value).with(:osfamily).returns('OpenBSD')
resource[:expiry] = "1997-06-01"
- provider.addcmd.must == ['/usr/sbin/useradd', '-e', 'June 01 1997', 'myuser']
+ expect(provider.addcmd).to eq(['/usr/sbin/useradd', '-e', 'June 01 1997', 'myuser'])
end
end
describe "#loginclass" do
before :each do
resource
end
it "should return the loginclass if set", :if => Puppet.features.libshadow? do
Shadow::Passwd.expects(:getspnam).with('myuser').returns shadow_entry
provider.send(:loginclass).should == 'staff'
end
it "should return the empty string when loginclass isn't set", :if => Puppet.features.libshadow? do
shadow_entry[:sp_loginclass] = ''
Shadow::Passwd.expects(:getspnam).with('myuser').returns shadow_entry
provider.send(:loginclass).should == ''
end
it "should return nil when loginclass isn't available", :if => Puppet.features.libshadow? do
shadow_entry[:sp_loginclass] = nil
Shadow::Passwd.expects(:getspnam).with('myuser').returns shadow_entry
provider.send(:loginclass).should be_nil
end
end
end
diff --git a/spec/unit/provider/user/pw_spec.rb b/spec/unit/provider/user/pw_spec.rb
index 7a815c328..0ca3ad418 100755
--- a/spec/unit/provider/user/pw_spec.rb
+++ b/spec/unit/provider/user/pw_spec.rb
@@ -1,214 +1,214 @@
#! /usr/bin/env ruby
require 'spec_helper'
provider_class = Puppet::Type.type(:user).provider(:pw)
describe provider_class do
let :resource do
Puppet::Type.type(:user).new(:name => "testuser", :provider => :pw)
end
describe "when creating users" do
let :provider do
prov = resource.provider
prov.expects(:exists?).returns nil
prov
end
it "should run pw with no additional flags when no properties are given" do
- provider.addcmd.must == [provider_class.command(:pw), "useradd", "testuser"]
+ expect(provider.addcmd).to eq([provider_class.command(:pw), "useradd", "testuser"])
provider.expects(:execute).with([provider_class.command(:pw), "useradd", "testuser"], kind_of(Hash))
provider.create
end
it "should use -o when allowdupe is enabled" do
resource[:allowdupe] = true
provider.expects(:execute).with(includes("-o"), kind_of(Hash))
provider.create
end
it "should use -c with the correct argument when the comment property is set" do
resource[:comment] = "Testuser Name"
provider.expects(:execute).with(all_of(includes("-c"), includes("Testuser Name")), kind_of(Hash))
provider.create
end
it "should use -e with the correct argument when the expiry property is set" do
resource[:expiry] = "2010-02-19"
provider.expects(:execute).with(all_of(includes("-e"), includes("19-02-2010")), kind_of(Hash))
provider.create
end
it "should use -e 00-00-0000 if the expiry property has to be removed" do
resource[:expiry] = :absent
provider.expects(:execute).with(all_of(includes("-e"), includes("00-00-0000")), kind_of(Hash))
provider.create
end
it "should use -g with the correct argument when the gid property is set" do
resource[:gid] = 12345
provider.expects(:execute).with(all_of(includes("-g"), includes(12345)), kind_of(Hash))
provider.create
end
it "should use -G with the correct argument when the groups property is set" do
resource[:groups] = "group1"
provider.expects(:execute).with(all_of(includes("-G"), includes("group1")), kind_of(Hash))
provider.create
end
it "should use -G with all the given groups when the groups property is set to an array" do
resource[:groups] = ["group1", "group2"]
provider.expects(:execute).with(all_of(includes("-G"), includes("group1,group2")), kind_of(Hash))
provider.create
end
it "should use -d with the correct argument when the home property is set" do
resource[:home] = "/home/testuser"
provider.expects(:execute).with(all_of(includes("-d"), includes("/home/testuser")), kind_of(Hash))
provider.create
end
it "should use -m when the managehome property is enabled" do
resource[:managehome] = true
provider.expects(:execute).with(includes("-m"), kind_of(Hash))
provider.create
end
it "should call the password set function with the correct argument when the password property is set" do
resource[:password] = "*"
provider.expects(:execute)
provider.expects(:password=).with("*")
provider.create
end
it "should use -s with the correct argument when the shell property is set" do
resource[:shell] = "/bin/sh"
provider.expects(:execute).with(all_of(includes("-s"), includes("/bin/sh")), kind_of(Hash))
provider.create
end
it "should use -u with the correct argument when the uid property is set" do
resource[:uid] = 12345
provider.expects(:execute).with(all_of(includes("-u"), includes(12345)), kind_of(Hash))
provider.create
end
# (#7500) -p should not be used to set a password (it means something else)
it "should not use -p when a password is given" do
resource[:password] = "*"
- provider.addcmd.should_not include("-p")
+ expect(provider.addcmd).not_to include("-p")
provider.expects(:password=)
provider.expects(:execute).with(Not(includes("-p")), kind_of(Hash))
provider.create
end
end
describe "when deleting users" do
it "should run pw with no additional flags" do
provider = resource.provider
provider.expects(:exists?).returns true
- provider.deletecmd.must == [provider_class.command(:pw), "userdel", "testuser"]
+ expect(provider.deletecmd).to eq([provider_class.command(:pw), "userdel", "testuser"])
provider.expects(:execute).with([provider_class.command(:pw), "userdel", "testuser"])
provider.delete
end
# The above test covers this, but given the consequences of
# accidentally deleting a user's home directory it seems better to
# have an explicit test.
it "should not use -r when managehome is not set" do
provider = resource.provider
provider.expects(:exists?).returns true
resource[:managehome] = false
provider.expects(:execute).with(Not(includes("-r")))
provider.delete
end
it "should use -r when managehome is set" do
provider = resource.provider
provider.expects(:exists?).returns true
resource[:managehome] = true
provider.expects(:execute).with(includes("-r"))
provider.delete
end
end
describe "when modifying users" do
let :provider do
resource.provider
end
it "should run pw with the correct arguments" do
- provider.modifycmd("uid", 12345).must == [provider_class.command(:pw), "usermod", "testuser", "-u", 12345]
+ expect(provider.modifycmd("uid", 12345)).to eq([provider_class.command(:pw), "usermod", "testuser", "-u", 12345])
provider.expects(:execute).with([provider_class.command(:pw), "usermod", "testuser", "-u", 12345])
provider.uid = 12345
end
it "should use -c with the correct argument when the comment property is changed" do
resource[:comment] = "Testuser Name"
provider.expects(:execute).with(all_of(includes("-c"), includes("Testuser New Name")))
provider.comment = "Testuser New Name"
end
it "should use -e with the correct argument when the expiry property is changed" do
resource[:expiry] = "2010-02-19"
provider.expects(:execute).with(all_of(includes("-e"), includes("19-02-2011")))
provider.expiry = "2011-02-19"
end
it "should use -e with the correct argument when the expiry property is removed" do
resource[:expiry] = :absent
provider.expects(:execute).with(all_of(includes("-e"), includes("00-00-0000")))
provider.expiry = :absent
end
it "should use -g with the correct argument when the gid property is changed" do
resource[:gid] = 12345
provider.expects(:execute).with(all_of(includes("-g"), includes(54321)))
provider.gid = 54321
end
it "should use -G with the correct argument when the groups property is changed" do
resource[:groups] = "group1"
provider.expects(:execute).with(all_of(includes("-G"), includes("group2")))
provider.groups = "group2"
end
it "should use -G with all the given groups when the groups property is changed with an array" do
resource[:groups] = ["group1", "group2"]
provider.expects(:execute).with(all_of(includes("-G"), includes("group3,group4")))
provider.groups = "group3,group4"
end
it "should use -d with the correct argument when the home property is changed" do
resource[:home] = "/home/testuser"
provider.expects(:execute).with(all_of(includes("-d"), includes("/newhome/testuser")))
provider.home = "/newhome/testuser"
end
it "should use -m and -d with the correct argument when the home property is changed and managehome is enabled" do
resource[:home] = "/home/testuser"
resource[:managehome] = true
provider.expects(:execute).with(all_of(includes("-d"), includes("/newhome/testuser"), includes("-m")))
provider.home = "/newhome/testuser"
end
it "should call the password set function with the correct argument when the password property is changed" do
resource[:password] = "*"
provider.expects(:password=).with("!")
provider.password = "!"
end
it "should use -s with the correct argument when the shell property is changed" do
resource[:shell] = "/bin/sh"
provider.expects(:execute).with(all_of(includes("-s"), includes("/bin/tcsh")))
provider.shell = "/bin/tcsh"
end
it "should use -u with the correct argument when the uid property is changed" do
resource[:uid] = 12345
provider.expects(:execute).with(all_of(includes("-u"), includes(54321)))
provider.uid = 54321
end
end
end
diff --git a/spec/unit/provider/user/user_role_add_spec.rb b/spec/unit/provider/user/user_role_add_spec.rb
index a7bdf10ff..a1575c04f 100755
--- a/spec/unit/provider/user/user_role_add_spec.rb
+++ b/spec/unit/provider/user/user_role_add_spec.rb
@@ -1,357 +1,357 @@
require 'spec_helper'
require 'puppet_spec/files'
require 'tempfile'
describe Puppet::Type.type(:user).provider(:user_role_add), :unless => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
let(:resource) { Puppet::Type.type(:user).new(:name => 'myuser', :managehome => false, :allowdupe => false) }
let(:provider) { described_class.new(resource) }
before do
resource.stubs(:should).returns "fakeval"
resource.stubs(:should).with(:keys).returns Hash.new
resource.stubs(:[]).returns "fakeval"
end
describe "#command" do
before do
klass = stub("provider")
klass.stubs(:command).with(:foo).returns("userfoo")
klass.stubs(:command).with(:role_foo).returns("rolefoo")
provider.stubs(:class).returns(klass)
end
it "should use the command if not a role and ensure!=role" do
provider.stubs(:is_role?).returns(false)
provider.stubs(:exists?).returns(false)
resource.stubs(:[]).with(:ensure).returns(:present)
provider.class.stubs(:foo)
- provider.command(:foo).should == "userfoo"
+ expect(provider.command(:foo)).to eq("userfoo")
end
it "should use the role command when a role" do
provider.stubs(:is_role?).returns(true)
- provider.command(:foo).should == "rolefoo"
+ expect(provider.command(:foo)).to eq("rolefoo")
end
it "should use the role command when !exists and ensure=role" do
provider.stubs(:is_role?).returns(false)
provider.stubs(:exists?).returns(false)
resource.stubs(:[]).with(:ensure).returns(:role)
- provider.command(:foo).should == "rolefoo"
+ expect(provider.command(:foo)).to eq("rolefoo")
end
end
describe "#transition" do
it "should return the type set to whatever is passed in" do
provider.expects(:command).with(:modify).returns("foomod")
provider.transition("bar").include?("type=bar")
end
end
describe "#create" do
before do
provider.stubs(:password=)
end
it "should use the add command when the user is not a role" do
provider.stubs(:is_role?).returns(false)
provider.expects(:addcmd).returns("useradd")
provider.expects(:run).at_least_once
provider.create
end
it "should use transition(normal) when the user is a role" do
provider.stubs(:is_role?).returns(true)
provider.expects(:transition).with("normal")
provider.expects(:run)
provider.create
end
it "should set password age rules" do
resource = Puppet::Type.type(:user).new :name => "myuser", :password_min_age => 5, :password_max_age => 10, :provider => :user_role_add
provider = described_class.new(resource)
provider.stubs(:user_attributes)
provider.stubs(:execute)
provider.expects(:execute).with { |cmd, *args| args == ["-n", 5, "-x", 10, "myuser"] }
provider.create
end
end
describe "#destroy" do
it "should use the delete command if the user exists and is not a role" do
provider.stubs(:exists?).returns(true)
provider.stubs(:is_role?).returns(false)
provider.expects(:deletecmd)
provider.expects(:run)
provider.destroy
end
it "should use the delete command if the user is a role" do
provider.stubs(:exists?).returns(true)
provider.stubs(:is_role?).returns(true)
provider.expects(:deletecmd)
provider.expects(:run)
provider.destroy
end
end
describe "#create_role" do
it "should use the transition(role) if the user exists" do
provider.stubs(:exists?).returns(true)
provider.stubs(:is_role?).returns(false)
provider.expects(:transition).with("role")
provider.expects(:run)
provider.create_role
end
it "should use the add command when role doesn't exists" do
provider.stubs(:exists?).returns(false)
provider.expects(:addcmd)
provider.expects(:run)
provider.create_role
end
end
describe "with :allow_duplicates" do
before do
resource.stubs(:allowdupe?).returns true
provider.stubs(:is_role?).returns(false)
provider.stubs(:execute)
resource.stubs(:system?).returns false
provider.expects(:execute).with { |args| args.include?("-o") }
end
it "should add -o when the user is being created" do
provider.stubs(:password=)
provider.create
end
it "should add -o when the uid is being modified" do
provider.uid = 150
end
end
[:roles, :auths, :profiles].each do |val|
context "#send" do
describe "when getting #{val}" do
it "should get the user_attributes" do
provider.expects(:user_attributes)
provider.send(val)
end
it "should get the #{val} attribute" do
attributes = mock("attributes")
attributes.expects(:[]).with(val)
provider.stubs(:user_attributes).returns(attributes)
provider.send(val)
end
end
end
end
describe "#keys" do
it "should get the user_attributes" do
provider.expects(:user_attributes)
provider.keys
end
it "should call removed_managed_attributes" do
provider.stubs(:user_attributes).returns({ :type => "normal", :foo => "something" })
provider.expects(:remove_managed_attributes)
provider.keys
end
it "should removed managed attribute (type, auths, roles, etc)" do
provider.stubs(:user_attributes).returns({ :type => "normal", :foo => "something" })
- provider.keys.should == { :foo => "something" }
+ expect(provider.keys).to eq({ :foo => "something" })
end
end
describe "#add_properties" do
it "should call build_keys_cmd" do
resource.stubs(:should).returns ""
resource.expects(:should).with(:keys).returns({ :foo => "bar" })
provider.expects(:build_keys_cmd).returns([])
provider.add_properties
end
it "should add the elements of the keys hash to an array" do
resource.stubs(:should).returns ""
resource.expects(:should).with(:keys).returns({ :foo => "bar"})
- provider.add_properties.must == ["-K", "foo=bar"]
+ expect(provider.add_properties).to eq(["-K", "foo=bar"])
end
end
describe "#build_keys_cmd" do
it "should build cmd array with keypairs separated by -K ending with user" do
- provider.build_keys_cmd({"foo" => "bar", "baz" => "boo"}).should.eql? ["-K", "foo=bar", "-K", "baz=boo"]
+ expect(provider.build_keys_cmd({"foo" => "bar", "baz" => "boo"})).to eq(["-K", "foo=bar", "-K", "baz=boo"])
end
end
describe "#keys=" do
before do
provider.stubs(:is_role?).returns(false)
end
it "should run a command" do
provider.expects(:run)
provider.keys=({})
end
it "should build the command" do
resource.stubs(:[]).with(:name).returns("someuser")
provider.stubs(:command).returns("usermod")
provider.expects(:build_keys_cmd).returns(["-K", "foo=bar"])
provider.expects(:run).with(["usermod", "-K", "foo=bar", "someuser"], "modify attribute key pairs")
provider.keys=({})
end
end
describe "#password" do
before do
@array = mock "array"
end
it "should readlines of /etc/shadow" do
File.expects(:readlines).with("/etc/shadow").returns([])
provider.password
end
it "should reject anything that doesn't start with alpha numerics" do
@array.expects(:reject).returns([])
File.stubs(:readlines).with("/etc/shadow").returns(@array)
provider.password
end
it "should collect splitting on ':'" do
@array.stubs(:reject).returns(@array)
@array.expects(:collect).returns([])
File.stubs(:readlines).with("/etc/shadow").returns(@array)
provider.password
end
it "should find the matching user" do
resource.stubs(:[]).with(:name).returns("username")
@array.stubs(:reject).returns(@array)
@array.stubs(:collect).returns([["username", "hashedpassword"], ["someoneelse", "theirpassword"]])
File.stubs(:readlines).with("/etc/shadow").returns(@array)
- provider.password.must == "hashedpassword"
+ expect(provider.password).to eq("hashedpassword")
end
it "should get the right password" do
resource.stubs(:[]).with(:name).returns("username")
File.stubs(:readlines).with("/etc/shadow").returns(["#comment", " nonsense", " ", "username:hashedpassword:stuff:foo:bar:::", "other:pword:yay:::"])
- provider.password.must == "hashedpassword"
+ expect(provider.password).to eq("hashedpassword")
end
end
describe "#password=" do
let(:path) { tmpfile('etc-shadow') }
before :each do
provider.stubs(:target_file_path).returns(path)
end
def write_fixture(content)
File.open(path, 'w') { |f| f.print(content) }
end
it "should update the target user" do
write_fixture <<FIXTURE
fakeval:seriously:15315:0:99999:7:::
FIXTURE
provider.password = "totally"
- File.read(path).should =~ /^fakeval:totally:/
+ expect(File.read(path)).to match(/^fakeval:totally:/)
end
it "should only update the target user" do
Date.expects(:today).returns Date.new(2011,12,07)
write_fixture <<FIXTURE
before:seriously:15315:0:99999:7:::
fakeval:seriously:15315:0:99999:7:::
fakevalish:seriously:15315:0:99999:7:::
after:seriously:15315:0:99999:7:::
FIXTURE
provider.password = "totally"
- File.read(path).should == <<EOT
+ expect(File.read(path)).to eq <<EOT
before:seriously:15315:0:99999:7:::
fakeval:totally:15315:0:99999:7:::
fakevalish:seriously:15315:0:99999:7:::
after:seriously:15315:0:99999:7:::
EOT
end
# This preserves the current semantics, but is it right? --daniel 2012-02-05
it "should do nothing if the target user is missing" do
fixture = <<FIXTURE
before:seriously:15315:0:99999:7:::
fakevalish:seriously:15315:0:99999:7:::
after:seriously:15315:0:99999:7:::
FIXTURE
write_fixture fixture
provider.password = "totally"
- File.read(path).should == fixture
+ expect(File.read(path)).to eq(fixture)
end
it "should update the lastchg field" do
Date.expects(:today).returns Date.new(2013,5,12) # 15837 days after 1970-01-01
write_fixture <<FIXTURE
before:seriously:15315:0:99999:7:::
fakeval:seriously:15629:0:99999:7:::
fakevalish:seriously:15315:0:99999:7:::
after:seriously:15315:0:99999:7:::
FIXTURE
provider.password = "totally"
- File.read(path).should == <<EOT
+ expect(File.read(path)).to eq <<EOT
before:seriously:15315:0:99999:7:::
fakeval:totally:15837:0:99999:7:::
fakevalish:seriously:15315:0:99999:7:::
after:seriously:15315:0:99999:7:::
EOT
end
end
describe "#shadow_entry" do
it "should return the line for the right user" do
File.stubs(:readlines).returns(["someuser:!:10:5:20:7:1::\n", "fakeval:*:20:10:30:7:2::\n", "testuser:*:30:15:40:7:3::\n"])
- provider.shadow_entry.should == ["fakeval", "*", "20", "10", "30", "7", "2", "", ""]
+ expect(provider.shadow_entry).to eq(["fakeval", "*", "20", "10", "30", "7", "2", "", ""])
end
end
describe "#password_max_age" do
it "should return a maximum age number" do
File.stubs(:readlines).returns(["fakeval:NP:12345:0:50::::\n"])
- provider.password_max_age.should == "50"
+ expect(provider.password_max_age).to eq("50")
end
it "should return -1 for no maximum" do
File.stubs(:readlines).returns(["fakeval:NP:12345::::::\n"])
- provider.password_max_age.should == -1
+ expect(provider.password_max_age).to eq(-1)
end
it "should return -1 for no maximum when failed attempts are present" do
File.stubs(:readlines).returns(["fakeval:NP:12345::::::3\n"])
- provider.password_max_age.should == -1
+ expect(provider.password_max_age).to eq(-1)
end
end
describe "#password_min_age" do
it "should return a minimum age number" do
File.stubs(:readlines).returns(["fakeval:NP:12345:10:50::::\n"])
- provider.password_min_age.should == "10"
+ expect(provider.password_min_age).to eq("10")
end
it "should return -1 for no minimum" do
File.stubs(:readlines).returns(["fakeval:NP:12345::::::\n"])
- provider.password_min_age.should == -1
+ expect(provider.password_min_age).to eq(-1)
end
it "should return -1 for no minimum when failed attempts are present" do
File.stubs(:readlines).returns(["fakeval:NP:12345::::::3\n"])
- provider.password_min_age.should == -1
+ expect(provider.password_min_age).to eq(-1)
end
end
end
diff --git a/spec/unit/provider/user/useradd_spec.rb b/spec/unit/provider/user/useradd_spec.rb
index b4c41b5ae..ef4f41844 100755
--- a/spec/unit/provider/user/useradd_spec.rb
+++ b/spec/unit/provider/user/useradd_spec.rb
@@ -1,446 +1,446 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:user).provider(:useradd) do
before :each do
described_class.stubs(:command).with(:password).returns '/usr/bin/chage'
described_class.stubs(:command).with(:add).returns '/usr/sbin/useradd'
described_class.stubs(:command).with(:localadd).returns '/usr/sbin/luseradd'
described_class.stubs(:command).with(:modify).returns '/usr/sbin/usermod'
described_class.stubs(:command).with(:delete).returns '/usr/sbin/userdel'
end
let(:resource) do
Puppet::Type.type(:user).new(
:name => 'myuser',
:managehome => :false,
:system => :false,
:provider => provider
)
end
let(:provider) { described_class.new(:name => 'myuser') }
let(:shadow_entry) {
return unless Puppet.features.libshadow?
entry = Struct::PasswdEntry.new
entry[:sp_namp] = 'myuser' # login name
entry[:sp_pwdp] = '$6$FvW8Ib8h$qQMI/CR9m.QzIicZKutLpBgCBBdrch1IX0rTnxuI32K1pD9.RXZrmeKQlaC.RzODNuoUtPPIyQDufunvLOQWF0' # encrypted password
entry[:sp_lstchg] = 15573 # date of last password change
entry[:sp_min] = 10 # minimum password age
entry[:sp_max] = 20 # maximum password age
entry[:sp_warn] = 7 # password warning period
entry[:sp_inact] = -1 # password inactivity period
entry[:sp_expire] = 15706 # account expiration date
entry
}
describe "#create" do
before do
provider.stubs(:exists?).returns(false)
end
it "should add -g when no gid is specified and group already exists" do
Puppet::Util.stubs(:gid).returns(true)
resource[:ensure] = :present
provider.expects(:execute).with(includes('-g'), kind_of(Hash))
provider.create
end
it "should use -G to set groups" do
Facter.stubs(:value).with(:osfamily).returns('Not RedHat')
resource[:ensure] = :present
resource[:groups] = ['group1', 'group2']
provider.expects(:execute).with(['/usr/sbin/useradd', '-G', 'group1,group2', 'myuser'], kind_of(Hash))
provider.create
end
it "should use -G to set groups without -M on RedHat" do
Facter.stubs(:value).with(:osfamily).returns('RedHat')
resource[:ensure] = :present
resource[:groups] = ['group1', 'group2']
provider.expects(:execute).with(['/usr/sbin/useradd', '-G', 'group1,group2', '-M', 'myuser'], kind_of(Hash))
provider.create
end
it "should add -o when allowdupe is enabled and the user is being created" do
resource[:allowdupe] = true
provider.expects(:execute).with(includes('-o'), kind_of(Hash))
provider.create
end
describe "on systems that support has_system", :if => described_class.system_users? do
it "should add -r when system is enabled" do
resource[:system] = :true
- provider.should be_system_users
+ expect(provider).to be_system_users
provider.expects(:execute).with(includes('-r'), kind_of(Hash))
provider.create
end
end
describe "on systems that do not support has_system", :unless => described_class.system_users? do
it "should not add -r when system is enabled" do
resource[:system] = :true
- provider.should_not be_system_users
+ expect(provider).not_to be_system_users
provider.expects(:execute).with(['/usr/sbin/useradd', 'myuser'], kind_of(Hash))
provider.create
end
end
it "should set password age rules" do
described_class.has_feature :manages_password_age
resource[:password_min_age] = 5
resource[:password_max_age] = 10
provider.expects(:execute).with(includes('/usr/sbin/useradd'), kind_of(Hash))
provider.expects(:execute).with(['/usr/bin/chage', '-m', 5, '-M', 10, 'myuser'])
provider.create
end
describe "on systems with the libuser and forcelocal=true" do
before do
described_class.has_feature :libuser
resource[:forcelocal] = true
end
it "should use luseradd instead of useradd" do
provider.expects(:execute).with(includes('/usr/sbin/luseradd'), has_entry(:custom_environment, has_key('LIBUSER_CONF')))
provider.create
end
it "should NOT use -o when allowdupe=true" do
resource[:allowdupe] = :true
provider.expects(:execute).with(Not(includes('-o')), has_entry(:custom_environment, has_key('LIBUSER_CONF')))
provider.create
end
it "should raise an exception for duplicate UIDs" do
resource[:uid] = 505
provider.stubs(:finduser).returns(true)
- lambda { provider.create }.should raise_error(Puppet::Error, "UID 505 already exists, use allowdupe to force user creation")
+ expect { provider.create }.to raise_error(Puppet::Error, "UID 505 already exists, use allowdupe to force user creation")
end
it "should not use -G for luseradd and should call usermod with -G after luseradd when groups property is set" do
resource[:groups] = ['group1', 'group2']
provider.expects(:execute).with(Not(includes("-G")), has_entry(:custom_environment, has_key('LIBUSER_CONF')))
provider.expects(:execute).with(includes('/usr/sbin/usermod'))
provider.create
end
it "should not use -m when managehome set" do
resource[:managehome] = :true
provider.expects(:execute).with(Not(includes('-m')), has_entry(:custom_environment, has_key('LIBUSER_CONF')))
provider.create
end
it "should not use -e with luseradd, should call usermod with -e after luseradd when expiry is set" do
resource[:expiry] = '2038-01-24'
provider.expects(:execute).with(all_of(includes('/usr/sbin/luseradd'), Not(includes('-e'))), has_entry(:custom_environment, has_key('LIBUSER_CONF')))
provider.expects(:execute).with(all_of(includes('/usr/sbin/usermod'), includes('-e')))
provider.create
end
it "should use userdel to delete users" do
resource[:ensure] = :absent
provider.stubs(:exists?).returns(true)
provider.expects(:execute).with(includes('/usr/sbin/userdel'))
provider.delete
end
end
describe "on systems that allow to set shell" do
it "should trigger shell validation" do
resource[:shell] = '/bin/bash'
provider.expects(:check_valid_shell)
provider.expects(:execute).with(includes('-s'), kind_of(Hash))
provider.create
end
end
end
describe "#uid=" do
it "should add -o when allowdupe is enabled and the uid is being modified" do
resource[:allowdupe] = :true
provider.expects(:execute).with(['/usr/sbin/usermod', '-u', 150, '-o', 'myuser'])
provider.uid = 150
end
end
describe "#expiry=" do
it "should pass expiry to usermod as MM/DD/YY when on Solaris" do
Facter.expects(:value).with(:operatingsystem).returns 'Solaris'
resource[:expiry] = '2012-10-31'
provider.expects(:execute).with(['/usr/sbin/usermod', '-e', '10/31/2012', 'myuser'])
provider.expiry = '2012-10-31'
end
it "should pass expiry to usermod as YYYY-MM-DD when not on Solaris" do
Facter.expects(:value).with(:operatingsystem).returns 'not_solaris'
resource[:expiry] = '2012-10-31'
provider.expects(:execute).with(['/usr/sbin/usermod', '-e', '2012-10-31', 'myuser'])
provider.expiry = '2012-10-31'
end
it "should use -e with an empty string when the expiry property is removed" do
resource[:expiry] = :absent
provider.expects(:execute).with(['/usr/sbin/usermod', '-e', '', 'myuser'])
provider.expiry = :absent
end
end
describe "#check_allow_dup" do
it "should return an array with a flag if dup is allowed" do
resource[:allowdupe] = :true
- provider.check_allow_dup.must == ["-o"]
+ expect(provider.check_allow_dup).to eq(["-o"])
end
it "should return an empty array if no dup is allowed" do
resource[:allowdupe] = :false
- provider.check_allow_dup.must == []
+ expect(provider.check_allow_dup).to eq([])
end
end
describe "#check_system_users" do
it "should check system users" do
described_class.expects(:system_users?).returns true
resource.expects(:system?)
provider.check_system_users
end
it "should return an array with a flag if it's a system user" do
described_class.expects(:system_users?).returns true
resource[:system] = :true
- provider.check_system_users.must == ["-r"]
+ expect(provider.check_system_users).to eq(["-r"])
end
it "should return an empty array if it's not a system user" do
described_class.expects(:system_users?).returns true
resource[:system] = :false
- provider.check_system_users.must == []
+ expect(provider.check_system_users).to eq([])
end
it "should return an empty array if system user is not featured" do
described_class.expects(:system_users?).returns false
resource[:system] = :true
- provider.check_system_users.must == []
+ expect(provider.check_system_users).to eq([])
end
end
describe "#check_manage_home" do
it "should return an array with -m flag if home is managed" do
resource[:managehome] = :true
provider.expects(:execute).with(includes('-m'), kind_of(Hash))
provider.create
end
it "should return an array with -r flag if home is managed" do
resource[:managehome] = :true
resource[:ensure] = :absent
provider.stubs(:exists?).returns(true)
provider.expects(:execute).with(includes('-r'))
provider.delete
end
it "should use -M flag if home is not managed and on Redhat" do
Facter.stubs(:value).with(:osfamily).returns("RedHat")
resource[:managehome] = :false
provider.expects(:execute).with(includes('-M'), kind_of(Hash))
provider.create
end
it "should not use -M flag if home is not managed and not on Redhat" do
Facter.stubs(:value).with(:osfamily).returns("not RedHat")
resource[:managehome] = :false
provider.expects(:execute).with(Not(includes('-M')), kind_of(Hash))
provider.create
end
end
describe "#addcmd" do
before do
resource[:allowdupe] = :true
resource[:managehome] = :true
resource[:system] = :true
resource[:groups] = [ 'somegroup' ]
end
it "should call command with :add" do
provider.expects(:command).with(:add)
provider.addcmd
end
it "should add properties" do
provider.expects(:add_properties).returns(['-foo_add_properties'])
- provider.addcmd.should include '-foo_add_properties'
+ expect(provider.addcmd).to include '-foo_add_properties'
end
it "should check and add if dup allowed" do
provider.expects(:check_allow_dup).returns(['-allow_dup_flag'])
- provider.addcmd.should include '-allow_dup_flag'
+ expect(provider.addcmd).to include '-allow_dup_flag'
end
it "should check and add if home is managed" do
provider.expects(:check_manage_home).returns(['-manage_home_flag'])
- provider.addcmd.should include '-manage_home_flag'
+ expect(provider.addcmd).to include '-manage_home_flag'
end
it "should add the resource :name" do
- provider.addcmd.should include 'myuser'
+ expect(provider.addcmd).to include 'myuser'
end
describe "on systems featuring system_users", :if => described_class.system_users? do
it "should return an array with -r if system? is true" do
resource[:system] = :true
- provider.addcmd.should include("-r")
+ expect(provider.addcmd).to include("-r")
end
it "should return an array without -r if system? is false" do
resource[:system] = :false
- provider.addcmd.should_not include("-r")
+ expect(provider.addcmd).not_to include("-r")
end
end
describe "on systems not featuring system_users", :unless => described_class.system_users? do
[:false, :true].each do |system|
it "should return an array without -r if system? is #{system}" do
resource[:system] = system
- provider.addcmd.should_not include("-r")
+ expect(provider.addcmd).not_to include("-r")
end
end
end
it "should return an array with the full command and expiry as MM/DD/YY when on Solaris" do
Facter.stubs(:value).with(:operatingsystem).returns 'Solaris'
described_class.expects(:system_users?).returns true
resource[:expiry] = "2012-08-18"
- provider.addcmd.must == ['/usr/sbin/useradd', '-e', '08/18/2012', '-G', 'somegroup', '-o', '-m', '-r', 'myuser']
+ expect(provider.addcmd).to eq(['/usr/sbin/useradd', '-e', '08/18/2012', '-G', 'somegroup', '-o', '-m', '-r', 'myuser'])
end
it "should return an array with the full command and expiry as YYYY-MM-DD when not on Solaris" do
Facter.stubs(:value).with(:operatingsystem).returns 'not_solaris'
described_class.expects(:system_users?).returns true
resource[:expiry] = "2012-08-18"
- provider.addcmd.must == ['/usr/sbin/useradd', '-e', '2012-08-18', '-G', 'somegroup', '-o', '-m', '-r', 'myuser']
+ expect(provider.addcmd).to eq(['/usr/sbin/useradd', '-e', '2012-08-18', '-G', 'somegroup', '-o', '-m', '-r', 'myuser'])
end
it "should return an array without -e if expiry is undefined full command" do
described_class.expects(:system_users?).returns true
- provider.addcmd.must == ["/usr/sbin/useradd", "-G", "somegroup", "-o", "-m", "-r", "myuser"]
+ expect(provider.addcmd).to eq(["/usr/sbin/useradd", "-G", "somegroup", "-o", "-m", "-r", "myuser"])
end
it "should pass -e \"\" if the expiry has to be removed" do
described_class.expects(:system_users?).returns true
resource[:expiry] = :absent
- provider.addcmd.must == ['/usr/sbin/useradd', '-e', '', '-G', 'somegroup', '-o', '-m', '-r', 'myuser']
+ expect(provider.addcmd).to eq(['/usr/sbin/useradd', '-e', '', '-G', 'somegroup', '-o', '-m', '-r', 'myuser'])
end
end
{
:password_min_age => 10,
:password_max_age => 20,
:password => '$6$FvW8Ib8h$qQMI/CR9m.QzIicZKutLpBgCBBdrch1IX0rTnxuI32K1pD9.RXZrmeKQlaC.RzODNuoUtPPIyQDufunvLOQWF0'
}.each_pair do |property, expected_value|
describe "##{property}" do
before :each do
resource # just to link the resource to the provider
end
it "should return absent if libshadow feature is not present" do
Puppet.features.stubs(:libshadow?).returns false
# Shadow::Passwd.expects(:getspnam).never # if we really don't have libshadow we dont have Shadow::Passwd either
- provider.send(property).should == :absent
+ expect(provider.send(property)).to eq(:absent)
end
it "should return absent if user cannot be found", :if => Puppet.features.libshadow? do
Shadow::Passwd.expects(:getspnam).with('myuser').returns nil
- provider.send(property).should == :absent
+ expect(provider.send(property)).to eq(:absent)
end
it "should return the correct value if libshadow is present", :if => Puppet.features.libshadow? do
Shadow::Passwd.expects(:getspnam).with('myuser').returns shadow_entry
- provider.send(property).should == expected_value
+ expect(provider.send(property)).to eq(expected_value)
end
end
end
describe '#expiry' do
before :each do
resource # just to link the resource to the provider
end
it "should return absent if libshadow feature is not present" do
Puppet.features.stubs(:libshadow?).returns false
- provider.expiry.should == :absent
+ expect(provider.expiry).to eq(:absent)
end
it "should return absent if user cannot be found", :if => Puppet.features.libshadow? do
Shadow::Passwd.expects(:getspnam).with('myuser').returns nil
- provider.expiry.should == :absent
+ expect(provider.expiry).to eq(:absent)
end
it "should return absent if expiry is -1", :if => Puppet.features.libshadow? do
shadow_entry.sp_expire = -1
Shadow::Passwd.expects(:getspnam).with('myuser').returns shadow_entry
- provider.expiry.should == :absent
+ expect(provider.expiry).to eq(:absent)
end
it "should convert to YYYY-MM-DD", :if => Puppet.features.libshadow? do
Shadow::Passwd.expects(:getspnam).with('myuser').returns shadow_entry
- provider.expiry.should == '2013-01-01'
+ expect(provider.expiry).to eq('2013-01-01')
end
end
describe "#passcmd" do
before do
resource[:allowdupe] = :true
resource[:managehome] = :true
resource[:system] = :true
described_class.has_feature :manages_password_age
end
it "should call command with :pass" do
# command(:password) is only called inside passcmd if
# password_min_age or password_max_age is set
resource[:password_min_age] = 123
provider.expects(:command).with(:password)
provider.passcmd
end
it "should return nil if neither min nor max is set" do
- provider.passcmd.must be_nil
+ expect(provider.passcmd).to be_nil
end
it "should return a chage command array with -m <value> and the user name if password_min_age is set" do
resource[:password_min_age] = 123
- provider.passcmd.must == ['/usr/bin/chage','-m',123,'myuser']
+ expect(provider.passcmd).to eq(['/usr/bin/chage','-m',123,'myuser'])
end
it "should return a chage command array with -M <value> if password_max_age is set" do
resource[:password_max_age] = 999
- provider.passcmd.must == ['/usr/bin/chage','-M',999,'myuser']
+ expect(provider.passcmd).to eq(['/usr/bin/chage','-M',999,'myuser'])
end
it "should return a chage command array with -M <value> -m <value> if both password_min_age and password_max_age are set" do
resource[:password_min_age] = 123
resource[:password_max_age] = 999
- provider.passcmd.must == ['/usr/bin/chage','-m',123,'-M',999,'myuser']
+ expect(provider.passcmd).to eq(['/usr/bin/chage','-m',123,'-M',999,'myuser'])
end
end
describe "#check_valid_shell" do
it "should raise an error if shell does not exist" do
resource[:shell] = 'foo/bin/bash'
- lambda { provider.check_valid_shell }.should raise_error(Puppet::Error, /Shell foo\/bin\/bash must exist/)
+ expect { provider.check_valid_shell }.to raise_error(Puppet::Error, /Shell foo\/bin\/bash must exist/)
end
it "should raise an error if the shell is not executable" do
resource[:shell] = 'LICENSE'
- lambda { provider.check_valid_shell }.should raise_error(Puppet::Error, /Shell LICENSE must be executable/)
+ expect { provider.check_valid_shell }.to raise_error(Puppet::Error, /Shell LICENSE must be executable/)
end
end
end
diff --git a/spec/unit/provider/user/windows_adsi_spec.rb b/spec/unit/provider/user/windows_adsi_spec.rb
index 47d097b0c..8a9d680aa 100755
--- a/spec/unit/provider/user/windows_adsi_spec.rb
+++ b/spec/unit/provider/user/windows_adsi_spec.rb
@@ -1,173 +1,173 @@
#!/usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:user).provider(:windows_adsi), :if => Puppet.features.microsoft_windows? do
let(:resource) do
Puppet::Type.type(:user).new(
:title => 'testuser',
:comment => 'Test J. User',
:provider => :windows_adsi
)
end
let(:provider) { resource.provider }
let(:connection) { stub 'connection' }
before :each do
Puppet::Util::Windows::ADSI.stubs(:computer_name).returns('testcomputername')
Puppet::Util::Windows::ADSI.stubs(:connect).returns connection
end
describe ".instances" do
it "should enumerate all users" do
names = ['user1', 'user2', 'user3']
stub_users = names.map{|n| stub(:name => n)}
connection.stubs(:execquery).with('select name from win32_useraccount where localaccount = "TRUE"').returns(stub_users)
- described_class.instances.map(&:name).should =~ names
+ expect(described_class.instances.map(&:name)).to match(names)
end
end
it "should provide access to a Puppet::Util::Windows::ADSI::User object" do
- provider.user.should be_a(Puppet::Util::Windows::ADSI::User)
+ expect(provider.user).to be_a(Puppet::Util::Windows::ADSI::User)
end
describe "when managing groups" do
it 'should return the list of groups as a comma-separated list' do
provider.user.stubs(:groups).returns ['group1', 'group2', 'group3']
- provider.groups.should == 'group1,group2,group3'
+ expect(provider.groups).to eq('group1,group2,group3')
end
it "should return absent if there are no groups" do
provider.user.stubs(:groups).returns []
- provider.groups.should == ''
+ expect(provider.groups).to eq('')
end
it 'should be able to add a user to a set of groups' do
resource[:membership] = :minimum
provider.user.expects(:set_groups).with('group1,group2', true)
provider.groups = 'group1,group2'
resource[:membership] = :inclusive
provider.user.expects(:set_groups).with('group1,group2', false)
provider.groups = 'group1,group2'
end
end
describe "when creating a user" do
it "should create the user on the system and set its other properties" do
resource[:groups] = ['group1', 'group2']
resource[:membership] = :inclusive
resource[:comment] = 'a test user'
resource[:home] = 'C:\Users\testuser'
user = stub 'user'
Puppet::Util::Windows::ADSI::User.expects(:create).with('testuser').returns user
user.stubs(:groups).returns(['group2', 'group3'])
create = sequence('create')
user.expects(:password=).in_sequence(create)
user.expects(:commit).in_sequence(create)
user.expects(:set_groups).with('group1,group2', false).in_sequence(create)
user.expects(:[]=).with('Description', 'a test user')
user.expects(:[]=).with('HomeDirectory', 'C:\Users\testuser')
provider.create
end
it "should load the profile if managehome is set" do
resource[:password] = '0xDeadBeef'
resource[:managehome] = true
user = stub_everything 'user'
Puppet::Util::Windows::ADSI::User.expects(:create).with('testuser').returns user
Puppet::Util::Windows::User.expects(:load_profile).with('testuser', '0xDeadBeef')
provider.create
end
it "should set a user's password" do
provider.user.expects(:password=).with('plaintextbad')
provider.password = "plaintextbad"
end
it "should test a valid user password" do
resource[:password] = 'plaintext'
provider.user.expects(:password_is?).with('plaintext').returns true
- provider.password.should == 'plaintext'
+ expect(provider.password).to eq('plaintext')
end
it "should test a bad user password" do
resource[:password] = 'plaintext'
provider.user.expects(:password_is?).with('plaintext').returns false
- provider.password.should be_nil
+ expect(provider.password).to be_nil
end
it 'should not create a user if a group by the same name exists' do
Puppet::Util::Windows::ADSI::User.expects(:create).with('testuser').raises( Puppet::Error.new("Cannot create user if group 'testuser' exists.") )
expect{ provider.create }.to raise_error( Puppet::Error,
/Cannot create user if group 'testuser' exists./ )
end
end
it 'should be able to test whether a user exists' do
Puppet::Util::Windows::ADSI.stubs(:sid_uri_safe).returns(nil)
Puppet::Util::Windows::ADSI.stubs(:connect).returns stub('connection')
- provider.should be_exists
+ expect(provider).to be_exists
Puppet::Util::Windows::ADSI.stubs(:connect).returns nil
- provider.should_not be_exists
+ expect(provider).not_to be_exists
end
it 'should be able to delete a user' do
connection.expects(:Delete).with('user', 'testuser')
provider.delete
end
it 'should delete the profile if managehome is set' do
resource[:managehome] = true
sid = 'S-A-B-C'
Puppet::Util::Windows::SID.expects(:name_to_sid).with('testuser').returns(sid)
Puppet::Util::Windows::ADSI::UserProfile.expects(:delete).with(sid)
connection.expects(:Delete).with('user', 'testuser')
provider.delete
end
it "should commit the user when flushed" do
provider.user.expects(:commit)
provider.flush
end
it "should return the user's SID as uid" do
Puppet::Util::Windows::SID.expects(:name_to_sid).with('testuser').returns('S-1-5-21-1362942247-2130103807-3279964888-1111')
- provider.uid.should == 'S-1-5-21-1362942247-2130103807-3279964888-1111'
+ expect(provider.uid).to eq('S-1-5-21-1362942247-2130103807-3279964888-1111')
end
it "should fail when trying to manage the uid property" do
provider.expects(:fail).with { |msg| msg =~ /uid is read-only/ }
provider.send(:uid=, 500)
end
[:gid, :shell].each do |prop|
it "should fail when trying to manage the #{prop} property" do
provider.expects(:fail).with { |msg| msg =~ /No support for managing property #{prop}/ }
provider.send("#{prop}=", 'foo')
end
end
end
diff --git a/spec/unit/provider/vlan/cisco_spec.rb b/spec/unit/provider/vlan/cisco_spec.rb
index d6b93fafc..5d2c28d49 100755
--- a/spec/unit/provider/vlan/cisco_spec.rb
+++ b/spec/unit/provider/vlan/cisco_spec.rb
@@ -1,55 +1,55 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/provider/vlan/cisco'
provider_class = Puppet::Type.type(:vlan).provider(:cisco)
describe provider_class do
before do
@device = stub_everything 'device'
@resource = stub("resource", :name => "200")
@provider = provider_class.new(@device, @resource)
end
it "should have a parent of Puppet::Provider::Cisco" do
- provider_class.should < Puppet::Provider::Cisco
+ expect(provider_class).to be < Puppet::Provider::Cisco
end
it "should have an instances method" do
- provider_class.should respond_to(:instances)
+ expect(provider_class).to respond_to(:instances)
end
describe "when looking up instances at prefetch" do
before do
@device.stubs(:command).yields(@device)
end
it "should delegate to the device vlans" do
@device.expects(:parse_vlans)
provider_class.lookup(@device, "200")
end
it "should return only the given vlan" do
@device.expects(:parse_vlans).returns({"200" => { :description => "thisone" }, "1" => { :description => "nothisone" }})
- provider_class.lookup(@device, "200").should == {:description => "thisone" }
+ expect(provider_class.lookup(@device, "200")).to eq({:description => "thisone" })
end
end
describe "when an instance is being flushed" do
it "should call the device update_vlan method with its vlan id, current attributes, and desired attributes" do
@instance = provider_class.new(@device, :ensure => :present, :name => "200", :description => "myvlan")
@instance.description = "myvlan2"
@instance.resource = @resource
@resource.stubs(:[]).with(:name).returns("200")
device = stub_everything 'device'
@instance.stubs(:device).returns(device)
device.expects(:command).yields(device)
device.expects(:update_vlan).with(@instance.name, {:ensure => :present, :name => "200", :description => "myvlan"},
{:ensure => :present, :name => "200", :description => "myvlan2"})
@instance.flush
end
end
end
diff --git a/spec/unit/provider/yumrepo/inifile_spec.rb b/spec/unit/provider/yumrepo/inifile_spec.rb
index b0843276d..0b526c30b 100644
--- a/spec/unit/provider/yumrepo/inifile_spec.rb
+++ b/spec/unit/provider/yumrepo/inifile_spec.rb
@@ -1,309 +1,309 @@
require 'spec_helper'
describe Puppet::Type.type(:yumrepo).provider(:inifile) do
after(:each) do
described_class.clear
end
describe "enumerating all yum repo files" do
it "reads all files in the directories specified by reposdir" do
described_class.expects(:reposdir).returns ['/etc/yum.repos.d']
Dir.expects(:glob).with("/etc/yum.repos.d/*.repo").returns(['/etc/yum.repos.d/first.repo', '/etc/yum.repos.d/second.repo'])
actual = described_class.repofiles
expect(actual).to include("/etc/yum.repos.d/first.repo")
expect(actual).to include("/etc/yum.repos.d/second.repo")
end
it "includes '/etc/yum.conf' as the first element" do
described_class.expects(:reposdir).returns []
actual = described_class.repofiles
expect(actual[0]).to eq "/etc/yum.conf"
end
end
describe "generating the virtual inifile" do
let(:files) { ['/etc/yum.repos.d/first.repo', '/etc/yum.repos.d/second.repo', '/etc/yum.conf'] }
let(:collection) { mock('virtual inifile') }
before do
described_class.clear
Puppet::Util::IniConfig::FileCollection.expects(:new).returns collection
end
it "reads all files in the directories specified by self.repofiles" do
described_class.expects(:repofiles).returns(files)
files.each do |file|
Puppet::FileSystem.stubs(:file?).with(file).returns true
collection.expects(:read).with(file)
end
described_class.virtual_inifile
end
it "ignores repofile entries that are not files" do
described_class.expects(:repofiles).returns(files)
Puppet::FileSystem.stubs(:file?).with('/etc/yum.repos.d/first.repo').returns true
Puppet::FileSystem.stubs(:file?).with('/etc/yum.repos.d/second.repo').returns false
Puppet::FileSystem.stubs(:file?).with('/etc/yum.conf').returns true
collection.expects(:read).with('/etc/yum.repos.d/first.repo').once
collection.expects(:read).with('/etc/yum.repos.d/second.repo').never
collection.expects(:read).with('/etc/yum.conf').once
described_class.virtual_inifile
end
end
describe 'creating provider instances' do
let(:virtual_inifile) { stub('virtual inifile') }
before :each do
described_class.stubs(:virtual_inifile).returns(virtual_inifile)
end
let(:main_section) do
sect = Puppet::Util::IniConfig::Section.new('main', '/some/imaginary/file')
sect.entries << ['distroverpkg', 'centos-release']
sect.entries << ['plugins', '1']
sect
end
let(:updates_section) do
sect = Puppet::Util::IniConfig::Section.new('updates', '/some/imaginary/file')
sect.entries << ['name', 'Some long description of the repo']
sect.entries << ['enabled', '1']
sect
end
it "ignores the main section" do
virtual_inifile.expects(:each_section).multiple_yields(main_section, updates_section)
instances = described_class.instances
expect(instances).to have(1).items
expect(instances[0].name).to eq 'updates'
end
it "creates provider instances for every non-main section that was found" do
virtual_inifile.expects(:each_section).multiple_yields(main_section, updates_section)
sect = described_class.instances.first
expect(sect.name).to eq 'updates'
expect(sect.descr).to eq 'Some long description of the repo'
expect(sect.enabled).to eq '1'
end
end
describe "retrieving a section from the inifile" do
let(:collection) { stub('ini file collection') }
let(:ini_section) { stub('ini file section') }
before do
described_class.stubs(:virtual_inifile).returns(collection)
end
describe "and the requested section exists" do
before do
collection.stubs(:[]).with('updates').returns ini_section
end
it "returns the existing section" do
expect(described_class.section('updates')).to eq ini_section
end
it "doesn't create a new section" do
collection.expects(:add_section).never
described_class.section('updates')
end
end
describe "and the requested section doesn't exist" do
it "creates a section in the preferred repodir" do
described_class.stubs(:reposdir).returns ['/etc/yum.repos.d', '/etc/alternate.repos.d']
collection.expects(:[]).with('updates')
collection.expects(:add_section).with('updates', '/etc/alternate.repos.d/updates.repo')
described_class.section('updates')
end
it "creates a section in yum.conf if no repodirs exist" do
described_class.stubs(:reposdir).returns []
collection.expects(:[]).with('updates')
collection.expects(:add_section).with('updates', '/etc/yum.conf')
described_class.section('updates')
end
end
end
describe "setting and getting properties" do
let(:type_instance) do
Puppet::Type.type(:yumrepo).new(
:name => 'puppetlabs-products',
:ensure => :present,
:baseurl => 'http://yum.puppetlabs.com/el/6/products/$basearch',
:descr => 'Puppet Labs Products El 6 - $basearch',
:enabled => '1',
:gpgcheck => '1',
:gpgkey => 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-puppetlabs'
)
end
let(:provider) do
described_class.new(type_instance)
end
let(:section) do
stub('inifile puppetlabs section', :name => 'puppetlabs-products')
end
before do
type_instance.provider = provider
described_class.stubs(:section).with('puppetlabs-products').returns(section)
end
describe "methods used by ensurable" do
it "#create sets the yumrepo properties on the according section" do
section.expects(:[]=).with('baseurl', 'http://yum.puppetlabs.com/el/6/products/$basearch')
section.expects(:[]=).with('name', 'Puppet Labs Products El 6 - $basearch')
section.expects(:[]=).with('enabled', '1')
section.expects(:[]=).with('gpgcheck', '1')
section.expects(:[]=).with('gpgkey', 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-puppetlabs')
provider.create
end
it "#exists? checks if the repo has been marked as present" do
described_class.stubs(:section).returns(stub(:[]= => nil))
provider.create
expect(provider).to be_exist
end
it "#destroy deletes the associated ini file section" do
described_class.expects(:section).returns(section)
section.expects(:destroy=).with(true)
provider.destroy
end
end
describe "getting properties" do
it "maps the 'descr' property to the 'name' INI property" do
section.expects(:[]).with('name').returns 'Some rather long description of the repository'
expect(provider.descr).to eq 'Some rather long description of the repository'
end
it "gets the property from the INI section" do
section.expects(:[]).with('enabled').returns '1'
expect(provider.enabled).to eq '1'
end
it "sets the property as :absent if the INI property is nil" do
section.expects(:[]).with('exclude').returns nil
expect(provider.exclude).to eq :absent
end
end
describe "setting properties" do
it "maps the 'descr' property to the 'name' INI property" do
section.expects(:[]=).with('name', 'Some rather long description of the repository')
provider.descr = 'Some rather long description of the repository'
end
it "sets the property on the INI section" do
section.expects(:[]=).with('enabled', '0')
provider.enabled = '0'
end
it "sets the section field to nil when the specified value is absent" do
section.expects(:[]=).with('exclude', nil)
provider.exclude = :absent
end
end
end
describe 'reposdir' do
let(:defaults) { ['/etc/yum.repos.d', '/etc/yum/repos.d'] }
before do
Puppet::FileSystem.stubs(:exist?).with('/etc/yum.repos.d').returns(true)
Puppet::FileSystem.stubs(:exist?).with('/etc/yum/repos.d').returns(true)
end
it "returns the default directories if yum.conf doesn't contain a `reposdir` entry" do
described_class.stubs(:find_conf_value).with('reposdir', '/etc/yum.conf')
- described_class.reposdir('/etc/yum.conf').should == defaults
+ expect(described_class.reposdir('/etc/yum.conf')).to eq(defaults)
end
it "includes the directory specified by the yum.conf 'reposdir' entry when the directory is present" do
Puppet::FileSystem.expects(:exist?).with("/etc/yum/extra.repos.d").returns(true)
described_class.expects(:find_conf_value).with('reposdir', '/etc/yum.conf').returns "/etc/yum/extra.repos.d"
- described_class.reposdir('/etc/yum.conf').should include("/etc/yum/extra.repos.d")
+ expect(described_class.reposdir('/etc/yum.conf')).to include("/etc/yum/extra.repos.d")
end
it "doesn't include the directory specified by the yum.conf 'reposdir' entry when the directory is absent" do
Puppet::FileSystem.expects(:exist?).with("/etc/yum/extra.repos.d").returns(false)
described_class.expects(:find_conf_value).with('reposdir', '/etc/yum.conf').returns "/etc/yum/extra.repos.d"
- described_class.reposdir('/etc/yum.conf').should_not include("/etc/yum/extra.repos.d")
+ expect(described_class.reposdir('/etc/yum.conf')).not_to include("/etc/yum/extra.repos.d")
end
it "logs a warning and returns an empty array if none of the specified repo directories exist" do
Puppet::FileSystem.unstub(:exist?)
Puppet::FileSystem.stubs(:exist?).returns false
described_class.stubs(:find_conf_value).with('reposdir', '/etc/yum.conf')
Puppet.expects(:debug).with('No yum directories were found on the local filesystem')
expect(described_class.reposdir('/etc/yum.conf')).to be_empty
end
end
describe "looking up a conf value" do
describe "and the file doesn't exist" do
it "returns nil" do
Puppet::FileSystem.stubs(:exist?).returns false
expect(described_class.find_conf_value('reposdir')).to be_nil
end
end
describe "and the file exists" do
let(:pfile) { stub('yum.conf physical file') }
let(:sect) { stub('ini section') }
before do
Puppet::FileSystem.stubs(:exist?).with('/etc/yum.conf').returns true
Puppet::Util::IniConfig::PhysicalFile.stubs(:new).with('/etc/yum.conf').returns pfile
end
it "creates a PhysicalFile to parse the given file" do
pfile.expects(:get_section)
described_class.find_conf_value('reposdir')
end
it "returns nil if the file exists but the 'main' section doesn't exist" do
pfile.expects(:get_section).with('main')
expect(described_class.find_conf_value('reposdir')).to be_nil
end
it "returns nil if the file exists but the INI property doesn't exist" do
pfile.expects(:get_section).with('main').returns sect
sect.expects(:[]).with('reposdir')
expect(described_class.find_conf_value('reposdir')).to be_nil
end
it "returns the value if the value is defined in the PhysicalFile" do
pfile.expects(:get_section).with('main').returns sect
sect.expects(:[]).with('reposdir').returns '/etc/alternate.repos.d'
expect(described_class.find_conf_value('reposdir')).to eq '/etc/alternate.repos.d'
end
end
end
end
diff --git a/spec/unit/provider/zfs/zfs_spec.rb b/spec/unit/provider/zfs/zfs_spec.rb
index c86622197..9153165b8 100755
--- a/spec/unit/provider/zfs/zfs_spec.rb
+++ b/spec/unit/provider/zfs/zfs_spec.rb
@@ -1,106 +1,106 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:zfs).provider(:zfs) do
let(:name) { 'myzfs' }
let(:zfs) { '/usr/sbin/zfs' }
let(:resource) do
Puppet::Type.type(:zfs).new(:name => name, :provider => :zfs)
end
let(:provider) { resource.provider }
before do
provider.class.stubs(:which).with('zfs').returns(zfs)
end
context ".instances" do
it "should have an instances method" do
- provider.class.should respond_to(:instances)
+ expect(provider.class).to respond_to(:instances)
end
it "should list instances" do
provider.class.expects(:zfs).with(:list,'-H').returns File.read(my_fixture('zfs-list.out'))
instances = provider.class.instances.map { |p| {:name => p.get(:name), :ensure => p.get(:ensure)} }
- instances.size.should == 2
- instances[0].should == {:name => 'rpool', :ensure => :present}
- instances[1].should == {:name => 'rpool/ROOT', :ensure => :present}
+ expect(instances.size).to eq(2)
+ expect(instances[0]).to eq({:name => 'rpool', :ensure => :present})
+ expect(instances[1]).to eq({:name => 'rpool/ROOT', :ensure => :present})
end
end
context '#add_properties' do
it 'should return an array of properties' do
resource[:mountpoint] = '/foo'
- provider.add_properties.should == ['-o', "mountpoint=/foo"]
+ expect(provider.add_properties).to eq(['-o', "mountpoint=/foo"])
end
it 'should return an empty array' do
- provider.add_properties.should == []
+ expect(provider.add_properties).to eq([])
end
end
context "#create" do
it "should execute zfs create" do
provider.expects(:zfs).with(:create, name)
provider.create
end
Puppet::Type.type(:zfs).validproperties.each do |prop|
next if prop == :ensure
it "should include property #{prop}" do
resource[prop] = prop
provider.expects(:zfs).with(:create, '-o', "#{prop}=#{prop}", name)
provider.create
end
end
end
context "#destroy" do
it "should execute zfs destroy" do
provider.expects(:zfs).with(:destroy, name)
provider.destroy
end
end
context "#exists?" do
it "should return true if the resource exists" do
#return stuff because we have to slice and dice it
provider.expects(:zfs).with(:list, name)
- provider.should be_exists
+ expect(provider).to be_exists
end
it "should return false if returned values don't match the name" do
provider.expects(:zfs).with(:list, name).raises(Puppet::ExecutionFailure, "Failed")
- provider.should_not be_exists
+ expect(provider).not_to be_exists
end
end
describe "zfs properties" do
[:aclinherit, :aclmode, :atime, :canmount, :checksum,
:compression, :copies, :dedup, :devices, :exec, :logbias,
:mountpoint, :nbmand, :primarycache, :quota, :readonly,
:recordsize, :refquota, :refreservation, :reservation,
:secondarycache, :setuid, :shareiscsi, :sharenfs, :sharesmb,
:snapdir, :version, :volsize, :vscan, :xattr, :zoned].each do |prop|
it "should get #{prop}" do
provider.expects(:zfs).with(:get, '-H', '-o', 'value', prop, name).returns("value\n")
- provider.send(prop).should == 'value'
+ expect(provider.send(prop)).to eq('value')
end
it "should set #{prop}=value" do
provider.expects(:zfs).with(:set, "#{prop}=value", name)
provider.send("#{prop}=", "value")
end
end
end
end
diff --git a/spec/unit/provider/zone/solaris_spec.rb b/spec/unit/provider/zone/solaris_spec.rb
index 393df6b51..7141a0c95 100755
--- a/spec/unit/provider/zone/solaris_spec.rb
+++ b/spec/unit/provider/zone/solaris_spec.rb
@@ -1,195 +1,195 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:zone).provider(:solaris) do
let(:resource) { Puppet::Type.type(:zone).new(:name => 'dummy', :path => '/', :provider => :solaris) }
let(:provider) { described_class.new(resource) }
context "#configure" do
it "should add the create args to the create str" do
resource.stubs(:properties).returns([])
resource[:create_args] = "create_args"
provider.expects(:setconfig).with("create -b create_args")
provider.configure
end
it "should add the create args to the create str" do
iptype = stub "property"
iptype.stubs(:name).with().returns(:iptype)
iptype.stubs(:safe_insync?).with(iptype).returns(false)
provider.stubs(:properties).returns({:iptype => iptype})
resource.stubs(:properties).with().returns([iptype])
resource[:create_args] = "create_args"
provider.expects(:setconfig).with("create -b create_args\nset ip-type=shared")
provider.configure
end
end
context "#install" do
context "clone" do
it "should call zoneadm" do
provider.expects(:zoneadm).with(:install)
provider.install
end
it "with the resource's clone attribute" do
resource[:clone] = :clone_argument
provider.expects(:zoneadm).with(:clone, :clone_argument)
provider.install
end
end
context "not clone" do
it "should just install if there are no install args" do
# there is a nil check in type.rb:[]= so we cannot directly set nil.
resource.stubs(:[]).with(:clone).returns(nil)
resource.stubs(:[]).with(:install_args).returns(nil)
provider.expects(:zoneadm).with(:install)
provider.install
end
it "should add the install args to the command if they exist" do
# there is a nil check in type.rb:[]= so we cannot directly set nil.
resource.stubs(:[]).with(:clone).returns(nil)
resource.stubs(:[]).with(:install_args).returns('install args')
provider.expects(:zoneadm).with(:install, ["install", "args"])
provider.install
end
end
end
context "#instances" do
it "should list the instances correctly" do
described_class.expects(:adm).with(:list, "-cp").returns("0:dummy:running:/::native:shared")
instances = described_class.instances.map { |p| {:name => p.get(:name), :ensure => p.get(:ensure)} }
- instances.size.should == 1
- instances[0].should == {
+ expect(instances.size).to eq(1)
+ expect(instances[0]).to eq({
:name=>"dummy",
:ensure=>:running,
- }
+ })
end
end
context "#setconfig" do
it "should correctly set configuration" do
provider.expects(:command).with(:cfg).returns('/usr/sbin/zonecfg')
provider.expects(:exec_cmd).with(:input => "set zonepath=/\ncommit\nexit", :cmd => '/usr/sbin/zonecfg -z dummy -f -').returns({:out=>'', :exit => 0})
provider.setconfig("set zonepath=\/")
provider.flush
end
it "should correctly warn on 'not allowed'" do
provider.expects(:command).with(:cfg).returns('/usr/sbin/zonecfg')
provider.expects(:exec_cmd).with(:input => "set zonepath=/\ncommit\nexit", :cmd => '/usr/sbin/zonecfg -z dummy -f -').returns({:out=>"Zone z2 already installed; set zonepath not allowed.\n", :exit => 0})
provider.setconfig("set zonepath=\/")
expect {
provider.flush
}.to raise_error(ArgumentError, /Failed to apply configuration/)
end
end
context "#getconfig" do
zone_info =<<-EOF
zonename: dummy
zonepath: /dummy/z
brand: native
autoboot: true
bootargs:
pool:
limitpriv:
scheduling-class:
ip-type: shared
hostid:
net:
address: 1.1.1.1
physical: ex0001
defrouter not specified
net:
address: 1.1.1.2
physical: ex0002
defrouter not specified
EOF
it "should correctly parse zone info" do
provider.expects(:zonecfg).with(:info).returns(zone_info)
- provider.getconfig.should == {
+ expect(provider.getconfig).to eq({
:brand=>"native",
:autoboot=>"true",
:"ip-type"=>"shared",
:zonename=>"dummy",
"net"=>[{:physical=>"ex0001", :address=>"1.1.1.1"}, {:physical=>"ex0002", :address=>"1.1.1.2"}],
:zonepath=>"/dummy/z"
- }
+ })
end
end
context "#flush" do
it "should correctly execute pending commands" do
provider.expects(:command).with(:cfg).returns('/usr/sbin/zonecfg')
provider.expects(:exec_cmd).with(:input => "set iptype=shared\ncommit\nexit", :cmd => '/usr/sbin/zonecfg -z dummy -f -').returns({:out=>'', :exit => 0})
provider.setconfig("set iptype=shared")
provider.flush
end
it "should correctly raise error on failure" do
provider.expects(:command).with(:cfg).returns('/usr/sbin/zonecfg')
provider.expects(:exec_cmd).with(:input => "set iptype=shared\ncommit\nexit", :cmd => '/usr/sbin/zonecfg -z dummy -f -').returns({:out=>'', :exit => 1})
provider.setconfig("set iptype=shared")
expect {
provider.flush
}.to raise_error(ArgumentError, /Failed to apply/)
end
end
context "#start" do
it "should not require path if sysidcfg is specified" do
resource[:path] = '/mypath'
resource[:sysidcfg] = 'dummy'
Puppet::FileSystem.stubs(:exist?).with('/mypath/root/etc/sysidcfg').returns true
File.stubs(:directory?).with('/mypath/root/etc').returns true
provider.expects(:zoneadm).with(:boot)
provider.start
end
it "should require path if sysidcfg is specified" do
resource.stubs(:[]).with(:path).returns nil
resource.stubs(:[]).with(:sysidcfg).returns 'dummy'
expect {
provider.start
}.to raise_error(Puppet::Error, /Path is required/)
end
end
context "#line2hash" do
it "should parse lines correctly" do
- described_class.line2hash('0:dummy:running:/z::native:shared').should == {:ensure=>:running, :iptype=>"shared", :path=>"/z", :name=>"dummy", :id=>"0"}
+ expect(described_class.line2hash('0:dummy:running:/z::native:shared')).to eq({:ensure=>:running, :iptype=>"shared", :path=>"/z", :name=>"dummy", :id=>"0"})
end
it "should parse lines correctly(2)" do
- described_class.line2hash('0:dummy:running:/z:ipkg:native:shared').should == {:ensure=>:running, :iptype=>"shared", :path=>"/z", :name=>"dummy", :id=>"0"}
+ expect(described_class.line2hash('0:dummy:running:/z:ipkg:native:shared')).to eq({:ensure=>:running, :iptype=>"shared", :path=>"/z", :name=>"dummy", :id=>"0"})
end
it "should parse lines correctly(3)" do
- described_class.line2hash('-:dummy:running:/z:ipkg:native:shared').should == {:ensure=>:running, :iptype=>"shared", :path=>"/z", :name=>"dummy"}
+ expect(described_class.line2hash('-:dummy:running:/z:ipkg:native:shared')).to eq({:ensure=>:running, :iptype=>"shared", :path=>"/z", :name=>"dummy"})
end
it "should parse lines correctly(3)" do
- described_class.line2hash('-:dummy:running:/z:ipkg:native:exclusive').should == {:ensure=>:running, :iptype=>"exclusive", :path=>"/z", :name=>"dummy"}
+ expect(described_class.line2hash('-:dummy:running:/z:ipkg:native:exclusive')).to eq({:ensure=>:running, :iptype=>"exclusive", :path=>"/z", :name=>"dummy"})
end
end
context "#multi_conf" do
it "should correctly add and remove properties" do
provider.stubs(:properties).with().returns({:ip => ['1.1.1.1', '2.2.2.2']})
should = ['1.1.1.1', '3.3.3.3']
p = Proc.new do |a, str|
case a
when :add; 'add:' + str
when :rm; 'rm:' + str
end
end
- provider.multi_conf(:ip, should, &p).should == "rm:2.2.2.2\nadd:3.3.3.3"
+ expect(provider.multi_conf(:ip, should, &p)).to eq("rm:2.2.2.2\nadd:3.3.3.3")
end
end
context "single props" do
{:iptype => /set ip-type/, :autoboot => /set autoboot/, :path => /set zonepath/, :pool => /set pool/, :shares => /add rctl/}.each do |p, v|
it "#{p.to_s}: should correctly return conf string" do
- provider.send(p.to_s + '_conf', 'dummy').should =~ v
+ expect(provider.send(p.to_s + '_conf', 'dummy')).to match(v)
end
it "#{p.to_s}: should correctly set property string" do
provider.expects((p.to_s + '_conf').intern).returns('dummy')
provider.expects(:setconfig).with('dummy').returns('dummy2')
- provider.send(p.to_s + '=', 'dummy').should == 'dummy2'
+ expect(provider.send(p.to_s + '=', 'dummy')).to eq('dummy2')
end
end
end
end
diff --git a/spec/unit/provider/zpool/zpool_spec.rb b/spec/unit/provider/zpool/zpool_spec.rb
index 6fce286c1..919e638ef 100755
--- a/spec/unit/provider/zpool/zpool_spec.rb
+++ b/spec/unit/provider/zpool/zpool_spec.rb
@@ -1,251 +1,251 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:zpool).provider(:zpool) do
let(:name) { 'mypool' }
let(:zpool) { '/usr/sbin/zpool' }
let(:resource) do
Puppet::Type.type(:zpool).new(:name => name, :provider => :zpool)
end
let(:provider) { resource.provider }
before do
provider.class.stubs(:which).with('zpool').returns(zpool)
end
context '#current_pool' do
it "should call process_zpool_data with the result of get_pool_data only once" do
provider.stubs(:get_pool_data).returns(["foo", "disk"])
provider.expects(:process_zpool_data).with(["foo", "disk"]).returns("stuff").once
provider.current_pool
provider.current_pool
end
end
describe "self.instances" do
it "should have an instances method" do
- provider.class.should respond_to(:instances)
+ expect(provider.class).to respond_to(:instances)
end
it "should list instances" do
provider.class.expects(:zpool).with(:list,'-H').returns File.read(my_fixture('zpool-list.out'))
instances = provider.class.instances.map { |p| {:name => p.get(:name), :ensure => p.get(:ensure)} }
- instances.size.should == 2
- instances[0].should == {:name => 'rpool', :ensure => :present}
- instances[1].should == {:name => 'mypool', :ensure => :present}
+ expect(instances.size).to eq(2)
+ expect(instances[0]).to eq({:name => 'rpool', :ensure => :present})
+ expect(instances[1]).to eq({:name => 'mypool', :ensure => :present})
end
end
context '#flush' do
it "should reload the pool" do
provider.stubs(:get_pool_data)
provider.expects(:process_zpool_data).returns("stuff").times(2)
provider.current_pool
provider.flush
provider.current_pool
end
end
context '#process_zpool_data' do
let(:zpool_data) { ["foo", "disk"] }
describe "when there is no data" do
it "should return a hash with ensure=>:absent" do
- provider.process_zpool_data([])[:ensure].should == :absent
+ expect(provider.process_zpool_data([])[:ensure]).to eq(:absent)
end
end
describe "when there is a spare" do
it "should add the spare disk to the hash" do
zpool_data.concat ["spares", "spare_disk"]
- provider.process_zpool_data(zpool_data)[:spare].should == ["spare_disk"]
+ expect(provider.process_zpool_data(zpool_data)[:spare]).to eq(["spare_disk"])
end
end
describe "when there are two spares" do
it "should add the spare disk to the hash as a single string" do
zpool_data.concat ["spares", "spare_disk", "spare_disk2"]
- provider.process_zpool_data(zpool_data)[:spare].should == ["spare_disk spare_disk2"]
+ expect(provider.process_zpool_data(zpool_data)[:spare]).to eq(["spare_disk spare_disk2"])
end
end
describe "when there is a log" do
it "should add the log disk to the hash" do
zpool_data.concat ["logs", "log_disk"]
- provider.process_zpool_data(zpool_data)[:log].should == ["log_disk"]
+ expect(provider.process_zpool_data(zpool_data)[:log]).to eq(["log_disk"])
end
end
describe "when there are two logs" do
it "should add the log disks to the hash as a single string" do
zpool_data.concat ["spares", "spare_disk", "spare_disk2"]
- provider.process_zpool_data(zpool_data)[:spare].should == ["spare_disk spare_disk2"]
+ expect(provider.process_zpool_data(zpool_data)[:spare]).to eq(["spare_disk spare_disk2"])
end
end
describe "when the vdev is a single mirror" do
it "should call create_multi_array with mirror" do
zpool_data = ["mirrorpool", "mirror", "disk1", "disk2"]
- provider.process_zpool_data(zpool_data)[:mirror].should == ["disk1 disk2"]
+ expect(provider.process_zpool_data(zpool_data)[:mirror]).to eq(["disk1 disk2"])
end
end
describe "when the vdev is a single mirror on solaris 10u9 or later" do
it "should call create_multi_array with mirror" do
zpool_data = ["mirrorpool", "mirror-0", "disk1", "disk2"]
- provider.process_zpool_data(zpool_data)[:mirror].should == ["disk1 disk2"]
+ expect(provider.process_zpool_data(zpool_data)[:mirror]).to eq(["disk1 disk2"])
end
end
describe "when the vdev is a double mirror" do
it "should call create_multi_array with mirror" do
zpool_data = ["mirrorpool", "mirror", "disk1", "disk2", "mirror", "disk3", "disk4"]
- provider.process_zpool_data(zpool_data)[:mirror].should == ["disk1 disk2", "disk3 disk4"]
+ expect(provider.process_zpool_data(zpool_data)[:mirror]).to eq(["disk1 disk2", "disk3 disk4"])
end
end
describe "when the vdev is a double mirror on solaris 10u9 or later" do
it "should call create_multi_array with mirror" do
zpool_data = ["mirrorpool", "mirror-0", "disk1", "disk2", "mirror-1", "disk3", "disk4"]
- provider.process_zpool_data(zpool_data)[:mirror].should == ["disk1 disk2", "disk3 disk4"]
+ expect(provider.process_zpool_data(zpool_data)[:mirror]).to eq(["disk1 disk2", "disk3 disk4"])
end
end
describe "when the vdev is a raidz1" do
it "should call create_multi_array with raidz1" do
zpool_data = ["mirrorpool", "raidz1", "disk1", "disk2"]
- provider.process_zpool_data(zpool_data)[:raidz].should == ["disk1 disk2"]
+ expect(provider.process_zpool_data(zpool_data)[:raidz]).to eq(["disk1 disk2"])
end
end
describe "when the vdev is a raidz1 on solaris 10u9 or later" do
it "should call create_multi_array with raidz1" do
zpool_data = ["mirrorpool", "raidz1-0", "disk1", "disk2"]
- provider.process_zpool_data(zpool_data)[:raidz].should == ["disk1 disk2"]
+ expect(provider.process_zpool_data(zpool_data)[:raidz]).to eq(["disk1 disk2"])
end
end
describe "when the vdev is a raidz2" do
it "should call create_multi_array with raidz2 and set the raid_parity" do
zpool_data = ["mirrorpool", "raidz2", "disk1", "disk2"]
pool = provider.process_zpool_data(zpool_data)
- pool[:raidz].should == ["disk1 disk2"]
- pool[:raid_parity].should == "raidz2"
+ expect(pool[:raidz]).to eq(["disk1 disk2"])
+ expect(pool[:raid_parity]).to eq("raidz2")
end
end
describe "when the vdev is a raidz2 on solaris 10u9 or later" do
it "should call create_multi_array with raidz2 and set the raid_parity" do
zpool_data = ["mirrorpool", "raidz2-0", "disk1", "disk2"]
pool = provider.process_zpool_data(zpool_data)
- pool[:raidz].should == ["disk1 disk2"]
- pool[:raid_parity].should == "raidz2"
+ expect(pool[:raidz]).to eq(["disk1 disk2"])
+ expect(pool[:raid_parity]).to eq("raidz2")
end
end
end
describe "when calling the getters and setters" do
[:disk, :mirror, :raidz, :log, :spare].each do |field|
describe "when calling #{field}" do
it "should get the #{field} value from the current_pool hash" do
pool_hash = {}
pool_hash[field] = 'value'
provider.stubs(:current_pool).returns(pool_hash)
- provider.send(field).should == 'value'
+ expect(provider.send(field)).to eq('value')
end
end
describe "when setting the #{field}" do
it "should fail if readonly #{field} values change" do
provider.stubs(:current_pool).returns(Hash.new("currentvalue"))
expect {
provider.send((field.to_s + "=").intern, "shouldvalue")
}.to raise_error(Puppet::Error, /can\'t be changed/)
end
end
end
end
context '#create' do
context "when creating disks for a zpool" do
before do
resource[:disk] = "disk1"
end
it "should call create with the build_vdevs value" do
provider.expects(:zpool).with(:create, name, 'disk1')
provider.create
end
it "should call create with the 'spares' and 'log' values" do
resource[:spare] = ['value1']
resource[:log] = ['value2']
provider.expects(:zpool).with(:create, name, 'disk1', 'spare', 'value1', 'log', 'value2')
provider.create
end
end
context "when creating mirrors for a zpool" do
it "executes 'create' for a single group of mirrored devices" do
resource[:mirror] = ["disk1 disk2"]
provider.expects(:zpool).with(:create, name, 'mirror', 'disk1', 'disk2')
provider.create
end
it "repeats the 'mirror' keyword between groups of mirrored devices" do
resource[:mirror] = ["disk1 disk2", "disk3 disk4"]
provider.expects(:zpool).with(:create, name, 'mirror', 'disk1', 'disk2', 'mirror', 'disk3', 'disk4')
provider.create
end
end
describe "when creating raidz for a zpool" do
it "executes 'create' for a single raidz group" do
resource[:raidz] = ["disk1 disk2"]
provider.expects(:zpool).with(:create, name, 'raidz1', 'disk1', 'disk2')
provider.create
end
it "execute 'create' for a single raidz2 group" do
resource[:raidz] = ["disk1 disk2"]
resource[:raid_parity] = 'raidz2'
provider.expects(:zpool).with(:create, name, 'raidz2', 'disk1', 'disk2')
provider.create
end
it "repeats the 'raidz1' keyword between each group of raidz devices" do
resource[:raidz] = ["disk1 disk2", "disk3 disk4"]
provider.expects(:zpool).with(:create, name, 'raidz1', 'disk1', 'disk2', 'raidz1', 'disk3', 'disk4')
provider.create
end
end
end
context '#delete' do
it "should call zpool with destroy and the pool name" do
provider.expects(:zpool).with(:destroy, name)
provider.destroy
end
end
context '#exists?' do
it "should get the current pool" do
provider.expects(:current_pool).returns({:pool => 'somepool'})
provider.exists?
end
it "should return false if the current_pool is absent" do
provider.expects(:current_pool).returns({:pool => :absent})
- provider.should_not be_exists
+ expect(provider).not_to be_exists
end
it "should return true if the current_pool has values" do
provider.expects(:current_pool).returns({:pool => name})
- provider.should be_exists
+ expect(provider).to be_exists
end
end
end
diff --git a/spec/unit/provider_spec.rb b/spec/unit/provider_spec.rb
index 3c55431fc..f40bf9dcd 100755
--- a/spec/unit/provider_spec.rb
+++ b/spec/unit/provider_spec.rb
@@ -1,701 +1,722 @@
#! /usr/bin/env ruby
require 'spec_helper'
def existing_command
Puppet.features.microsoft_windows? ? "cmd" : "echo"
end
describe Puppet::Provider do
before :each do
Puppet::Type.newtype(:test) do
newparam(:name) { isnamevar }
end
end
after :each do
Puppet::Type.rmtype(:test)
end
let :type do Puppet::Type.type(:test) end
let :provider do type.provide(:default) {} end
subject { provider }
describe "has command" do
it "installs a method to run the command specified by the path" do
echo_command = expect_command_executed(:echo, "/bin/echo", "an argument")
allow_creation_of(echo_command)
provider = provider_of do
has_command(:echo, "/bin/echo")
end
provider.echo("an argument")
end
it "installs a command that is run with a given environment" do
echo_command = expect_command_executed(:echo, "/bin/echo", "an argument")
allow_creation_of(echo_command, {
:EV => "value",
:OTHER => "different"
})
provider = provider_of do
has_command(:echo, "/bin/echo") do
environment :EV => "value", :OTHER => "different"
end
end
provider.echo("an argument")
end
it "is required by default" do
provider = provider_of do
has_command(:does_not_exist, "/does/not/exist")
end
- provider.should_not be_suitable
+ expect(provider).not_to be_suitable
end
it "is required by default" do
provider = provider_of do
has_command(:does_exist, File.expand_path("/exists/somewhere"))
end
file_exists_and_is_executable(File.expand_path("/exists/somewhere"))
- provider.should be_suitable
+ expect(provider).to be_suitable
end
it "can be specified as optional" do
provider = provider_of do
has_command(:does_not_exist, "/does/not/exist") do
is_optional
end
end
- provider.should be_suitable
+ expect(provider).to be_suitable
end
end
describe "has required commands" do
it "installs methods to run executables by path" do
echo_command = expect_command_executed(:echo, "/bin/echo", "an argument")
ls_command = expect_command_executed(:ls, "/bin/ls")
allow_creation_of(echo_command)
allow_creation_of(ls_command)
provider = provider_of do
commands :echo => "/bin/echo", :ls => "/bin/ls"
end
provider.echo("an argument")
provider.ls
end
it "allows the provider to be suitable if the executable is present" do
provider = provider_of do
commands :always_exists => File.expand_path("/this/command/exists")
end
file_exists_and_is_executable(File.expand_path("/this/command/exists"))
- provider.should be_suitable
+ expect(provider).to be_suitable
end
it "does not allow the provider to be suitable if the executable is not present" do
provider = provider_of do
commands :does_not_exist => "/this/command/does/not/exist"
end
- provider.should_not be_suitable
+ expect(provider).not_to be_suitable
end
end
describe "has optional commands" do
it "installs methods to run executables" do
echo_command = expect_command_executed(:echo, "/bin/echo", "an argument")
ls_command = expect_command_executed(:ls, "/bin/ls")
allow_creation_of(echo_command)
allow_creation_of(ls_command)
provider = provider_of do
optional_commands :echo => "/bin/echo", :ls => "/bin/ls"
end
provider.echo("an argument")
provider.ls
end
it "allows the provider to be suitable even if the executable is not present" do
provider = provider_of do
optional_commands :does_not_exist => "/this/command/does/not/exist"
end
- provider.should be_suitable
+ expect(provider).to be_suitable
end
end
it "should have a specifity class method" do
- Puppet::Provider.should respond_to(:specificity)
+ expect(Puppet::Provider).to respond_to(:specificity)
end
it "should be Comparable" do
res = Puppet::Type.type(:notify).new(:name => "res")
# Normally I wouldn't like the stubs, but the only way to name a class
# otherwise is to assign it to a constant, and that hurts more here in
# testing world. --daniel 2012-01-29
a = Class.new(Puppet::Provider).new(res)
a.class.stubs(:name).returns "Puppet::Provider::Notify::A"
b = Class.new(Puppet::Provider).new(res)
b.class.stubs(:name).returns "Puppet::Provider::Notify::B"
c = Class.new(Puppet::Provider).new(res)
c.class.stubs(:name).returns "Puppet::Provider::Notify::C"
[[a, b, c], [a, c, b], [b, a, c], [b, c, a], [c, a, b], [c, b, a]].each do |this|
- this.sort.should == [a, b, c]
+ expect(this.sort).to eq([a, b, c])
end
- a.should be < b
- a.should be < c
- b.should be > a
- b.should be < c
- c.should be > a
- c.should be > b
+ expect(a).to be < b
+ expect(a).to be < c
+ expect(b).to be > a
+ expect(b).to be < c
+ expect(c).to be > a
+ expect(c).to be > b
- [a, b, c].each {|x| a.should be <= x }
- [a, b, c].each {|x| c.should be >= x }
+ [a, b, c].each {|x| expect(a).to be <= x }
+ [a, b, c].each {|x| expect(c).to be >= x }
- b.should be_between(a, c)
+ expect(b).to be_between(a, c)
end
context "when creating instances" do
context "with a resource" do
let :resource do type.new(:name => "fred") end
subject { provider.new(resource) }
it "should set the resource correctly" do
- subject.resource.must equal resource
+ expect(subject.resource).to equal resource
end
it "should set the name from the resource" do
- subject.name.should == resource.name
+ expect(subject.name).to eq(resource.name)
end
end
context "with a hash" do
subject { provider.new(:name => "fred") }
it "should set the name" do
- subject.name.should == "fred"
+ expect(subject.name).to eq("fred")
end
- it "should not have a resource" do subject.resource.should be_nil end
+ it "should not have a resource" do expect(subject.resource).to be_nil end
end
context "with no arguments" do
subject { provider.new }
it "should raise an internal error if asked for the name" do
expect { subject.name }.to raise_error Puppet::DevError
end
- it "should not have a resource" do subject.resource.should be_nil end
+ it "should not have a resource" do expect(subject.resource).to be_nil end
end
end
context "when confining" do
it "should be suitable by default" do
- subject.should be_suitable
+ expect(subject).to be_suitable
end
it "should not be default by default" do
- subject.should_not be_default
+ expect(subject).not_to be_default
end
{ { :true => true } => true,
{ :true => false } => false,
{ :false => false } => true,
{ :false => true } => false,
{ :operatingsystem => Facter.value(:operatingsystem) } => true,
{ :operatingsystem => :yayness } => false,
{ :nothing => :yayness } => false,
{ :exists => Puppet::Util.which(existing_command) } => true,
{ :exists => "/this/file/does/not/exist" } => false,
{ :true => true, :exists => Puppet::Util.which(existing_command) } => true,
{ :true => true, :exists => "/this/file/does/not/exist" } => false,
{ :operatingsystem => Facter.value(:operatingsystem),
:exists => Puppet::Util.which(existing_command) } => true,
{ :operatingsystem => :yayness,
:exists => Puppet::Util.which(existing_command) } => false,
{ :operatingsystem => Facter.value(:operatingsystem),
:exists => "/this/file/does/not/exist" } => false,
{ :operatingsystem => :yayness,
:exists => "/this/file/does/not/exist" } => false,
}.each do |confines, result|
it "should confine #{confines.inspect} to #{result}" do
confines.each {|test, value| subject.confine test => value }
- subject.send(result ? :should : :should_not, be_suitable)
+ if result
+ expect(subject).to be_suitable
+ else
+ expect(subject).to_not be_suitable
+ end
end
end
it "should not override a confine even if a second has the same type" do
subject.confine :true => false
- subject.should_not be_suitable
+ expect(subject).not_to be_suitable
subject.confine :true => true
- subject.should_not be_suitable
+ expect(subject).not_to be_suitable
end
it "should not be suitable if any confine fails" do
subject.confine :true => false
- subject.should_not be_suitable
+ expect(subject).not_to be_suitable
10.times do
subject.confine :true => true
- subject.should_not be_suitable
+ expect(subject).not_to be_suitable
end
end
end
context "default providers" do
let :os do Facter.value(:operatingsystem) end
- it { should respond_to :specificity }
+ it { is_expected.to respond_to :specificity }
it "should find the default provider" do
type.provide(:nondefault) {}
subject.defaultfor :operatingsystem => os
- subject.name.should == type.defaultprovider.name
+ expect(subject.name).to eq(type.defaultprovider.name)
end
describe "when there are multiple defaultfor's of equal specificity" do
before :each do
subject.defaultfor :operatingsystem => :os1
subject.defaultfor :operatingsystem => :os2
end
let(:alternate) { type.provide(:alternate) {} }
it "should be default for the first defaultfor" do
Facter.expects(:value).with(:operatingsystem).at_least_once.returns :os1
- provider.should be_default
- alternate.should_not be_default
+ expect(provider).to be_default
+ expect(alternate).not_to be_default
end
it "should be default for the last defaultfor" do
Facter.expects(:value).with(:operatingsystem).at_least_once.returns :os2
- provider.should be_default
- alternate.should_not be_default
+ expect(provider).to be_default
+ expect(alternate).not_to be_default
end
end
describe "when there are multiple defaultfor's with different specificity" do
before :each do
subject.defaultfor :operatingsystem => :os1
subject.defaultfor :operatingsystem => :os2, :operatingsystemmajrelease => "42"
end
let(:alternate) { type.provide(:alternate) {} }
it "should be default for a more specific, but matching, defaultfor" do
Facter.expects(:value).with(:operatingsystem).at_least_once.returns :os2
Facter.expects(:value).with(:operatingsystemmajrelease).at_least_once.returns "42"
- provider.should be_default
- alternate.should_not be_default
+ expect(provider).to be_default
+ expect(alternate).not_to be_default
end
it "should be default for a less specific, but matching, defaultfor" do
Facter.expects(:value).with(:operatingsystem).at_least_once.returns :os1
- provider.should be_default
- alternate.should_not be_default
+ expect(provider).to be_default
+ expect(alternate).not_to be_default
end
end
it "should consider any true value enough to be default" do
alternate = type.provide(:alternate) {}
subject.defaultfor :operatingsystem => [:one, :two, :three, os]
- subject.name.should == type.defaultprovider.name
+ expect(subject.name).to eq(type.defaultprovider.name)
- subject.should be_default
- alternate.should_not be_default
+ expect(subject).to be_default
+ expect(alternate).not_to be_default
end
it "should not be default if the defaultfor doesn't match" do
- subject.should_not be_default
+ expect(subject).not_to be_default
subject.defaultfor :operatingsystem => :one
- subject.should_not be_default
+ expect(subject).not_to be_default
end
it "should consider two defaults to be higher specificity than one default" do
Facter.expects(:value).with(:osfamily).at_least_once.returns "solaris"
Facter.expects(:value).with(:operatingsystemrelease).at_least_once.returns "5.10"
one = type.provide(:one) do
defaultfor :osfamily => "solaris"
end
two = type.provide(:two) do
defaultfor :osfamily => "solaris", :operatingsystemrelease => "5.10"
end
- two.specificity.should > one.specificity
+ expect(two.specificity).to be > one.specificity
end
it "should consider a subclass more specific than its parent class" do
parent = type.provide(:parent)
child = type.provide(:child, :parent => parent)
- child.specificity.should > parent.specificity
+ expect(child.specificity).to be > parent.specificity
end
describe "using a :feature key" do
before :each do
Puppet.features.add(:yay) do true end
Puppet.features.add(:boo) do false end
end
it "is default for an available feature" do
one = type.provide(:one) do
defaultfor :feature => :yay
end
- one.should be_default
+ expect(one).to be_default
end
it "is not default for a missing feature" do
two = type.provide(:two) do
defaultfor :feature => :boo
end
- two.should_not be_default
+ expect(two).not_to be_default
end
end
end
context "provider commands" do
it "should raise for unknown commands" do
expect { subject.command(:something) }.to raise_error(Puppet::DevError)
end
it "should handle command inheritance" do
parent = type.provide("parent")
child = type.provide("child", :parent => parent.name)
command = Puppet::Util.which('sh') || Puppet::Util.which('cmd.exe')
parent.commands :sh => command
- Puppet::FileSystem.exist?(parent.command(:sh)).should be_true
- parent.command(:sh).should =~ /#{Regexp.escape(command)}$/
+ expect(Puppet::FileSystem.exist?(parent.command(:sh))).to be_truthy
+ expect(parent.command(:sh)).to match(/#{Regexp.escape(command)}$/)
- Puppet::FileSystem.exist?(child.command(:sh)).should be_true
- child.command(:sh).should =~ /#{Regexp.escape(command)}$/
+ expect(Puppet::FileSystem.exist?(child.command(:sh))).to be_truthy
+ expect(child.command(:sh)).to match(/#{Regexp.escape(command)}$/)
end
it "#1197: should find commands added in the same run" do
subject.commands :testing => "puppet-bug-1197"
- subject.command(:testing).should be_nil
+ expect(subject.command(:testing)).to be_nil
subject.stubs(:which).with("puppet-bug-1197").returns("/puppet-bug-1197")
- subject.command(:testing).should == "/puppet-bug-1197"
+ expect(subject.command(:testing)).to eq("/puppet-bug-1197")
# Ideally, we would also test that `suitable?` returned the right thing
# here, but it is impossible to get access to the methods that do that
# without digging way down into the implementation. --daniel 2012-03-20
end
context "with optional commands" do
before :each do
subject.optional_commands :cmd => "/no/such/binary/exists"
end
- it { should be_suitable }
+ it { is_expected.to be_suitable }
it "should not be suitable if a mandatory command is also missing" do
subject.commands :foo => "/no/such/binary/either"
- subject.should_not be_suitable
+ expect(subject).not_to be_suitable
end
it "should define a wrapper for the command" do
- subject.should respond_to(:cmd)
+ expect(subject).to respond_to(:cmd)
end
it "should return nil if the command is requested" do
- subject.command(:cmd).should be_nil
+ expect(subject.command(:cmd)).to be_nil
end
it "should raise if the command is invoked" do
expect { subject.cmd }.to raise_error(Puppet::Error, /Command cmd is missing/)
end
end
end
context "execution" do
before :each do
Puppet.expects(:deprecation_warning).never
end
it "delegates instance execute to Puppet::Util::Execution" do
Puppet::Util::Execution.expects(:execute).with("a_command", { :option => "value" })
provider.new.send(:execute, "a_command", { :option => "value" })
end
it "delegates class execute to Puppet::Util::Execution" do
Puppet::Util::Execution.expects(:execute).with("a_command", { :option => "value" })
provider.send(:execute, "a_command", { :option => "value" })
end
it "delegates instance execpipe to Puppet::Util::Execution" do
block = Proc.new { }
Puppet::Util::Execution.expects(:execpipe).with("a_command", true, block)
provider.new.send(:execpipe, "a_command", true, block)
end
it "delegates class execpipe to Puppet::Util::Execution" do
block = Proc.new { }
Puppet::Util::Execution.expects(:execpipe).with("a_command", true, block)
provider.send(:execpipe, "a_command", true, block)
end
it "delegates instance execfail to Puppet::Util::Execution" do
Puppet::Util::Execution.expects(:execfail).with("a_command", "an exception to raise")
provider.new.send(:execfail, "a_command", "an exception to raise")
end
it "delegates class execfail to Puppet::Util::Execution" do
Puppet::Util::Execution.expects(:execfail).with("a_command", "an exception to raise")
provider.send(:execfail, "a_command", "an exception to raise")
end
end
context "mk_resource_methods" do
before :each do
type.newproperty(:prop)
type.newparam(:param)
provider.mk_resource_methods
end
let(:instance) { provider.new(nil) }
it "defaults to :absent" do
expect(instance.prop).to eq(:absent)
expect(instance.param).to eq(:absent)
end
it "should update when set" do
instance.prop = 'hello'
instance.param = 'goodbye'
expect(instance.prop).to eq('hello')
expect(instance.param).to eq('goodbye')
end
it "treats nil the same as absent" do
instance.prop = "value"
instance.param = "value"
instance.prop = nil
instance.param = nil
expect(instance.prop).to eq(:absent)
expect(instance.param).to eq(:absent)
end
it "preserves false as false" do
instance.prop = false
instance.param = false
expect(instance.prop).to eq(false)
expect(instance.param).to eq(false)
end
end
context "source" do
it "should default to the provider name" do
- subject.source.should == :default
+ expect(subject.source).to eq(:default)
end
it "should default to the provider name for a child provider" do
- type.provide(:sub, :parent => subject.name).source.should == :sub
+ expect(type.provide(:sub, :parent => subject.name).source).to eq(:sub)
end
it "should override if requested" do
provider = type.provide(:sub, :parent => subject.name, :source => subject.source)
- provider.source.should == subject.source
+ expect(provider.source).to eq(subject.source)
end
it "should override to anything you want" do
expect { subject.source = :banana }.to change { subject.source }.
from(:default).to(:banana)
end
end
context "features" do
before :each do
type.feature :numeric, '', :methods => [:one, :two]
type.feature :alpha, '', :methods => [:a, :b]
type.feature :nomethods, ''
end
{ :no => { :alpha => false, :numeric => false, :methods => [] },
:numeric => { :alpha => false, :numeric => true, :methods => [:one, :two] },
:alpha => { :alpha => true, :numeric => false, :methods => [:a, :b] },
:all => {
:alpha => true, :numeric => true,
:methods => [:a, :b, :one, :two]
},
:alpha_and_partial => {
:alpha => true, :numeric => false,
:methods => [:a, :b, :one]
},
:numeric_and_partial => {
:alpha => false, :numeric => true,
:methods => [:a, :one, :two]
},
:all_partial => { :alpha => false, :numeric => false, :methods => [:a, :one] },
:other_and_none => { :alpha => false, :numeric => false, :methods => [:foo, :bar] },
:other_and_alpha => {
:alpha => true, :numeric => false,
:methods => [:foo, :bar, :a, :b]
},
}.each do |name, setup|
context "with #{name.to_s.gsub('_', ' ')} features" do
let :provider do
provider = type.provide(name)
setup[:methods].map do |method|
provider.send(:define_method, method) do true end
end
type.provider(name)
end
- let :numeric? do setup[:numeric] ? :should : :should_not end
- let :alpha? do setup[:alpha] ? :should : :should_not end
-
- subject { provider }
+ context "provider class" do
+ subject { provider }
- it { should respond_to(:has_features) }
- it { should respond_to(:has_feature) }
+ it { is_expected.to respond_to(:has_features) }
+ it { is_expected.to respond_to(:has_feature) }
- context "provider class" do
- it { should respond_to(:nomethods?) }
- it { should_not be_nomethods }
+ it { is_expected.to respond_to(:nomethods?) }
+ it { is_expected.not_to be_nomethods }
- it { should respond_to(:numeric?) }
- it { subject.send(numeric?, be_numeric) }
- it { subject.send(numeric?, be_satisfies(:numeric)) }
+ it { is_expected.to respond_to(:numeric?) }
+ if setup[:numeric]
+ it { is_expected.to be_numeric }
+ it { is_expected.to be_satisfies(:numeric) }
+ else
+ it { is_expected.not_to be_numeric }
+ it { is_expected.not_to be_satisfies(:numeric) }
+ end
- it { should respond_to(:alpha?) }
- it { subject.send(alpha?, be_alpha) }
- it { subject.send(alpha?, be_satisfies(:alpha)) }
+ it { is_expected.to respond_to(:alpha?) }
+ if setup[:alpha]
+ it { is_expected.to be_alpha }
+ it { is_expected.to be_satisfies(:alpha) }
+ else
+ it { is_expected.not_to be_alpha }
+ it { is_expected.not_to be_satisfies(:alpha) }
+ end
end
context "provider instance" do
subject { provider.new }
- it { should respond_to(:numeric?) }
- it { subject.send(numeric?, be_numeric) }
- it { subject.send(numeric?, be_satisfies(:numeric)) }
+ it { is_expected.to respond_to(:numeric?) }
+ if setup[:numeric]
+ it { is_expected.to be_numeric }
+ it { is_expected.to be_satisfies(:numeric) }
+ else
+ it { is_expected.not_to be_numeric }
+ it { is_expected.not_to be_satisfies(:numeric) }
+ end
- it { should respond_to(:alpha?) }
- it { subject.send(alpha?, be_alpha) }
- it { subject.send(alpha?, be_satisfies(:alpha)) }
+ it { is_expected.to respond_to(:alpha?) }
+ if setup[:alpha]
+ it { is_expected.to be_alpha }
+ it { is_expected.to be_satisfies(:alpha) }
+ else
+ it { is_expected.not_to be_alpha }
+ it { is_expected.not_to be_satisfies(:alpha) }
+ end
end
end
end
context "feature with no methods" do
before :each do
type.feature :undemanding, ''
end
- it { should respond_to(:undemanding?) }
+ it { is_expected.to respond_to(:undemanding?) }
context "when the feature is not declared" do
- it { should_not be_undemanding }
- it { should_not be_satisfies(:undemanding) }
+ it { is_expected.not_to be_undemanding }
+ it { is_expected.not_to be_satisfies(:undemanding) }
end
context "when the feature is declared" do
before :each do
subject.has_feature :undemanding
end
- it { should be_undemanding }
- it { should be_satisfies(:undemanding) }
+ it { is_expected.to be_undemanding }
+ it { is_expected.to be_satisfies(:undemanding) }
end
end
context "supports_parameter?" do
before :each do
type.newparam(:no_feature)
type.newparam(:one_feature, :required_features => :alpha)
type.newparam(:two_features, :required_features => [:alpha, :numeric])
end
let :providers do
{
:zero => type.provide(:zero),
:one => type.provide(:one) do has_features :alpha end,
:two => type.provide(:two) do has_features :alpha, :numeric end
}
end
{ :zero => { :yes => [:no_feature], :no => [:one_feature, :two_features] },
:one => { :yes => [:no_feature, :one_feature], :no => [:two_features] },
:two => { :yes => [:no_feature, :one_feature, :two_features], :no => [] }
}.each do |name, data|
data[:yes].each do |param|
it "should support #{param} with provider #{name}" do
- providers[name].should be_supports_parameter(param)
+ expect(providers[name]).to be_supports_parameter(param)
end
end
data[:no].each do |param|
it "should not support #{param} with provider #{name}" do
- providers[name].should_not be_supports_parameter(param)
+ expect(providers[name]).not_to be_supports_parameter(param)
end
end
end
end
end
def provider_of(options = {}, &block)
type = Puppet::Type.newtype(:dummy) do
provide(:dummy, options, &block)
end
type.provider(:dummy)
end
def expect_command_executed(name, path, *args)
command = Puppet::Provider::Command.new(name, path, Puppet::Util, Puppet::Util::Execution)
command.expects(:execute).with(*args)
command
end
def allow_creation_of(command, environment = {})
Puppet::Provider::Command.stubs(:new).with(command.name, command.executable, Puppet::Util, Puppet::Util::Execution, { :failonfail => true, :combine => true, :custom_environment => environment }).returns(command)
end
def file_exists_and_is_executable(path)
FileTest.expects(:file?).with(path).returns(true)
FileTest.expects(:executable?).with(path).returns(true)
end
end
diff --git a/spec/unit/puppet_spec.rb b/spec/unit/puppet_spec.rb
index edca3af0a..a519147e8 100755
--- a/spec/unit/puppet_spec.rb
+++ b/spec/unit/puppet_spec.rb
@@ -1,48 +1,48 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet'
require 'puppet_spec/files'
require 'semver'
describe Puppet do
include PuppetSpec::Files
context "#version" do
it "should be valid semver" do
- SemVer.should be_valid Puppet.version
+ expect(SemVer).to be_valid Puppet.version
end
end
Puppet::Util::Log.eachlevel do |level|
it "should have a method for sending '#{level}' logs" do
- Puppet.should respond_to(level)
+ expect(Puppet).to respond_to(level)
end
end
it "should be able to change the path" do
newpath = ENV["PATH"] + File::PATH_SEPARATOR + "/something/else"
Puppet[:path] = newpath
- ENV["PATH"].should == newpath
+ expect(ENV["PATH"]).to eq(newpath)
end
it "should change $LOAD_PATH when :libdir changes" do
one = tmpdir('load-path-one')
two = tmpdir('load-path-two')
- one.should_not == two
+ expect(one).not_to eq(two)
Puppet[:libdir] = one
- $LOAD_PATH.should include one
- $LOAD_PATH.should_not include two
+ expect($LOAD_PATH).to include one
+ expect($LOAD_PATH).not_to include two
Puppet[:libdir] = two
- $LOAD_PATH.should_not include one
- $LOAD_PATH.should include two
+ expect($LOAD_PATH).not_to include one
+ expect($LOAD_PATH).to include two
end
context "newtype" do
it "should issue a deprecation warning" do
subject.expects(:deprecation_warning).with("Puppet.newtype is deprecated and will be removed in a future release. Use Puppet::Type.newtype instead.")
subject.newtype("sometype")
end
end
end
diff --git a/spec/unit/relationship_spec.rb b/spec/unit/relationship_spec.rb
index 9ecdf19d6..382f32818 100755
--- a/spec/unit/relationship_spec.rb
+++ b/spec/unit/relationship_spec.rb
@@ -1,224 +1,224 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/relationship'
describe Puppet::Relationship do
before do
@edge = Puppet::Relationship.new(:a, :b)
end
it "should have a :source attribute" do
- @edge.should respond_to(:source)
+ expect(@edge).to respond_to(:source)
end
it "should have a :target attribute" do
- @edge.should respond_to(:target)
+ expect(@edge).to respond_to(:target)
end
it "should have a :callback attribute" do
@edge.callback = :foo
- @edge.callback.should == :foo
+ expect(@edge.callback).to eq(:foo)
end
it "should have an :event attribute" do
@edge.event = :NONE
- @edge.event.should == :NONE
+ expect(@edge.event).to eq(:NONE)
end
it "should require a callback if a non-NONE event is specified" do
- proc { @edge.event = :something }.should raise_error(ArgumentError)
+ expect { @edge.event = :something }.to raise_error(ArgumentError)
end
it "should have a :label attribute" do
- @edge.should respond_to(:label)
+ expect(@edge).to respond_to(:label)
end
it "should provide a :ref method that describes the edge" do
@edge = Puppet::Relationship.new("a", "b")
- @edge.ref.should == "a => b"
+ expect(@edge.ref).to eq("a => b")
end
it "should be able to produce a label as a hash with its event and callback" do
@edge.callback = :foo
@edge.event = :bar
- @edge.label.should == {:callback => :foo, :event => :bar}
+ expect(@edge.label).to eq({:callback => :foo, :event => :bar})
end
it "should work if nil options are provided" do
- lambda { Puppet::Relationship.new("a", "b", nil) }.should_not raise_error
+ expect { Puppet::Relationship.new("a", "b", nil) }.not_to raise_error
end
end
describe Puppet::Relationship, " when initializing" do
before do
@edge = Puppet::Relationship.new(:a, :b)
end
it "should use the first argument as the source" do
- @edge.source.should == :a
+ expect(@edge.source).to eq(:a)
end
it "should use the second argument as the target" do
- @edge.target.should == :b
+ expect(@edge.target).to eq(:b)
end
it "should set the rest of the arguments as the event and callback" do
@edge = Puppet::Relationship.new(:a, :b, :callback => :foo, :event => :bar)
- @edge.callback.should == :foo
- @edge.event.should == :bar
+ expect(@edge.callback).to eq(:foo)
+ expect(@edge.event).to eq(:bar)
end
it "should accept events specified as strings" do
@edge = Puppet::Relationship.new(:a, :b, "event" => :NONE)
- @edge.event.should == :NONE
+ expect(@edge.event).to eq(:NONE)
end
it "should accept callbacks specified as strings" do
@edge = Puppet::Relationship.new(:a, :b, "callback" => :foo)
- @edge.callback.should == :foo
+ expect(@edge.callback).to eq(:foo)
end
end
describe Puppet::Relationship, " when matching edges with no specified event" do
before do
@edge = Puppet::Relationship.new(:a, :b)
end
it "should not match :NONE" do
- @edge.should_not be_match(:NONE)
+ expect(@edge).not_to be_match(:NONE)
end
it "should not match :ALL_EVENTS" do
- @edge.should_not be_match(:ALL_EVENTS)
+ expect(@edge).not_to be_match(:ALL_EVENTS)
end
it "should not match any other events" do
- @edge.should_not be_match(:whatever)
+ expect(@edge).not_to be_match(:whatever)
end
end
describe Puppet::Relationship, " when matching edges with :NONE as the event" do
before do
@edge = Puppet::Relationship.new(:a, :b, :event => :NONE)
end
it "should not match :NONE" do
- @edge.should_not be_match(:NONE)
+ expect(@edge).not_to be_match(:NONE)
end
it "should not match :ALL_EVENTS" do
- @edge.should_not be_match(:ALL_EVENTS)
+ expect(@edge).not_to be_match(:ALL_EVENTS)
end
it "should not match other events" do
- @edge.should_not be_match(:yayness)
+ expect(@edge).not_to be_match(:yayness)
end
end
describe Puppet::Relationship, " when matching edges with :ALL as the event" do
before do
@edge = Puppet::Relationship.new(:a, :b, :event => :ALL_EVENTS, :callback => :whatever)
end
it "should not match :NONE" do
- @edge.should_not be_match(:NONE)
+ expect(@edge).not_to be_match(:NONE)
end
it "should match :ALL_EVENTS" do
- @edge.should be_match(:ALL_EVENTS)
+ expect(@edge).to be_match(:ALL_EVENTS)
end
it "should match all other events" do
- @edge.should be_match(:foo)
+ expect(@edge).to be_match(:foo)
end
end
describe Puppet::Relationship, " when matching edges with a non-standard event" do
before do
@edge = Puppet::Relationship.new(:a, :b, :event => :random, :callback => :whatever)
end
it "should not match :NONE" do
- @edge.should_not be_match(:NONE)
+ expect(@edge).not_to be_match(:NONE)
end
it "should not match :ALL_EVENTS" do
- @edge.should_not be_match(:ALL_EVENTS)
+ expect(@edge).not_to be_match(:ALL_EVENTS)
end
it "should match events with the same name" do
- @edge.should be_match(:random)
+ expect(@edge).to be_match(:random)
end
end
describe Puppet::Relationship, "when converting to pson" do
before do
@edge = Puppet::Relationship.new(:a, :b, :event => :random, :callback => :whatever)
end
it "should store the stringified source as the source in the data" do
- PSON.parse(@edge.to_pson)["source"].should == "a"
+ expect(PSON.parse(@edge.to_pson)["source"]).to eq("a")
end
it "should store the stringified target as the target in the data" do
- PSON.parse(@edge.to_pson)['target'].should == "b"
+ expect(PSON.parse(@edge.to_pson)['target']).to eq("b")
end
it "should store the psonified event as the event in the data" do
- PSON.parse(@edge.to_pson)["event"].should == "random"
+ expect(PSON.parse(@edge.to_pson)["event"]).to eq("random")
end
it "should not store an event when none is set" do
@edge.event = nil
- PSON.parse(@edge.to_pson)["event"].should be_nil
+ expect(PSON.parse(@edge.to_pson)["event"]).to be_nil
end
it "should store the psonified callback as the callback in the data" do
@edge.callback = "whatever"
- PSON.parse(@edge.to_pson)["callback"].should == "whatever"
+ expect(PSON.parse(@edge.to_pson)["callback"]).to eq("whatever")
end
it "should not store a callback when none is set in the edge" do
@edge.callback = nil
- PSON.parse(@edge.to_pson)["callback"].should be_nil
+ expect(PSON.parse(@edge.to_pson)["callback"]).to be_nil
end
end
describe Puppet::Relationship, "when converting from pson" do
before do
@event = "random"
@callback = "whatever"
@data = {
"source" => "mysource",
"target" => "mytarget",
"event" => @event,
"callback" => @callback
}
@pson = {
"type" => "Puppet::Relationship",
"data" => @data
}
end
def pson_result_should
Puppet::Relationship.expects(:new).with { |*args| yield args }
end
# LAK:NOTE For all of these tests, we convert back to the edge so we can
# trap the actual data structure then.
it "should pass the source in as the first argument" do
- Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget").source.should == "mysource"
+ expect(Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget").source).to eq("mysource")
end
it "should pass the target in as the second argument" do
- Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget").target.should == "mytarget"
+ expect(Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget").target).to eq("mytarget")
end
it "should pass the event as an argument if it's provided" do
- Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget", "event" => "myevent", "callback" => "eh").event.should == "myevent"
+ expect(Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget", "event" => "myevent", "callback" => "eh").event).to eq("myevent")
end
it "should pass the callback as an argument if it's provided" do
- Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget", "callback" => "mycallback").callback.should == "mycallback"
+ expect(Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget", "callback" => "mycallback").callback).to eq("mycallback")
end
end
diff --git a/spec/unit/reports/store_spec.rb b/spec/unit/reports/store_spec.rb
index f56eccd19..7c1f1580f 100755
--- a/spec/unit/reports/store_spec.rb
+++ b/spec/unit/reports/store_spec.rb
@@ -1,60 +1,60 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/reports'
require 'time'
require 'pathname'
require 'tempfile'
require 'fileutils'
processor = Puppet::Reports.report(:store)
describe processor do
describe "#process" do
include PuppetSpec::Files
before :each do
Puppet[:reportdir] = File.join(tmpdir('reports'), 'reports')
@report = YAML.load_file(File.join(PuppetSpec::FIXTURE_DIR, 'yaml/report2.6.x.yaml')).extend processor
end
it "should create a report directory for the client if one doesn't exist" do
@report.process
- File.should be_directory(File.join(Puppet[:reportdir], @report.host))
+ expect(File).to be_directory(File.join(Puppet[:reportdir], @report.host))
end
it "should write the report to the file in YAML" do
Time.stubs(:now).returns(Time.utc(2011,01,06,12,00,00))
@report.process
- File.read(File.join(Puppet[:reportdir], @report.host, "201101061200.yaml")).should == @report.to_yaml
+ expect(File.read(File.join(Puppet[:reportdir], @report.host, "201101061200.yaml"))).to eq(@report.to_yaml)
end
it "rejects invalid hostnames" do
@report.host = ".."
Puppet::FileSystem.expects(:exist?).never
expect { @report.process }.to raise_error(ArgumentError, /Invalid node/)
end
end
describe "::destroy" do
it "rejects invalid hostnames" do
Puppet::FileSystem.expects(:unlink).never
expect { processor.destroy("..") }.to raise_error(ArgumentError, /Invalid node/)
end
end
describe "::validate_host" do
['..', 'hello/', '/hello', 'he/llo', 'hello/..', '.'].each do |node|
it "rejects #{node.inspect}" do
expect { processor.validate_host(node) }.to raise_error(ArgumentError, /Invalid node/)
end
end
['.hello', 'hello.', '..hi', 'hi..'].each do |node|
it "accepts #{node.inspect}" do
processor.validate_host(node)
end
end
end
end
diff --git a/spec/unit/reports_spec.rb b/spec/unit/reports_spec.rb
index dfab2f690..49a238edc 100755
--- a/spec/unit/reports_spec.rb
+++ b/spec/unit/reports_spec.rb
@@ -1,60 +1,60 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/reports'
describe Puppet::Reports do
it "should instance-load report types" do
- Puppet::Reports.instance_loader(:report).should be_instance_of(Puppet::Util::Autoload)
+ expect(Puppet::Reports.instance_loader(:report)).to be_instance_of(Puppet::Util::Autoload)
end
it "should have a method for registering report types" do
- Puppet::Reports.should respond_to(:register_report)
+ expect(Puppet::Reports).to respond_to(:register_report)
end
it "should have a method for retrieving report types by name" do
- Puppet::Reports.should respond_to(:report)
+ expect(Puppet::Reports).to respond_to(:report)
end
it "should provide a method for returning documentation for all reports" do
Puppet::Reports.expects(:loaded_instances).with(:report).returns([:one, :two])
one = mock 'one', :doc => "onedoc"
two = mock 'two', :doc => "twodoc"
Puppet::Reports.expects(:report).with(:one).returns(one)
Puppet::Reports.expects(:report).with(:two).returns(two)
doc = Puppet::Reports.reportdocs
- doc.include?("onedoc").should be_true
- doc.include?("twodoc").should be_true
+ expect(doc.include?("onedoc")).to be_truthy
+ expect(doc.include?("twodoc")).to be_truthy
end
end
describe Puppet::Reports, " when loading report types" do
it "should use the instance loader to retrieve report types" do
Puppet::Reports.expects(:loaded_instance).with(:report, :myreporttype)
Puppet::Reports.report(:myreporttype)
end
end
describe Puppet::Reports, " when registering report types" do
it "should evaluate the supplied block as code for a module" do
Puppet::Reports.expects(:genmodule).returns(Module.new)
Puppet::Reports.register_report(:testing) { }
end
it "should extend the report type with the Puppet::Util::Docs module" do
mod = stub 'module', :define_method => true
Puppet::Reports.expects(:genmodule).with { |name, options, block| options[:extend] == Puppet::Util::Docs }.returns(mod)
Puppet::Reports.register_report(:testing) { }
end
it "should define a :report_name method in the module that returns the name of the report" do
mod = mock 'module'
mod.expects(:define_method).with(:report_name)
Puppet::Reports.expects(:genmodule).returns(mod)
Puppet::Reports.register_report(:testing) { }
end
end
diff --git a/spec/unit/resource/catalog_spec.rb b/spec/unit/resource/catalog_spec.rb
index 5bc38c0bf..b887c032b 100755
--- a/spec/unit/resource/catalog_spec.rb
+++ b/spec/unit/resource/catalog_spec.rb
@@ -1,866 +1,866 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/json'
describe Puppet::Resource::Catalog, "when compiling" do
include JSONMatchers
include PuppetSpec::Files
before do
@basepath = make_absolute("/somepath")
# stub this to not try to create state.yaml
Puppet::Util::Storage.stubs(:store)
end
# audit only resources are unmanaged
# as are resources without properties with should values
it "should write its managed resources' types, namevars" do
catalog = Puppet::Resource::Catalog.new("host")
resourcefile = tmpfile('resourcefile')
Puppet[:resourcefile] = resourcefile
res = Puppet::Type.type('file').new(:title => File.expand_path('/tmp/sam'), :ensure => 'present')
res.file = 'site.pp'
res.line = 21
res2 = Puppet::Type.type('exec').new(:title => 'bob', :command => "#{File.expand_path('/bin/rm')} -rf /")
res2.file = File.expand_path('/modules/bob/manifests/bob.pp')
res2.line = 42
res3 = Puppet::Type.type('file').new(:title => File.expand_path('/tmp/susan'), :audit => 'all')
res3.file = 'site.pp'
res3.line = 63
res4 = Puppet::Type.type('file').new(:title => File.expand_path('/tmp/lilly'))
res4.file = 'site.pp'
res4.line = 84
comp_res = Puppet::Type.type('component').new(:title => 'Class[Main]')
catalog.add_resource(res, res2, res3, res4, comp_res)
catalog.write_resource_file
- File.readlines(resourcefile).map(&:chomp).should =~ [
+ expect(File.readlines(resourcefile).map(&:chomp)).to match_array([
"file[#{File.expand_path('/tmp/sam')}]",
"exec[#{File.expand_path('/bin/rm')} -rf /]"
- ]
+ ])
end
it "should log an error if unable to write to the resource file" do
catalog = Puppet::Resource::Catalog.new("host")
Puppet[:resourcefile] = File.expand_path('/not/writable/file')
catalog.add_resource(Puppet::Type.type('file').new(:title => File.expand_path('/tmp/foo')))
catalog.write_resource_file
- @logs.size.should == 1
- @logs.first.message.should =~ /Could not create resource file/
- @logs.first.level.should == :err
+ expect(@logs.size).to eq(1)
+ expect(@logs.first.message).to match(/Could not create resource file/)
+ expect(@logs.first.level).to eq(:err)
end
it "should be able to write its list of classes to the class file" do
@catalog = Puppet::Resource::Catalog.new("host")
@catalog.add_class "foo", "bar"
Puppet[:classfile] = File.expand_path("/class/file")
fh = mock 'filehandle'
File.expects(:open).with(Puppet[:classfile], "w").yields fh
fh.expects(:puts).with "foo\nbar"
@catalog.write_class_file
end
it "should have a client_version attribute" do
@catalog = Puppet::Resource::Catalog.new("host")
@catalog.client_version = 5
- @catalog.client_version.should == 5
+ expect(@catalog.client_version).to eq(5)
end
it "should have a server_version attribute" do
@catalog = Puppet::Resource::Catalog.new("host")
@catalog.server_version = 5
- @catalog.server_version.should == 5
+ expect(@catalog.server_version).to eq(5)
end
describe "when compiling" do
it "should accept tags" do
config = Puppet::Resource::Catalog.new("mynode")
config.tag("one")
- config.should be_tagged("one")
+ expect(config).to be_tagged("one")
end
it "should accept multiple tags at once" do
config = Puppet::Resource::Catalog.new("mynode")
config.tag("one", "two")
- config.should be_tagged("one")
- config.should be_tagged("two")
+ expect(config).to be_tagged("one")
+ expect(config).to be_tagged("two")
end
it "should convert all tags to strings" do
config = Puppet::Resource::Catalog.new("mynode")
config.tag("one", :two)
- config.should be_tagged("one")
- config.should be_tagged("two")
+ expect(config).to be_tagged("one")
+ expect(config).to be_tagged("two")
end
it "should tag with both the qualified name and the split name" do
config = Puppet::Resource::Catalog.new("mynode")
config.tag("one::two")
- config.should be_tagged("one")
- config.should be_tagged("one::two")
+ expect(config).to be_tagged("one")
+ expect(config).to be_tagged("one::two")
end
it "should accept classes" do
config = Puppet::Resource::Catalog.new("mynode")
config.add_class("one")
- config.classes.should == %w{one}
+ expect(config.classes).to eq(%w{one})
config.add_class("two", "three")
- config.classes.should == %w{one two three}
+ expect(config.classes).to eq(%w{one two three})
end
it "should tag itself with passed class names" do
config = Puppet::Resource::Catalog.new("mynode")
config.add_class("one")
- config.should be_tagged("one")
+ expect(config).to be_tagged("one")
end
end
describe "when converting to a RAL catalog" do
before do
@original = Puppet::Resource::Catalog.new("mynode")
@original.tag(*%w{one two three})
@original.add_class *%w{four five six}
@top = Puppet::Resource.new :class, 'top'
@topobject = Puppet::Resource.new :file, @basepath+'/topobject'
@middle = Puppet::Resource.new :class, 'middle'
@middleobject = Puppet::Resource.new :file, @basepath+'/middleobject'
@bottom = Puppet::Resource.new :class, 'bottom'
@bottomobject = Puppet::Resource.new :file, @basepath+'/bottomobject'
@resources = [@top, @topobject, @middle, @middleobject, @bottom, @bottomobject]
@original.add_resource(*@resources)
@original.add_edge(@top, @topobject)
@original.add_edge(@top, @middle)
@original.add_edge(@middle, @middleobject)
@original.add_edge(@middle, @bottom)
@original.add_edge(@bottom, @bottomobject)
@catalog = @original.to_ral
end
it "should add all resources as RAL instances" do
@resources.each do |resource|
# Warning: a failure here will result in "global resource iteration is
# deprecated" being raised, because the rspec rendering to get the
# result tries to call `each` on the resource, and that raises.
- @catalog.resource(resource.ref).must be_a_kind_of(Puppet::Type)
+ expect(@catalog.resource(resource.ref)).to be_a_kind_of(Puppet::Type)
end
end
it "should copy the tag list to the new catalog" do
- @catalog.tags.sort.should == @original.tags.sort
+ expect(@catalog.tags.sort).to eq(@original.tags.sort)
end
it "should copy the class list to the new catalog" do
- @catalog.classes.should == @original.classes
+ expect(@catalog.classes).to eq(@original.classes)
end
it "should duplicate the original edges" do
@original.edges.each do |edge|
- @catalog.edge?(@catalog.resource(edge.source.ref), @catalog.resource(edge.target.ref)).should be_true
+ expect(@catalog.edge?(@catalog.resource(edge.source.ref), @catalog.resource(edge.target.ref))).to be_truthy
end
end
it "should set itself as the catalog for each converted resource" do
- @catalog.vertices.each { |v| v.catalog.object_id.should equal(@catalog.object_id) }
+ @catalog.vertices.each { |v| expect(v.catalog.object_id).to equal(@catalog.object_id) }
end
# This tests #931.
it "should not lose track of resources whose names vary" do
changer = Puppet::Resource.new :file, @basepath+'/test/', :parameters => {:ensure => :directory}
config = Puppet::Resource::Catalog.new('test')
config.add_resource(changer)
config.add_resource(@top)
config.add_edge(@top, changer)
catalog = config.to_ral
- catalog.resource("File[#{@basepath}/test/]").must equal(catalog.resource("File[#{@basepath}/test]"))
+ expect(catalog.resource("File[#{@basepath}/test/]")).to equal(catalog.resource("File[#{@basepath}/test]"))
end
after do
# Remove all resource instances.
@catalog.clear(true)
end
end
describe "when filtering" do
before :each do
@original = Puppet::Resource::Catalog.new("mynode")
@original.tag(*%w{one two three})
@original.add_class *%w{four five six}
@r1 = stub_everything 'r1', :ref => "File[/a]"
@r1.stubs(:respond_to?).with(:ref).returns(true)
@r1.stubs(:copy_as_resource).returns(@r1)
@r1.stubs(:is_a?).with(Puppet::Resource).returns(true)
@r2 = stub_everything 'r2', :ref => "File[/b]"
@r2.stubs(:respond_to?).with(:ref).returns(true)
@r2.stubs(:copy_as_resource).returns(@r2)
@r2.stubs(:is_a?).with(Puppet::Resource).returns(true)
@resources = [@r1,@r2]
@original.add_resource(@r1,@r2)
end
it "should transform the catalog to a resource catalog" do
@original.expects(:to_catalog).with { |h,b| h == :to_resource }
@original.filter
end
it "should scan each catalog resource in turn and apply filtering block" do
@resources.each { |r| r.expects(:test?) }
@original.filter do |r|
r.test?
end
end
it "should filter out resources which produce true when the filter block is evaluated" do
- @original.filter do |r|
+ expect(@original.filter do |r|
r == @r1
- end.resource("File[/a]").should be_nil
+ end.resource("File[/a]")).to be_nil
end
it "should not consider edges against resources that were filtered out" do
@original.add_edge(@r1,@r2)
- @original.filter do |r|
+ expect(@original.filter do |r|
r == @r1
- end.edge?(@r1,@r2).should_not be
+ end.edge?(@r1,@r2)).not_to be
end
end
describe "when functioning as a resource container" do
before do
@catalog = Puppet::Resource::Catalog.new("host")
@one = Puppet::Type.type(:notify).new :name => "one"
@two = Puppet::Type.type(:notify).new :name => "two"
@dupe = Puppet::Type.type(:notify).new :name => "one"
end
it "should provide a method to add one or more resources" do
@catalog.add_resource @one, @two
- @catalog.resource(@one.ref).must equal(@one)
- @catalog.resource(@two.ref).must equal(@two)
+ expect(@catalog.resource(@one.ref)).to equal(@one)
+ expect(@catalog.resource(@two.ref)).to equal(@two)
end
it "should add resources to the relationship graph if it exists" do
relgraph = @catalog.relationship_graph
@catalog.add_resource @one
- relgraph.should be_vertex(@one)
+ expect(relgraph).to be_vertex(@one)
end
it "should set itself as the resource's catalog if it is not a relationship graph" do
@one.expects(:catalog=).with(@catalog)
@catalog.add_resource @one
end
it "should make all vertices available by resource reference" do
@catalog.add_resource(@one)
- @catalog.resource(@one.ref).must equal(@one)
- @catalog.vertices.find { |r| r.ref == @one.ref }.must equal(@one)
+ expect(@catalog.resource(@one.ref)).to equal(@one)
+ expect(@catalog.vertices.find { |r| r.ref == @one.ref }).to equal(@one)
end
it "tracks the container through edges" do
@catalog.add_resource(@two)
@catalog.add_resource(@one)
@catalog.add_edge(@one, @two)
- @catalog.container_of(@two).must == @one
+ expect(@catalog.container_of(@two)).to eq(@one)
end
it "a resource without a container is contained in nil" do
@catalog.add_resource(@one)
- @catalog.container_of(@one).must be_nil
+ expect(@catalog.container_of(@one)).to be_nil
end
it "should canonize how resources are referred to during retrieval when both type and title are provided" do
@catalog.add_resource(@one)
- @catalog.resource("notify", "one").must equal(@one)
+ expect(@catalog.resource("notify", "one")).to equal(@one)
end
it "should canonize how resources are referred to during retrieval when just the title is provided" do
@catalog.add_resource(@one)
- @catalog.resource("notify[one]", nil).must equal(@one)
+ expect(@catalog.resource("notify[one]", nil)).to equal(@one)
end
describe 'with a duplicate resource' do
def resource_at(type, name, file, line)
resource = Puppet::Resource.new(type, name)
resource.file = file
resource.line = line
Puppet::Type.type(type).new(resource)
end
let(:orig) { resource_at(:notify, 'duplicate-title', '/path/to/orig/file', 42) }
let(:dupe) { resource_at(:notify, 'duplicate-title', '/path/to/dupe/file', 314) }
it "should print the locations of the original duplicated resource" do
@catalog.add_resource(orig)
expect { @catalog.add_resource(dupe) }.to raise_error { |error|
- error.should be_a Puppet::Resource::Catalog::DuplicateResourceError
+ expect(error).to be_a Puppet::Resource::Catalog::DuplicateResourceError
- error.message.should match %r[Duplicate declaration: Notify\[duplicate-title\] is already declared]
- error.message.should match %r[in file /path/to/orig/file:42]
- error.message.should match %r[cannot redeclare]
- error.message.should match %r[at /path/to/dupe/file:314]
+ expect(error.message).to match %r[Duplicate declaration: Notify\[duplicate-title\] is already declared]
+ expect(error.message).to match %r[in file /path/to/orig/file:42]
+ expect(error.message).to match %r[cannot redeclare]
+ expect(error.message).to match %r[at /path/to/dupe/file:314]
}
end
end
it "should remove all resources when asked" do
@catalog.add_resource @one
@catalog.add_resource @two
@one.expects :remove
@two.expects :remove
@catalog.clear(true)
end
it "should support a mechanism for finishing resources" do
@one.expects :finish
@two.expects :finish
@catalog.add_resource @one
@catalog.add_resource @two
@catalog.finalize
end
it "should make default resources when finalizing" do
@catalog.expects(:make_default_resources)
@catalog.finalize
end
it "should add default resources to the catalog upon creation" do
@catalog.make_default_resources
- @catalog.resource(:schedule, "daily").should_not be_nil
+ expect(@catalog.resource(:schedule, "daily")).not_to be_nil
end
it "should optionally support an initialization block and should finalize after such blocks" do
@one.expects :finish
@two.expects :finish
config = Puppet::Resource::Catalog.new("host") do |conf|
conf.add_resource @one
conf.add_resource @two
end
end
it "should inform the resource that it is the resource's catalog" do
@one.expects(:catalog=).with(@catalog)
@catalog.add_resource @one
end
it "should be able to find resources by reference" do
@catalog.add_resource @one
- @catalog.resource(@one.ref).must equal(@one)
+ expect(@catalog.resource(@one.ref)).to equal(@one)
end
it "should be able to find resources by reference or by type/title tuple" do
@catalog.add_resource @one
- @catalog.resource("notify", "one").must equal(@one)
+ expect(@catalog.resource("notify", "one")).to equal(@one)
end
it "should have a mechanism for removing resources" do
@catalog.add_resource(@one)
- @catalog.resource(@one.ref).must be
- @catalog.vertex?(@one).must be_true
+ expect(@catalog.resource(@one.ref)).to be
+ expect(@catalog.vertex?(@one)).to be_truthy
@catalog.remove_resource(@one)
- @catalog.resource(@one.ref).must be_nil
- @catalog.vertex?(@one).must be_false
+ expect(@catalog.resource(@one.ref)).to be_nil
+ expect(@catalog.vertex?(@one)).to be_falsey
end
it "should have a method for creating aliases for resources" do
@catalog.add_resource @one
@catalog.alias(@one, "other")
- @catalog.resource("notify", "other").must equal(@one)
+ expect(@catalog.resource("notify", "other")).to equal(@one)
end
it "should ignore conflicting aliases that point to the aliased resource" do
@catalog.alias(@one, "other")
- lambda { @catalog.alias(@one, "other") }.should_not raise_error
+ expect { @catalog.alias(@one, "other") }.not_to raise_error
end
it "should create aliases for isomorphic resources whose names do not match their titles" do
resource = Puppet::Type::File.new(:title => "testing", :path => @basepath+"/something")
@catalog.add_resource(resource)
- @catalog.resource(:file, @basepath+"/something").must equal(resource)
+ expect(@catalog.resource(:file, @basepath+"/something")).to equal(resource)
end
it "should not create aliases for non-isomorphic resources whose names do not match their titles" do
resource = Puppet::Type.type(:exec).new(:title => "testing", :command => "echo", :path => %w{/bin /usr/bin /usr/local/bin})
@catalog.add_resource(resource)
# Yay, I've already got a 'should' method
- @catalog.resource(:exec, "echo").object_id.should == nil.object_id
+ expect(@catalog.resource(:exec, "echo").object_id).to eq(nil.object_id)
end
# This test is the same as the previous, but the behaviour should be explicit.
it "should alias using the class name from the resource reference, not the resource class name" do
@catalog.add_resource @one
@catalog.alias(@one, "other")
- @catalog.resource("notify", "other").must equal(@one)
+ expect(@catalog.resource("notify", "other")).to equal(@one)
end
it "should fail to add an alias if the aliased name already exists" do
@catalog.add_resource @one
- proc { @catalog.alias @two, "one" }.should raise_error(ArgumentError)
+ expect { @catalog.alias @two, "one" }.to raise_error(ArgumentError)
end
it "should not fail when a resource has duplicate aliases created" do
@catalog.add_resource @one
- proc { @catalog.alias @one, "one" }.should_not raise_error
+ expect { @catalog.alias @one, "one" }.not_to raise_error
end
it "should not create aliases that point back to the resource" do
@catalog.alias(@one, "one")
- @catalog.resource(:notify, "one").must be_nil
+ expect(@catalog.resource(:notify, "one")).to be_nil
end
it "should be able to look resources up by their aliases" do
@catalog.add_resource @one
@catalog.alias @one, "two"
- @catalog.resource(:notify, "two").must equal(@one)
+ expect(@catalog.resource(:notify, "two")).to equal(@one)
end
it "should remove resource aliases when the target resource is removed" do
@catalog.add_resource @one
@catalog.alias(@one, "other")
@one.expects :remove
@catalog.remove_resource(@one)
- @catalog.resource("notify", "other").must be_nil
+ expect(@catalog.resource("notify", "other")).to be_nil
end
it "should add an alias for the namevar when the title and name differ on isomorphic resource types" do
resource = Puppet::Type.type(:file).new :path => @basepath+"/something", :title => "other", :content => "blah"
resource.expects(:isomorphic?).returns(true)
@catalog.add_resource(resource)
- @catalog.resource(:file, "other").must equal(resource)
- @catalog.resource(:file, @basepath+"/something").ref.should == resource.ref
+ expect(@catalog.resource(:file, "other")).to equal(resource)
+ expect(@catalog.resource(:file, @basepath+"/something").ref).to eq(resource.ref)
end
it "should not add an alias for the namevar when the title and name differ on non-isomorphic resource types" do
resource = Puppet::Type.type(:file).new :path => @basepath+"/something", :title => "other", :content => "blah"
resource.expects(:isomorphic?).returns(false)
@catalog.add_resource(resource)
- @catalog.resource(:file, resource.title).must equal(resource)
+ expect(@catalog.resource(:file, resource.title)).to equal(resource)
# We can't use .should here, because the resources respond to that method.
raise "Aliased non-isomorphic resource" if @catalog.resource(:file, resource.name)
end
it "should provide a method to create additional resources that also registers the resource" do
args = {:name => "/yay", :ensure => :file}
resource = stub 'file', :ref => "File[/yay]", :catalog= => @catalog, :title => "/yay", :[] => "/yay"
Puppet::Type.type(:file).expects(:new).with(args).returns(resource)
@catalog.create_resource :file, args
- @catalog.resource("File[/yay]").must equal(resource)
+ expect(@catalog.resource("File[/yay]")).to equal(resource)
end
describe "when adding resources with multiple namevars" do
before :each do
Puppet::Type.newtype(:multiple) do
newparam(:color, :namevar => true)
newparam(:designation, :namevar => true)
def self.title_patterns
[ [
/^(\w+) (\w+)$/,
[
[:color, lambda{|x| x}],
[:designation, lambda{|x| x}]
]
] ]
end
end
end
it "should add an alias using the uniqueness key" do
@resource = Puppet::Type.type(:multiple).new(:title => "some resource", :color => "red", :designation => "5")
@catalog.add_resource(@resource)
- @catalog.resource(:multiple, "some resource").must == @resource
- @catalog.resource("Multiple[some resource]").must == @resource
- @catalog.resource("Multiple[red 5]").must == @resource
+ expect(@catalog.resource(:multiple, "some resource")).to eq(@resource)
+ expect(@catalog.resource("Multiple[some resource]")).to eq(@resource)
+ expect(@catalog.resource("Multiple[red 5]")).to eq(@resource)
end
it "should conflict with a resource with the same uniqueness key" do
@resource = Puppet::Type.type(:multiple).new(:title => "some resource", :color => "red", :designation => "5")
@other = Puppet::Type.type(:multiple).new(:title => "another resource", :color => "red", :designation => "5")
@catalog.add_resource(@resource)
expect { @catalog.add_resource(@other) }.to raise_error(ArgumentError, /Cannot alias Multiple\[another resource\] to \["red", "5"\].*resource \["Multiple", "red", "5"\] already declared/)
end
it "should conflict when its uniqueness key matches another resource's title" do
path = make_absolute("/tmp/foo")
@resource = Puppet::Type.type(:file).new(:title => path)
@other = Puppet::Type.type(:file).new(:title => "another file", :path => path)
@catalog.add_resource(@resource)
expect { @catalog.add_resource(@other) }.to raise_error(ArgumentError, /Cannot alias File\[another file\] to \["#{Regexp.escape(path)}"\].*resource \["File", "#{Regexp.escape(path)}"\] already declared/)
end
it "should conflict when its uniqueness key matches the uniqueness key derived from another resource's title" do
@resource = Puppet::Type.type(:multiple).new(:title => "red leader")
@other = Puppet::Type.type(:multiple).new(:title => "another resource", :color => "red", :designation => "leader")
@catalog.add_resource(@resource)
expect { @catalog.add_resource(@other) }.to raise_error(ArgumentError, /Cannot alias Multiple\[another resource\] to \["red", "leader"\].*resource \["Multiple", "red", "leader"\] already declared/)
end
end
end
describe "when applying" do
before :each do
@catalog = Puppet::Resource::Catalog.new("host")
@transaction = Puppet::Transaction.new(@catalog, nil, Puppet::Graph::RandomPrioritizer.new)
Puppet::Transaction.stubs(:new).returns(@transaction)
@transaction.stubs(:evaluate)
@transaction.stubs(:for_network_device=)
Puppet.settings.stubs(:use)
end
it "should create and evaluate a transaction" do
@transaction.expects(:evaluate)
@catalog.apply
end
it "should return the transaction" do
- @catalog.apply.should equal(@transaction)
+ expect(@catalog.apply).to equal(@transaction)
end
it "should yield the transaction if a block is provided" do
@catalog.apply do |trans|
- trans.should equal(@transaction)
+ expect(trans).to equal(@transaction)
end
end
it "should default to being a host catalog" do
- @catalog.host_config.should be_true
+ expect(@catalog.host_config).to be_truthy
end
it "should be able to be set to a non-host_config" do
@catalog.host_config = false
- @catalog.host_config.should be_false
+ expect(@catalog.host_config).to be_falsey
end
it "should pass supplied tags on to the transaction" do
@transaction.expects(:tags=).with(%w{one two})
@catalog.apply(:tags => %w{one two})
end
it "should set ignoreschedules on the transaction if specified in apply()" do
@transaction.expects(:ignoreschedules=).with(true)
@catalog.apply(:ignoreschedules => true)
end
describe "host catalogs" do
# super() doesn't work in the setup method for some reason
before do
@catalog.host_config = true
Puppet::Util::Storage.stubs(:store)
end
it "should initialize the state database before applying a catalog" do
Puppet::Util::Storage.expects(:load)
# Short-circuit the apply, so we know we're loading before the transaction
Puppet::Transaction.expects(:new).raises ArgumentError
- proc { @catalog.apply }.should raise_error(ArgumentError)
+ expect { @catalog.apply }.to raise_error(ArgumentError)
end
it "should sync the state database after applying" do
Puppet::Util::Storage.expects(:store)
@transaction.stubs :any_failed? => false
@catalog.apply
end
end
describe "non-host catalogs" do
before do
@catalog.host_config = false
end
it "should never send reports" do
Puppet[:report] = true
Puppet[:summarize] = true
@catalog.apply
end
it "should never modify the state database" do
Puppet::Util::Storage.expects(:load).never
Puppet::Util::Storage.expects(:store).never
@catalog.apply
end
end
end
describe "when creating a relationship graph" do
before do
@catalog = Puppet::Resource::Catalog.new("host")
end
it "should get removed when the catalog is cleaned up" do
@catalog.relationship_graph.expects(:clear)
@catalog.clear
- @catalog.instance_variable_get("@relationship_graph").should be_nil
+ expect(@catalog.instance_variable_get("@relationship_graph")).to be_nil
end
end
describe "when writing dot files" do
before do
@catalog = Puppet::Resource::Catalog.new("host")
@name = :test
@file = File.join(Puppet[:graphdir], @name.to_s + ".dot")
end
it "should only write when it is a host catalog" do
File.expects(:open).with(@file).never
@catalog.host_config = false
Puppet[:graph] = true
@catalog.write_graph(@name)
end
end
describe "when indirecting" do
before do
@real_indirection = Puppet::Resource::Catalog.indirection
@indirection = stub 'indirection', :name => :catalog
end
it "should use the value of the 'catalog_terminus' setting to determine its terminus class" do
# Puppet only checks the terminus setting the first time you ask
# so this returns the object to the clean state
# at the expense of making this test less pure
Puppet::Resource::Catalog.indirection.reset_terminus_class
Puppet.settings[:catalog_terminus] = "rest"
- Puppet::Resource::Catalog.indirection.terminus_class.should == :rest
+ expect(Puppet::Resource::Catalog.indirection.terminus_class).to eq(:rest)
end
it "should allow the terminus class to be set manually" do
Puppet::Resource::Catalog.indirection.terminus_class = :rest
- Puppet::Resource::Catalog.indirection.terminus_class.should == :rest
+ expect(Puppet::Resource::Catalog.indirection.terminus_class).to eq(:rest)
end
after do
@real_indirection.reset_terminus_class
end
end
describe "when converting to yaml" do
before do
@catalog = Puppet::Resource::Catalog.new("me")
@catalog.add_edge("one", "two")
end
it "should be able to be dumped to yaml" do
- YAML.dump(@catalog).should be_instance_of(String)
+ expect(YAML.dump(@catalog)).to be_instance_of(String)
end
end
describe "when converting from yaml" do
before do
@catalog = Puppet::Resource::Catalog.new("me")
@catalog.add_edge("one", "two")
text = YAML.dump(@catalog)
@newcatalog = YAML.load(text)
end
it "should get converted back to a catalog" do
- @newcatalog.should be_instance_of(Puppet::Resource::Catalog)
+ expect(@newcatalog).to be_instance_of(Puppet::Resource::Catalog)
end
it "should have all vertices" do
- @newcatalog.vertex?("one").should be_true
- @newcatalog.vertex?("two").should be_true
+ expect(@newcatalog.vertex?("one")).to be_truthy
+ expect(@newcatalog.vertex?("two")).to be_truthy
end
it "should have all edges" do
- @newcatalog.edge?("one", "two").should be_true
+ expect(@newcatalog.edge?("one", "two")).to be_truthy
end
end
end
describe Puppet::Resource::Catalog, "when converting a resource catalog to pson" do
include JSONMatchers
include PuppetSpec::Compiler
it "should validate an empty catalog against the schema" do
empty_catalog = compile_to_catalog("")
expect(empty_catalog.to_pson).to validate_against('api/schemas/catalog.json')
end
it "should validate a noop catalog against the schema" do
noop_catalog = compile_to_catalog("create_resources('file', {})")
expect(noop_catalog.to_pson).to validate_against('api/schemas/catalog.json')
end
it "should validate a single resource catalog against the schema" do
catalog = compile_to_catalog("create_resources('file', {'/etc/foo'=>{'ensure'=>'present'}})")
expect(catalog.to_pson).to validate_against('api/schemas/catalog.json')
end
it "should validate a virtual resource catalog against the schema" do
catalog = compile_to_catalog("create_resources('@file', {'/etc/foo'=>{'ensure'=>'present'}})\nrealize(File['/etc/foo'])")
expect(catalog.to_pson).to validate_against('api/schemas/catalog.json')
end
it "should validate a single exported resource catalog against the schema" do
catalog = compile_to_catalog("create_resources('@@file', {'/etc/foo'=>{'ensure'=>'present'}})")
expect(catalog.to_pson).to validate_against('api/schemas/catalog.json')
end
it "should validate a two resource catalog against the schema" do
catalog = compile_to_catalog("create_resources('notify', {'foo'=>{'message'=>'one'}, 'bar'=>{'message'=>'two'}})")
expect(catalog.to_pson).to validate_against('api/schemas/catalog.json')
end
it "should validate a two parameter class catalog against the schema" do
catalog = compile_to_catalog(<<-MANIFEST)
class multi_param_class ($one, $two) {
notify {'foo':
message => "One is $one, two is $two",
}
}
class {'multi_param_class':
one => 'hello',
two => 'world',
}
MANIFEST
expect(catalog.to_pson).to validate_against('api/schemas/catalog.json')
end
end
describe Puppet::Resource::Catalog, "when converting to pson" do
before do
@catalog = Puppet::Resource::Catalog.new("myhost")
end
def pson_output_should
@catalog.class.expects(:from_data_hash).with { |hash| yield hash }.returns(:something)
end
[:name, :version, :classes].each do |param|
it "should set its #{param} to the #{param} of the resource" do
@catalog.send(param.to_s + "=", "testing") unless @catalog.send(param)
- pson_output_should { |hash| hash[param.to_s].should == @catalog.send(param) }
+ pson_output_should { |hash| expect(hash[param.to_s]).to eq(@catalog.send(param)) }
Puppet::Resource::Catalog.from_data_hash PSON.parse @catalog.to_pson
end
end
it "should convert its resources to a PSON-encoded array and store it as the 'resources' data" do
one = stub 'one', :to_data_hash => "one_resource", :ref => "Foo[one]"
two = stub 'two', :to_data_hash => "two_resource", :ref => "Foo[two]"
@catalog.add_resource(one)
@catalog.add_resource(two)
# TODO this should really guarantee sort order
- PSON.parse(@catalog.to_pson,:create_additions => false)['resources'].sort.should == ["one_resource", "two_resource"].sort
+ expect(PSON.parse(@catalog.to_pson,:create_additions => false)['resources'].sort).to eq(["one_resource", "two_resource"].sort)
end
it "should convert its edges to a PSON-encoded array and store it as the 'edges' data" do
one = stub 'one', :to_data_hash => "one_resource", :ref => 'Foo[one]'
two = stub 'two', :to_data_hash => "two_resource", :ref => 'Foo[two]'
three = stub 'three', :to_data_hash => "three_resource", :ref => 'Foo[three]'
@catalog.add_edge(one, two)
@catalog.add_edge(two, three)
@catalog.edges_between(one, two )[0].expects(:to_data_hash).returns "one_two_pson"
@catalog.edges_between(two, three)[0].expects(:to_data_hash).returns "two_three_pson"
- PSON.parse(@catalog.to_pson,:create_additions => false)['edges'].sort.should == %w{one_two_pson two_three_pson}.sort
+ expect(PSON.parse(@catalog.to_pson,:create_additions => false)['edges'].sort).to eq(%w{one_two_pson two_three_pson}.sort)
end
end
describe Puppet::Resource::Catalog, "when converting from pson" do
before do
@data = {
'name' => "myhost"
}
end
it "should create it with the provided name" do
@data['version'] = 50
@data['tags'] = %w{one two}
@data['classes'] = %w{one two}
@data['edges'] = [Puppet::Relationship.new("File[/foo]", "File[/bar]",
:event => "one",
:callback => "refresh").to_data_hash]
@data['resources'] = [Puppet::Resource.new(:file, "/foo").to_data_hash,
Puppet::Resource.new(:file, "/bar").to_data_hash]
catalog = Puppet::Resource::Catalog.from_data_hash PSON.parse @data.to_pson
expect(catalog.name).to eq('myhost')
expect(catalog.version).to eq(@data['version'])
expect(catalog).to be_tagged("one")
expect(catalog).to be_tagged("two")
expect(catalog.classes).to eq(@data['classes'])
expect(catalog.resources.collect(&:ref)).to eq(["File[/foo]", "File[/bar]"])
expect(catalog.edges.collect(&:event)).to eq(["one"])
expect(catalog.edges[0].source).to eq(catalog.resource(:file, "/foo"))
expect(catalog.edges[0].target).to eq(catalog.resource(:file, "/bar"))
end
it "should fail if the source resource cannot be found" do
@data['edges'] = [Puppet::Relationship.new("File[/missing]", "File[/bar]").to_data_hash]
@data['resources'] = [Puppet::Resource.new(:file, "/bar").to_data_hash]
expect { Puppet::Resource::Catalog.from_data_hash PSON.parse @data.to_pson }.to raise_error(ArgumentError, /Could not find relationship source/)
end
it "should fail if the target resource cannot be found" do
@data['edges'] = [Puppet::Relationship.new("File[/bar]", "File[/missing]").to_data_hash]
@data['resources'] = [Puppet::Resource.new(:file, "/bar").to_data_hash]
expect { Puppet::Resource::Catalog.from_data_hash PSON.parse @data.to_pson }.to raise_error(ArgumentError, /Could not find relationship target/)
end
end
diff --git a/spec/unit/resource/status_spec.rb b/spec/unit/resource/status_spec.rb
index 59616b9d6..7ebc9a9fe 100755
--- a/spec/unit/resource/status_spec.rb
+++ b/spec/unit/resource/status_spec.rb
@@ -1,194 +1,194 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/resource/status'
describe Puppet::Resource::Status do
include PuppetSpec::Files
before do
@resource = Puppet::Type.type(:file).new :path => make_absolute("/my/file")
@containment_path = ["foo", "bar", "baz"]
@resource.stubs(:pathbuilder).returns @containment_path
@status = Puppet::Resource::Status.new(@resource)
end
it "should compute type and title correctly" do
- @status.resource_type.should == "File"
- @status.title.should == make_absolute("/my/file")
+ expect(@status.resource_type).to eq("File")
+ expect(@status.title).to eq(make_absolute("/my/file"))
end
[:file, :line, :evaluation_time].each do |attr|
it "should support #{attr}" do
@status.send(attr.to_s + "=", "foo")
- @status.send(attr).should == "foo"
+ expect(@status.send(attr)).to eq("foo")
end
end
[:skipped, :failed, :restarted, :failed_to_restart, :changed, :out_of_sync, :scheduled].each do |attr|
it "should support #{attr}" do
@status.send(attr.to_s + "=", "foo")
- @status.send(attr).should == "foo"
+ expect(@status.send(attr)).to eq("foo")
end
it "should have a boolean method for determining whehter it was #{attr}" do
@status.send(attr.to_s + "=", "foo")
- @status.should send("be_#{attr}")
+ expect(@status).to send("be_#{attr}")
end
end
it "should accept a resource at initialization" do
- Puppet::Resource::Status.new(@resource).resource.should_not be_nil
+ expect(Puppet::Resource::Status.new(@resource).resource).not_to be_nil
end
it "should set its source description to the resource's path" do
@resource.expects(:path).returns "/my/path"
- Puppet::Resource::Status.new(@resource).source_description.should == "/my/path"
+ expect(Puppet::Resource::Status.new(@resource).source_description).to eq("/my/path")
end
it "should set its containment path" do
- Puppet::Resource::Status.new(@resource).containment_path.should == @containment_path
+ expect(Puppet::Resource::Status.new(@resource).containment_path).to eq(@containment_path)
end
[:file, :line].each do |attr|
it "should copy the resource's #{attr}" do
@resource.expects(attr).returns "foo"
- Puppet::Resource::Status.new(@resource).send(attr).should == "foo"
+ expect(Puppet::Resource::Status.new(@resource).send(attr)).to eq("foo")
end
end
it "should copy the resource's tags" do
@resource.expects(:tags).returns %w{foo bar}
status = Puppet::Resource::Status.new(@resource)
- status.should be_tagged("foo")
- status.should be_tagged("bar")
+ expect(status).to be_tagged("foo")
+ expect(status).to be_tagged("bar")
end
it "should always convert the resource to a string" do
@resource.expects(:to_s).returns "foo"
- Puppet::Resource::Status.new(@resource).resource.should == "foo"
+ expect(Puppet::Resource::Status.new(@resource).resource).to eq("foo")
end
it "should support tags" do
- Puppet::Resource::Status.ancestors.should include(Puppet::Util::Tagging)
+ expect(Puppet::Resource::Status.ancestors).to include(Puppet::Util::Tagging)
end
it "should create a timestamp at its creation time" do
- @status.time.should be_instance_of(Time)
+ expect(@status.time).to be_instance_of(Time)
end
it "should support adding events" do
event = Puppet::Transaction::Event.new(:name => :foobar)
@status.add_event(event)
- @status.events.should == [event]
+ expect(@status.events).to eq([event])
end
it "should use '<<' to add events" do
event = Puppet::Transaction::Event.new(:name => :foobar)
- (@status << event).should equal(@status)
- @status.events.should == [event]
+ expect(@status << event).to equal(@status)
+ expect(@status.events).to eq([event])
end
it "records an event for a failure caused by an error" do
@status.failed_because(StandardError.new("the message"))
expect(@status.events[0].message).to eq("the message")
expect(@status.events[0].status).to eq("failure")
expect(@status.events[0].name).to eq(:resource_error)
end
it "should count the number of successful events and set changed" do
3.times{ @status << Puppet::Transaction::Event.new(:status => 'success') }
- @status.change_count.should == 3
+ expect(@status.change_count).to eq(3)
- @status.changed.should == true
- @status.out_of_sync.should == true
+ expect(@status.changed).to eq(true)
+ expect(@status.out_of_sync).to eq(true)
end
it "should not start with any changes" do
- @status.change_count.should == 0
+ expect(@status.change_count).to eq(0)
- @status.changed.should == false
- @status.out_of_sync.should == false
+ expect(@status.changed).to eq(false)
+ expect(@status.out_of_sync).to eq(false)
end
it "should not treat failure, audit, or noop events as changed" do
['failure', 'audit', 'noop'].each do |s| @status << Puppet::Transaction::Event.new(:status => s) end
- @status.change_count.should == 0
- @status.changed.should == false
+ expect(@status.change_count).to eq(0)
+ expect(@status.changed).to eq(false)
end
it "should not treat audit events as out of sync" do
@status << Puppet::Transaction::Event.new(:status => 'audit')
- @status.out_of_sync_count.should == 0
- @status.out_of_sync.should == false
+ expect(@status.out_of_sync_count).to eq(0)
+ expect(@status.out_of_sync).to eq(false)
end
['failure', 'noop', 'success'].each do |event_status|
it "should treat #{event_status} events as out of sync" do
3.times do @status << Puppet::Transaction::Event.new(:status => event_status) end
- @status.out_of_sync_count.should == 3
- @status.out_of_sync.should == true
+ expect(@status.out_of_sync_count).to eq(3)
+ expect(@status.out_of_sync).to eq(true)
end
end
describe "When converting to YAML" do
it "should include only documented attributes" do
@status.file = "/foo.rb"
@status.line = 27
@status.evaluation_time = 2.7
@status.tags = %w{one two}
- @status.to_yaml_properties.should =~ Puppet::Resource::Status::YAML_ATTRIBUTES
+ expect(@status.to_yaml_properties).to match_array(Puppet::Resource::Status::YAML_ATTRIBUTES)
end
end
it "should round trip through pson" do
@status.file = "/foo.rb"
@status.line = 27
@status.evaluation_time = 2.7
@status.tags = %w{one two}
@status << Puppet::Transaction::Event.new(:name => :mode_changed, :status => 'audit')
@status.failed = false
@status.changed = true
@status.out_of_sync = true
@status.skipped = false
- @status.containment_path.should == @containment_path
+ expect(@status.containment_path).to eq(@containment_path)
tripped = Puppet::Resource::Status.from_data_hash(PSON.parse(@status.to_pson))
- tripped.title.should == @status.title
- tripped.containment_path.should == @status.containment_path
- tripped.file.should == @status.file
- tripped.line.should == @status.line
- tripped.resource.should == @status.resource
- tripped.resource_type.should == @status.resource_type
- tripped.evaluation_time.should == @status.evaluation_time
- tripped.tags.should == @status.tags
- tripped.time.should == @status.time
- tripped.failed.should == @status.failed
- tripped.changed.should == @status.changed
- tripped.out_of_sync.should == @status.out_of_sync
- tripped.skipped.should == @status.skipped
-
- tripped.change_count.should == @status.change_count
- tripped.out_of_sync_count.should == @status.out_of_sync_count
- events_as_hashes(tripped).should == events_as_hashes(@status)
+ expect(tripped.title).to eq(@status.title)
+ expect(tripped.containment_path).to eq(@status.containment_path)
+ expect(tripped.file).to eq(@status.file)
+ expect(tripped.line).to eq(@status.line)
+ expect(tripped.resource).to eq(@status.resource)
+ expect(tripped.resource_type).to eq(@status.resource_type)
+ expect(tripped.evaluation_time).to eq(@status.evaluation_time)
+ expect(tripped.tags).to eq(@status.tags)
+ expect(tripped.time).to eq(@status.time)
+ expect(tripped.failed).to eq(@status.failed)
+ expect(tripped.changed).to eq(@status.changed)
+ expect(tripped.out_of_sync).to eq(@status.out_of_sync)
+ expect(tripped.skipped).to eq(@status.skipped)
+
+ expect(tripped.change_count).to eq(@status.change_count)
+ expect(tripped.out_of_sync_count).to eq(@status.out_of_sync_count)
+ expect(events_as_hashes(tripped)).to eq(events_as_hashes(@status))
end
def events_as_hashes(report)
report.events.collect do |e|
{
:audited => e.audited,
:property => e.property,
:previous_value => e.previous_value,
:desired_value => e.desired_value,
:historical_value => e.historical_value,
:message => e.message,
:name => e.name,
:status => e.status,
:time => e.time,
}
end
end
end
diff --git a/spec/unit/resource/type_collection_helper_spec.rb b/spec/unit/resource/type_collection_helper_spec.rb
index 85b0b59ce..36050f715 100755
--- a/spec/unit/resource/type_collection_helper_spec.rb
+++ b/spec/unit/resource/type_collection_helper_spec.rb
@@ -1,24 +1,24 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/resource/type_collection_helper'
class RTCHelperTester
include Puppet::Resource::TypeCollectionHelper
end
describe Puppet::Resource::TypeCollectionHelper do
before do
@helper = RTCHelperTester.new
end
it "should use its current environment to retrieve the known resource type collection" do
env = stub 'environment'
@helper.expects(:environment).returns env
rtc = stub 'known_resource_types'
env.expects(:known_resource_types).returns rtc
- @helper.known_resource_types.should equal(rtc)
+ expect(@helper.known_resource_types).to equal(rtc)
end
end
diff --git a/spec/unit/resource/type_collection_spec.rb b/spec/unit/resource/type_collection_spec.rb
index 9e81f275c..c05be28cd 100755
--- a/spec/unit/resource/type_collection_spec.rb
+++ b/spec/unit/resource/type_collection_spec.rb
@@ -1,313 +1,313 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/resource/type_collection'
require 'puppet/resource/type'
describe Puppet::Resource::TypeCollection do
include PuppetSpec::Files
let(:environment) { Puppet::Node::Environment.create(:testing, []) }
before do
@instance = Puppet::Resource::Type.new(:hostclass, "foo")
@code = Puppet::Resource::TypeCollection.new(environment)
end
it "should consider '<<' to be an alias to 'add' but should return self" do
@code.expects(:add).with "foo"
@code.expects(:add).with "bar"
@code << "foo" << "bar"
end
it "should set itself as the code collection for added resource types" do
node = Puppet::Resource::Type.new(:node, "foo")
@code.add(node)
- @code.node("foo").should equal(node)
+ expect(@code.node("foo")).to equal(node)
- node.resource_type_collection.should equal(@code)
+ expect(node.resource_type_collection).to equal(@code)
end
it "should store node resource types as nodes" do
node = Puppet::Resource::Type.new(:node, "foo")
@code.add(node)
- @code.node("foo").should equal(node)
+ expect(@code.node("foo")).to equal(node)
end
it "should fail if a duplicate node is added" do
@code.add(Puppet::Resource::Type.new(:node, "foo"))
expect do
@code.add(Puppet::Resource::Type.new(:node, "foo"))
end.to raise_error(Puppet::ParseError, /cannot redefine/)
end
it "should store hostclasses as hostclasses" do
klass = Puppet::Resource::Type.new(:hostclass, "foo")
@code.add(klass)
- @code.hostclass("foo").should equal(klass)
+ expect(@code.hostclass("foo")).to equal(klass)
end
it "merge together hostclasses of the same name" do
klass1 = Puppet::Resource::Type.new(:hostclass, "foo", :doc => "first")
klass2 = Puppet::Resource::Type.new(:hostclass, "foo", :doc => "second")
@code.add(klass1)
@code.add(klass2)
- @code.hostclass("foo").doc.should == "firstsecond"
+ expect(@code.hostclass("foo").doc).to eq("firstsecond")
end
it "should store definitions as definitions" do
define = Puppet::Resource::Type.new(:definition, "foo")
@code.add(define)
- @code.definition("foo").should equal(define)
+ expect(@code.definition("foo")).to equal(define)
end
it "should fail if a duplicate definition is added" do
@code.add(Puppet::Resource::Type.new(:definition, "foo"))
expect do
@code.add(Puppet::Resource::Type.new(:definition, "foo"))
end.to raise_error(Puppet::ParseError, /cannot be redefined/)
end
it "should remove all nodes, classes, and definitions when cleared" do
loader = Puppet::Resource::TypeCollection.new(environment)
loader.add Puppet::Resource::Type.new(:hostclass, "class")
loader.add Puppet::Resource::Type.new(:definition, "define")
loader.add Puppet::Resource::Type.new(:node, "node")
loader.clear
- loader.hostclass("class").should be_nil
- loader.definition("define").should be_nil
- loader.node("node").should be_nil
+ expect(loader.hostclass("class")).to be_nil
+ expect(loader.definition("define")).to be_nil
+ expect(loader.node("node")).to be_nil
end
describe "when looking up names" do
before do
@type = Puppet::Resource::Type.new(:hostclass, "ns::klass")
end
it "should not attempt to import anything when the type is already defined" do
@code.add @type
@code.loader.expects(:import).never
- @code.find_hostclass("ns::klass").should equal(@type)
+ expect(@code.find_hostclass("ns::klass")).to equal(@type)
end
describe "that need to be loaded" do
it "should use the loader to load the files" do
@code.loader.expects(:try_load_fqname).with(:hostclass, "klass")
@code.find_hostclass("klass")
end
it "should use the loader to load the files" do
@code.loader.expects(:try_load_fqname).with(:hostclass, "ns::klass")
@code.find_hostclass("ns::klass")
end
it "should downcase the name and downcase and array-fy the namespaces before passing to the loader" do
@code.loader.expects(:try_load_fqname).with(:hostclass, "ns::klass")
@code.find_hostclass("ns::klass")
end
it "should use the class returned by the loader" do
@code.loader.expects(:try_load_fqname).returns(:klass)
@code.expects(:hostclass).with("ns::klass").returns(false)
- @code.find_hostclass("ns::klass").should == :klass
+ expect(@code.find_hostclass("ns::klass")).to eq(:klass)
end
it "should return nil if the name isn't found" do
@code.loader.stubs(:try_load_fqname).returns(nil)
- @code.find_hostclass("Ns::Klass").should be_nil
+ expect(@code.find_hostclass("Ns::Klass")).to be_nil
end
it "already-loaded names at broader scopes should not shadow autoloaded names" do
@code.add Puppet::Resource::Type.new(:hostclass, "bar")
@code.loader.expects(:try_load_fqname).with(:hostclass, "foo::bar").returns(:foobar)
- @code.find_hostclass("foo::bar").should == :foobar
+ expect(@code.find_hostclass("foo::bar")).to eq(:foobar)
end
context 'when debugging' do
# This test requires that debugging is on, it will otherwise not make a call to debug,
# which is the easiest way to detect that that a certain path has been taken.
before(:each) do
Puppet.debug = true
end
after (:each) do
Puppet.debug = false
end
it "should not try to autoload names that we couldn't autoload in a previous step if ignoremissingtypes is enabled" do
Puppet[:ignoremissingtypes] = true
@code.loader.expects(:try_load_fqname).with(:hostclass, "ns::klass").returns(nil)
- @code.find_hostclass("ns::klass").should be_nil
+ expect(@code.find_hostclass("ns::klass")).to be_nil
Puppet.expects(:debug).at_least_once.with {|msg| msg =~ /Not attempting to load hostclass/}
- @code.find_hostclass("ns::klass").should be_nil
+ expect(@code.find_hostclass("ns::klass")).to be_nil
end
end
end
end
%w{hostclass node definition}.each do |data|
describe "behavior of add for #{data}" do
it "should return the added #{data}" do
loader = Puppet::Resource::TypeCollection.new(environment)
instance = Puppet::Resource::Type.new(data, "foo")
- loader.add(instance).should equal(instance)
+ expect(loader.add(instance)).to equal(instance)
end
it "should retrieve #{data} insensitive to case" do
loader = Puppet::Resource::TypeCollection.new(environment)
instance = Puppet::Resource::Type.new(data, "Bar")
loader.add instance
- loader.send(data, "bAr").should equal(instance)
+ expect(loader.send(data, "bAr")).to equal(instance)
end
it "should return nil when asked for a #{data} that has not been added" do
- Puppet::Resource::TypeCollection.new(environment).send(data, "foo").should be_nil
+ expect(Puppet::Resource::TypeCollection.new(environment).send(data, "foo")).to be_nil
end
end
end
describe "when finding a qualified instance" do
it "should return any found instance if the instance name is fully qualified" do
loader = Puppet::Resource::TypeCollection.new(environment)
instance = Puppet::Resource::Type.new(:hostclass, "foo::bar")
loader.add instance
- loader.find_hostclass("::foo::bar").should equal(instance)
+ expect(loader.find_hostclass("::foo::bar")).to equal(instance)
end
it "should return nil if the instance name is fully qualified and no such instance exists" do
loader = Puppet::Resource::TypeCollection.new(environment)
- loader.find_hostclass("::foo::bar").should be_nil
+ expect(loader.find_hostclass("::foo::bar")).to be_nil
end
it "should be able to find classes in the base namespace" do
loader = Puppet::Resource::TypeCollection.new(environment)
instance = Puppet::Resource::Type.new(:hostclass, "foo")
loader.add instance
- loader.find_hostclass("foo").should equal(instance)
+ expect(loader.find_hostclass("foo")).to equal(instance)
end
it "should return the unqualified object if it exists in a provided namespace" do
loader = Puppet::Resource::TypeCollection.new(environment)
instance = Puppet::Resource::Type.new(:hostclass, "foo::bar")
loader.add instance
- loader.find_hostclass("foo::bar").should equal(instance)
+ expect(loader.find_hostclass("foo::bar")).to equal(instance)
end
it "should return nil if the object cannot be found" do
loader = Puppet::Resource::TypeCollection.new(environment)
instance = Puppet::Resource::Type.new(:hostclass, "foo::bar::baz")
loader.add instance
- loader.find_hostclass("foo::bar::eh").should be_nil
+ expect(loader.find_hostclass("foo::bar::eh")).to be_nil
end
describe "when topscope has a class that has the same name as a local class" do
before do
@loader = Puppet::Resource::TypeCollection.new(environment)
[ "foo::bar", "bar" ].each do |name|
@loader.add Puppet::Resource::Type.new(:hostclass, name)
end
end
it "looks up the given name, no more, no less" do
- @loader.find_hostclass("bar").name.should == 'bar'
- @loader.find_hostclass("::bar").name.should == 'bar'
- @loader.find_hostclass("foo::bar").name.should == 'foo::bar'
- @loader.find_hostclass("::foo::bar").name.should == 'foo::bar'
+ expect(@loader.find_hostclass("bar").name).to eq('bar')
+ expect(@loader.find_hostclass("::bar").name).to eq('bar')
+ expect(@loader.find_hostclass("foo::bar").name).to eq('foo::bar')
+ expect(@loader.find_hostclass("::foo::bar").name).to eq('foo::bar')
end
end
it "should not look in the local scope for classes when the name is qualified" do
@loader = Puppet::Resource::TypeCollection.new(environment)
@loader.add Puppet::Resource::Type.new(:hostclass, "foo::bar")
- @loader.find_hostclass("::bar").should == nil
+ expect(@loader.find_hostclass("::bar")).to eq(nil)
end
end
it "should be able to find nodes" do
node = Puppet::Resource::Type.new(:node, "bar")
loader = Puppet::Resource::TypeCollection.new(environment)
loader.add(node)
- loader.find_node("bar").should == node
+ expect(loader.find_node("bar")).to eq(node)
end
it "should indicate whether any nodes are defined" do
loader = Puppet::Resource::TypeCollection.new(environment)
loader.add_node(Puppet::Resource::Type.new(:node, "foo"))
- loader.should be_nodes
+ expect(loader).to be_nodes
end
it "should indicate whether no nodes are defined" do
- Puppet::Resource::TypeCollection.new(environment).should_not be_nodes
+ expect(Puppet::Resource::TypeCollection.new(environment)).not_to be_nodes
end
describe "when finding nodes" do
before :each do
@loader = Puppet::Resource::TypeCollection.new(environment)
end
it "should return any node whose name exactly matches the provided node name" do
node = Puppet::Resource::Type.new(:node, "foo")
@loader << node
- @loader.node("foo").should equal(node)
+ expect(@loader.node("foo")).to equal(node)
end
it "should return the first regex node whose regex matches the provided node name" do
node1 = Puppet::Resource::Type.new(:node, /\w/)
node2 = Puppet::Resource::Type.new(:node, /\d/)
@loader << node1 << node2
- @loader.node("foo10").should equal(node1)
+ expect(@loader.node("foo10")).to equal(node1)
end
it "should preferentially return a node whose name is string-equal over returning a node whose regex matches a provided name" do
node1 = Puppet::Resource::Type.new(:node, /\w/)
node2 = Puppet::Resource::Type.new(:node, "foo")
@loader << node1 << node2
- @loader.node("foo").should equal(node2)
+ expect(@loader.node("foo")).to equal(node2)
end
end
describe "when determining the configuration version" do
before do
@code = Puppet::Resource::TypeCollection.new(environment)
end
it "should default to the current time" do
time = Time.now
Time.stubs(:now).returns time
- @code.version.should == time.to_i
+ expect(@code.version).to eq(time.to_i)
end
context "when config_version script is specified" do
let(:environment) { Puppet::Node::Environment.create(:testing, [], '', '/my/foo') }
it "should use the output of the environment's config_version setting if one is provided" do
Puppet::Util::Execution.expects(:execute).with(["/my/foo"]).returns "output\n"
- @code.version.should == "output"
+ expect(@code.version).to eq("output")
end
it "should raise a puppet parser error if executing config_version fails" do
Puppet::Util::Execution.expects(:execute).raises(Puppet::ExecutionFailure.new("msg"))
- lambda { @code.version }.should raise_error(Puppet::ParseError)
+ expect { @code.version }.to raise_error(Puppet::ParseError)
end
end
end
end
diff --git a/spec/unit/resource/type_spec.rb b/spec/unit/resource/type_spec.rb
index b1ddf847b..32a474429 100755
--- a/spec/unit/resource/type_spec.rb
+++ b/spec/unit/resource/type_spec.rb
@@ -1,772 +1,772 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/resource/type'
require 'puppet/pops'
require 'matchers/json'
describe Puppet::Resource::Type do
include JSONMatchers
it "should have a 'name' attribute" do
- Puppet::Resource::Type.new(:hostclass, "foo").name.should == "foo"
+ expect(Puppet::Resource::Type.new(:hostclass, "foo").name).to eq("foo")
end
[:code, :doc, :line, :file, :resource_type_collection].each do |attr|
it "should have a '#{attr}' attribute" do
type = Puppet::Resource::Type.new(:hostclass, "foo")
type.send(attr.to_s + "=", "yay")
- type.send(attr).should == "yay"
+ expect(type.send(attr)).to eq("yay")
end
end
[:hostclass, :node, :definition].each do |type|
it "should know when it is a #{type}" do
- Puppet::Resource::Type.new(type, "foo").send("#{type}?").should be_true
+ expect(Puppet::Resource::Type.new(type, "foo").send("#{type}?")).to be_truthy
end
end
it "should indirect 'resource_type'" do
- Puppet::Resource::Type.indirection.name.should == :resource_type
+ expect(Puppet::Resource::Type.indirection.name).to eq(:resource_type)
end
it "should default to 'parser' for its terminus class" do
- Puppet::Resource::Type.indirection.terminus_class.should == :parser
+ expect(Puppet::Resource::Type.indirection.terminus_class).to eq(:parser)
end
describe "when converting to json" do
before do
@type = Puppet::Resource::Type.new(:hostclass, "foo")
end
def from_json(json)
Puppet::Resource::Type.from_data_hash(json)
end
def double_convert
Puppet::Resource::Type.from_data_hash(PSON.parse(@type.to_pson))
end
it "should include the name and type" do
- double_convert.name.should == @type.name
- double_convert.type.should == @type.type
+ expect(double_convert.name).to eq(@type.name)
+ expect(double_convert.type).to eq(@type.type)
end
it "should validate with only name and kind" do
expect(@type.to_pson).to validate_against('api/schemas/resource_type.json')
end
it "should validate with all fields set" do
@type.set_arguments("one" => nil, "two" => "foo")
@type.line = 100
@type.doc = "A weird type"
@type.file = "/etc/manifests/thing.pp"
@type.parent = "one::two"
expect(@type.to_pson).to validate_against('api/schemas/resource_type.json')
end
it "should include any arguments" do
@type.set_arguments("one" => nil, "two" => "foo")
- double_convert.arguments.should == {"one" => nil, "two" => "foo"}
+ expect(double_convert.arguments).to eq({"one" => nil, "two" => "foo"})
end
it "should not include arguments if none are present" do
- @type.to_pson["arguments"].should be_nil
+ expect(@type.to_pson["arguments"]).to be_nil
end
[:line, :doc, :file, :parent].each do |attr|
it "should include #{attr} when set" do
@type.send(attr.to_s + "=", "value")
- double_convert.send(attr).should == "value"
+ expect(double_convert.send(attr)).to eq("value")
end
it "should not include #{attr} when not set" do
- @type.to_pson[attr.to_s].should be_nil
+ expect(@type.to_pson[attr.to_s]).to be_nil
end
end
it "should not include docs if they are empty" do
@type.doc = ""
- @type.to_pson["doc"].should be_nil
+ expect(@type.to_pson["doc"]).to be_nil
end
end
describe "when a node" do
it "should allow a regex as its name" do
- lambda { Puppet::Resource::Type.new(:node, /foo/) }.should_not raise_error
+ expect { Puppet::Resource::Type.new(:node, /foo/) }.not_to raise_error
end
it "should allow an AST::HostName instance as its name" do
regex = Puppet::Parser::AST::Regex.new(:value => /foo/)
name = Puppet::Parser::AST::HostName.new(:value => regex)
- lambda { Puppet::Resource::Type.new(:node, name) }.should_not raise_error
+ expect { Puppet::Resource::Type.new(:node, name) }.not_to raise_error
end
it "should match against the regexp in the AST::HostName when a HostName instance is provided" do
regex = Puppet::Parser::AST::Regex.new(:value => /\w/)
name = Puppet::Parser::AST::HostName.new(:value => regex)
node = Puppet::Resource::Type.new(:node, name)
- node.match("foo").should be_true
+ expect(node.match("foo")).to be_truthy
end
it "should return the value of the hostname if provided a string-form AST::HostName instance as the name" do
name = Puppet::Parser::AST::HostName.new(:value => "foo")
node = Puppet::Resource::Type.new(:node, name)
- node.name.should == "foo"
+ expect(node.name).to eq("foo")
end
describe "and the name is a regex" do
it "should have a method that indicates that this is the case" do
- Puppet::Resource::Type.new(:node, /w/).should be_name_is_regex
+ expect(Puppet::Resource::Type.new(:node, /w/)).to be_name_is_regex
end
it "should set its namespace to ''" do
- Puppet::Resource::Type.new(:node, /w/).namespace.should == ""
+ expect(Puppet::Resource::Type.new(:node, /w/).namespace).to eq("")
end
it "should return the regex converted to a string when asked for its name" do
- Puppet::Resource::Type.new(:node, /ww/).name.should == "ww"
+ expect(Puppet::Resource::Type.new(:node, /ww/).name).to eq("ww")
end
it "should downcase the regex when returning the name as a string" do
- Puppet::Resource::Type.new(:node, /W/).name.should == "w"
+ expect(Puppet::Resource::Type.new(:node, /W/).name).to eq("w")
end
it "should remove non-alpha characters when returning the name as a string" do
- Puppet::Resource::Type.new(:node, /w*w/).name.should_not include("*")
+ expect(Puppet::Resource::Type.new(:node, /w*w/).name).not_to include("*")
end
it "should remove leading dots when returning the name as a string" do
- Puppet::Resource::Type.new(:node, /.ww/).name.should_not =~ /^\./
+ expect(Puppet::Resource::Type.new(:node, /.ww/).name).not_to match(/^\./)
end
it "should have a method for matching its regex name against a provided name" do
- Puppet::Resource::Type.new(:node, /.ww/).should respond_to(:match)
+ expect(Puppet::Resource::Type.new(:node, /.ww/)).to respond_to(:match)
end
it "should return true when its regex matches the provided name" do
- Puppet::Resource::Type.new(:node, /\w/).match("foo").should be_true
+ expect(Puppet::Resource::Type.new(:node, /\w/).match("foo")).to be_truthy
end
it "should return true when its regex matches the provided name" do
- Puppet::Resource::Type.new(:node, /\w/).match("foo").should be_true
+ expect(Puppet::Resource::Type.new(:node, /\w/).match("foo")).to be_truthy
end
it "should return false when its regex does not match the provided name" do
- (!!Puppet::Resource::Type.new(:node, /\d/).match("foo")).should be_false
+ expect(!!Puppet::Resource::Type.new(:node, /\d/).match("foo")).to be_falsey
end
it "should return true when its name, as a string, is matched against an equal string" do
- Puppet::Resource::Type.new(:node, "foo").match("foo").should be_true
+ expect(Puppet::Resource::Type.new(:node, "foo").match("foo")).to be_truthy
end
it "should return false when its name is matched against an unequal string" do
- Puppet::Resource::Type.new(:node, "foo").match("bar").should be_false
+ expect(Puppet::Resource::Type.new(:node, "foo").match("bar")).to be_falsey
end
it "should match names insensitive to case" do
- Puppet::Resource::Type.new(:node, "fOo").match("foO").should be_true
+ expect(Puppet::Resource::Type.new(:node, "fOo").match("foO")).to be_truthy
end
end
end
describe "when initializing" do
it "should require a resource super type" do
- Puppet::Resource::Type.new(:hostclass, "foo").type.should == :hostclass
+ expect(Puppet::Resource::Type.new(:hostclass, "foo").type).to eq(:hostclass)
end
it "should fail if provided an invalid resource super type" do
- lambda { Puppet::Resource::Type.new(:nope, "foo") }.should raise_error(ArgumentError)
+ expect { Puppet::Resource::Type.new(:nope, "foo") }.to raise_error(ArgumentError)
end
it "should set its name to the downcased, stringified provided name" do
- Puppet::Resource::Type.new(:hostclass, "Foo::Bar".intern).name.should == "foo::bar"
+ expect(Puppet::Resource::Type.new(:hostclass, "Foo::Bar".intern).name).to eq("foo::bar")
end
it "should set its namespace to the downcased, stringified qualified name for classes" do
- Puppet::Resource::Type.new(:hostclass, "Foo::Bar::Baz".intern).namespace.should == "foo::bar::baz"
+ expect(Puppet::Resource::Type.new(:hostclass, "Foo::Bar::Baz".intern).namespace).to eq("foo::bar::baz")
end
[:definition, :node].each do |type|
it "should set its namespace to the downcased, stringified qualified portion of the name for #{type}s" do
- Puppet::Resource::Type.new(type, "Foo::Bar::Baz".intern).namespace.should == "foo::bar"
+ expect(Puppet::Resource::Type.new(type, "Foo::Bar::Baz".intern).namespace).to eq("foo::bar")
end
end
%w{code line file doc}.each do |arg|
it "should set #{arg} if provided" do
type = Puppet::Resource::Type.new(:hostclass, "foo", arg.to_sym => "something")
- type.send(arg).should == "something"
+ expect(type.send(arg)).to eq("something")
end
end
it "should set any provided arguments with the keys as symbols" do
type = Puppet::Resource::Type.new(:hostclass, "foo", :arguments => {:foo => "bar", :baz => "biz"})
- type.should be_valid_parameter("foo")
- type.should be_valid_parameter("baz")
+ expect(type).to be_valid_parameter("foo")
+ expect(type).to be_valid_parameter("baz")
end
it "should set any provided arguments with they keys as strings" do
type = Puppet::Resource::Type.new(:hostclass, "foo", :arguments => {"foo" => "bar", "baz" => "biz"})
- type.should be_valid_parameter(:foo)
- type.should be_valid_parameter(:baz)
+ expect(type).to be_valid_parameter(:foo)
+ expect(type).to be_valid_parameter(:baz)
end
it "should function if provided no arguments" do
type = Puppet::Resource::Type.new(:hostclass, "foo")
- type.should_not be_valid_parameter(:foo)
+ expect(type).not_to be_valid_parameter(:foo)
end
end
describe "when testing the validity of an attribute" do
it "should return true if the parameter was typed at initialization" do
- Puppet::Resource::Type.new(:hostclass, "foo", :arguments => {"foo" => "bar"}).should be_valid_parameter("foo")
+ expect(Puppet::Resource::Type.new(:hostclass, "foo", :arguments => {"foo" => "bar"})).to be_valid_parameter("foo")
end
it "should return true if it is a metaparam" do
- Puppet::Resource::Type.new(:hostclass, "foo").should be_valid_parameter("require")
+ expect(Puppet::Resource::Type.new(:hostclass, "foo")).to be_valid_parameter("require")
end
it "should return true if the parameter is named 'name'" do
- Puppet::Resource::Type.new(:hostclass, "foo").should be_valid_parameter("name")
+ expect(Puppet::Resource::Type.new(:hostclass, "foo")).to be_valid_parameter("name")
end
it "should return false if it is not a metaparam and was not provided at initialization" do
- Puppet::Resource::Type.new(:hostclass, "foo").should_not be_valid_parameter("yayness")
+ expect(Puppet::Resource::Type.new(:hostclass, "foo")).not_to be_valid_parameter("yayness")
end
end
describe "when setting its parameters in the scope" do
def variable_expression(name)
varexpr = Puppet::Pops::Model::Factory.QNAME(name).var().current
Puppet::Parser::AST::PopsBridge::Expression.new(:value => varexpr)
end
before do
@scope = Puppet::Parser::Scope.new(Puppet::Parser::Compiler.new(Puppet::Node.new("foo")), :source => stub("source"))
@resource = Puppet::Parser::Resource.new(:foo, "bar", :scope => @scope)
@type = Puppet::Resource::Type.new(:definition, "foo")
@resource.environment.known_resource_types.add @type
end
['module_name', 'name', 'title'].each do |variable|
it "should allow #{variable} to be evaluated as param default" do
@type.instance_eval { @module_name = "bar" }
@type.set_arguments :foo => variable_expression(variable)
@type.set_resource_parameters(@resource, @scope)
- @scope['foo'].should == 'bar'
+ expect(@scope['foo']).to eq('bar')
end
end
# this test is to clarify a crazy edge case
# if you specify these special names as params, the resource
# will override the special variables
it "should allow the resource to override defaults" do
@type.set_arguments :name => nil
@resource[:name] = 'foobar'
@type.set_arguments :foo => variable_expression('name')
@type.set_resource_parameters(@resource, @scope)
- @scope['foo'].should == 'foobar'
+ expect(@scope['foo']).to eq('foobar')
end
it "should set each of the resource's parameters as variables in the scope" do
@type.set_arguments :foo => nil, :boo => nil
@resource[:foo] = "bar"
@resource[:boo] = "baz"
@type.set_resource_parameters(@resource, @scope)
- @scope['foo'].should == "bar"
- @scope['boo'].should == "baz"
+ expect(@scope['foo']).to eq("bar")
+ expect(@scope['boo']).to eq("baz")
end
it "should set the variables as strings" do
@type.set_arguments :foo => nil
@resource[:foo] = "bar"
@type.set_resource_parameters(@resource, @scope)
- @scope['foo'].should == "bar"
+ expect(@scope['foo']).to eq("bar")
end
it "should fail if any of the resource's parameters are not valid attributes" do
@type.set_arguments :foo => nil
@resource[:boo] = "baz"
- lambda { @type.set_resource_parameters(@resource, @scope) }.should raise_error(Puppet::ParseError)
+ expect { @type.set_resource_parameters(@resource, @scope) }.to raise_error(Puppet::ParseError)
end
it "should evaluate and set its default values as variables for parameters not provided by the resource" do
@type.set_arguments :foo => Puppet::Parser::AST::Leaf.new(:value => "something")
@type.set_resource_parameters(@resource, @scope)
- @scope['foo'].should == "something"
+ expect(@scope['foo']).to eq("something")
end
it "should set all default values as parameters in the resource" do
@type.set_arguments :foo => Puppet::Parser::AST::Leaf.new(:value => "something")
@type.set_resource_parameters(@resource, @scope)
- @resource[:foo].should == "something"
+ expect(@resource[:foo]).to eq("something")
end
it "should fail if the resource does not provide a value for a required argument" do
@type.set_arguments :foo => nil
- lambda { @type.set_resource_parameters(@resource, @scope) }.should raise_error(Puppet::ParseError)
+ expect { @type.set_resource_parameters(@resource, @scope) }.to raise_error(Puppet::ParseError)
end
it "should set the resource's title as a variable if not otherwise provided" do
@type.set_resource_parameters(@resource, @scope)
- @scope['title'].should == "bar"
+ expect(@scope['title']).to eq("bar")
end
it "should set the resource's name as a variable if not otherwise provided" do
@type.set_resource_parameters(@resource, @scope)
- @scope['name'].should == "bar"
+ expect(@scope['name']).to eq("bar")
end
it "should set its module name in the scope if available" do
@type.instance_eval { @module_name = "mymod" }
@type.set_resource_parameters(@resource, @scope)
- @scope["module_name"].should == "mymod"
+ expect(@scope["module_name"]).to eq("mymod")
end
it "should set its caller module name in the scope if available" do
@scope.expects(:parent_module_name).returns "mycaller"
@type.set_resource_parameters(@resource, @scope)
- @scope["caller_module_name"].should == "mycaller"
+ expect(@scope["caller_module_name"]).to eq("mycaller")
end
end
describe "when describing and managing parent classes" do
before do
environment = Puppet::Node::Environment.create(:testing, [])
@krt = environment.known_resource_types
@parent = Puppet::Resource::Type.new(:hostclass, "bar")
@krt.add @parent
@child = Puppet::Resource::Type.new(:hostclass, "foo", :parent => "bar")
@krt.add @child
@scope = Puppet::Parser::Scope.new(Puppet::Parser::Compiler.new(Puppet::Node.new("foo", :environment => environment)))
end
it "should be able to define a parent" do
Puppet::Resource::Type.new(:hostclass, "foo", :parent => "bar")
end
it "should use the code collection to find the parent resource type" do
- @child.parent_type(@scope).should equal(@parent)
+ expect(@child.parent_type(@scope)).to equal(@parent)
end
it "should be able to find parent nodes" do
parent = Puppet::Resource::Type.new(:node, "bar")
@krt.add parent
child = Puppet::Resource::Type.new(:node, "foo", :parent => "bar")
@krt.add child
- child.parent_type(@scope).should equal(parent)
+ expect(child.parent_type(@scope)).to equal(parent)
end
it "should cache a reference to the parent type" do
@krt.stubs(:hostclass).with("foo::bar").returns nil
@krt.expects(:hostclass).with("bar").once.returns @parent
@child.parent_type(@scope)
@child.parent_type
end
it "should correctly state when it is another type's child" do
@child.parent_type(@scope)
- @child.should be_child_of(@parent)
+ expect(@child).to be_child_of(@parent)
end
it "should be considered the child of a parent's parent" do
@grandchild = Puppet::Resource::Type.new(:hostclass, "baz", :parent => "foo")
@krt.add @grandchild
@child.parent_type(@scope)
@grandchild.parent_type(@scope)
- @grandchild.should be_child_of(@parent)
+ expect(@grandchild).to be_child_of(@parent)
end
it "should correctly state when it is not another type's child" do
@notchild = Puppet::Resource::Type.new(:hostclass, "baz")
@krt.add @notchild
- @notchild.should_not be_child_of(@parent)
+ expect(@notchild).not_to be_child_of(@parent)
end
end
describe "when evaluating its code" do
before do
@compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("mynode"))
@scope = Puppet::Parser::Scope.new @compiler
@resource = Puppet::Parser::Resource.new(:class, "foo", :scope => @scope)
# This is so the internal resource lookup works, yo.
@compiler.catalog.add_resource @resource
@type = Puppet::Resource::Type.new(:hostclass, "foo")
@resource.environment.known_resource_types.add @type
end
it "should add node regex captures to its scope" do
@type = Puppet::Resource::Type.new(:node, /f(\w)o(.*)$/)
match = @type.match('foo')
code = stub 'code'
@type.stubs(:code).returns code
subscope = stub 'subscope', :compiler => @compiler
@scope.expects(:newscope).with(:source => @type, :namespace => '', :resource => @resource).returns subscope
elevel = 876
subscope.expects(:ephemeral_level).returns elevel
subscope.expects(:ephemeral_from).with(match, nil, nil).returns subscope
code.expects(:safeevaluate).with(subscope)
subscope.expects(:unset_ephemeral_var).with(elevel)
# Just to keep the stub quiet about intermediate calls
@type.expects(:set_resource_parameters).with(@resource, subscope)
@type.evaluate_code(@resource)
end
it "should add hostclass names to the classes list" do
@type.evaluate_code(@resource)
- @compiler.catalog.classes.should be_include("foo")
+ expect(@compiler.catalog.classes).to be_include("foo")
end
it "should not add defined resource names to the classes list" do
@type = Puppet::Resource::Type.new(:definition, "foo")
@type.evaluate_code(@resource)
- @compiler.catalog.classes.should_not be_include("foo")
+ expect(@compiler.catalog.classes).not_to be_include("foo")
end
it "should set all of its parameters in a subscope" do
subscope = stub 'subscope', :compiler => @compiler
@scope.expects(:newscope).with(:source => @type, :namespace => 'foo', :resource => @resource).returns subscope
@type.expects(:set_resource_parameters).with(@resource, subscope)
@type.evaluate_code(@resource)
end
it "should not create a subscope for the :main class" do
@resource.stubs(:title).returns(:main)
@type.expects(:subscope).never
@type.expects(:set_resource_parameters).with(@resource, @scope)
@type.evaluate_code(@resource)
end
it "should store the class scope" do
@type.evaluate_code(@resource)
- @scope.class_scope(@type).should be_instance_of(@scope.class)
+ expect(@scope.class_scope(@type)).to be_instance_of(@scope.class)
end
it "should still create a scope but not store it if the type is a definition" do
@type = Puppet::Resource::Type.new(:definition, "foo")
@type.evaluate_code(@resource)
- @scope.class_scope(@type).should be_nil
+ expect(@scope.class_scope(@type)).to be_nil
end
it "should evaluate the AST code if any is provided" do
code = stub 'code'
@type.stubs(:code).returns code
subscope = stub_everything("subscope", :compiler => @compiler)
@scope.stubs(:newscope).returns subscope
code.expects(:safeevaluate).with subscope
@type.evaluate_code(@resource)
end
it "should noop if there is no code" do
@type.expects(:code).returns nil
@type.evaluate_code(@resource)
end
describe "and it has a parent class" do
before do
@parent_type = Puppet::Resource::Type.new(:hostclass, "parent")
@type.parent = "parent"
@parent_resource = Puppet::Parser::Resource.new(:class, "parent", :scope => @scope)
@compiler.add_resource @scope, @parent_resource
@type.resource_type_collection = @scope.known_resource_types
@type.resource_type_collection.add @parent_type
end
it "should evaluate the parent's resource" do
@type.parent_type(@scope)
@type.evaluate_code(@resource)
- @scope.class_scope(@parent_type).should_not be_nil
+ expect(@scope.class_scope(@parent_type)).not_to be_nil
end
it "should not evaluate the parent's resource if it has already been evaluated" do
@parent_resource.evaluate
@type.parent_type(@scope)
@parent_resource.expects(:evaluate).never
@type.evaluate_code(@resource)
end
it "should use the parent's scope as its base scope" do
@type.parent_type(@scope)
@type.evaluate_code(@resource)
- @scope.class_scope(@type).parent.object_id.should == @scope.class_scope(@parent_type).object_id
+ expect(@scope.class_scope(@type).parent.object_id).to eq(@scope.class_scope(@parent_type).object_id)
end
end
describe "and it has a parent node" do
before do
@type = Puppet::Resource::Type.new(:node, "foo")
@parent_type = Puppet::Resource::Type.new(:node, "parent")
@type.parent = "parent"
@parent_resource = Puppet::Parser::Resource.new(:node, "parent", :scope => @scope)
@compiler.add_resource @scope, @parent_resource
@type.resource_type_collection = @scope.known_resource_types
@type.resource_type_collection.add(@parent_type)
end
it "should evaluate the parent's resource" do
@type.parent_type(@scope)
@type.evaluate_code(@resource)
- @scope.class_scope(@parent_type).should_not be_nil
+ expect(@scope.class_scope(@parent_type)).not_to be_nil
end
it "should not evaluate the parent's resource if it has already been evaluated" do
@parent_resource.evaluate
@type.parent_type(@scope)
@parent_resource.expects(:evaluate).never
@type.evaluate_code(@resource)
end
it "should use the parent's scope as its base scope" do
@type.parent_type(@scope)
@type.evaluate_code(@resource)
- @scope.class_scope(@type).parent.object_id.should == @scope.class_scope(@parent_type).object_id
+ expect(@scope.class_scope(@type).parent.object_id).to eq(@scope.class_scope(@parent_type).object_id)
end
end
end
describe "when creating a resource" do
before do
env = Puppet::Node::Environment.create('env', [])
@node = Puppet::Node.new("foo", :environment => env)
@compiler = Puppet::Parser::Compiler.new(@node)
@scope = Puppet::Parser::Scope.new(@compiler)
@top = Puppet::Resource::Type.new :hostclass, "top"
@middle = Puppet::Resource::Type.new :hostclass, "middle", :parent => "top"
@code = env.known_resource_types
@code.add @top
@code.add @middle
end
it "should create a resource instance" do
- @top.ensure_in_catalog(@scope).should be_instance_of(Puppet::Parser::Resource)
+ expect(@top.ensure_in_catalog(@scope)).to be_instance_of(Puppet::Parser::Resource)
end
it "should set its resource type to 'class' when it is a hostclass" do
- Puppet::Resource::Type.new(:hostclass, "top").ensure_in_catalog(@scope).type.should == "Class"
+ expect(Puppet::Resource::Type.new(:hostclass, "top").ensure_in_catalog(@scope).type).to eq("Class")
end
it "should set its resource type to 'node' when it is a node" do
- Puppet::Resource::Type.new(:node, "top").ensure_in_catalog(@scope).type.should == "Node"
+ expect(Puppet::Resource::Type.new(:node, "top").ensure_in_catalog(@scope).type).to eq("Node")
end
it "should fail when it is a definition" do
- lambda { Puppet::Resource::Type.new(:definition, "top").ensure_in_catalog(@scope) }.should raise_error(ArgumentError)
+ expect { Puppet::Resource::Type.new(:definition, "top").ensure_in_catalog(@scope) }.to raise_error(ArgumentError)
end
it "should add the created resource to the scope's catalog" do
@top.ensure_in_catalog(@scope)
- @compiler.catalog.resource(:class, "top").should be_instance_of(Puppet::Parser::Resource)
+ expect(@compiler.catalog.resource(:class, "top")).to be_instance_of(Puppet::Parser::Resource)
end
it "should add specified parameters to the resource" do
@top.ensure_in_catalog(@scope, {'one'=>'1', 'two'=>'2'})
- @compiler.catalog.resource(:class, "top")['one'].should == '1'
- @compiler.catalog.resource(:class, "top")['two'].should == '2'
+ expect(@compiler.catalog.resource(:class, "top")['one']).to eq('1')
+ expect(@compiler.catalog.resource(:class, "top")['two']).to eq('2')
end
it "should not require params for a param class" do
@top.ensure_in_catalog(@scope, {})
- @compiler.catalog.resource(:class, "top").should be_instance_of(Puppet::Parser::Resource)
+ expect(@compiler.catalog.resource(:class, "top")).to be_instance_of(Puppet::Parser::Resource)
end
it "should evaluate the parent class if one exists" do
@middle.ensure_in_catalog(@scope)
- @compiler.catalog.resource(:class, "top").should be_instance_of(Puppet::Parser::Resource)
+ expect(@compiler.catalog.resource(:class, "top")).to be_instance_of(Puppet::Parser::Resource)
end
it "should evaluate the parent class if one exists" do
@middle.ensure_in_catalog(@scope, {})
- @compiler.catalog.resource(:class, "top").should be_instance_of(Puppet::Parser::Resource)
+ expect(@compiler.catalog.resource(:class, "top")).to be_instance_of(Puppet::Parser::Resource)
end
it "should fail if you try to create duplicate class resources" do
othertop = Puppet::Parser::Resource.new(:class, 'top',:source => @source, :scope => @scope )
# add the same class resource to the catalog
@compiler.catalog.add_resource(othertop)
- lambda { @top.ensure_in_catalog(@scope, {}) }.should raise_error(Puppet::Resource::Catalog::DuplicateResourceError)
+ expect { @top.ensure_in_catalog(@scope, {}) }.to raise_error(Puppet::Resource::Catalog::DuplicateResourceError)
end
it "should fail to evaluate if a parent class is defined but cannot be found" do
othertop = Puppet::Resource::Type.new :hostclass, "something", :parent => "yay"
@code.add othertop
- lambda { othertop.ensure_in_catalog(@scope) }.should raise_error(Puppet::ParseError)
+ expect { othertop.ensure_in_catalog(@scope) }.to raise_error(Puppet::ParseError)
end
it "should not create a new resource if one already exists" do
@compiler.catalog.expects(:resource).with(:class, "top").returns("something")
@compiler.catalog.expects(:add_resource).never
@top.ensure_in_catalog(@scope)
end
it "should return the existing resource when not creating a new one" do
@compiler.catalog.expects(:resource).with(:class, "top").returns("something")
@compiler.catalog.expects(:add_resource).never
- @top.ensure_in_catalog(@scope).should == "something"
+ expect(@top.ensure_in_catalog(@scope)).to eq("something")
end
it "should not create a new parent resource if one already exists and it has a parent class" do
@top.ensure_in_catalog(@scope)
top_resource = @compiler.catalog.resource(:class, "top")
@middle.ensure_in_catalog(@scope)
- @compiler.catalog.resource(:class, "top").should equal(top_resource)
+ expect(@compiler.catalog.resource(:class, "top")).to equal(top_resource)
end
# #795 - tag before evaluation.
it "should tag the catalog with the resource tags when it is evaluated" do
@middle.ensure_in_catalog(@scope)
- @compiler.catalog.should be_tagged("middle")
+ expect(@compiler.catalog).to be_tagged("middle")
end
it "should tag the catalog with the parent class tags when it is evaluated" do
@middle.ensure_in_catalog(@scope)
- @compiler.catalog.should be_tagged("top")
+ expect(@compiler.catalog).to be_tagged("top")
end
end
describe "when merging code from another instance" do
def code(str)
factory = Puppet::Pops::Model::Factory.literal(str)
end
it "should fail unless it is a class" do
- lambda { Puppet::Resource::Type.new(:node, "bar").merge("foo") }.should raise_error(Puppet::Error)
+ expect { Puppet::Resource::Type.new(:node, "bar").merge("foo") }.to raise_error(Puppet::Error)
end
it "should fail unless the source instance is a class" do
dest = Puppet::Resource::Type.new(:hostclass, "bar")
source = Puppet::Resource::Type.new(:node, "foo")
- lambda { dest.merge(source) }.should raise_error(Puppet::Error)
+ expect { dest.merge(source) }.to raise_error(Puppet::Error)
end
it "should fail if both classes have different parent classes" do
code = Puppet::Resource::TypeCollection.new("env")
{"a" => "b", "c" => "d"}.each do |parent, child|
code.add Puppet::Resource::Type.new(:hostclass, parent)
code.add Puppet::Resource::Type.new(:hostclass, child, :parent => parent)
end
- lambda { code.hostclass("b").merge(code.hostclass("d")) }.should raise_error(Puppet::Error)
+ expect { code.hostclass("b").merge(code.hostclass("d")) }.to raise_error(Puppet::Error)
end
it "should fail if it's named 'main' and 'freeze_main' is enabled" do
Puppet.settings[:freeze_main] = true
code = Puppet::Resource::TypeCollection.new("env")
code.add Puppet::Resource::Type.new(:hostclass, "")
other = Puppet::Resource::Type.new(:hostclass, "")
- lambda { code.hostclass("").merge(other) }.should raise_error(Puppet::Error)
+ expect { code.hostclass("").merge(other) }.to raise_error(Puppet::Error)
end
it "should copy the other class's parent if it has not parent" do
dest = Puppet::Resource::Type.new(:hostclass, "bar")
parent = Puppet::Resource::Type.new(:hostclass, "parent")
source = Puppet::Resource::Type.new(:hostclass, "foo", :parent => "parent")
dest.merge(source)
- dest.parent.should == "parent"
+ expect(dest.parent).to eq("parent")
end
it "should copy the other class's documentation as its docs if it has no docs" do
dest = Puppet::Resource::Type.new(:hostclass, "bar")
source = Puppet::Resource::Type.new(:hostclass, "foo", :doc => "yayness")
dest.merge(source)
- dest.doc.should == "yayness"
+ expect(dest.doc).to eq("yayness")
end
it "should append the other class's docs to its docs if it has any" do
dest = Puppet::Resource::Type.new(:hostclass, "bar", :doc => "fooness")
source = Puppet::Resource::Type.new(:hostclass, "foo", :doc => "yayness")
dest.merge(source)
- dest.doc.should == "foonessyayness"
+ expect(dest.doc).to eq("foonessyayness")
end
it "should set the other class's code as its code if it has none" do
dest = Puppet::Resource::Type.new(:hostclass, "bar")
source = Puppet::Resource::Type.new(:hostclass, "foo", :code => code("bar"))
dest.merge(source)
- dest.code.value.should == "bar"
+ expect(dest.code.value).to eq("bar")
end
it "should append the other class's code to its code if it has any" do
# PUP-3274, the code merging at the top still uses AST::BlockExpression
# But does not do mutating changes to code blocks, instead a new block is created
# with references to the two original blocks.
# TODO: fix this when the code merging is changed at the very top in 4x.
#
dcode = Puppet::Parser::AST::BlockExpression.new(:children => [code("dest")])
dest = Puppet::Resource::Type.new(:hostclass, "bar", :code => dcode)
scode = Puppet::Parser::AST::BlockExpression.new(:children => [code("source")])
source = Puppet::Resource::Type.new(:hostclass, "foo", :code => scode)
dest.merge(source)
- dest.code.children.collect { |l| l.children[0].value }.should == %w{dest source}
+ expect(dest.code.children.collect { |l| l.children[0].value }).to eq(%w{dest source})
end
end
end
diff --git a/spec/unit/resource_spec.rb b/spec/unit/resource_spec.rb
index 0e20333f6..3d8165654 100755
--- a/spec/unit/resource_spec.rb
+++ b/spec/unit/resource_spec.rb
@@ -1,1001 +1,1002 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/resource'
describe Puppet::Resource do
include PuppetSpec::Files
let(:basepath) { make_absolute("/somepath") }
let(:environment) { Puppet::Node::Environment.create(:testing, []) }
[:catalog, :file, :line].each do |attr|
it "should have an #{attr} attribute" do
resource = Puppet::Resource.new("file", "/my/file")
- resource.should respond_to(attr)
- resource.should respond_to(attr.to_s + "=")
+ expect(resource).to respond_to(attr)
+ expect(resource).to respond_to(attr.to_s + "=")
end
end
it "should have a :title attribute" do
- Puppet::Resource.new(:user, "foo").title.should == "foo"
+ expect(Puppet::Resource.new(:user, "foo").title).to eq("foo")
end
it "should require the type and title" do
expect { Puppet::Resource.new }.to raise_error(ArgumentError)
end
it "should canonize types to capitalized strings" do
- Puppet::Resource.new(:user, "foo").type.should == "User"
+ expect(Puppet::Resource.new(:user, "foo").type).to eq("User")
end
it "should canonize qualified types so all strings are capitalized" do
- Puppet::Resource.new("foo::bar", "foo").type.should == "Foo::Bar"
+ expect(Puppet::Resource.new("foo::bar", "foo").type).to eq("Foo::Bar")
end
it "should tag itself with its type" do
- Puppet::Resource.new("file", "/f").should be_tagged("file")
+ expect(Puppet::Resource.new("file", "/f")).to be_tagged("file")
end
it "should tag itself with its title if the title is a valid tag" do
- Puppet::Resource.new("user", "bar").should be_tagged("bar")
+ expect(Puppet::Resource.new("user", "bar")).to be_tagged("bar")
end
it "should not tag itself with its title if the title is a not valid tag" do
- Puppet::Resource.new("file", "/bar").should_not be_tagged("/bar")
+ expect(Puppet::Resource.new("file", "/bar")).not_to be_tagged("/bar")
end
it "should allow setting of attributes" do
- Puppet::Resource.new("file", "/bar", :file => "/foo").file.should == "/foo"
- Puppet::Resource.new("file", "/bar", :exported => true).should be_exported
+ expect(Puppet::Resource.new("file", "/bar", :file => "/foo").file).to eq("/foo")
+ expect(Puppet::Resource.new("file", "/bar", :exported => true)).to be_exported
end
it "should set its type to 'Class' and its title to the passed title if the passed type is :component and the title has no square brackets in it" do
ref = Puppet::Resource.new(:component, "foo")
- ref.type.should == "Class"
- ref.title.should == "Foo"
+ expect(ref.type).to eq("Class")
+ expect(ref.title).to eq("Foo")
end
it "should interpret the title as a reference and assign appropriately if the type is :component and the title contains square brackets" do
ref = Puppet::Resource.new(:component, "foo::bar[yay]")
- ref.type.should == "Foo::Bar"
- ref.title.should == "yay"
+ expect(ref.type).to eq("Foo::Bar")
+ expect(ref.title).to eq("yay")
end
it "should set the type to 'Class' if it is nil and the title contains no square brackets" do
ref = Puppet::Resource.new(nil, "yay")
- ref.type.should == "Class"
- ref.title.should == "Yay"
+ expect(ref.type).to eq("Class")
+ expect(ref.title).to eq("Yay")
end
it "should interpret the title as a reference and assign appropriately if the type is nil and the title contains square brackets" do
ref = Puppet::Resource.new(nil, "foo::bar[yay]")
- ref.type.should == "Foo::Bar"
- ref.title.should == "yay"
+ expect(ref.type).to eq("Foo::Bar")
+ expect(ref.title).to eq("yay")
end
it "should interpret the title as a reference and assign appropriately if the type is nil and the title contains nested square brackets" do
ref = Puppet::Resource.new(nil, "foo::bar[baz[yay]]")
- ref.type.should == "Foo::Bar"
- ref.title.should =="baz[yay]"
+ expect(ref.type).to eq("Foo::Bar")
+ expect(ref.title).to eq("baz[yay]")
end
it "should interpret the type as a reference and assign appropriately if the title is nil and the type contains square brackets" do
ref = Puppet::Resource.new("foo::bar[baz]")
- ref.type.should == "Foo::Bar"
- ref.title.should =="baz"
+ expect(ref.type).to eq("Foo::Bar")
+ expect(ref.title).to eq("baz")
end
it "should not interpret the title as a reference if the type is a non component or whit reference" do
ref = Puppet::Resource.new("Notify", "foo::bar[baz]")
- ref.type.should == "Notify"
- ref.title.should =="foo::bar[baz]"
+ expect(ref.type).to eq("Notify")
+ expect(ref.title).to eq("foo::bar[baz]")
end
it "should be able to extract its information from a Puppet::Type instance" do
ral = Puppet::Type.type(:file).new :path => basepath+"/foo"
ref = Puppet::Resource.new(ral)
- ref.type.should == "File"
- ref.title.should == basepath+"/foo"
+ expect(ref.type).to eq("File")
+ expect(ref.title).to eq(basepath+"/foo")
end
it "should fail if the title is nil and the type is not a valid resource reference string" do
expect { Puppet::Resource.new("resource-spec-foo") }.to raise_error(ArgumentError)
end
it 'should fail if strict is set and type does not exist' do
expect { Puppet::Resource.new('resource-spec-foo', 'title', {:strict=>true}) }.to raise_error(ArgumentError, 'Invalid resource type resource-spec-foo')
end
it 'should fail if strict is set and class does not exist' do
expect { Puppet::Resource.new('Class', 'resource-spec-foo', {:strict=>true}) }.to raise_error(ArgumentError, 'Could not find declared class resource-spec-foo')
end
it "should fail if the title is a hash and the type is not a valid resource reference string" do
expect { Puppet::Resource.new({:type => "resource-spec-foo", :title => "bar"}) }.
to raise_error ArgumentError, /Puppet::Resource.new does not take a hash/
end
it "should be taggable" do
- Puppet::Resource.ancestors.should be_include(Puppet::Util::Tagging)
+ expect(Puppet::Resource.ancestors).to be_include(Puppet::Util::Tagging)
end
it "should have an 'exported' attribute" do
resource = Puppet::Resource.new("file", "/f")
resource.exported = true
- resource.exported.should == true
- resource.should be_exported
+ expect(resource.exported).to eq(true)
+ expect(resource).to be_exported
end
describe "and munging its type and title" do
describe "when modeling a builtin resource" do
it "should be able to find the resource type" do
- Puppet::Resource.new("file", "/my/file").resource_type.should equal(Puppet::Type.type(:file))
+ expect(Puppet::Resource.new("file", "/my/file").resource_type).to equal(Puppet::Type.type(:file))
end
it "should set its type to the capitalized type name" do
- Puppet::Resource.new("file", "/my/file").type.should == "File"
+ expect(Puppet::Resource.new("file", "/my/file").type).to eq("File")
end
end
describe "when modeling a defined resource" do
describe "that exists" do
before do
@type = Puppet::Resource::Type.new(:definition, "foo::bar")
environment.known_resource_types.add @type
end
it "should set its type to the capitalized type name" do
- Puppet::Resource.new("foo::bar", "/my/file", :environment => environment).type.should == "Foo::Bar"
+ expect(Puppet::Resource.new("foo::bar", "/my/file", :environment => environment).type).to eq("Foo::Bar")
end
it "should be able to find the resource type" do
- Puppet::Resource.new("foo::bar", "/my/file", :environment => environment).resource_type.should equal(@type)
+ expect(Puppet::Resource.new("foo::bar", "/my/file", :environment => environment).resource_type).to equal(@type)
end
it "should set its title to the provided title" do
- Puppet::Resource.new("foo::bar", "/my/file", :environment => environment).title.should == "/my/file"
+ expect(Puppet::Resource.new("foo::bar", "/my/file", :environment => environment).title).to eq("/my/file")
end
end
describe "that does not exist" do
it "should set its resource type to the capitalized resource type name" do
- Puppet::Resource.new("foo::bar", "/my/file").type.should == "Foo::Bar"
+ expect(Puppet::Resource.new("foo::bar", "/my/file").type).to eq("Foo::Bar")
end
end
end
describe "when modeling a node" do
# Life's easier with nodes, because they can't be qualified.
it "should set its type to 'Node' and its title to the provided title" do
node = Puppet::Resource.new("node", "foo")
- node.type.should == "Node"
- node.title.should == "foo"
+ expect(node.type).to eq("Node")
+ expect(node.title).to eq("foo")
end
end
describe "when modeling a class" do
it "should set its type to 'Class'" do
- Puppet::Resource.new("class", "foo").type.should == "Class"
+ expect(Puppet::Resource.new("class", "foo").type).to eq("Class")
end
describe "that exists" do
before do
@type = Puppet::Resource::Type.new(:hostclass, "foo::bar")
environment.known_resource_types.add @type
end
it "should set its title to the capitalized, fully qualified resource type" do
- Puppet::Resource.new("class", "foo::bar", :environment => environment).title.should == "Foo::Bar"
+ expect(Puppet::Resource.new("class", "foo::bar", :environment => environment).title).to eq("Foo::Bar")
end
it "should be able to find the resource type" do
- Puppet::Resource.new("class", "foo::bar", :environment => environment).resource_type.should equal(@type)
+ expect(Puppet::Resource.new("class", "foo::bar", :environment => environment).resource_type).to equal(@type)
end
end
describe "that does not exist" do
it "should set its type to 'Class' and its title to the capitalized provided name" do
klass = Puppet::Resource.new("class", "foo::bar")
- klass.type.should == "Class"
- klass.title.should == "Foo::Bar"
+ expect(klass.type).to eq("Class")
+ expect(klass.title).to eq("Foo::Bar")
end
end
describe "and its name is set to the empty string" do
it "should set its title to :main" do
- Puppet::Resource.new("class", "").title.should == :main
+ expect(Puppet::Resource.new("class", "").title).to eq(:main)
end
describe "and a class exists whose name is the empty string" do # this was a bit tough to track down
it "should set its title to :main" do
@type = Puppet::Resource::Type.new(:hostclass, "")
environment.known_resource_types.add @type
- Puppet::Resource.new("class", "", :environment => environment).title.should == :main
+ expect(Puppet::Resource.new("class", "", :environment => environment).title).to eq(:main)
end
end
end
describe "and its name is set to :main" do
it "should set its title to :main" do
- Puppet::Resource.new("class", :main).title.should == :main
+ expect(Puppet::Resource.new("class", :main).title).to eq(:main)
end
describe "and a class exists whose name is the empty string" do # this was a bit tough to track down
it "should set its title to :main" do
@type = Puppet::Resource::Type.new(:hostclass, "")
environment.known_resource_types.add @type
- Puppet::Resource.new("class", :main, :environment => environment).title.should == :main
+ expect(Puppet::Resource.new("class", :main, :environment => environment).title).to eq(:main)
end
end
end
end
end
it "should return nil when looking up resource types that don't exist" do
- Puppet::Resource.new("foobar", "bar").resource_type.should be_nil
+ expect(Puppet::Resource.new("foobar", "bar").resource_type).to be_nil
end
it "should not fail when an invalid parameter is used and strict mode is disabled" do
type = Puppet::Resource::Type.new(:definition, "foobar")
environment.known_resource_types.add type
resource = Puppet::Resource.new("foobar", "/my/file", :environment => environment)
resource[:yay] = true
end
it "should be considered equivalent to another resource if their type and title match and no parameters are set" do
- Puppet::Resource.new("file", "/f").should == Puppet::Resource.new("file", "/f")
+ expect(Puppet::Resource.new("file", "/f")).to eq(Puppet::Resource.new("file", "/f"))
end
it "should be considered equivalent to another resource if their type, title, and parameters are equal" do
- Puppet::Resource.new("file", "/f", :parameters => {:foo => "bar"}).should == Puppet::Resource.new("file", "/f", :parameters => {:foo => "bar"})
+ expect(Puppet::Resource.new("file", "/f", :parameters => {:foo => "bar"})).to eq(Puppet::Resource.new("file", "/f", :parameters => {:foo => "bar"}))
end
it "should not be considered equivalent to another resource if their type and title match but parameters are different" do
- Puppet::Resource.new("file", "/f", :parameters => {:fee => "baz"}).should_not == Puppet::Resource.new("file", "/f", :parameters => {:foo => "bar"})
+ expect(Puppet::Resource.new("file", "/f", :parameters => {:fee => "baz"})).not_to eq(Puppet::Resource.new("file", "/f", :parameters => {:foo => "bar"}))
end
it "should not be considered equivalent to a non-resource" do
- Puppet::Resource.new("file", "/f").should_not == "foo"
+ expect(Puppet::Resource.new("file", "/f")).not_to eq("foo")
end
it "should not be considered equivalent to another resource if their types do not match" do
- Puppet::Resource.new("file", "/f").should_not == Puppet::Resource.new("exec", "/f")
+ expect(Puppet::Resource.new("file", "/f")).not_to eq(Puppet::Resource.new("exec", "/f"))
end
it "should not be considered equivalent to another resource if their titles do not match" do
- Puppet::Resource.new("file", "/foo").should_not == Puppet::Resource.new("file", "/f")
+ expect(Puppet::Resource.new("file", "/foo")).not_to eq(Puppet::Resource.new("file", "/f"))
end
describe "when setting default parameters" do
let(:foo_node) { Puppet::Node.new('foo', :environment => environment) }
let(:compiler) { Puppet::Parser::Compiler.new(foo_node) }
let(:scope) { Puppet::Parser::Scope.new(compiler) }
def ast_leaf(value)
Puppet::Parser::AST::Leaf.new({:value => value})
end
it "should fail when asked to set default values and it is not a parser resource" do
environment.known_resource_types.add(
Puppet::Resource::Type.new(:definition, "default_param", :arguments => {"a" => ast_leaf("default")})
)
resource = Puppet::Resource.new("default_param", "name", :environment => environment)
- lambda { resource.set_default_parameters(scope) }.should raise_error(Puppet::DevError)
+ expect { resource.set_default_parameters(scope) }.to raise_error(Puppet::DevError)
end
it "should evaluate and set any default values when no value is provided" do
environment.known_resource_types.add(
Puppet::Resource::Type.new(:definition, "default_param", :arguments => {"a" => ast_leaf("a_default_value")})
)
resource = Puppet::Parser::Resource.new("default_param", "name", :scope => scope)
resource.set_default_parameters(scope)
- resource["a"].should == "a_default_value"
+ expect(resource["a"]).to eq("a_default_value")
end
it "should skip attributes with no default value" do
environment.known_resource_types.add(
Puppet::Resource::Type.new(:definition, "no_default_param", :arguments => {"a" => ast_leaf("a_default_value")})
)
resource = Puppet::Parser::Resource.new("no_default_param", "name", :scope => scope)
- lambda { resource.set_default_parameters(scope) }.should_not raise_error
+ expect { resource.set_default_parameters(scope) }.not_to raise_error
end
it "should return the list of default parameters set" do
environment.known_resource_types.add(
Puppet::Resource::Type.new(:definition, "default_param", :arguments => {"a" => ast_leaf("a_default_value")})
)
resource = Puppet::Parser::Resource.new("default_param", "name", :scope => scope)
- resource.set_default_parameters(scope).should == ["a"]
+ expect(resource.set_default_parameters(scope)).to eq(["a"])
end
describe "when the resource type is :hostclass" do
let(:environment_name) { "testing env" }
let(:fact_values) { { :a => 1 } }
let(:port) { Puppet::Parser::AST::Leaf.new(:value => '80') }
let(:apache) { Puppet::Resource::Type.new(:hostclass, 'apache', :arguments => { 'port' => port }) }
before do
environment.known_resource_types.add(apache)
scope.stubs(:host).returns('host')
scope.stubs(:environment).returns(environment)
scope.stubs(:facts).returns(Puppet::Node::Facts.new("facts", fact_values))
end
context "when no value is provided" do
let(:resource) do
Puppet::Parser::Resource.new("class", "apache", :scope => scope)
end
it "should query the data_binding terminus using a namespaced key" do
Puppet::DataBinding.indirection.expects(:find).with(
'apache::port', all_of(has_key(:environment), has_key(:variables)))
resource.set_default_parameters(scope)
end
it "should use the value from the data_binding terminus" do
Puppet::DataBinding.indirection.expects(:find).returns('443')
resource.set_default_parameters(scope)
- resource[:port].should == '443'
+ expect(resource[:port]).to eq('443')
end
it "should use the default value if the data_binding terminus returns nil" do
Puppet::DataBinding.indirection.expects(:find).returns(nil)
resource.set_default_parameters(scope)
- resource[:port].should == '80'
+ expect(resource[:port]).to eq('80')
end
it "should fail with error message about data binding on a hiera failure" do
Puppet::DataBinding.indirection.expects(:find).raises(Puppet::DataBinding::LookupError, 'Forgettabotit')
expect {
resource.set_default_parameters(scope)
}.to raise_error(Puppet::Error, /Error from DataBinding 'hiera' while looking up 'apache::port':.*Forgettabotit/)
end
end
context "when a value is provided" do
let(:port_parameter) do
Puppet::Parser::Resource::Param.new(
{ :name => 'port', :value => '8080' }
)
end
let(:resource) do
Puppet::Parser::Resource.new("class", "apache", :scope => scope,
:parameters => [port_parameter])
end
it "should not query the data_binding terminus" do
Puppet::DataBinding.indirection.expects(:find).never
resource.set_default_parameters(scope)
end
it "should not query the injector" do
compiler.injector.expects(:find).never
resource.set_default_parameters(scope)
end
it "should use the value provided" do
Puppet::DataBinding.indirection.expects(:find).never
- resource.set_default_parameters(scope).should == []
- resource[:port].should == '8080'
+ expect(resource.set_default_parameters(scope)).to eq([])
+ expect(resource[:port]).to eq('8080')
end
end
end
end
describe "when validating all required parameters are present" do
it "should be able to validate that all required parameters are present" do
environment.known_resource_types.add(
Puppet::Resource::Type.new(:definition, "required_param", :arguments => {"a" => nil})
)
- lambda { Puppet::Resource.new("required_param", "name", :environment => environment).validate_complete }.should raise_error(Puppet::ParseError)
+ expect { Puppet::Resource.new("required_param", "name", :environment => environment).validate_complete }.to raise_error(Puppet::ParseError)
end
it "should not fail when all required parameters are present" do
environment.known_resource_types.add(
Puppet::Resource::Type.new(:definition, "no_required_param")
)
resource = Puppet::Resource.new("no_required_param", "name", :environment => environment)
resource["a"] = "meh"
- lambda { resource.validate_complete }.should_not raise_error
+ expect { resource.validate_complete }.not_to raise_error
end
it "should not validate against builtin types" do
- lambda { Puppet::Resource.new("file", "/bar").validate_complete }.should_not raise_error
+ expect { Puppet::Resource.new("file", "/bar").validate_complete }.not_to raise_error
end
end
describe "when referring to a resource with name canonicalization" do
it "should canonicalize its own name" do
res = Puppet::Resource.new("file", "/path/")
- res.uniqueness_key.should == ["/path"]
- res.ref.should == "File[/path/]"
+ expect(res.uniqueness_key).to eq(["/path"])
+ expect(res.ref).to eq("File[/path/]")
end
end
describe "when running in strict mode" do
it "should be strict" do
- Puppet::Resource.new("file", "/path", :strict => true).should be_strict
+ expect(Puppet::Resource.new("file", "/path", :strict => true)).to be_strict
end
it "should fail if invalid parameters are used" do
expect { Puppet::Resource.new("file", "/path", :strict => true, :parameters => {:nosuchparam => "bar"}) }.to raise_error
end
it "should fail if the resource type cannot be resolved" do
expect { Puppet::Resource.new("nosuchtype", "/path", :strict => true) }.to raise_error
end
end
describe "when managing parameters" do
before do
@resource = Puppet::Resource.new("file", "/my/file")
end
it "should correctly detect when provided parameters are not valid for builtin types" do
- Puppet::Resource.new("file", "/my/file").should_not be_valid_parameter("foobar")
+ expect(Puppet::Resource.new("file", "/my/file")).not_to be_valid_parameter("foobar")
end
it "should correctly detect when provided parameters are valid for builtin types" do
- Puppet::Resource.new("file", "/my/file").should be_valid_parameter("mode")
+ expect(Puppet::Resource.new("file", "/my/file")).to be_valid_parameter("mode")
end
it "should correctly detect when provided parameters are not valid for defined resource types" do
type = Puppet::Resource::Type.new(:definition, "foobar")
environment.known_resource_types.add type
- Puppet::Resource.new("foobar", "/my/file", :environment => environment).should_not be_valid_parameter("myparam")
+ expect(Puppet::Resource.new("foobar", "/my/file", :environment => environment)).not_to be_valid_parameter("myparam")
end
it "should correctly detect when provided parameters are valid for defined resource types" do
type = Puppet::Resource::Type.new(:definition, "foobar", :arguments => {"myparam" => nil})
environment.known_resource_types.add type
- Puppet::Resource.new("foobar", "/my/file", :environment => environment).should be_valid_parameter("myparam")
+ expect(Puppet::Resource.new("foobar", "/my/file", :environment => environment)).to be_valid_parameter("myparam")
end
it "should allow setting and retrieving of parameters" do
@resource[:foo] = "bar"
- @resource[:foo].should == "bar"
+ expect(@resource[:foo]).to eq("bar")
end
it "should allow setting of parameters at initialization" do
- Puppet::Resource.new("file", "/my/file", :parameters => {:foo => "bar"})[:foo].should == "bar"
+ expect(Puppet::Resource.new("file", "/my/file", :parameters => {:foo => "bar"})[:foo]).to eq("bar")
end
it "should canonicalize retrieved parameter names to treat symbols and strings equivalently" do
@resource[:foo] = "bar"
- @resource["foo"].should == "bar"
+ expect(@resource["foo"]).to eq("bar")
end
it "should canonicalize set parameter names to treat symbols and strings equivalently" do
@resource["foo"] = "bar"
- @resource[:foo].should == "bar"
+ expect(@resource[:foo]).to eq("bar")
end
it "should set the namevar when asked to set the name" do
resource = Puppet::Resource.new("user", "bob")
Puppet::Type.type(:user).stubs(:key_attributes).returns [:myvar]
resource[:name] = "bob"
- resource[:myvar].should == "bob"
+ expect(resource[:myvar]).to eq("bob")
end
it "should return the namevar when asked to return the name" do
resource = Puppet::Resource.new("user", "bob")
Puppet::Type.type(:user).stubs(:key_attributes).returns [:myvar]
resource[:myvar] = "test"
- resource[:name].should == "test"
+ expect(resource[:name]).to eq("test")
end
it "should be able to set the name for non-builtin types" do
resource = Puppet::Resource.new(:foo, "bar")
resource[:name] = "eh"
expect { resource[:name] = "eh" }.to_not raise_error
end
it "should be able to return the name for non-builtin types" do
resource = Puppet::Resource.new(:foo, "bar")
resource[:name] = "eh"
- resource[:name].should == "eh"
+ expect(resource[:name]).to eq("eh")
end
it "should be able to iterate over parameters" do
@resource[:foo] = "bar"
@resource[:fee] = "bare"
params = {}
@resource.each do |key, value|
params[key] = value
end
- params.should == {:foo => "bar", :fee => "bare"}
+ expect(params).to eq({:foo => "bar", :fee => "bare"})
end
it "should include Enumerable" do
- @resource.class.ancestors.should be_include(Enumerable)
+ expect(@resource.class.ancestors).to be_include(Enumerable)
end
it "should have a method for testing whether a parameter is included" do
@resource[:foo] = "bar"
- @resource.should be_has_key(:foo)
- @resource.should_not be_has_key(:eh)
+ expect(@resource).to be_has_key(:foo)
+ expect(@resource).not_to be_has_key(:eh)
end
it "should have a method for providing the list of parameters" do
@resource[:foo] = "bar"
@resource[:bar] = "foo"
keys = @resource.keys
- keys.should be_include(:foo)
- keys.should be_include(:bar)
+ expect(keys).to be_include(:foo)
+ expect(keys).to be_include(:bar)
end
it "should have a method for providing the number of parameters" do
@resource[:foo] = "bar"
- @resource.length.should == 1
+ expect(@resource.length).to eq(1)
end
it "should have a method for deleting parameters" do
@resource[:foo] = "bar"
@resource.delete(:foo)
- @resource[:foo].should be_nil
+ expect(@resource[:foo]).to be_nil
end
it "should have a method for testing whether the parameter list is empty" do
- @resource.should be_empty
+ expect(@resource).to be_empty
@resource[:foo] = "bar"
- @resource.should_not be_empty
+ expect(@resource).not_to be_empty
end
it "should be able to produce a hash of all existing parameters" do
@resource[:foo] = "bar"
@resource[:fee] = "yay"
hash = @resource.to_hash
- hash[:foo].should == "bar"
- hash[:fee].should == "yay"
+ expect(hash[:foo]).to eq("bar")
+ expect(hash[:fee]).to eq("yay")
end
it "should not provide direct access to the internal parameters hash when producing a hash" do
hash = @resource.to_hash
hash[:foo] = "bar"
- @resource[:foo].should be_nil
+ expect(@resource[:foo]).to be_nil
end
it "should use the title as the namevar to the hash if no namevar is present" do
resource = Puppet::Resource.new("user", "bob")
Puppet::Type.type(:user).stubs(:key_attributes).returns [:myvar]
- resource.to_hash[:myvar].should == "bob"
+ expect(resource.to_hash[:myvar]).to eq("bob")
end
it "should set :name to the title if :name is not present for non-builtin types" do
krt = Puppet::Resource::TypeCollection.new("myenv")
krt.add Puppet::Resource::Type.new(:definition, :foo)
resource = Puppet::Resource.new :foo, "bar"
resource.stubs(:known_resource_types).returns krt
- resource.to_hash[:name].should == "bar"
+ expect(resource.to_hash[:name]).to eq("bar")
end
end
describe "when serializing a native type" do
before do
@resource = Puppet::Resource.new("file", "/my/file")
@resource["one"] = "test"
@resource["two"] = "other"
end
# PUP-3272, needs to work becuse serialization is not only to network
#
it "should produce an equivalent yaml object" do
text = @resource.render('yaml')
newresource = Puppet::Resource.convert_from('yaml', text)
- newresource.should equal_resource_attributes_of(@resource)
+ expect(newresource).to equal_resource_attributes_of(@resource)
end
# PUP-3272, since serialization to network is done in pson, not yaml
it "should produce an equivalent pson object" do
text = @resource.render('pson')
newresource = Puppet::Resource.convert_from('pson', text)
- newresource.should equal_resource_attributes_of(@resource)
+ expect(newresource).to equal_resource_attributes_of(@resource)
end
end
describe "when serializing a defined type" do
before do
type = Puppet::Resource::Type.new(:definition, "foo::bar")
environment.known_resource_types.add type
@resource = Puppet::Resource.new('foo::bar', 'xyzzy', :environment => environment)
@resource['one'] = 'test'
@resource['two'] = 'other'
@resource.resource_type
end
it "doesn't include transient instance variables (#4506)" do
expect(@resource.to_yaml_properties).to_not include(:@rstype)
end
it "produces an equivalent pson object" do
text = @resource.render('pson')
newresource = Puppet::Resource.convert_from('pson', text)
- newresource.should equal_resource_attributes_of(@resource)
+ expect(newresource).to equal_resource_attributes_of(@resource)
end
end
describe "when converting to a RAL resource" do
it "should use the resource type's :new method to create the resource if the resource is of a builtin type" do
resource = Puppet::Resource.new("file", basepath+"/my/file")
result = resource.to_ral
- result.must be_instance_of(Puppet::Type.type(:file))
- result[:path].should == basepath+"/my/file"
+ expect(result).to be_instance_of(Puppet::Type.type(:file))
+ expect(result[:path]).to eq(basepath+"/my/file")
end
it "should convert to a component instance if the resource type is not of a builtin type" do
resource = Puppet::Resource.new("foobar", "somename")
result = resource.to_ral
- result.must be_instance_of(Puppet::Type.type(:component))
- result.title.should == "Foobar[somename]"
+ expect(result).to be_instance_of(Puppet::Type.type(:component))
+ expect(result.title).to eq("Foobar[somename]")
end
end
describe "when converting to puppet code" do
before do
@resource = Puppet::Resource.new("one::two", "/my/file",
:parameters => {
:noop => true,
:foo => %w{one two},
:ensure => 'present',
}
)
end
it "should align, sort and add trailing commas to attributes with ensure first" do
- @resource.to_manifest.should == <<-HEREDOC.gsub(/^\s{8}/, '').gsub(/\n$/, '')
+ expect(@resource.to_manifest).to eq <<-HEREDOC.gsub(/^\s{8}/, '').gsub(/\n$/, '')
one::two { '/my/file':
ensure => 'present',
foo => ['one', 'two'],
noop => 'true',
}
HEREDOC
end
end
describe "when converting to Yaml for Hiera" do
before do
@resource = Puppet::Resource.new("one::two", "/my/file",
:parameters => {
:noop => true,
:foo => %w{one two},
:ensure => 'present',
}
)
end
it "should align and sort to attributes with ensure first" do
- @resource.to_hierayaml.should == <<-HEREDOC.gsub(/^\s{8}/, '')
+ expect(@resource.to_hierayaml).to eq <<-HEREDOC.gsub(/^\s{8}/, '')
/my/file:
ensure: 'present'
foo : ['one', 'two']
noop : 'true'
HEREDOC
end
end
describe "when converting to pson" do
# LAK:NOTE For all of these tests, we convert back to the resource so we can
# trap the actual data structure then.
it "should set its type to the provided type" do
- Puppet::Resource.from_data_hash(PSON.parse(Puppet::Resource.new("File", "/foo").to_pson)).type.should == "File"
+ expect(Puppet::Resource.from_data_hash(PSON.parse(Puppet::Resource.new("File", "/foo").to_pson)).type).to eq("File")
end
it "should set its title to the provided title" do
- Puppet::Resource.from_data_hash(PSON.parse(Puppet::Resource.new("File", "/foo").to_pson)).title.should == "/foo"
+ expect(Puppet::Resource.from_data_hash(PSON.parse(Puppet::Resource.new("File", "/foo").to_pson)).title).to eq("/foo")
end
it "should include all tags from the resource" do
resource = Puppet::Resource.new("File", "/foo")
resource.tag("yay")
- Puppet::Resource.from_data_hash(PSON.parse(resource.to_pson)).tags.should == resource.tags
+ expect(Puppet::Resource.from_data_hash(PSON.parse(resource.to_pson)).tags).to eq(resource.tags)
end
it "should include the file if one is set" do
resource = Puppet::Resource.new("File", "/foo")
resource.file = "/my/file"
- Puppet::Resource.from_data_hash(PSON.parse(resource.to_pson)).file.should == "/my/file"
+ expect(Puppet::Resource.from_data_hash(PSON.parse(resource.to_pson)).file).to eq("/my/file")
end
it "should include the line if one is set" do
resource = Puppet::Resource.new("File", "/foo")
resource.line = 50
- Puppet::Resource.from_data_hash(PSON.parse(resource.to_pson)).line.should == 50
+ expect(Puppet::Resource.from_data_hash(PSON.parse(resource.to_pson)).line).to eq(50)
end
it "should include the 'exported' value if one is set" do
resource = Puppet::Resource.new("File", "/foo")
resource.exported = true
- Puppet::Resource.from_data_hash(PSON.parse(resource.to_pson)).exported?.should be_true
+ expect(Puppet::Resource.from_data_hash(PSON.parse(resource.to_pson)).exported?).to be_truthy
end
it "should set 'exported' to false if no value is set" do
resource = Puppet::Resource.new("File", "/foo")
- Puppet::Resource.from_data_hash(PSON.parse(resource.to_pson)).exported?.should be_false
+ expect(Puppet::Resource.from_data_hash(PSON.parse(resource.to_pson)).exported?).to be_falsey
end
it "should set all of its parameters as the 'parameters' entry" do
resource = Puppet::Resource.new("File", "/foo")
resource[:foo] = %w{bar eh}
resource[:fee] = %w{baz}
result = Puppet::Resource.from_data_hash(PSON.parse(resource.to_pson))
- result["foo"].should == %w{bar eh}
- result["fee"].should == %w{baz}
+ expect(result["foo"]).to eq(%w{bar eh})
+ expect(result["fee"]).to eq(%w{baz})
end
it "should serialize relationships as reference strings" do
resource = Puppet::Resource.new("File", "/foo")
resource[:requires] = Puppet::Resource.new("File", "/bar")
result = Puppet::Resource.from_data_hash(PSON.parse(resource.to_pson))
- result[:requires].should == "File[/bar]"
+ expect(result[:requires]).to eq("File[/bar]")
end
it "should serialize multiple relationships as arrays of reference strings" do
resource = Puppet::Resource.new("File", "/foo")
resource[:requires] = [Puppet::Resource.new("File", "/bar"), Puppet::Resource.new("File", "/baz")]
result = Puppet::Resource.from_data_hash(PSON.parse(resource.to_pson))
- result[:requires].should == [ "File[/bar]", "File[/baz]" ]
+ expect(result[:requires]).to eq([ "File[/bar]", "File[/baz]" ])
end
end
describe "when converting from pson" do
def pson_result_should
Puppet::Resource.expects(:new).with { |hash| yield hash }
end
before do
@data = {
'type' => "file",
'title' => basepath+"/yay",
}
end
it "should set its type to the provided type" do
- Puppet::Resource.from_data_hash(@data).type.should == "File"
+ expect(Puppet::Resource.from_data_hash(@data).type).to eq("File")
end
it "should set its title to the provided title" do
- Puppet::Resource.from_data_hash(@data).title.should == basepath+"/yay"
+ expect(Puppet::Resource.from_data_hash(@data).title).to eq(basepath+"/yay")
end
it "should tag the resource with any provided tags" do
@data['tags'] = %w{foo bar}
resource = Puppet::Resource.from_data_hash(@data)
- resource.tags.should be_include("foo")
- resource.tags.should be_include("bar")
+ expect(resource.tags).to be_include("foo")
+ expect(resource.tags).to be_include("bar")
end
it "should set its file to the provided file" do
@data['file'] = "/foo/bar"
- Puppet::Resource.from_data_hash(@data).file.should == "/foo/bar"
+ expect(Puppet::Resource.from_data_hash(@data).file).to eq("/foo/bar")
end
it "should set its line to the provided line" do
@data['line'] = 50
- Puppet::Resource.from_data_hash(@data).line.should == 50
+ expect(Puppet::Resource.from_data_hash(@data).line).to eq(50)
end
it "should 'exported' to true if set in the pson data" do
@data['exported'] = true
- Puppet::Resource.from_data_hash(@data).exported.should be_true
+ expect(Puppet::Resource.from_data_hash(@data).exported).to be_truthy
end
it "should 'exported' to false if not set in the pson data" do
- Puppet::Resource.from_data_hash(@data).exported.should be_false
+ expect(Puppet::Resource.from_data_hash(@data).exported).to be_falsey
end
it "should fail if no title is provided" do
@data.delete('title')
expect { Puppet::Resource.from_data_hash(@data) }.to raise_error(ArgumentError)
end
it "should fail if no type is provided" do
@data.delete('type')
expect { Puppet::Resource.from_data_hash(@data) }.to raise_error(ArgumentError)
end
it "should set each of the provided parameters" do
@data['parameters'] = {'foo' => %w{one two}, 'fee' => %w{three four}}
resource = Puppet::Resource.from_data_hash(@data)
- resource['foo'].should == %w{one two}
- resource['fee'].should == %w{three four}
+ expect(resource['foo']).to eq(%w{one two})
+ expect(resource['fee']).to eq(%w{three four})
end
it "should convert single-value array parameters to normal values" do
@data['parameters'] = {'foo' => %w{one}}
resource = Puppet::Resource.from_data_hash(@data)
- resource['foo'].should == %w{one}
+ expect(resource['foo']).to eq(%w{one})
end
end
it "implements copy_as_resource" do
resource = Puppet::Resource.new("file", "/my/file")
- resource.copy_as_resource.should == resource
+ expect(resource.copy_as_resource).to eq(resource)
end
describe "because it is an indirector model" do
it "should include Puppet::Indirector" do
- Puppet::Resource.should be_is_a(Puppet::Indirector)
+ expect(Puppet::Resource).to be_is_a(Puppet::Indirector)
end
it "should have a default terminus" do
- Puppet::Resource.indirection.terminus_class.should be
+ expect(Puppet::Resource.indirection.terminus_class).to be
end
it "should have a name" do
- Puppet::Resource.new("file", "/my/file").name.should == "File//my/file"
+ expect(Puppet::Resource.new("file", "/my/file").name).to eq("File//my/file")
end
end
describe "when resolving resources with a catalog" do
it "should resolve all resources using the catalog" do
catalog = mock 'catalog'
resource = Puppet::Resource.new("foo::bar", "yay")
resource.catalog = catalog
catalog.expects(:resource).with("Foo::Bar[yay]").returns(:myresource)
- resource.resolve.should == :myresource
+ expect(resource.resolve).to eq(:myresource)
end
end
describe "when generating the uniqueness key" do
it "should include all of the key_attributes in alphabetical order by attribute name" do
Puppet::Type.type(:file).stubs(:key_attributes).returns [:myvar, :owner, :path]
Puppet::Type.type(:file).stubs(:title_patterns).returns(
[ [ /(.*)/, [ [:path, lambda{|x| x} ] ] ] ]
)
res = Puppet::Resource.new("file", "/my/file", :parameters => {:owner => 'root', :content => 'hello'})
- res.uniqueness_key.should == [ nil, 'root', '/my/file']
+ expect(res.uniqueness_key).to eq([ nil, 'root', '/my/file'])
end
end
describe '#parse_title' do
describe 'with a composite namevar' do
before do
Puppet::Type.newtype(:composite) do
newparam(:name)
newparam(:value)
# Configure two title patterns to match a title that is either
# separated with a colon or exclamation point. The first capture
# will be used for the :name param, and the second capture will be
# used for the :value param.
def self.title_patterns
identity = lambda {|x| x }
reverse = lambda {|x| x.reverse }
[
[
/^(.*?):(.*?)$/,
[
[:name, identity],
[:value, identity],
]
],
[
/^(.*?)!(.*?)$/,
[
[:name, reverse],
[:value, reverse],
]
],
]
end
end
end
describe "with no matching title patterns" do
subject { Puppet::Resource.new(:composite, 'unmatching title')}
it "should raise an exception if no title patterns match" do
expect do
subject.to_hash
end.to raise_error(Puppet::Error, /No set of title patterns matched/)
end
end
describe "with a matching title pattern" do
subject { Puppet::Resource.new(:composite, 'matching:title') }
it "should not raise an exception if there was a match" do
expect do
subject.to_hash
end.to_not raise_error
end
it "should set the resource parameters from the parsed title values" do
h = subject.to_hash
- h[:name].should == 'matching'
- h[:value].should == 'title'
+ expect(h[:name]).to eq('matching')
+ expect(h[:value]).to eq('title')
end
end
describe "and multiple title patterns" do
subject { Puppet::Resource.new(:composite, 'matching!title') }
it "should use the first title pattern that matches" do
h = subject.to_hash
- h[:name].should == 'gnihctam'
- h[:value].should == 'eltit'
+ expect(h[:name]).to eq('gnihctam')
+ expect(h[:value]).to eq('eltit')
end
end
end
end
describe "#prune_parameters" do
before do
Puppet::Type.newtype('blond') do
newproperty(:ensure)
newproperty(:height)
newproperty(:weight)
newproperty(:sign)
newproperty(:friends)
newparam(:admits_to_dying_hair)
newparam(:admits_to_age)
newparam(:name)
end
end
it "should strip all parameters and strip properties that are nil, empty or absent except for ensure" do
resource = Puppet::Resource.new("blond", "Bambi", :parameters => {
:ensure => 'absent',
:height => '',
:weight => 'absent',
:friends => [],
:admits_to_age => true,
:admits_to_dying_hair => false
})
pruned_resource = resource.prune_parameters
- pruned_resource.should == Puppet::Resource.new("blond", "Bambi", :parameters => {:ensure => 'absent'})
+ expect(pruned_resource).to eq(Puppet::Resource.new("blond", "Bambi", :parameters => {:ensure => 'absent'}))
end
it "should leave parameters alone if in parameters_to_include" do
resource = Puppet::Resource.new("blond", "Bambi", :parameters => {
:admits_to_age => true,
:admits_to_dying_hair => false
})
pruned_resource = resource.prune_parameters(:parameters_to_include => [:admits_to_dying_hair])
- pruned_resource.should == Puppet::Resource.new("blond", "Bambi", :parameters => {:admits_to_dying_hair => false})
+ expect(pruned_resource).to eq(Puppet::Resource.new("blond", "Bambi", :parameters => {:admits_to_dying_hair => false}))
end
it "should leave properties if not nil, absent or empty" do
resource = Puppet::Resource.new("blond", "Bambi", :parameters => {
:ensure => 'silly',
:height => '7 ft 5 in',
:friends => ['Oprah'],
})
pruned_resource = resource.prune_parameters
- pruned_resource.should ==
+ expect(pruned_resource).to eq(
resource = Puppet::Resource.new("blond", "Bambi", :parameters => {
:ensure => 'silly',
:height => '7 ft 5 in',
:friends => ['Oprah'],
})
+ )
end
end
end
diff --git a/spec/unit/scheduler/job_spec.rb b/spec/unit/scheduler/job_spec.rb
index c1d002cfc..0f68b7ea2 100644
--- a/spec/unit/scheduler/job_spec.rb
+++ b/spec/unit/scheduler/job_spec.rb
@@ -1,79 +1,79 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/scheduler'
describe Puppet::Scheduler::Job do
let(:run_interval) { 10 }
let(:job) { described_class.new(run_interval) }
it "has a minimum run interval of 0" do
- Puppet::Scheduler::Job.new(-1).run_interval.should == 0
+ expect(Puppet::Scheduler::Job.new(-1).run_interval).to eq(0)
end
describe "when not run yet" do
it "is ready" do
- job.ready?(2).should be
+ expect(job.ready?(2)).to be
end
it "gives the time to next run as 0" do
- job.interval_to_next_from(2).should == 0
+ expect(job.interval_to_next_from(2)).to eq(0)
end
end
describe "when run at least once" do
let(:last_run) { 50 }
before(:each) do
job.run(last_run)
end
it "is ready when the time is greater than the last run plus the interval" do
- job.ready?(last_run + run_interval + 1).should be
+ expect(job.ready?(last_run + run_interval + 1)).to be
end
it "is ready when the time is equal to the last run plus the interval" do
- job.ready?(last_run + run_interval).should be
+ expect(job.ready?(last_run + run_interval)).to be
end
it "is not ready when the time is less than the last run plus the interval" do
- job.ready?(last_run + run_interval - 1).should_not be
+ expect(job.ready?(last_run + run_interval - 1)).not_to be
end
context "when calculating the next run" do
it "returns the run interval if now == last run" do
- job.interval_to_next_from(last_run).should == run_interval
+ expect(job.interval_to_next_from(last_run)).to eq(run_interval)
end
it "when time is between the last and next runs gives the remaining portion of the run_interval" do
time_since_last_run = 2
now = last_run + time_since_last_run
- job.interval_to_next_from(now).should == run_interval - time_since_last_run
+ expect(job.interval_to_next_from(now)).to eq(run_interval - time_since_last_run)
end
it "when time is later than last+interval returns 0" do
time_since_last_run = run_interval + 5
now = last_run + time_since_last_run
- job.interval_to_next_from(now).should == 0
+ expect(job.interval_to_next_from(now)).to eq(0)
end
end
end
it "starts enabled" do
- job.enabled?.should be
+ expect(job.enabled?).to be
end
it "can be disabled" do
job.disable
- job.enabled?.should_not be
+ expect(job.enabled?).not_to be
end
it "has the job instance as a parameter" do
passed_job = nil
job = Puppet::Scheduler::Job.new(run_interval) do |j|
passed_job = j
end
job.run(5)
- passed_job.should eql(job)
+ expect(passed_job).to eql(job)
end
end
diff --git a/spec/unit/scheduler/scheduler_spec.rb b/spec/unit/scheduler/scheduler_spec.rb
index 1bd289764..17a0868a4 100644
--- a/spec/unit/scheduler/scheduler_spec.rb
+++ b/spec/unit/scheduler/scheduler_spec.rb
@@ -1,116 +1,116 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/scheduler'
describe Puppet::Scheduler::Scheduler do
let(:now) { 183550 }
let(:timer) { MockTimer.new(now) }
class MockTimer
attr_reader :wait_for_calls
def initialize(start=1729)
@now = start
@wait_for_calls = []
end
def wait_for(seconds)
@wait_for_calls << seconds
@now += seconds
end
def now
@now
end
end
def one_time_job(interval)
Puppet::Scheduler::Job.new(interval) { |j| j.disable }
end
def disabled_job(interval)
job = Puppet::Scheduler::Job.new(interval) { |j| j.disable }
job.disable
job
end
let(:scheduler) { Puppet::Scheduler::Scheduler.new(timer) }
it "uses the minimum interval" do
later_job = one_time_job(7)
earlier_job = one_time_job(2)
later_job.last_run = now
earlier_job.last_run = now
scheduler.run_loop([later_job, earlier_job])
- timer.wait_for_calls.should == [2, 5]
+ expect(timer.wait_for_calls).to eq([2, 5])
end
it "ignores disabled jobs when calculating intervals" do
enabled = one_time_job(7)
enabled.last_run = now
disabled = disabled_job(2)
scheduler.run_loop([enabled, disabled])
- timer.wait_for_calls.should == [7]
+ expect(timer.wait_for_calls).to eq([7])
end
it "asks the timer to wait for the job interval" do
job = one_time_job(5)
job.last_run = now
scheduler.run_loop([job])
- timer.wait_for_calls.should == [5]
+ expect(timer.wait_for_calls).to eq([5])
end
it "does not run when there are no jobs" do
scheduler.run_loop([])
- timer.wait_for_calls.should be_empty
+ expect(timer.wait_for_calls).to be_empty
end
it "does not run when there are only disabled jobs" do
disabled_job = Puppet::Scheduler::Job.new(0)
disabled_job.disable
scheduler.run_loop([disabled_job])
- timer.wait_for_calls.should be_empty
+ expect(timer.wait_for_calls).to be_empty
end
it "stops running when there are no more enabled jobs" do
disabling_job = Puppet::Scheduler::Job.new(0) do |j|
j.disable
end
scheduler.run_loop([disabling_job])
- timer.wait_for_calls.size.should == 1
+ expect(timer.wait_for_calls.size).to eq(1)
end
it "marks the start of the run loop" do
disabled_job = Puppet::Scheduler::Job.new(0)
disabled_job.disable
scheduler.run_loop([disabled_job])
- disabled_job.start_time.should == now
+ expect(disabled_job.start_time).to eq(now)
end
it "calculates the next interval from the start of a job" do
countdown = 2
slow_job = Puppet::Scheduler::Job.new(10) do |job|
timer.wait_for(3)
countdown -= 1
job.disable if countdown == 0
end
scheduler.run_loop([slow_job])
- timer.wait_for_calls.should == [0, 3, 7, 3]
+ expect(timer.wait_for_calls).to eq([0, 3, 7, 3])
end
end
diff --git a/spec/unit/scheduler/splay_job_spec.rb b/spec/unit/scheduler/splay_job_spec.rb
index 0f53f5175..e44def27e 100644
--- a/spec/unit/scheduler/splay_job_spec.rb
+++ b/spec/unit/scheduler/splay_job_spec.rb
@@ -1,35 +1,35 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/scheduler'
describe Puppet::Scheduler::SplayJob do
let(:run_interval) { 10 }
let(:last_run) { 50 }
let(:splay_limit) { 5 }
let(:start_time) { 23 }
let(:job) { described_class.new(run_interval, splay_limit) }
it "does not apply a splay after the first run" do
job.run(last_run)
- job.interval_to_next_from(last_run).should == run_interval
+ expect(job.interval_to_next_from(last_run)).to eq(run_interval)
end
it "calculates the first run splayed from the start time" do
job.start_time = start_time
- job.interval_to_next_from(start_time).should == job.splay
+ expect(job.interval_to_next_from(start_time)).to eq(job.splay)
end
it "interval to the next run decreases as time advances" do
time_passed = 3
job.start_time = start_time
- job.interval_to_next_from(start_time + time_passed).should == job.splay - time_passed
+ expect(job.interval_to_next_from(start_time + time_passed)).to eq(job.splay - time_passed)
end
it "is not immediately ready if splayed" do
job.start_time = start_time
job.expects(:splay).returns(6)
- job.ready?(start_time).should_not be
+ expect(job.ready?(start_time)).not_to be
end
end
diff --git a/spec/unit/semver_spec.rb b/spec/unit/semver_spec.rb
index d4fc5da04..028326e96 100644
--- a/spec/unit/semver_spec.rb
+++ b/spec/unit/semver_spec.rb
@@ -1,303 +1,305 @@
require 'spec_helper'
require 'semver'
describe SemVer do
- describe 'MAX should be +Infinity' do
- SemVer::MAX.major.infinite?.should == 1
+ describe 'MAX' do
+ it 'should be +Infinity' do
+ expect(SemVer::MAX.major.infinite?).to eq(1)
+ end
end
describe '::valid?' do
it 'should validate basic version strings' do
%w[ 0.0.0 999.999.999 v0.0.0 v999.999.999 ].each do |vstring|
- SemVer.valid?(vstring).should be_true
+ expect(SemVer.valid?(vstring)).to be_truthy
end
end
it 'should validate special version strings' do
%w[ 0.0.0-foo 999.999.999-bar v0.0.0-a v999.999.999-beta ].each do |vstring|
- SemVer.valid?(vstring).should be_true
+ expect(SemVer.valid?(vstring)).to be_truthy
end
end
it 'should fail to validate invalid version strings' do
%w[ nope 0.0foo 999.999 x0.0.0 z.z.z 1.2.3beta 1.x.y ].each do |vstring|
- SemVer.valid?(vstring).should be_false
+ expect(SemVer.valid?(vstring)).to be_falsey
end
end
end
describe '::pre' do
it 'should append a dash when no dash appears in the string' do
- SemVer.pre('1.2.3').should == '1.2.3-'
+ expect(SemVer.pre('1.2.3')).to eq('1.2.3-')
end
it 'should not append a dash when a dash appears in the string' do
- SemVer.pre('1.2.3-a').should == '1.2.3-a'
+ expect(SemVer.pre('1.2.3-a')).to eq('1.2.3-a')
end
end
describe '::find_matching' do
before :all do
@versions = %w[
0.0.1
0.0.2
1.0.0-rc1
1.0.0-rc2
1.0.0
1.0.1
1.1.0
1.1.1
1.1.2
1.1.3
1.1.4
1.2.0
1.2.1
2.0.0-rc1
].map { |v| SemVer.new(v) }
end
it 'should match exact versions by string' do
@versions.each do |version|
- SemVer.find_matching(version, @versions).should == version
+ expect(SemVer.find_matching(version, @versions)).to eq(version)
end
end
it 'should return nil if no versions match' do
%w[ 3.0.0 2.0.0-rc2 1.0.0-alpha ].each do |v|
- SemVer.find_matching(v, @versions).should be_nil
+ expect(SemVer.find_matching(v, @versions)).to be_nil
end
end
it 'should find the greatest match for partial versions' do
- SemVer.find_matching('1.0', @versions).should == 'v1.0.1'
- SemVer.find_matching('1.1', @versions).should == 'v1.1.4'
- SemVer.find_matching('1', @versions).should == 'v1.2.1'
- SemVer.find_matching('2', @versions).should == 'v2.0.0-rc1'
- SemVer.find_matching('2.1', @versions).should == nil
+ expect(SemVer.find_matching('1.0', @versions)).to eq('v1.0.1')
+ expect(SemVer.find_matching('1.1', @versions)).to eq('v1.1.4')
+ expect(SemVer.find_matching('1', @versions)).to eq('v1.2.1')
+ expect(SemVer.find_matching('2', @versions)).to eq('v2.0.0-rc1')
+ expect(SemVer.find_matching('2.1', @versions)).to eq(nil)
end
it 'should find the greatest match for versions with placeholders' do
- SemVer.find_matching('1.0.x', @versions).should == 'v1.0.1'
- SemVer.find_matching('1.1.x', @versions).should == 'v1.1.4'
- SemVer.find_matching('1.x', @versions).should == 'v1.2.1'
- SemVer.find_matching('1.x.x', @versions).should == 'v1.2.1'
- SemVer.find_matching('2.x', @versions).should == 'v2.0.0-rc1'
- SemVer.find_matching('2.x.x', @versions).should == 'v2.0.0-rc1'
- SemVer.find_matching('2.1.x', @versions).should == nil
+ expect(SemVer.find_matching('1.0.x', @versions)).to eq('v1.0.1')
+ expect(SemVer.find_matching('1.1.x', @versions)).to eq('v1.1.4')
+ expect(SemVer.find_matching('1.x', @versions)).to eq('v1.2.1')
+ expect(SemVer.find_matching('1.x.x', @versions)).to eq('v1.2.1')
+ expect(SemVer.find_matching('2.x', @versions)).to eq('v2.0.0-rc1')
+ expect(SemVer.find_matching('2.x.x', @versions)).to eq('v2.0.0-rc1')
+ expect(SemVer.find_matching('2.1.x', @versions)).to eq(nil)
end
end
describe '::[]' do
it "should produce expected ranges" do
tests = {
'1.2.3-alpha' => SemVer.new('v1.2.3-alpha') .. SemVer.new('v1.2.3-alpha'),
'1.2.3' => SemVer.new('v1.2.3-') .. SemVer.new('v1.2.3'),
'>1.2.3-alpha' => SemVer.new('v1.2.3-alpha-') .. SemVer::MAX,
'>1.2.3' => SemVer.new('v1.2.4-') .. SemVer::MAX,
'<1.2.3-alpha' => SemVer::MIN ... SemVer.new('v1.2.3-alpha'),
'<1.2.3' => SemVer::MIN ... SemVer.new('v1.2.3-'),
'>=1.2.3-alpha' => SemVer.new('v1.2.3-alpha') .. SemVer::MAX,
'>=1.2.3' => SemVer.new('v1.2.3-') .. SemVer::MAX,
'<=1.2.3-alpha' => SemVer::MIN .. SemVer.new('v1.2.3-alpha'),
'<=1.2.3' => SemVer::MIN .. SemVer.new('v1.2.3'),
'>1.2.3-a <1.2.3-b' => SemVer.new('v1.2.3-a-') ... SemVer.new('v1.2.3-b'),
'>1.2.3 <1.2.5' => SemVer.new('v1.2.4-') ... SemVer.new('v1.2.5-'),
'>=1.2.3-a <= 1.2.3-b' => SemVer.new('v1.2.3-a') .. SemVer.new('v1.2.3-b'),
'>=1.2.3 <=1.2.5' => SemVer.new('v1.2.3-') .. SemVer.new('v1.2.5'),
'1.2.3-a - 2.3.4-b' => SemVer.new('v1.2.3-a') .. SemVer.new('v2.3.4-b'),
'1.2.3 - 2.3.4' => SemVer.new('v1.2.3-') .. SemVer.new('v2.3.4'),
'~1.2.3' => SemVer.new('v1.2.3-') ... SemVer.new('v1.3.0-'),
'~1.2' => SemVer.new('v1.2.0-') ... SemVer.new('v2.0.0-'),
'~1' => SemVer.new('v1.0.0-') ... SemVer.new('v2.0.0-'),
'1.2.x' => SemVer.new('v1.2.0') ... SemVer.new('v1.3.0-'),
'1.x' => SemVer.new('v1.0.0') ... SemVer.new('v2.0.0-'),
}
tests.each do |vstring, expected|
- SemVer[vstring].should == expected
+ expect(SemVer[vstring]).to eq(expected)
end
end
it "should suit up" do
suitability = {
[ '1.2.3', 'v1.2.2' ] => false,
[ '>=1.2.3', 'v1.2.2' ] => false,
[ '<=1.2.3', 'v1.2.2' ] => true,
[ '>= 1.2.3', 'v1.2.2' ] => false,
[ '<= 1.2.3', 'v1.2.2' ] => true,
[ '1.2.3 - 1.2.4', 'v1.2.2' ] => false,
[ '~1.2.3', 'v1.2.2' ] => false,
[ '~1.2', 'v1.2.2' ] => true,
[ '~1', 'v1.2.2' ] => true,
[ '1.2.x', 'v1.2.2' ] => true,
[ '1.x', 'v1.2.2' ] => true,
[ '1.2.3', 'v1.2.3-alpha' ] => true,
[ '>=1.2.3', 'v1.2.3-alpha' ] => true,
[ '<=1.2.3', 'v1.2.3-alpha' ] => true,
[ '>= 1.2.3', 'v1.2.3-alpha' ] => true,
[ '<= 1.2.3', 'v1.2.3-alpha' ] => true,
[ '>1.2.3', 'v1.2.3-alpha' ] => false,
[ '<1.2.3', 'v1.2.3-alpha' ] => false,
[ '> 1.2.3', 'v1.2.3-alpha' ] => false,
[ '< 1.2.3', 'v1.2.3-alpha' ] => false,
[ '1.2.3 - 1.2.4', 'v1.2.3-alpha' ] => true,
[ '1.2.3 - 1.2.4', 'v1.2.4-alpha' ] => true,
[ '1.2.3 - 1.2.4', 'v1.2.5-alpha' ] => false,
[ '~1.2.3', 'v1.2.3-alpha' ] => true,
[ '~1.2.3', 'v1.3.0-alpha' ] => false,
[ '~1.2', 'v1.2.3-alpha' ] => true,
[ '~1.2', 'v2.0.0-alpha' ] => false,
[ '~1', 'v1.2.3-alpha' ] => true,
[ '~1', 'v2.0.0-alpha' ] => false,
[ '1.2.x', 'v1.2.3-alpha' ] => true,
[ '1.2.x', 'v1.3.0-alpha' ] => false,
[ '1.x', 'v1.2.3-alpha' ] => true,
[ '1.x', 'v2.0.0-alpha' ] => false,
[ '1.2.3', 'v1.2.3' ] => true,
[ '>=1.2.3', 'v1.2.3' ] => true,
[ '<=1.2.3', 'v1.2.3' ] => true,
[ '>= 1.2.3', 'v1.2.3' ] => true,
[ '<= 1.2.3', 'v1.2.3' ] => true,
[ '1.2.3 - 1.2.4', 'v1.2.3' ] => true,
[ '~1.2.3', 'v1.2.3' ] => true,
[ '~1.2', 'v1.2.3' ] => true,
[ '~1', 'v1.2.3' ] => true,
[ '1.2.x', 'v1.2.3' ] => true,
[ '1.x', 'v1.2.3' ] => true,
[ '1.2.3', 'v1.2.4' ] => false,
[ '>=1.2.3', 'v1.2.4' ] => true,
[ '<=1.2.3', 'v1.2.4' ] => false,
[ '>= 1.2.3', 'v1.2.4' ] => true,
[ '<= 1.2.3', 'v1.2.4' ] => false,
[ '1.2.3 - 1.2.4', 'v1.2.4' ] => true,
[ '~1.2.3', 'v1.2.4' ] => true,
[ '~1.2', 'v1.2.4' ] => true,
[ '~1', 'v1.2.4' ] => true,
[ '1.2.x', 'v1.2.4' ] => true,
[ '1.x', 'v1.2.4' ] => true,
}
suitability.each do |arguments, expected|
range, vstring = arguments
actual = SemVer[range] === SemVer.new(vstring)
- actual.should == expected
+ expect(actual).to eq(expected)
end
end
end
describe 'instantiation' do
it 'should raise an exception when passed an invalid version string' do
expect { SemVer.new('invalidVersion') }.to raise_exception ArgumentError
end
it 'should populate the appropriate fields for a basic version string' do
version = SemVer.new('1.2.3')
- version.major.should == 1
- version.minor.should == 2
- version.tiny.should == 3
- version.special.should == ''
+ expect(version.major).to eq(1)
+ expect(version.minor).to eq(2)
+ expect(version.tiny).to eq(3)
+ expect(version.special).to eq('')
end
it 'should populate the appropriate fields for a special version string' do
version = SemVer.new('3.4.5-beta6')
- version.major.should == 3
- version.minor.should == 4
- version.tiny.should == 5
- version.special.should == '-beta6'
+ expect(version.major).to eq(3)
+ expect(version.minor).to eq(4)
+ expect(version.tiny).to eq(5)
+ expect(version.special).to eq('-beta6')
end
end
describe '#matched_by?' do
subject { SemVer.new('v1.2.3-beta') }
describe 'should match against' do
describe 'literal version strings' do
- it { should be_matched_by('1.2.3-beta') }
+ it { is_expected.to be_matched_by('1.2.3-beta') }
- it { should_not be_matched_by('1.2.3-alpha') }
- it { should_not be_matched_by('1.2.4-beta') }
- it { should_not be_matched_by('1.3.3-beta') }
- it { should_not be_matched_by('2.2.3-beta') }
+ it { is_expected.not_to be_matched_by('1.2.3-alpha') }
+ it { is_expected.not_to be_matched_by('1.2.4-beta') }
+ it { is_expected.not_to be_matched_by('1.3.3-beta') }
+ it { is_expected.not_to be_matched_by('2.2.3-beta') }
end
describe 'partial version strings' do
- it { should be_matched_by('1.2.3') }
- it { should be_matched_by('1.2') }
- it { should be_matched_by('1') }
+ it { is_expected.to be_matched_by('1.2.3') }
+ it { is_expected.to be_matched_by('1.2') }
+ it { is_expected.to be_matched_by('1') }
end
describe 'version strings with placeholders' do
- it { should be_matched_by('1.2.x') }
- it { should be_matched_by('1.x.3') }
- it { should be_matched_by('1.x.x') }
- it { should be_matched_by('1.x') }
+ it { is_expected.to be_matched_by('1.2.x') }
+ it { is_expected.to be_matched_by('1.x.3') }
+ it { is_expected.to be_matched_by('1.x.x') }
+ it { is_expected.to be_matched_by('1.x') }
end
end
end
describe 'comparisons' do
describe 'against a string' do
it 'should just work' do
- SemVer.new('1.2.3').should == '1.2.3'
+ expect(SemVer.new('1.2.3')).to eq('1.2.3')
end
end
describe 'against a symbol' do
it 'should just work' do
- SemVer.new('1.2.3').should == :'1.2.3'
+ expect(SemVer.new('1.2.3')).to eq(:'1.2.3')
end
end
describe 'on a basic version (v1.2.3)' do
subject { SemVer.new('v1.2.3') }
- it { should == SemVer.new('1.2.3') }
+ it { is_expected.to eq(SemVer.new('1.2.3')) }
# Different major versions
- it { should > SemVer.new('0.2.3') }
- it { should < SemVer.new('2.2.3') }
+ it { is_expected.to be > SemVer.new('0.2.3') }
+ it { is_expected.to be < SemVer.new('2.2.3') }
# Different minor versions
- it { should > SemVer.new('1.1.3') }
- it { should < SemVer.new('1.3.3') }
+ it { is_expected.to be > SemVer.new('1.1.3') }
+ it { is_expected.to be < SemVer.new('1.3.3') }
# Different tiny versions
- it { should > SemVer.new('1.2.2') }
- it { should < SemVer.new('1.2.4') }
+ it { is_expected.to be > SemVer.new('1.2.2') }
+ it { is_expected.to be < SemVer.new('1.2.4') }
# Against special versions
- it { should > SemVer.new('1.2.3-beta') }
- it { should < SemVer.new('1.2.4-beta') }
+ it { is_expected.to be > SemVer.new('1.2.3-beta') }
+ it { is_expected.to be < SemVer.new('1.2.4-beta') }
end
describe 'on a special version (v1.2.3-beta)' do
subject { SemVer.new('v1.2.3-beta') }
- it { should == SemVer.new('1.2.3-beta') }
+ it { is_expected.to eq(SemVer.new('1.2.3-beta')) }
# Same version, final release
- it { should < SemVer.new('1.2.3') }
+ it { is_expected.to be < SemVer.new('1.2.3') }
# Different major versions
- it { should > SemVer.new('0.2.3') }
- it { should < SemVer.new('2.2.3') }
+ it { is_expected.to be > SemVer.new('0.2.3') }
+ it { is_expected.to be < SemVer.new('2.2.3') }
# Different minor versions
- it { should > SemVer.new('1.1.3') }
- it { should < SemVer.new('1.3.3') }
+ it { is_expected.to be > SemVer.new('1.1.3') }
+ it { is_expected.to be < SemVer.new('1.3.3') }
# Different tiny versions
- it { should > SemVer.new('1.2.2') }
- it { should < SemVer.new('1.2.4') }
+ it { is_expected.to be > SemVer.new('1.2.2') }
+ it { is_expected.to be < SemVer.new('1.2.4') }
# Against special versions
- it { should > SemVer.new('1.2.3-alpha') }
- it { should < SemVer.new('1.2.3-beta2') }
+ it { is_expected.to be > SemVer.new('1.2.3-alpha') }
+ it { is_expected.to be < SemVer.new('1.2.3-beta2') }
end
end
end
diff --git a/spec/unit/settings/config_file_spec.rb b/spec/unit/settings/config_file_spec.rb
index 9353eea3f..3de16ecc8 100644
--- a/spec/unit/settings/config_file_spec.rb
+++ b/spec/unit/settings/config_file_spec.rb
@@ -1,149 +1,149 @@
#! /usr/bin/env ruby -S rspec
require 'spec_helper'
require 'puppet/settings/config_file'
describe Puppet::Settings::ConfigFile do
NOTHING = {}
def the_parse_of(*lines)
config.parse_file(filename, lines.join("\n"))
end
let(:identity_transformer) { Proc.new { |value| value } }
let(:config) { Puppet::Settings::ConfigFile.new(identity_transformer) }
let(:filename) { "a/fake/filename.conf" }
Conf = Puppet::Settings::ConfigFile::Conf
Section = Puppet::Settings::ConfigFile::Section
Meta = Puppet::Settings::ConfigFile::Meta
NO_META = Puppet::Settings::ConfigFile::NO_META
it "interprets an empty file to contain a main section with no entries" do
result = the_parse_of("")
expect(result).to eq(Conf.new.with_section(Section.new(:main)))
end
it "interprets an empty main section the same as an empty file" do
- the_parse_of("").should == config.parse_file(filename, "[main]")
+ expect(the_parse_of("")).to eq(config.parse_file(filename, "[main]"))
end
it "places an entry in no section in main" do
result = the_parse_of("var = value")
expect(result).to eq(Conf.new.with_section(Section.new(:main).with_setting(:var, "value", NO_META)))
end
it "places an entry after a section header in that section" do
result = the_parse_of("[agent]", "var = value")
expect(result).to eq(Conf.new.
with_section(Section.new(:main)).
with_section(Section.new(:agent).
with_setting(:var, "value", NO_META)))
end
it "does not include trailing whitespace in the value" do
result = the_parse_of("var = value\t ")
expect(result).to eq(Conf.new.
with_section(Section.new(:main).
with_setting(:var, "value", NO_META)))
end
it "does not include leading whitespace in the name" do
result = the_parse_of(" \t var=value")
expect(result).to eq(Conf.new.
with_section(Section.new(:main).
with_setting(:var, "value", NO_META)))
end
it "skips lines that are commented out" do
result = the_parse_of("#var = value")
expect(result).to eq(Conf.new.with_section(Section.new(:main)))
end
it "skips lines that are entirely whitespace" do
result = the_parse_of(" \t ")
expect(result).to eq(Conf.new.with_section(Section.new(:main)))
end
it "errors when a line is not a known form" do
expect { the_parse_of("unknown") }.to raise_error Puppet::Settings::ParseError, /Could not match line/
end
it "errors providing correct line number when line is not a known form" do
multi_line_config = <<-EOF
[main]
foo=bar
badline
EOF
expect { the_parse_of(multi_line_config) }.to(
raise_error(Puppet::Settings::ParseError, /Could not match line/) do |exception|
expect(exception.line).to eq(3)
end
)
end
it "stores file meta information in the _meta section" do
result = the_parse_of("var = value { owner = me, group = you, mode = 0666 }")
expect(result).to eq(Conf.new.with_section(Section.new(:main).
with_setting(:var, "value",
Meta.new("me", "you", "0666"))))
end
it "errors when there is unknown meta information" do
expect { the_parse_of("var = value { unknown = no }") }.
to raise_error ArgumentError, /Invalid file option 'unknown'/
end
it "errors when the mode is not numeric" do
expect { the_parse_of("var = value { mode = no }") }.
to raise_error ArgumentError, "File modes must be numbers"
end
it "errors when the options are not key-value pairs" do
expect { the_parse_of("var = value { mode }") }.
to raise_error ArgumentError, "Could not parse 'value { mode }'"
end
it "may specify legal sections" do
text = <<-EOF
[legal]
a = 'b'
[illegal]
one = 'e'
two = 'f'
EOF
expect { config.parse_file(filename, text, [:legal]) }.
to raise_error Puppet::Error,
/Illegal section 'legal' in config file #{filename} at line 1/
end
it "transforms values with the given function" do
config = Puppet::Settings::ConfigFile.new(Proc.new { |value| value + " changed" })
result = config.parse_file(filename, "var = value")
expect(result).to eq(Conf.new.
with_section(Section.new(:main).
with_setting(:var, "value changed", NO_META)))
end
it "does not try to transform an entry named 'mode'" do
config = Puppet::Settings::ConfigFile.new(Proc.new { raise "Should not transform" })
result = config.parse_file(filename, "mode = value")
expect(result).to eq(Conf.new.
with_section(Section.new(:main).
with_setting(:mode, "value", NO_META)))
end
end
diff --git a/spec/unit/settings/directory_setting_spec.rb b/spec/unit/settings/directory_setting_spec.rb
index f08b4e1a9..13c5cfacb 100755
--- a/spec/unit/settings/directory_setting_spec.rb
+++ b/spec/unit/settings/directory_setting_spec.rb
@@ -1,32 +1,32 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/settings'
require 'puppet/settings/directory_setting'
describe Puppet::Settings::DirectorySetting do
DirectorySetting = Puppet::Settings::DirectorySetting
include PuppetSpec::Files
before do
@basepath = make_absolute("/somepath")
end
describe "when being converted to a resource" do
before do
@settings = mock 'settings'
@dir = Puppet::Settings::DirectorySetting.new(
:settings => @settings, :desc => "eh", :name => :mydir, :section => "mysect")
@settings.stubs(:value).with(:mydir).returns @basepath
end
it "should return :directory as its type" do
- @dir.type.should == :directory
+ expect(@dir.type).to eq(:directory)
end
end
end
diff --git a/spec/unit/settings/duration_setting_spec.rb b/spec/unit/settings/duration_setting_spec.rb
index 92cd428e7..bde8e3b1e 100755
--- a/spec/unit/settings/duration_setting_spec.rb
+++ b/spec/unit/settings/duration_setting_spec.rb
@@ -1,49 +1,49 @@
#!/usr/bin/env ruby
require 'spec_helper'
require 'puppet/settings'
require 'puppet/settings/duration_setting'
describe Puppet::Settings::DurationSetting do
subject { described_class.new(:settings => mock('settings'), :desc => "test") }
describe "when munging the setting" do
it "should return the same value if given an integer" do
- subject.munge(5).should == 5
+ expect(subject.munge(5)).to eq(5)
end
it "should return the same value if given nil" do
- subject.munge(nil).should be_nil
+ expect(subject.munge(nil)).to be_nil
end
it "should return an integer if given a decimal string" do
- subject.munge("12").should == 12
+ expect(subject.munge("12")).to eq(12)
end
it "should fail if given anything but a well-formed string, integer, or nil" do
[ '', 'foo', '2 d', '2d ', true, Time.now, 8.3, [] ].each do |value|
expect { subject.munge(value) }.to raise_error(Puppet::Settings::ValidationError)
end
end
it "should parse strings with units of 'y', 'd', 'h', 'm', or 's'" do
# Note: the year value won't jive with most methods of calculating
# year due to the Julian calandar having 365.25 days in a year
{
'3y' => 94608000,
'3d' => 259200,
'3h' => 10800,
'3m' => 180,
'3s' => 3
}.each do |value, converted_value|
# subject.munge(value).should == converted_value
- subject.munge(value).should == converted_value
+ expect(subject.munge(value)).to eq(converted_value)
end
end
# This is to support the `filetimeout` setting
it "should allow negative values" do
- subject.munge(-1).should == -1
+ expect(subject.munge(-1)).to eq(-1)
end
end
end
diff --git a/spec/unit/settings/file_setting_spec.rb b/spec/unit/settings/file_setting_spec.rb
index c77cc5981..90badcedb 100755
--- a/spec/unit/settings/file_setting_spec.rb
+++ b/spec/unit/settings/file_setting_spec.rb
@@ -1,298 +1,298 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/settings'
require 'puppet/settings/file_setting'
describe Puppet::Settings::FileSetting do
FileSetting = Puppet::Settings::FileSetting
include PuppetSpec::Files
describe "when controlling permissions" do
def settings(wanted_values = {})
real_values = {
:user => 'root',
:group => 'root',
:mkusers => false,
:service_user_available? => false,
:service_group_available? => false
}.merge(wanted_values)
settings = mock("settings")
settings.stubs(:[]).with(:user).returns real_values[:user]
settings.stubs(:[]).with(:group).returns real_values[:group]
settings.stubs(:[]).with(:mkusers).returns real_values[:mkusers]
settings.stubs(:service_user_available?).returns real_values[:service_user_available?]
settings.stubs(:service_group_available?).returns real_values[:service_group_available?]
settings
end
context "owner" do
it "can always be root" do
settings = settings(:user => "the_service", :mkusers => true)
setting = FileSetting.new(:settings => settings, :owner => "root", :desc => "a setting")
- setting.owner.should == "root"
+ expect(setting.owner).to eq("root")
end
it "is the service user if we are making users" do
settings = settings(:user => "the_service", :mkusers => true, :service_user_available? => false)
setting = FileSetting.new(:settings => settings, :owner => "service", :desc => "a setting")
- setting.owner.should == "the_service"
+ expect(setting.owner).to eq("the_service")
end
it "is the service user if the user is available on the system" do
settings = settings(:user => "the_service", :mkusers => false, :service_user_available? => true)
setting = FileSetting.new(:settings => settings, :owner => "service", :desc => "a setting")
- setting.owner.should == "the_service"
+ expect(setting.owner).to eq("the_service")
end
it "is root when the setting specifies service and the user is not available on the system" do
settings = settings(:user => "the_service", :mkusers => false, :service_user_available? => false)
setting = FileSetting.new(:settings => settings, :owner => "service", :desc => "a setting")
- setting.owner.should == "root"
+ expect(setting.owner).to eq("root")
end
it "is unspecified when no specific owner is wanted" do
- FileSetting.new(:settings => settings(), :desc => "a setting").owner.should be_nil
+ expect(FileSetting.new(:settings => settings(), :desc => "a setting").owner).to be_nil
end
it "does not allow other owners" do
expect { FileSetting.new(:settings => settings(), :desc => "a setting", :name => "testing", :default => "the default", :owner => "invalid") }.
to raise_error(FileSetting::SettingError, /The :owner parameter for the setting 'testing' must be either 'root' or 'service'/)
end
end
context "group" do
it "is unspecified when no specific group is wanted" do
setting = FileSetting.new(:settings => settings(), :desc => "a setting")
- setting.group.should be_nil
+ expect(setting.group).to be_nil
end
it "is root if root is requested" do
settings = settings(:group => "the_group")
setting = FileSetting.new(:settings => settings, :group => "root", :desc => "a setting")
- setting.group.should == "root"
+ expect(setting.group).to eq("root")
end
it "is the service group if we are making users" do
settings = settings(:group => "the_service", :mkusers => true)
setting = FileSetting.new(:settings => settings, :group => "service", :desc => "a setting")
- setting.group.should == "the_service"
+ expect(setting.group).to eq("the_service")
end
it "is the service user if the group is available on the system" do
settings = settings(:group => "the_service", :mkusers => false, :service_group_available? => true)
setting = FileSetting.new(:settings => settings, :group => "service", :desc => "a setting")
- setting.group.should == "the_service"
+ expect(setting.group).to eq("the_service")
end
it "is unspecified when the setting specifies service and the group is not available on the system" do
settings = settings(:group => "the_service", :mkusers => false, :service_group_available? => false)
setting = FileSetting.new(:settings => settings, :group => "service", :desc => "a setting")
- setting.group.should be_nil
+ expect(setting.group).to be_nil
end
it "does not allow other groups" do
expect { FileSetting.new(:settings => settings(), :group => "invalid", :name => 'testing', :desc => "a setting") }.
to raise_error(FileSetting::SettingError, /The :group parameter for the setting 'testing' must be either 'root' or 'service'/)
end
end
end
it "should be able to be converted into a resource" do
- FileSetting.new(:settings => mock("settings"), :desc => "eh").should respond_to(:to_resource)
+ expect(FileSetting.new(:settings => mock("settings"), :desc => "eh")).to respond_to(:to_resource)
end
describe "when being converted to a resource" do
before do
@basepath = make_absolute("/somepath")
@settings = mock 'settings'
@file = Puppet::Settings::FileSetting.new(:settings => @settings, :desc => "eh", :name => :myfile, :section => "mysect")
@file.stubs(:create_files?).returns true
@settings.stubs(:value).with(:myfile, nil, false).returns @basepath
end
it "should return :file as its type" do
- @file.type.should == :file
+ expect(@file.type).to eq(:file)
end
it "should skip non-existent files if 'create_files' is not enabled" do
@file.expects(:create_files?).returns false
@file.expects(:type).returns :file
Puppet::FileSystem.expects(:exist?).with(@basepath).returns false
- @file.to_resource.should be_nil
+ expect(@file.to_resource).to be_nil
end
it "should manage existent files even if 'create_files' is not enabled" do
@file.expects(:create_files?).returns false
@file.expects(:type).returns :file
Puppet::FileSystem.stubs(:exist?)
Puppet::FileSystem.expects(:exist?).with(@basepath).returns true
- @file.to_resource.should be_instance_of(Puppet::Resource)
+ expect(@file.to_resource).to be_instance_of(Puppet::Resource)
end
describe "on POSIX systems", :if => Puppet.features.posix? do
it "should skip files in /dev" do
@settings.stubs(:value).with(:myfile, nil, false).returns "/dev/file"
- @file.to_resource.should be_nil
+ expect(@file.to_resource).to be_nil
end
end
it "should skip files whose paths are not strings" do
@settings.stubs(:value).with(:myfile, nil, false).returns :foo
- @file.to_resource.should be_nil
+ expect(@file.to_resource).to be_nil
end
it "should return a file resource with the path set appropriately" do
resource = @file.to_resource
- resource.type.should == "File"
- resource.title.should == @basepath
+ expect(resource.type).to eq("File")
+ expect(resource.title).to eq(@basepath)
end
it "should fully qualified returned files if necessary (#795)" do
@settings.stubs(:value).with(:myfile, nil, false).returns "myfile"
path = File.expand_path('myfile')
- @file.to_resource.title.should == path
+ expect(@file.to_resource.title).to eq(path)
end
it "should set the mode on the file if a mode is provided as an octal number" do
@file.mode = 0755
- @file.to_resource[:mode].should == '755'
+ expect(@file.to_resource[:mode]).to eq('755')
end
it "should set the mode on the file if a mode is provided as a string" do
@file.mode = '0755'
- @file.to_resource[:mode].should == '755'
+ expect(@file.to_resource[:mode]).to eq('755')
end
it "should not set the mode on a the file if manage_internal_file_permissions is disabled" do
Puppet[:manage_internal_file_permissions] = false
@file.stubs(:mode).returns(0755)
- @file.to_resource[:mode].should == nil
+ expect(@file.to_resource[:mode]).to eq(nil)
end
it "should set the owner if running as root and the owner is provided" do
Puppet.features.expects(:root?).returns true
Puppet.features.stubs(:microsoft_windows?).returns false
@file.stubs(:owner).returns "foo"
- @file.to_resource[:owner].should == "foo"
+ expect(@file.to_resource[:owner]).to eq("foo")
end
it "should not set the owner if manage_internal_file_permissions is disabled" do
Puppet[:manage_internal_file_permissions] = false
Puppet.features.stubs(:root?).returns true
@file.stubs(:owner).returns "foo"
- @file.to_resource[:owner].should == nil
+ expect(@file.to_resource[:owner]).to eq(nil)
end
it "should set the group if running as root and the group is provided" do
Puppet.features.expects(:root?).returns true
Puppet.features.stubs(:microsoft_windows?).returns false
@file.stubs(:group).returns "foo"
- @file.to_resource[:group].should == "foo"
+ expect(@file.to_resource[:group]).to eq("foo")
end
it "should not set the group if manage_internal_file_permissions is disabled" do
Puppet[:manage_internal_file_permissions] = false
Puppet.features.stubs(:root?).returns true
@file.stubs(:group).returns "foo"
- @file.to_resource[:group].should == nil
+ expect(@file.to_resource[:group]).to eq(nil)
end
it "should not set owner if not running as root" do
Puppet.features.expects(:root?).returns false
Puppet.features.stubs(:microsoft_windows?).returns false
@file.stubs(:owner).returns "foo"
- @file.to_resource[:owner].should be_nil
+ expect(@file.to_resource[:owner]).to be_nil
end
it "should not set group if not running as root" do
Puppet.features.expects(:root?).returns false
Puppet.features.stubs(:microsoft_windows?).returns false
@file.stubs(:group).returns "foo"
- @file.to_resource[:group].should be_nil
+ expect(@file.to_resource[:group]).to be_nil
end
describe "on Microsoft Windows systems" do
before :each do
Puppet.features.stubs(:microsoft_windows?).returns true
end
it "should not set owner" do
@file.stubs(:owner).returns "foo"
- @file.to_resource[:owner].should be_nil
+ expect(@file.to_resource[:owner]).to be_nil
end
it "should not set group" do
@file.stubs(:group).returns "foo"
- @file.to_resource[:group].should be_nil
+ expect(@file.to_resource[:group]).to be_nil
end
end
it "should set :ensure to the file type" do
@file.expects(:type).returns :directory
- @file.to_resource[:ensure].should == :directory
+ expect(@file.to_resource[:ensure]).to eq(:directory)
end
it "should set the loglevel to :debug" do
- @file.to_resource[:loglevel].should == :debug
+ expect(@file.to_resource[:loglevel]).to eq(:debug)
end
it "should set the backup to false" do
- @file.to_resource[:backup].should be_false
+ expect(@file.to_resource[:backup]).to be_falsey
end
it "should tag the resource with the settings section" do
@file.expects(:section).returns "mysect"
- @file.to_resource.should be_tagged("mysect")
+ expect(@file.to_resource).to be_tagged("mysect")
end
it "should tag the resource with the setting name" do
- @file.to_resource.should be_tagged("myfile")
+ expect(@file.to_resource).to be_tagged("myfile")
end
it "should tag the resource with 'settings'" do
- @file.to_resource.should be_tagged("settings")
+ expect(@file.to_resource).to be_tagged("settings")
end
it "should set links to 'follow'" do
- @file.to_resource[:links].should == :follow
+ expect(@file.to_resource[:links]).to eq(:follow)
end
end
describe "#munge" do
it 'does not expand the path of the special value :memory: so we can set dblocation to an in-memory database' do
filesetting = FileSetting.new(:settings => mock("settings"), :desc => "eh")
- filesetting.munge(':memory:').should == ':memory:'
+ expect(filesetting.munge(':memory:')).to eq(':memory:')
end
end
end
diff --git a/spec/unit/settings/path_setting_spec.rb b/spec/unit/settings/path_setting_spec.rb
index b7bc3198c..ee1ec4b0b 100755
--- a/spec/unit/settings/path_setting_spec.rb
+++ b/spec/unit/settings/path_setting_spec.rb
@@ -1,30 +1,30 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Settings::PathSetting do
subject { described_class.new(:settings => mock('settings'), :desc => "test") }
context "#munge" do
it "should expand all path elements" do
munged = subject.munge("hello#{File::PATH_SEPARATOR}good/morning#{File::PATH_SEPARATOR}goodbye")
munged.split(File::PATH_SEPARATOR).each do |p|
- Puppet::Util.should be_absolute_path(p)
+ expect(Puppet::Util).to be_absolute_path(p)
end
end
it "should leave nil as nil" do
- subject.munge(nil).should be_nil
+ expect(subject.munge(nil)).to be_nil
end
context "on Windows", :if => Puppet.features.microsoft_windows? do
it "should convert \\ to /" do
- subject.munge('C:\test\directory').should == 'C:/test/directory'
+ expect(subject.munge('C:\test\directory')).to eq('C:/test/directory')
end
it "should work with UNC paths" do
- subject.munge('//localhost/some/path').should == '//localhost/some/path'
- subject.munge('\\\\localhost\some\path').should == '//localhost/some/path'
+ expect(subject.munge('//localhost/some/path')).to eq('//localhost/some/path')
+ expect(subject.munge('\\\\localhost\some\path')).to eq('//localhost/some/path')
end
end
end
end
diff --git a/spec/unit/settings/priority_setting_spec.rb b/spec/unit/settings/priority_setting_spec.rb
index 62cad5def..f6ba6b3df 100755
--- a/spec/unit/settings/priority_setting_spec.rb
+++ b/spec/unit/settings/priority_setting_spec.rb
@@ -1,66 +1,66 @@
#!/usr/bin/env ruby
require 'spec_helper'
require 'puppet/settings'
require 'puppet/settings/priority_setting'
require 'puppet/util/platform'
describe Puppet::Settings::PrioritySetting do
let(:setting) { described_class.new(:settings => mock('settings'), :desc => "test") }
it "is of type :priority" do
- setting.type.should == :priority
+ expect(setting.type).to eq(:priority)
end
describe "when munging the setting" do
it "passes nil through" do
- setting.munge(nil).should be_nil
+ expect(setting.munge(nil)).to be_nil
end
it "returns the same value if given an integer" do
- setting.munge(5).should == 5
+ expect(setting.munge(5)).to eq(5)
end
it "returns an integer if given a decimal string" do
- setting.munge('12').should == 12
+ expect(setting.munge('12')).to eq(12)
end
it "returns a negative integer if given a negative integer string" do
- setting.munge('-5').should == -5
+ expect(setting.munge('-5')).to eq(-5)
end
it "fails if given anything else" do
[ 'foo', 'realtime', true, 8.3, [] ].each do |value|
expect {
setting.munge(value)
}.to raise_error(Puppet::Settings::ValidationError)
end
end
describe "on a Unix-like platform it", :unless => Puppet::Util::Platform.windows? do
it "parses high, normal, low, and idle priorities" do
{
'high' => -10,
'normal' => 0,
'low' => 10,
'idle' => 19
}.each do |value, converted_value|
- setting.munge(value).should == converted_value
+ expect(setting.munge(value)).to eq(converted_value)
end
end
end
describe "on a Windows-like platform it", :if => Puppet::Util::Platform.windows? do
it "parses high, normal, low, and idle priorities" do
{
'high' => Puppet::Util::Windows::Process::HIGH_PRIORITY_CLASS,
'normal' => Puppet::Util::Windows::Process::NORMAL_PRIORITY_CLASS,
'low' => Puppet::Util::Windows::Process::BELOW_NORMAL_PRIORITY_CLASS,
'idle' => Puppet::Util::Windows::Process::IDLE_PRIORITY_CLASS
}.each do |value, converted_value|
- setting.munge(value).should == converted_value
+ expect(setting.munge(value)).to eq(converted_value)
end
end
end
end
end
diff --git a/spec/unit/settings/string_setting_spec.rb b/spec/unit/settings/string_setting_spec.rb
index cba80ee84..62319dbad 100644
--- a/spec/unit/settings/string_setting_spec.rb
+++ b/spec/unit/settings/string_setting_spec.rb
@@ -1,75 +1,75 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/settings'
require 'puppet/settings/string_setting'
describe Puppet::Settings::StringSetting do
StringSetting = Puppet::Settings::StringSetting
before(:each) do
@test_setting_name = :test_setting
@test_setting_default = "my_crazy_default/$var"
@application_setting = "application/$var"
@application_defaults = { }
Puppet::Settings::REQUIRED_APP_SETTINGS.each do |key|
@application_defaults[key] = "foo"
end
@application_defaults[:run_mode] = :user
@settings = Puppet::Settings.new
@application_defaults.each { |k,v| @settings.define_settings :main, k => {:default=>"", :desc => "blah"} }
@settings.define_settings :main, :var => { :default => "interpolate!",
:type => :string,
:desc => "my var desc" },
@test_setting_name => { :default => @test_setting_default,
:type => :string,
:desc => "my test desc" }
@test_setting = @settings.setting(@test_setting_name)
end
describe "#default" do
describe "with no arguments" do
it "should return the setting default" do
- @test_setting.default.should == @test_setting_default
+ expect(@test_setting.default).to eq(@test_setting_default)
end
it "should be uninterpolated" do
- @test_setting.default.should_not =~ /interpolate/
+ expect(@test_setting.default).not_to match(/interpolate/)
end
end
describe "checking application defaults first" do
describe "if application defaults set" do
before(:each) do
@settings.initialize_app_defaults @application_defaults.merge @test_setting_name => @application_setting
end
it "should return the application-set default" do
- @test_setting.default(true).should == @application_setting
+ expect(@test_setting.default(true)).to eq(@application_setting)
end
it "should be uninterpolated" do
- @test_setting.default(true).should_not =~ /interpolate/
+ expect(@test_setting.default(true)).not_to match(/interpolate/)
end
end
describe "if application defaults not set" do
it "should return the regular default" do
- @test_setting.default(true).should == @test_setting_default
+ expect(@test_setting.default(true)).to eq(@test_setting_default)
end
it "should be uninterpolated" do
- @test_setting.default(true).should_not =~ /interpolate/
+ expect(@test_setting.default(true)).not_to match(/interpolate/)
end
end
end
end
describe "#value" do
it "should be interpolated" do
- @test_setting.value.should =~ /interpolate/
+ expect(@test_setting.value).to match(/interpolate/)
end
end
end
diff --git a/spec/unit/settings/terminus_setting_spec.rb b/spec/unit/settings/terminus_setting_spec.rb
index 6b8828cf9..cde525c29 100644
--- a/spec/unit/settings/terminus_setting_spec.rb
+++ b/spec/unit/settings/terminus_setting_spec.rb
@@ -1,28 +1,28 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Settings::TerminusSetting do
let(:setting) { described_class.new(:settings => mock('settings'), :desc => "test") }
describe "#munge" do
it "converts strings to symbols" do
- setting.munge("string").should == :string
+ expect(setting.munge("string")).to eq(:string)
end
it "converts '' to nil" do
- setting.munge('').should be_nil
+ expect(setting.munge('')).to be_nil
end
it "preserves symbols" do
- setting.munge(:symbol).should == :symbol
+ expect(setting.munge(:symbol)).to eq(:symbol)
end
it "preserves nil" do
- setting.munge(nil).should be_nil
+ expect(setting.munge(nil)).to be_nil
end
it "does not allow unknown types through" do
expect { setting.munge(["not a terminus type"]) }.to raise_error Puppet::Settings::ValidationError
end
end
end
diff --git a/spec/unit/settings/value_translator_spec.rb b/spec/unit/settings/value_translator_spec.rb
index a2464c045..b86d70f3a 100644
--- a/spec/unit/settings/value_translator_spec.rb
+++ b/spec/unit/settings/value_translator_spec.rb
@@ -1,77 +1,77 @@
#! /usr/bin/env ruby -S rspec
require 'spec_helper'
require 'puppet/settings/value_translator'
describe Puppet::Settings::ValueTranslator do
let(:translator) { Puppet::Settings::ValueTranslator.new }
context "booleans" do
it "translates strings representing booleans to booleans" do
- translator['true'].should == true
- translator['false'].should == false
+ expect(translator['true']).to eq(true)
+ expect(translator['false']).to eq(false)
end
it "translates boolean values into themselves" do
- translator[true].should == true
- translator[false].should == false
+ expect(translator[true]).to eq(true)
+ expect(translator[false]).to eq(false)
end
it "leaves a boolean string with whitespace as a string" do
- translator[' true'].should == " true"
- translator['true '].should == "true"
+ expect(translator[' true']).to eq(" true")
+ expect(translator['true ']).to eq("true")
- translator[' false'].should == " false"
- translator['false '].should == "false"
+ expect(translator[' false']).to eq(" false")
+ expect(translator['false ']).to eq("false")
end
end
context "numbers" do
it "translates integer strings to integers" do
- translator["1"].should == 1
- translator["2"].should == 2
+ expect(translator["1"]).to eq(1)
+ expect(translator["2"]).to eq(2)
end
it "translates numbers starting with a 0 as octal" do
- translator["011"].should == 9
+ expect(translator["011"]).to eq(9)
end
it "leaves hex numbers as strings" do
- translator["0x11"].should == "0x11"
+ expect(translator["0x11"]).to eq("0x11")
end
end
context "arbitrary strings" do
it "translates an empty string as the empty string" do
- translator[""].should == ""
+ expect(translator[""]).to eq("")
end
it "strips double quotes" do
- translator['"a string"'].should == 'a string'
+ expect(translator['"a string"']).to eq('a string')
end
it "strips single quotes" do
- translator["'a string'"].should == "a string"
+ expect(translator["'a string'"]).to eq("a string")
end
it "does not strip preceding whitespace" do
- translator[" \ta string"].should == " \ta string"
+ expect(translator[" \ta string"]).to eq(" \ta string")
end
it "strips trailing whitespace" do
- translator["a string\t "].should == "a string"
+ expect(translator["a string\t "]).to eq("a string")
end
it "leaves leading quote that is preceded by whitespace" do
- translator[" 'a string'"].should == " 'a string"
+ expect(translator[" 'a string'"]).to eq(" 'a string")
end
it "leaves trailing quote that is succeeded by whitespace" do
- translator["'a string' "].should == "a string'"
+ expect(translator["'a string' "]).to eq("a string'")
end
it "leaves quotes that are not at the beginning or end of the string" do
- translator["a st'\"ring"].should == "a st'\"ring"
+ expect(translator["a st'\"ring"]).to eq("a st'\"ring")
end
end
end
diff --git a/spec/unit/settings_spec.rb b/spec/unit/settings_spec.rb
index 95d1ceb7a..971b63f28 100755
--- a/spec/unit/settings_spec.rb
+++ b/spec/unit/settings_spec.rb
@@ -1,1750 +1,1750 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'ostruct'
require 'puppet/settings/errors'
require 'puppet_spec/files'
require 'matchers/resource'
describe Puppet::Settings do
include PuppetSpec::Files
include Matchers::Resource
let(:main_config_file_default_location) do
File.join(Puppet::Util::RunMode[:master].conf_dir, "puppet.conf")
end
let(:user_config_file_default_location) do
File.join(Puppet::Util::RunMode[:user].conf_dir, "puppet.conf")
end
# Return a given object's file metadata.
def metadata(setting)
if setting.is_a?(Puppet::Settings::FileSetting)
{
:owner => setting.owner,
:group => setting.group,
:mode => setting.mode
}.delete_if { |key, value| value.nil? }
else
nil
end
end
describe "when specifying defaults" do
before do
@settings = Puppet::Settings.new
end
it "should start with no defined sections or parameters" do
# Note this relies on undocumented side effect that eachsection returns the Settings internal
# configuration on which keys returns all parameters.
- @settings.eachsection.keys.length.should == 0
+ expect(@settings.eachsection.keys.length).to eq(0)
end
it "should not allow specification of default values associated with a section as an array" do
expect {
@settings.define_settings(:section, :myvalue => ["defaultval", "my description"])
}.to raise_error
end
it "should not allow duplicate parameter specifications" do
@settings.define_settings(:section, :myvalue => { :default => "a", :desc => "b" })
- lambda { @settings.define_settings(:section, :myvalue => { :default => "c", :desc => "d" }) }.should raise_error(ArgumentError)
+ expect { @settings.define_settings(:section, :myvalue => { :default => "c", :desc => "d" }) }.to raise_error(ArgumentError)
end
it "should allow specification of default values associated with a section as a hash" do
@settings.define_settings(:section, :myvalue => {:default => "defaultval", :desc => "my description"})
end
it "should consider defined parameters to be valid" do
@settings.define_settings(:section, :myvalue => { :default => "defaultval", :desc => "my description" })
- @settings.valid?(:myvalue).should be_true
+ expect(@settings.valid?(:myvalue)).to be_truthy
end
it "should require a description when defaults are specified with a hash" do
- lambda { @settings.define_settings(:section, :myvalue => {:default => "a value"}) }.should raise_error(ArgumentError)
+ expect { @settings.define_settings(:section, :myvalue => {:default => "a value"}) }.to raise_error(ArgumentError)
end
it "should support specifying owner, group, and mode when specifying files" do
@settings.define_settings(:section, :myvalue => {:type => :file, :default => "/some/file", :owner => "service", :mode => "boo", :group => "service", :desc => "whatever"})
end
it "should support specifying a short name" do
@settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :short => "m"})
end
it "should support specifying the setting type" do
@settings.define_settings(:section, :myvalue => {:default => "/w", :desc => "b", :type => :string})
- @settings.setting(:myvalue).should be_instance_of(Puppet::Settings::StringSetting)
+ expect(@settings.setting(:myvalue)).to be_instance_of(Puppet::Settings::StringSetting)
end
it "should fail if an invalid setting type is specified" do
- lambda { @settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :type => :foo}) }.should raise_error(ArgumentError)
+ expect { @settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :type => :foo}) }.to raise_error(ArgumentError)
end
it "should fail when short names conflict" do
@settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :short => "m"})
- lambda { @settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :short => "m"}) }.should raise_error(ArgumentError)
+ expect { @settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :short => "m"}) }.to raise_error(ArgumentError)
end
end
describe "when initializing application defaults do" do
let(:default_values) do
values = {}
PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS.keys.each do |key|
values[key] = 'default value'
end
values
end
before do
@settings = Puppet::Settings.new
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
end
it "should fail if the app defaults hash is missing any required values" do
incomplete_default_values = default_values.reject { |key, _| key == :confdir }
expect {
@settings.initialize_app_defaults(default_values.reject { |key, _| key == :confdir })
}.to raise_error(Puppet::Settings::SettingsError)
end
# ultimately I'd like to stop treating "run_mode" as a normal setting, because it has so many special
# case behaviors / uses. However, until that time... we need to make sure that our private run_mode=
# setter method gets properly called during app initialization.
it "sets the preferred run mode when initializing the app defaults" do
@settings.initialize_app_defaults(default_values.merge(:run_mode => :master))
- @settings.preferred_run_mode.should == :master
+ expect(@settings.preferred_run_mode).to eq(:master)
end
end
describe "#call_hooks_deferred_to_application_initialization" do
let(:good_default) { "yay" }
let(:bad_default) { "$doesntexist" }
before(:each) do
@settings = Puppet::Settings.new
end
describe "when ignoring dependency interpolation errors" do
let(:options) { {:ignore_interpolation_dependency_errors => true} }
describe "if interpolation error" do
it "should not raise an error" do
hook_values = []
@settings.define_settings(:section, :badhook => {:default => bad_default, :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v }})
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to_not raise_error
end
end
describe "if no interpolation error" do
it "should not raise an error" do
hook_values = []
@settings.define_settings(:section, :goodhook => {:default => good_default, :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v }})
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to_not raise_error
end
end
end
describe "when not ignoring dependency interpolation errors" do
[ {}, {:ignore_interpolation_dependency_errors => false}].each do |options|
describe "if interpolation error" do
it "should raise an error" do
hook_values = []
@settings.define_settings(
:section,
:badhook => {
:default => bad_default,
:desc => "boo",
:call_hook => :on_initialize_and_write,
:hook => lambda { |v| hook_values << v }
}
)
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to raise_error(Puppet::Settings::InterpolationError)
end
it "should contain the setting name in error message" do
hook_values = []
@settings.define_settings(
:section,
:badhook => {
:default => bad_default,
:desc => "boo",
:call_hook => :on_initialize_and_write,
:hook => lambda { |v| hook_values << v }
}
)
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to raise_error(Puppet::Settings::InterpolationError, /badhook/)
end
end
describe "if no interpolation error" do
it "should not raise an error" do
hook_values = []
@settings.define_settings(
:section,
:goodhook => {
:default => good_default,
:desc => "boo",
:call_hook => :on_initialize_and_write,
:hook => lambda { |v| hook_values << v }
}
)
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to_not raise_error
end
end
end
end
end
describe "when setting values" do
before do
@settings = Puppet::Settings.new
@settings.define_settings :main, :myval => { :default => "val", :desc => "desc" }
@settings.define_settings :main, :bool => { :type => :boolean, :default => true, :desc => "desc" }
end
it "should provide a method for setting values from other objects" do
@settings[:myval] = "something else"
- @settings[:myval].should == "something else"
+ expect(@settings[:myval]).to eq("something else")
end
it "should support a getopt-specific mechanism for setting values" do
@settings.handlearg("--myval", "newval")
- @settings[:myval].should == "newval"
+ expect(@settings[:myval]).to eq("newval")
end
it "should support a getopt-specific mechanism for turning booleans off" do
@settings.override_default(:bool, true)
@settings.handlearg("--no-bool", "")
- @settings[:bool].should == false
+ expect(@settings[:bool]).to eq(false)
end
it "should support a getopt-specific mechanism for turning booleans on" do
# Turn it off first
@settings.override_default(:bool, false)
@settings.handlearg("--bool", "")
- @settings[:bool].should == true
+ expect(@settings[:bool]).to eq(true)
end
it "should consider a cli setting with no argument to be a boolean" do
# Turn it off first
@settings.override_default(:bool, false)
@settings.handlearg("--bool")
- @settings[:bool].should == true
+ expect(@settings[:bool]).to eq(true)
end
it "should consider a cli setting with an empty string as an argument to be an empty argument, if the setting itself is not a boolean" do
@settings.override_default(:myval, "bob")
@settings.handlearg("--myval", "")
- @settings[:myval].should == ""
+ expect(@settings[:myval]).to eq("")
end
it "should consider a cli setting with a boolean as an argument to be a boolean" do
# Turn it off first
@settings.override_default(:bool, false)
@settings.handlearg("--bool", "true")
- @settings[:bool].should == true
+ expect(@settings[:bool]).to eq(true)
end
it "should not consider a cli setting of a non boolean with a boolean as an argument to be a boolean" do
@settings.override_default(:myval, "bob")
@settings.handlearg("--no-myval", "")
- @settings[:myval].should == ""
+ expect(@settings[:myval]).to eq("")
end
it "should flag string settings from the CLI" do
@settings.handlearg("--myval", "12")
- @settings.set_by_cli?(:myval).should be_true
+ expect(@settings.set_by_cli?(:myval)).to be_truthy
end
it "should flag bool settings from the CLI" do
@settings.handlearg("--bool")
- @settings.set_by_cli?(:bool).should be_true
+ expect(@settings.set_by_cli?(:bool)).to be_truthy
end
it "should not flag settings memory as from CLI" do
@settings[:myval] = "12"
- @settings.set_by_cli?(:myval).should be_false
+ expect(@settings.set_by_cli?(:myval)).to be_falsey
end
it "should clear the cache when setting getopt-specific values" do
@settings.define_settings :mysection,
:one => { :default => "whah", :desc => "yay" },
:two => { :default => "$one yay", :desc => "bah" }
@settings.expects(:unsafe_flush_cache)
- @settings[:two].should == "whah yay"
+ expect(@settings[:two]).to eq("whah yay")
@settings.handlearg("--one", "else")
- @settings[:two].should == "else yay"
+ expect(@settings[:two]).to eq("else yay")
end
it "should clear the cache when the preferred_run_mode is changed" do
@settings.expects(:flush_cache)
@settings.preferred_run_mode = :master
end
it "should not clear other values when setting getopt-specific values" do
@settings[:myval] = "yay"
@settings.handlearg("--no-bool", "")
- @settings[:myval].should == "yay"
+ expect(@settings[:myval]).to eq("yay")
end
it "should clear the list of used sections" do
@settings.expects(:clearused)
@settings[:myval] = "yay"
end
describe "call_hook" do
Puppet::Settings::StringSetting.available_call_hook_values.each do |val|
describe "when :#{val}" do
describe "and definition invalid" do
it "should raise error if no hook defined" do
expect do
@settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => val})
end.to raise_error(ArgumentError, /no :hook/)
end
it "should include the setting name in the error message" do
expect do
@settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => val})
end.to raise_error(ArgumentError, /for :hooker/)
end
end
describe "and definition valid" do
before(:each) do
hook_values = []
@settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => val, :hook => lambda { |v| hook_values << v }})
end
it "should call the hook when value written" do
@settings.setting(:hooker).expects(:handle).with("something").once
@settings[:hooker] = "something"
end
end
end
end
it "should have a default value of :on_write_only" do
@settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :hook => lambda { |v| hook_values << v }})
- @settings.setting(:hooker).call_hook.should == :on_write_only
+ expect(@settings.setting(:hooker).call_hook).to eq(:on_write_only)
end
describe "when nil" do
it "should generate a warning" do
Puppet.expects(:warning)
@settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => nil, :hook => lambda { |v| hook_values << v }})
end
it "should use default" do
@settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => nil, :hook => lambda { |v| hook_values << v }})
- @settings.setting(:hooker).call_hook.should == :on_write_only
+ expect(@settings.setting(:hooker).call_hook).to eq(:on_write_only)
end
end
describe "when invalid" do
it "should raise an error" do
expect do
@settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => :foo, :hook => lambda { |v| hook_values << v }})
end.to raise_error(ArgumentError, /invalid.*call_hook/i)
end
end
describe "when :on_define_and_write" do
it "should call the hook at definition" do
hook_values = []
@settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| hook_values << v }})
- @settings.setting(:hooker).call_hook.should == :on_define_and_write
- hook_values.should == %w{yay}
+ expect(@settings.setting(:hooker).call_hook).to eq(:on_define_and_write)
+ expect(hook_values).to eq(%w{yay})
end
end
describe "when :on_initialize_and_write" do
before(:each) do
@hook_values = []
@settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| @hook_values << v }})
end
it "should not call the hook at definition" do
- @hook_values.should == []
- @hook_values.should_not == %w{yay}
+ expect(@hook_values).to eq([])
+ expect(@hook_values).not_to eq(%w{yay})
end
it "should call the hook at initialization" do
app_defaults = {}
Puppet::Settings::REQUIRED_APP_SETTINGS.each do |key|
app_defaults[key] = "foo"
end
app_defaults[:run_mode] = :user
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
@settings.setting(:hooker).expects(:handle).with("yay").once
@settings.initialize_app_defaults app_defaults
end
end
end
it "should call passed blocks when values are set" do
values = []
@settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :hook => lambda { |v| values << v }})
- values.should == []
+ expect(values).to eq([])
@settings[:hooker] = "something"
- values.should == %w{something}
+ expect(values).to eq(%w{something})
end
it "should call passed blocks when values are set via the command line" do
values = []
@settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :hook => lambda { |v| values << v }})
- values.should == []
+ expect(values).to eq([])
@settings.handlearg("--hooker", "yay")
- values.should == %w{yay}
+ expect(values).to eq(%w{yay})
end
it "should provide an option to call passed blocks during definition" do
values = []
@settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| values << v }})
- values.should == %w{yay}
+ expect(values).to eq(%w{yay})
end
it "should pass the fully interpolated value to the hook when called on definition" do
values = []
@settings.define_settings(:section, :one => { :default => "test", :desc => "a" })
@settings.define_settings(:section, :hooker => {:default => "$one/yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| values << v }})
- values.should == %w{test/yay}
+ expect(values).to eq(%w{test/yay})
end
it "should munge values using the setting-specific methods" do
@settings[:bool] = "false"
- @settings[:bool].should == false
+ expect(@settings[:bool]).to eq(false)
end
it "should prefer values set in ruby to values set on the cli" do
@settings[:myval] = "memarg"
@settings.handlearg("--myval", "cliarg")
- @settings[:myval].should == "memarg"
+ expect(@settings[:myval]).to eq("memarg")
end
it "should raise an error if we try to set a setting that hasn't been defined'" do
- lambda{
+ expect{
@settings[:why_so_serious] = "foo"
- }.should raise_error(ArgumentError, /unknown setting/)
+ }.to raise_error(ArgumentError, /unknown setting/)
end
it "allows overriding cli args based on the cli-set value" do
@settings.handlearg("--myval", "cliarg")
@settings.patch_value(:myval, "modified #{@settings[:myval]}", :cli)
expect(@settings[:myval]).to eq("modified cliarg")
end
end
describe "when returning values" do
before do
@settings = Puppet::Settings.new
@settings.define_settings :section,
:config => { :type => :file, :default => "/my/file", :desc => "eh" },
:one => { :default => "ONE", :desc => "a" },
:two => { :default => "$one TWO", :desc => "b"},
:three => { :default => "$one $two THREE", :desc => "c"},
:four => { :default => "$two $three FOUR", :desc => "d"},
:five => { :default => nil, :desc => "e" }
Puppet::FileSystem.stubs(:exist?).returns true
end
it "should provide a mechanism for returning set values" do
@settings[:one] = "other"
- @settings[:one].should == "other"
+ expect(@settings[:one]).to eq("other")
end
it "setting a value to nil causes it to return to its default" do
default_values = { :one => "skipped value" }
[:logdir, :confdir, :vardir].each do |key|
default_values[key] = 'default value'
end
@settings.define_settings :main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS
@settings.initialize_app_defaults(default_values)
@settings[:one] = "value will disappear"
@settings[:one] = nil
- @settings[:one].should == "ONE"
+ expect(@settings[:one]).to eq("ONE")
end
it "should interpolate default values for other parameters into returned parameter values" do
- @settings[:one].should == "ONE"
- @settings[:two].should == "ONE TWO"
- @settings[:three].should == "ONE ONE TWO THREE"
+ expect(@settings[:one]).to eq("ONE")
+ expect(@settings[:two]).to eq("ONE TWO")
+ expect(@settings[:three]).to eq("ONE ONE TWO THREE")
end
it "should interpolate default values that themselves need to be interpolated" do
- @settings[:four].should == "ONE TWO ONE ONE TWO THREE FOUR"
+ expect(@settings[:four]).to eq("ONE TWO ONE ONE TWO THREE FOUR")
end
it "should provide a method for returning uninterpolated values" do
@settings[:two] = "$one tw0"
- @settings.value(:two, nil, true).should == "$one tw0"
- @settings.value(:four, nil, true).should == "$two $three FOUR"
+ expect(@settings.value(:two, nil, true)).to eq("$one tw0")
+ expect(@settings.value(:four, nil, true)).to eq("$two $three FOUR")
end
it "should interpolate set values for other parameters into returned parameter values" do
@settings[:one] = "on3"
@settings[:two] = "$one tw0"
@settings[:three] = "$one $two thr33"
@settings[:four] = "$one $two $three f0ur"
- @settings[:one].should == "on3"
- @settings[:two].should == "on3 tw0"
- @settings[:three].should == "on3 on3 tw0 thr33"
- @settings[:four].should == "on3 on3 tw0 on3 on3 tw0 thr33 f0ur"
+ expect(@settings[:one]).to eq("on3")
+ expect(@settings[:two]).to eq("on3 tw0")
+ expect(@settings[:three]).to eq("on3 on3 tw0 thr33")
+ expect(@settings[:four]).to eq("on3 on3 tw0 on3 on3 tw0 thr33 f0ur")
end
it "should not cache interpolated values such that stale information is returned" do
- @settings[:two].should == "ONE TWO"
+ expect(@settings[:two]).to eq("ONE TWO")
@settings[:one] = "one"
- @settings[:two].should == "one TWO"
+ expect(@settings[:two]).to eq("one TWO")
end
it "should have a run_mode that defaults to user" do
- @settings.preferred_run_mode.should == :user
+ expect(@settings.preferred_run_mode).to eq(:user)
end
it "interpolates a boolean false without raising an error" do
@settings.define_settings(:section,
:trip_wire => { :type => :boolean, :default => false, :desc => "a trip wire" },
:tripping => { :default => '$trip_wire', :desc => "once tripped if interpolated was false" })
- @settings[:tripping].should == "false"
+ expect(@settings[:tripping]).to eq("false")
end
end
describe "when choosing which value to return" do
before do
@settings = Puppet::Settings.new
@settings.define_settings :section,
:config => { :type => :file, :default => "/my/file", :desc => "a" },
:one => { :default => "ONE", :desc => "a" },
:two => { :default => "TWO", :desc => "b" }
Puppet::FileSystem.stubs(:exist?).returns true
@settings.preferred_run_mode = :agent
end
it "should return default values if no values have been set" do
- @settings[:one].should == "ONE"
+ expect(@settings[:one]).to eq("ONE")
end
it "should return values set on the cli before values set in the configuration file" do
text = "[main]\none = fileval\n"
@settings.stubs(:read_file).returns(text)
@settings.handlearg("--one", "clival")
@settings.send(:parse_config_files)
- @settings[:one].should == "clival"
+ expect(@settings[:one]).to eq("clival")
end
it "should return values set in the mode-specific section before values set in the main section" do
text = "[main]\none = mainval\n[agent]\none = modeval\n"
@settings.stubs(:read_file).returns(text)
@settings.send(:parse_config_files)
- @settings[:one].should == "modeval"
+ expect(@settings[:one]).to eq("modeval")
end
it "should not return values outside of its search path" do
text = "[other]\none = oval\n"
file = "/some/file"
@settings.stubs(:read_file).returns(text)
@settings.send(:parse_config_files)
- @settings[:one].should == "ONE"
+ expect(@settings[:one]).to eq("ONE")
end
it 'should use the current environment for $environment' do
@settings.define_settings :main, :config_version => { :default => "$environment/foo", :desc => "mydocs" }
- @settings.value(:config_version, "myenv").should == "myenv/foo"
+ expect(@settings.value(:config_version, "myenv")).to eq("myenv/foo")
end
end
describe "when locating config files" do
before do
@settings = Puppet::Settings.new
end
describe "when root" do
it "should look for the main config file default location config settings haven't been overridden'" do
Puppet.features.stubs(:root?).returns(true)
Puppet::FileSystem.expects(:exist?).with(main_config_file_default_location).returns(false)
Puppet::FileSystem.expects(:exist?).with(user_config_file_default_location).never
@settings.send(:parse_config_files)
end
end
describe "when not root" do
it "should look for user config file default location if config settings haven't been overridden'" do
Puppet.features.stubs(:root?).returns(false)
seq = sequence "load config files"
Puppet::FileSystem.expects(:exist?).with(user_config_file_default_location).returns(false).in_sequence(seq)
@settings.send(:parse_config_files)
end
end
end
describe "when parsing its configuration" do
before do
@settings = Puppet::Settings.new
@settings.stubs(:service_user_available?).returns true
@settings.stubs(:service_group_available?).returns true
@file = make_absolute("/some/file")
@userconfig = make_absolute("/test/userconfigfile")
@settings.define_settings :section, :user => { :default => "suser", :desc => "doc" }, :group => { :default => "sgroup", :desc => "doc" }
@settings.define_settings :section,
:config => { :type => :file, :default => @file, :desc => "eh" },
:one => { :default => "ONE", :desc => "a" },
:two => { :default => "$one TWO", :desc => "b" },
:three => { :default => "$one $two THREE", :desc => "c" }
@settings.stubs(:user_config_file).returns(@userconfig)
Puppet::FileSystem.stubs(:exist?).with(@file).returns true
Puppet::FileSystem.stubs(:exist?).with(@userconfig).returns false
end
it "should not ignore the report setting" do
@settings.define_settings :section, :report => { :default => "false", :desc => "a" }
# This is needed in order to make sure we pass on windows
myfile = File.expand_path(@file)
@settings[:config] = myfile
text = <<-CONF
[puppetd]
report=true
CONF
Puppet::FileSystem.expects(:exist?).with(myfile).returns(true)
@settings.expects(:read_file).returns(text)
@settings.send(:parse_config_files)
- @settings[:report].should be_true
+ expect(@settings[:report]).to be_truthy
end
it "should use its current ':config' value for the file to parse" do
myfile = make_absolute("/my/file") # do not stub expand_path here, as this leads to a stack overflow, when mocha tries to use it
@settings[:config] = myfile
Puppet::FileSystem.expects(:exist?).with(myfile).returns(true)
Puppet::FileSystem.expects(:read).with(myfile).returns "[main]"
@settings.send(:parse_config_files)
end
it "should not try to parse non-existent files" do
Puppet::FileSystem.expects(:exist?).with(@file).returns false
File.expects(:read).with(@file).never
@settings.send(:parse_config_files)
end
it "should return values set in the configuration file" do
text = "[main]
one = fileval
"
@settings.expects(:read_file).returns(text)
@settings.send(:parse_config_files)
- @settings[:one].should == "fileval"
+ expect(@settings[:one]).to eq("fileval")
end
#484 - this should probably be in the regression area
it "should not throw an exception on unknown parameters" do
text = "[main]\nnosuchparam = mval\n"
@settings.expects(:read_file).returns(text)
- lambda { @settings.send(:parse_config_files) }.should_not raise_error
+ expect { @settings.send(:parse_config_files) }.not_to raise_error
end
it "should convert booleans in the configuration file into Ruby booleans" do
text = "[main]
one = true
two = false
"
@settings.expects(:read_file).returns(text)
@settings.send(:parse_config_files)
- @settings[:one].should == true
- @settings[:two].should == false
+ expect(@settings[:one]).to eq(true)
+ expect(@settings[:two]).to eq(false)
end
it "should convert integers in the configuration file into Ruby Integers" do
text = "[main]
one = 65
"
@settings.expects(:read_file).returns(text)
@settings.send(:parse_config_files)
- @settings[:one].should == 65
+ expect(@settings[:one]).to eq(65)
end
it "should support specifying all metadata (owner, group, mode) in the configuration file" do
@settings.define_settings :section, :myfile => { :type => :file, :default => make_absolute("/myfile"), :desc => "a" }
otherfile = make_absolute("/other/file")
@settings.parse_config(<<-CONF)
[main]
myfile = #{otherfile} {owner = service, group = service, mode = 644}
CONF
- @settings[:myfile].should == otherfile
- metadata(@settings.setting(:myfile)).should == {:owner => "suser", :group => "sgroup", :mode => "644"}
+ expect(@settings[:myfile]).to eq(otherfile)
+ expect(metadata(@settings.setting(:myfile))).to eq({:owner => "suser", :group => "sgroup", :mode => "644"})
end
it "should support specifying a single piece of metadata (owner, group, or mode) in the configuration file" do
@settings.define_settings :section, :myfile => { :type => :file, :default => make_absolute("/myfile"), :desc => "a" }
otherfile = make_absolute("/other/file")
@settings.parse_config(<<-CONF)
[main]
myfile = #{otherfile} {owner = service}
CONF
- @settings[:myfile].should == otherfile
- metadata(@settings.setting(:myfile)).should == {:owner => "suser"}
+ expect(@settings[:myfile]).to eq(otherfile)
+ expect(metadata(@settings.setting(:myfile))).to eq({:owner => "suser"})
end
it "should support loading metadata (owner, group, or mode) from a run_mode section in the configuration file" do
default_values = {}
PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS.keys.each do |key|
default_values[key] = 'default value'
end
@settings.define_settings :main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS
@settings.define_settings :master, :myfile => { :type => :file, :default => make_absolute("/myfile"), :desc => "a" }
otherfile = make_absolute("/other/file")
text = "[master]
myfile = #{otherfile} {mode = 664}
"
@settings.expects(:read_file).returns(text)
# will start initialization as user
- @settings.preferred_run_mode.should == :user
+ expect(@settings.preferred_run_mode).to eq(:user)
@settings.send(:parse_config_files)
# change app run_mode to master
@settings.initialize_app_defaults(default_values.merge(:run_mode => :master))
- @settings.preferred_run_mode.should == :master
+ expect(@settings.preferred_run_mode).to eq(:master)
# initializing the app should have reloaded the metadata based on run_mode
- @settings[:myfile].should == otherfile
- metadata(@settings.setting(:myfile)).should == {:mode => "664"}
+ expect(@settings[:myfile]).to eq(otherfile)
+ expect(metadata(@settings.setting(:myfile))).to eq({:mode => "664"})
end
it "does not use the metadata from the same setting in a different section" do
default_values = {}
PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS.keys.each do |key|
default_values[key] = 'default value'
end
file = make_absolute("/file")
default_mode = "0600"
@settings.define_settings :main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS
@settings.define_settings :master, :myfile => { :type => :file, :default => file, :desc => "a", :mode => default_mode }
text = "[master]
myfile = #{file}/foo
[agent]
myfile = #{file} {mode = 664}
"
@settings.expects(:read_file).returns(text)
# will start initialization as user
- @settings.preferred_run_mode.should == :user
+ expect(@settings.preferred_run_mode).to eq(:user)
@settings.send(:parse_config_files)
# change app run_mode to master
@settings.initialize_app_defaults(default_values.merge(:run_mode => :master))
- @settings.preferred_run_mode.should == :master
+ expect(@settings.preferred_run_mode).to eq(:master)
# initializing the app should have reloaded the metadata based on run_mode
- @settings[:myfile].should == "#{file}/foo"
- metadata(@settings.setting(:myfile)).should == { :mode => default_mode }
+ expect(@settings[:myfile]).to eq("#{file}/foo")
+ expect(metadata(@settings.setting(:myfile))).to eq({ :mode => default_mode })
end
it "should call hooks associated with values set in the configuration file" do
values = []
@settings.define_settings :section, :mysetting => {:default => "defval", :desc => "a", :hook => proc { |v| values << v }}
text = "[main]
mysetting = setval
"
@settings.expects(:read_file).returns(text)
@settings.send(:parse_config_files)
- values.should == ["setval"]
+ expect(values).to eq(["setval"])
end
it "should not call the same hook for values set multiple times in the configuration file" do
values = []
@settings.define_settings :section, :mysetting => {:default => "defval", :desc => "a", :hook => proc { |v| values << v }}
text = "[user]
mysetting = setval
[main]
mysetting = other
"
@settings.expects(:read_file).returns(text)
@settings.send(:parse_config_files)
- values.should == ["setval"]
+ expect(values).to eq(["setval"])
end
it "should pass the interpolated value to the hook when one is available" do
values = []
@settings.define_settings :section, :base => {:default => "yay", :desc => "a", :hook => proc { |v| values << v }}
@settings.define_settings :section, :mysetting => {:default => "defval", :desc => "a", :hook => proc { |v| values << v }}
text = "[main]
mysetting = $base/setval
"
@settings.expects(:read_file).returns(text)
@settings.send(:parse_config_files)
- values.should == ["yay/setval"]
+ expect(values).to eq(["yay/setval"])
end
it "should allow hooks invoked at parse time to be deferred" do
hook_invoked = false
@settings.define_settings :section, :deferred => {:desc => '',
:hook => proc { |v| hook_invoked = true },
:call_hook => :on_initialize_and_write, }
@settings.define_settings(:main,
:logdir => { :type => :directory, :default => nil, :desc => "logdir" },
:confdir => { :type => :directory, :default => nil, :desc => "confdir" },
:vardir => { :type => :directory, :default => nil, :desc => "vardir" })
text = <<-EOD
[main]
deferred=$confdir/goose
EOD
@settings.stubs(:read_file).returns(text)
@settings.initialize_global_settings
- hook_invoked.should be_false
+ expect(hook_invoked).to be_falsey
@settings.initialize_app_defaults(:logdir => '/path/to/logdir', :confdir => '/path/to/confdir', :vardir => '/path/to/vardir')
- hook_invoked.should be_true
- @settings[:deferred].should eq(File.expand_path('/path/to/confdir/goose'))
+ expect(hook_invoked).to be_truthy
+ expect(@settings[:deferred]).to eq(File.expand_path('/path/to/confdir/goose'))
end
it "does not require the value for a setting without a hook to resolve during global setup" do
hook_invoked = false
@settings.define_settings :section, :can_cause_problems => {:desc => '' }
@settings.define_settings(:main,
:logdir => { :type => :directory, :default => nil, :desc => "logdir" },
:confdir => { :type => :directory, :default => nil, :desc => "confdir" },
:vardir => { :type => :directory, :default => nil, :desc => "vardir" })
text = <<-EOD
[main]
can_cause_problems=$confdir/goose
EOD
@settings.stubs(:read_file).returns(text)
@settings.initialize_global_settings
@settings.initialize_app_defaults(:logdir => '/path/to/logdir', :confdir => '/path/to/confdir', :vardir => '/path/to/vardir')
- @settings[:can_cause_problems].should eq(File.expand_path('/path/to/confdir/goose'))
+ expect(@settings[:can_cause_problems]).to eq(File.expand_path('/path/to/confdir/goose'))
end
it "should allow empty values" do
@settings.define_settings :section, :myarg => { :default => "myfile", :desc => "a" }
text = "[main]
myarg =
"
@settings.stubs(:read_file).returns(text)
@settings.send(:parse_config_files)
- @settings[:myarg].should == ""
+ expect(@settings[:myarg]).to eq("")
end
describe "deprecations" do
let(:settings) { Puppet::Settings.new }
let(:app_defaults) {
{
:logdir => "/dev/null",
:confdir => "/dev/null",
:vardir => "/dev/null",
}
}
def assert_accessing_setting_is_deprecated(settings, setting)
Puppet.expects(:deprecation_warning).with("Accessing '#{setting}' as a setting is deprecated.")
Puppet.expects(:deprecation_warning).with("Modifying '#{setting}' as a setting is deprecated.")
settings[setting.intern] = apath = File.expand_path('foo')
expect(settings[setting.intern]).to eq(apath)
end
before(:each) do
settings.define_settings(:main, {
:logdir => { :default => 'a', :desc => 'a' },
:confdir => { :default => 'b', :desc => 'b' },
:vardir => { :default => 'c', :desc => 'c' },
})
end
context "complete" do
let(:completely_deprecated_settings) do
settings.define_settings(:main, {
:completely_deprecated_setting => {
:default => 'foo',
:desc => 'a deprecated setting',
:deprecated => :completely,
}
})
settings
end
it "warns when set in puppet.conf" do
Puppet.expects(:deprecation_warning).with(regexp_matches(/completely_deprecated_setting is deprecated\./), 'setting-completely_deprecated_setting')
completely_deprecated_settings.parse_config(<<-CONF)
completely_deprecated_setting='should warn'
CONF
completely_deprecated_settings.initialize_app_defaults(app_defaults)
end
it "warns when set on the commandline" do
Puppet.expects(:deprecation_warning).with(regexp_matches(/completely_deprecated_setting is deprecated\./), 'setting-completely_deprecated_setting')
args = ["--completely_deprecated_setting", "/some/value"]
completely_deprecated_settings.send(:parse_global_options, args)
completely_deprecated_settings.initialize_app_defaults(app_defaults)
end
it "warns when set in code" do
assert_accessing_setting_is_deprecated(completely_deprecated_settings, 'completely_deprecated_setting')
end
end
context "partial" do
let(:partially_deprecated_settings) do
settings.define_settings(:main, {
:partially_deprecated_setting => {
:default => 'foo',
:desc => 'a partially deprecated setting',
:deprecated => :allowed_on_commandline,
}
})
settings
end
it "warns for a deprecated setting allowed on the command line set in puppet.conf" do
Puppet.expects(:deprecation_warning).with(regexp_matches(/partially_deprecated_setting is deprecated in puppet\.conf/), 'puppet-conf-setting-partially_deprecated_setting')
partially_deprecated_settings.parse_config(<<-CONF)
partially_deprecated_setting='should warn'
CONF
partially_deprecated_settings.initialize_app_defaults(app_defaults)
end
it "does not warn when manifest is set on command line" do
Puppet.expects(:deprecation_warning).never
args = ["--partially_deprecated_setting", "/some/value"]
partially_deprecated_settings.send(:parse_global_options, args)
partially_deprecated_settings.initialize_app_defaults(app_defaults)
end
it "warns when set in code" do
assert_accessing_setting_is_deprecated(partially_deprecated_settings, 'partially_deprecated_setting')
end
end
end
end
describe "when there are multiple config files" do
let(:main_config_text) { "[main]\none = main\ntwo = main2" }
let(:user_config_text) { "[main]\none = user\n" }
let(:seq) { sequence "config_file_sequence" }
before :each do
@settings = Puppet::Settings.new
@settings.define_settings(:section,
{ :confdir => { :default => nil, :desc => "Conf dir" },
:config => { :default => "$confdir/puppet.conf", :desc => "Config" },
:one => { :default => "ONE", :desc => "a" },
:two => { :default => "TWO", :desc => "b" }, })
end
context "running non-root without explicit config file" do
before :each do
Puppet.features.stubs(:root?).returns(false)
Puppet::FileSystem.expects(:exist?).
with(user_config_file_default_location).
returns(true).in_sequence(seq)
@settings.expects(:read_file).
with(user_config_file_default_location).
returns(user_config_text).in_sequence(seq)
end
it "should return values from the user config file" do
@settings.send(:parse_config_files)
- @settings[:one].should == "user"
+ expect(@settings[:one]).to eq("user")
end
it "should not return values from the main config file" do
@settings.send(:parse_config_files)
- @settings[:two].should == "TWO"
+ expect(@settings[:two]).to eq("TWO")
end
end
context "running as root without explicit config file" do
before :each do
Puppet.features.stubs(:root?).returns(true)
Puppet::FileSystem.expects(:exist?).
with(main_config_file_default_location).
returns(true).in_sequence(seq)
@settings.expects(:read_file).
with(main_config_file_default_location).
returns(main_config_text).in_sequence(seq)
end
it "should return values from the main config file" do
@settings.send(:parse_config_files)
- @settings[:one].should == "main"
+ expect(@settings[:one]).to eq("main")
end
it "should not return values from the user config file" do
@settings.send(:parse_config_files)
- @settings[:two].should == "main2"
+ expect(@settings[:two]).to eq("main2")
end
end
context "running with an explicit config file as a user (e.g. Apache + Passenger)" do
before :each do
Puppet.features.stubs(:root?).returns(false)
@settings[:confdir] = File.dirname(main_config_file_default_location)
Puppet::FileSystem.expects(:exist?).
with(main_config_file_default_location).
returns(true).in_sequence(seq)
@settings.expects(:read_file).
with(main_config_file_default_location).
returns(main_config_text).in_sequence(seq)
end
it "should return values from the main config file" do
@settings.send(:parse_config_files)
- @settings[:one].should == "main"
+ expect(@settings[:one]).to eq("main")
end
it "should not return values from the user config file" do
@settings.send(:parse_config_files)
- @settings[:two].should == "main2"
+ expect(@settings[:two]).to eq("main2")
end
end
end
describe "when reparsing its configuration" do
before do
@file = make_absolute("/test/file")
@userconfig = make_absolute("/test/userconfigfile")
@settings = Puppet::Settings.new
@settings.define_settings :section,
:config => { :type => :file, :default => @file, :desc => "a" },
:one => { :default => "ONE", :desc => "a" },
:two => { :default => "$one TWO", :desc => "b" },
:three => { :default => "$one $two THREE", :desc => "c" }
Puppet::FileSystem.stubs(:exist?).with(@file).returns true
Puppet::FileSystem.stubs(:exist?).with(@userconfig).returns false
@settings.stubs(:user_config_file).returns(@userconfig)
end
it "does not create the WatchedFile instance and should not parse if the file does not exist" do
Puppet::FileSystem.expects(:exist?).with(@file).returns false
Puppet::Util::WatchedFile.expects(:new).never
@settings.expects(:parse_config_files).never
@settings.reparse_config_files
end
context "and watched file exists" do
before do
@watched_file = Puppet::Util::WatchedFile.new(@file)
Puppet::Util::WatchedFile.expects(:new).with(@file).returns @watched_file
end
it "uses a WatchedFile instance to determine if the file has changed" do
@watched_file.expects(:changed?)
@settings.reparse_config_files
end
it "does not reparse if the file has not changed" do
@watched_file.expects(:changed?).returns false
@settings.expects(:parse_config_files).never
@settings.reparse_config_files
end
it "reparses if the file has changed" do
@watched_file.expects(:changed?).returns true
@settings.expects(:parse_config_files)
@settings.reparse_config_files
end
it "replaces in-memory values with on-file values" do
@watched_file.stubs(:changed?).returns(true)
@settings[:one] = "init"
# Now replace the value
text = "[main]\none = disk-replace\n"
@settings.stubs(:read_file).returns(text)
@settings.reparse_config_files
- @settings[:one].should == "disk-replace"
+ expect(@settings[:one]).to eq("disk-replace")
end
end
it "should retain parameters set by cli when configuration files are reparsed" do
@settings.handlearg("--one", "clival")
text = "[main]\none = on-disk\n"
@settings.stubs(:read_file).returns(text)
@settings.send(:parse_config_files)
- @settings[:one].should == "clival"
+ expect(@settings[:one]).to eq("clival")
end
it "should remove in-memory values that are no longer set in the file" do
# Init the value
text = "[main]\none = disk-init\n"
@settings.expects(:read_file).returns(text)
@settings.send(:parse_config_files)
- @settings[:one].should == "disk-init"
+ expect(@settings[:one]).to eq("disk-init")
# Now replace the value
text = "[main]\ntwo = disk-replace\n"
@settings.expects(:read_file).returns(text)
@settings.send(:parse_config_files)
# The originally-overridden value should be replaced with the default
- @settings[:one].should == "ONE"
+ expect(@settings[:one]).to eq("ONE")
# and we should now have the new value in memory
- @settings[:two].should == "disk-replace"
+ expect(@settings[:two]).to eq("disk-replace")
end
it "should retain in-memory values if the file has a syntax error" do
# Init the value
text = "[main]\none = initial-value\n"
@settings.expects(:read_file).with(@file).returns(text)
@settings.send(:parse_config_files)
- @settings[:one].should == "initial-value"
+ expect(@settings[:one]).to eq("initial-value")
# Now replace the value with something bogus
text = "[main]\nkenny = killed-by-what-follows\n1 is 2, blah blah florp\n"
@settings.expects(:read_file).with(@file).returns(text)
@settings.send(:parse_config_files)
# The originally-overridden value should not be replaced with the default
- @settings[:one].should == "initial-value"
+ expect(@settings[:one]).to eq("initial-value")
# and we should not have the new value in memory
- @settings[:kenny].should be_nil
+ expect(@settings[:kenny]).to be_nil
end
end
it "should provide a method for creating a catalog of resources from its configuration" do
- Puppet::Settings.new.should respond_to(:to_catalog)
+ expect(Puppet::Settings.new).to respond_to(:to_catalog)
end
describe "when creating a catalog" do
before do
@settings = Puppet::Settings.new
@settings.stubs(:service_user_available?).returns true
@prefix = Puppet.features.posix? ? "" : "C:"
end
it "should add all file resources to the catalog if no sections have been specified" do
@settings.define_settings :main,
:maindir => { :type => :directory, :default => @prefix+"/maindir", :desc => "a"},
:seconddir => { :type => :directory, :default => @prefix+"/seconddir", :desc => "a"}
@settings.define_settings :other,
:otherdir => { :type => :directory, :default => @prefix+"/otherdir", :desc => "a" }
catalog = @settings.to_catalog
[@prefix+"/maindir", @prefix+"/seconddir", @prefix+"/otherdir"].each do |path|
- catalog.resource(:file, path).should be_instance_of(Puppet::Resource)
+ expect(catalog.resource(:file, path)).to be_instance_of(Puppet::Resource)
end
end
it "should add only files in the specified sections if section names are provided" do
@settings.define_settings :main, :maindir => { :type => :directory, :default => @prefix+"/maindir", :desc => "a" }
@settings.define_settings :other, :otherdir => { :type => :directory, :default => @prefix+"/otherdir", :desc => "a" }
catalog = @settings.to_catalog(:main)
- catalog.resource(:file, @prefix+"/otherdir").should be_nil
- catalog.resource(:file, @prefix+"/maindir").should be_instance_of(Puppet::Resource)
+ expect(catalog.resource(:file, @prefix+"/otherdir")).to be_nil
+ expect(catalog.resource(:file, @prefix+"/maindir")).to be_instance_of(Puppet::Resource)
end
it "should not try to add the same file twice" do
@settings.define_settings :main, :maindir => { :type => :directory, :default => @prefix+"/maindir", :desc => "a" }
@settings.define_settings :other, :otherdir => { :type => :directory, :default => @prefix+"/maindir", :desc => "a" }
- lambda { @settings.to_catalog }.should_not raise_error
+ expect { @settings.to_catalog }.not_to raise_error
end
it "should ignore files whose :to_resource method returns nil" do
@settings.define_settings :main, :maindir => { :type => :directory, :default => @prefix+"/maindir", :desc => "a" }
@settings.setting(:maindir).expects(:to_resource).returns nil
Puppet::Resource::Catalog.any_instance.expects(:add_resource).never
@settings.to_catalog
end
describe "on Microsoft Windows" do
before :each do
Puppet.features.stubs(:root?).returns true
Puppet.features.stubs(:microsoft_windows?).returns true
@settings.define_settings :foo,
:mkusers => { :type => :boolean, :default => true, :desc => "e" },
:user => { :default => "suser", :desc => "doc" },
:group => { :default => "sgroup", :desc => "doc" }
@settings.define_settings :other,
:otherdir => { :type => :directory, :default => "/otherdir", :desc => "a", :owner => "service", :group => "service"}
@catalog = @settings.to_catalog
end
it "it should not add users and groups to the catalog" do
- @catalog.resource(:user, "suser").should be_nil
- @catalog.resource(:group, "sgroup").should be_nil
+ expect(@catalog.resource(:user, "suser")).to be_nil
+ expect(@catalog.resource(:group, "sgroup")).to be_nil
end
end
describe "adding default directory environment to the catalog" do
let(:tmpenv) { tmpdir("envs") }
let(:default_path) { "#{tmpenv}/environments" }
before(:each) do
@settings.define_settings :main,
:environment => { :default => "production", :desc => "env"},
:environmentpath => { :type => :path, :default => default_path, :desc => "envpath"}
end
it "adds if environmentpath exists" do
envpath = "#{tmpenv}/custom_envpath"
@settings[:environmentpath] = envpath
Dir.mkdir(envpath)
catalog = @settings.to_catalog
expect(catalog.resource_keys).to include(["File", "#{envpath}/production"])
end
it "adds the first directory of environmentpath" do
envdir = "#{tmpenv}/custom_envpath"
envpath = "#{envdir}#{File::PATH_SEPARATOR}/some/other/envdir"
@settings[:environmentpath] = envpath
Dir.mkdir(envdir)
catalog = @settings.to_catalog
expect(catalog.resource_keys).to include(["File", "#{envdir}/production"])
end
it "handles a non-existent environmentpath" do
catalog = @settings.to_catalog
expect(catalog.resource_keys).to be_empty
end
it "handles a default environmentpath" do
Dir.mkdir(default_path)
catalog = @settings.to_catalog
expect(catalog.resource_keys).to include(["File", "#{default_path}/production"])
end
it "does not add if the path to the default directory environment exists as a symlink", :if => Puppet.features.manages_symlinks? do
Dir.mkdir(default_path)
Puppet::FileSystem.symlink("#{tmpenv}/nowhere", File.join(default_path, 'production'))
catalog = @settings.to_catalog
expect(catalog.resource_keys).to_not include(["File", "#{default_path}/production"])
end
end
describe "when adding users and groups to the catalog" do
before do
Puppet.features.stubs(:root?).returns true
Puppet.features.stubs(:microsoft_windows?).returns false
@settings.define_settings :foo,
:mkusers => { :type => :boolean, :default => true, :desc => "e" },
:user => { :default => "suser", :desc => "doc" },
:group => { :default => "sgroup", :desc => "doc" }
@settings.define_settings :other, :otherdir => {:type => :directory, :default => "/otherdir", :desc => "a", :owner => "service", :group => "service"}
@catalog = @settings.to_catalog
end
it "should add each specified user and group to the catalog if :mkusers is a valid setting, is enabled, and we're running as root" do
- @catalog.resource(:user, "suser").should be_instance_of(Puppet::Resource)
- @catalog.resource(:group, "sgroup").should be_instance_of(Puppet::Resource)
+ expect(@catalog.resource(:user, "suser")).to be_instance_of(Puppet::Resource)
+ expect(@catalog.resource(:group, "sgroup")).to be_instance_of(Puppet::Resource)
end
it "should only add users and groups to the catalog from specified sections" do
@settings.define_settings :yay, :yaydir => { :type => :directory, :default => "/yaydir", :desc => "a", :owner => "service", :group => "service"}
catalog = @settings.to_catalog(:other)
- catalog.resource(:user, "jane").should be_nil
- catalog.resource(:group, "billy").should be_nil
+ expect(catalog.resource(:user, "jane")).to be_nil
+ expect(catalog.resource(:group, "billy")).to be_nil
end
it "should not add users or groups to the catalog if :mkusers not running as root" do
Puppet.features.stubs(:root?).returns false
catalog = @settings.to_catalog
- catalog.resource(:user, "suser").should be_nil
- catalog.resource(:group, "sgroup").should be_nil
+ expect(catalog.resource(:user, "suser")).to be_nil
+ expect(catalog.resource(:group, "sgroup")).to be_nil
end
it "should not add users or groups to the catalog if :mkusers is not a valid setting" do
Puppet.features.stubs(:root?).returns true
settings = Puppet::Settings.new
settings.define_settings :other, :otherdir => {:type => :directory, :default => "/otherdir", :desc => "a", :owner => "service", :group => "service"}
catalog = settings.to_catalog
- catalog.resource(:user, "suser").should be_nil
- catalog.resource(:group, "sgroup").should be_nil
+ expect(catalog.resource(:user, "suser")).to be_nil
+ expect(catalog.resource(:group, "sgroup")).to be_nil
end
it "should not add users or groups to the catalog if :mkusers is a valid setting but is disabled" do
@settings[:mkusers] = false
catalog = @settings.to_catalog
- catalog.resource(:user, "suser").should be_nil
- catalog.resource(:group, "sgroup").should be_nil
+ expect(catalog.resource(:user, "suser")).to be_nil
+ expect(catalog.resource(:group, "sgroup")).to be_nil
end
it "should not try to add users or groups to the catalog twice" do
@settings.define_settings :yay, :yaydir => {:type => :directory, :default => "/yaydir", :desc => "a", :owner => "service", :group => "service"}
# This would fail if users/groups were added twice
- lambda { @settings.to_catalog }.should_not raise_error
+ expect { @settings.to_catalog }.not_to raise_error
end
it "should set :ensure to :present on each created user and group" do
- @catalog.resource(:user, "suser")[:ensure].should == :present
- @catalog.resource(:group, "sgroup")[:ensure].should == :present
+ expect(@catalog.resource(:user, "suser")[:ensure]).to eq(:present)
+ expect(@catalog.resource(:group, "sgroup")[:ensure]).to eq(:present)
end
it "should set each created user's :gid to the service group" do
- @settings.to_catalog.resource(:user, "suser")[:gid].should == "sgroup"
+ expect(@settings.to_catalog.resource(:user, "suser")[:gid]).to eq("sgroup")
end
it "should not attempt to manage the root user" do
Puppet.features.stubs(:root?).returns true
@settings.define_settings :foo, :foodir => {:type => :directory, :default => "/foodir", :desc => "a", :owner => "root", :group => "service"}
- @settings.to_catalog.resource(:user, "root").should be_nil
+ expect(@settings.to_catalog.resource(:user, "root")).to be_nil
end
end
end
it "should be able to be converted to a manifest" do
- Puppet::Settings.new.should respond_to(:to_manifest)
+ expect(Puppet::Settings.new).to respond_to(:to_manifest)
end
describe "when being converted to a manifest" do
it "should produce a string with the code for each resource joined by two carriage returns" do
@settings = Puppet::Settings.new
@settings.define_settings :main,
:maindir => { :type => :directory, :default => "/maindir", :desc => "a"},
:seconddir => { :type => :directory, :default => "/seconddir", :desc => "a"}
main = stub 'main_resource', :ref => "File[/maindir]"
main.expects(:to_manifest).returns "maindir"
second = stub 'second_resource', :ref => "File[/seconddir]"
second.expects(:to_manifest).returns "seconddir"
@settings.setting(:maindir).expects(:to_resource).returns main
@settings.setting(:seconddir).expects(:to_resource).returns second
- @settings.to_manifest.split("\n\n").sort.should == %w{maindir seconddir}
+ expect(@settings.to_manifest.split("\n\n").sort).to eq(%w{maindir seconddir})
end
end
describe "when using sections of the configuration to manage the local host" do
before do
@settings = Puppet::Settings.new
@settings.stubs(:service_user_available?).returns true
@settings.stubs(:service_group_available?).returns true
@settings.define_settings :main, :noop => { :default => false, :desc => "", :type => :boolean }
@settings.define_settings :main,
:maindir => { :type => :directory, :default => make_absolute("/maindir"), :desc => "a" },
:seconddir => { :type => :directory, :default => make_absolute("/seconddir"), :desc => "a"}
@settings.define_settings :main, :user => { :default => "suser", :desc => "doc" }, :group => { :default => "sgroup", :desc => "doc" }
@settings.define_settings :other, :otherdir => {:type => :directory, :default => make_absolute("/otherdir"), :desc => "a", :owner => "service", :group => "service", :mode => '0755'}
@settings.define_settings :third, :thirddir => { :type => :directory, :default => make_absolute("/thirddir"), :desc => "b"}
@settings.define_settings :files, :myfile => {:type => :file, :default => make_absolute("/myfile"), :desc => "a", :mode => '0755'}
end
it "should create a catalog with the specified sections" do
@settings.expects(:to_catalog).with(:main, :other).returns Puppet::Resource::Catalog.new("foo")
@settings.use(:main, :other)
end
it "should canonicalize the sections" do
@settings.expects(:to_catalog).with(:main, :other).returns Puppet::Resource::Catalog.new("foo")
@settings.use("main", "other")
end
it "should ignore sections that have already been used" do
@settings.expects(:to_catalog).with(:main).returns Puppet::Resource::Catalog.new("foo")
@settings.use(:main)
@settings.expects(:to_catalog).with(:other).returns Puppet::Resource::Catalog.new("foo")
@settings.use(:main, :other)
end
it "should convert the created catalog to a RAL catalog" do
@catalog = Puppet::Resource::Catalog.new("foo")
@settings.expects(:to_catalog).with(:main).returns @catalog
@catalog.expects(:to_ral).returns @catalog
@settings.use(:main)
end
it "should specify that it is not managing a host catalog" do
catalog = Puppet::Resource::Catalog.new("foo")
catalog.expects(:apply)
@settings.expects(:to_catalog).returns catalog
catalog.stubs(:to_ral).returns catalog
catalog.expects(:host_config=).with false
@settings.use(:main)
end
it "should support a method for re-using all currently used sections" do
@settings.expects(:to_catalog).with(:main, :third).times(2).returns Puppet::Resource::Catalog.new("foo")
@settings.use(:main, :third)
@settings.reuse
end
it "should fail with an appropriate message if any resources fail" do
@catalog = Puppet::Resource::Catalog.new("foo")
@catalog.stubs(:to_ral).returns @catalog
@settings.expects(:to_catalog).returns @catalog
@trans = mock("transaction")
@catalog.expects(:apply).yields(@trans)
@trans.expects(:any_failed?).returns(true)
resource = Puppet::Type.type(:notify).new(:title => 'failed')
status = Puppet::Resource::Status.new(resource)
event = Puppet::Transaction::Event.new(
:name => 'failure',
:status => 'failure',
:message => 'My failure')
status.add_event(event)
report = Puppet::Transaction::Report.new('apply')
report.add_resource_status(status)
@trans.expects(:report).returns report
@settings.expects(:raise).with(includes("My failure"))
@settings.use(:whatever)
end
end
describe "when dealing with printing configs" do
before do
@settings = Puppet::Settings.new
#these are the magic default values
@settings.stubs(:value).with(:configprint).returns("")
@settings.stubs(:value).with(:genconfig).returns(false)
@settings.stubs(:value).with(:genmanifest).returns(false)
@settings.stubs(:value).with(:environment).returns(nil)
end
describe "when checking print_config?" do
it "should return false when the :configprint, :genconfig and :genmanifest are not set" do
- @settings.print_configs?.should be_false
+ expect(@settings.print_configs?).to be_falsey
end
it "should return true when :configprint has a value" do
@settings.stubs(:value).with(:configprint).returns("something")
- @settings.print_configs?.should be_true
+ expect(@settings.print_configs?).to be_truthy
end
it "should return true when :genconfig has a value" do
@settings.stubs(:value).with(:genconfig).returns(true)
- @settings.print_configs?.should be_true
+ expect(@settings.print_configs?).to be_truthy
end
it "should return true when :genmanifest has a value" do
@settings.stubs(:value).with(:genmanifest).returns(true)
- @settings.print_configs?.should be_true
+ expect(@settings.print_configs?).to be_truthy
end
end
describe "when printing configs" do
describe "when :configprint has a value" do
it "should call print_config_options" do
@settings.stubs(:value).with(:configprint).returns("something")
@settings.expects(:print_config_options)
@settings.print_configs
end
it "should get the value of the option using the environment" do
@settings.stubs(:value).with(:configprint).returns("something")
@settings.stubs(:include?).with("something").returns(true)
@settings.expects(:value).with(:environment).returns("env")
@settings.expects(:value).with("something", "env").returns("foo")
@settings.stubs(:puts).with("foo")
@settings.print_configs
end
it "should print the value of the option" do
@settings.stubs(:value).with(:configprint).returns("something")
@settings.stubs(:include?).with("something").returns(true)
@settings.stubs(:value).with("something", nil).returns("foo")
@settings.expects(:puts).with("foo")
@settings.print_configs
end
it "should print the value pairs if there are multiple options" do
@settings.stubs(:value).with(:configprint).returns("bar,baz")
@settings.stubs(:include?).with("bar").returns(true)
@settings.stubs(:include?).with("baz").returns(true)
@settings.stubs(:value).with("bar", nil).returns("foo")
@settings.stubs(:value).with("baz", nil).returns("fud")
@settings.expects(:puts).with("bar = foo")
@settings.expects(:puts).with("baz = fud")
@settings.print_configs
end
it "should return true after printing" do
@settings.stubs(:value).with(:configprint).returns("something")
@settings.stubs(:include?).with("something").returns(true)
@settings.stubs(:value).with("something", nil).returns("foo")
@settings.stubs(:puts).with("foo")
- @settings.print_configs.should be_true
+ expect(@settings.print_configs).to be_truthy
end
it "should return false if a config param is not found" do
@settings.stubs :puts
@settings.stubs(:value).with(:configprint).returns("something")
@settings.stubs(:include?).with("something").returns(false)
- @settings.print_configs.should be_false
+ expect(@settings.print_configs).to be_falsey
end
end
describe "when genconfig is true" do
before do
@settings.stubs :puts
end
it "should call to_config" do
@settings.stubs(:value).with(:genconfig).returns(true)
@settings.expects(:to_config)
@settings.print_configs
end
it "should return true from print_configs" do
@settings.stubs(:value).with(:genconfig).returns(true)
@settings.stubs(:to_config)
- @settings.print_configs.should be_true
+ expect(@settings.print_configs).to be_truthy
end
end
describe "when genmanifest is true" do
before do
@settings.stubs :puts
end
it "should call to_config" do
@settings.stubs(:value).with(:genmanifest).returns(true)
@settings.expects(:to_manifest)
@settings.print_configs
end
it "should return true from print_configs" do
@settings.stubs(:value).with(:genmanifest).returns(true)
@settings.stubs(:to_manifest)
- @settings.print_configs.should be_true
+ expect(@settings.print_configs).to be_truthy
end
end
end
end
describe "when determining if the service user is available" do
let(:settings) do
settings = Puppet::Settings.new
settings.define_settings :main, :user => { :default => nil, :desc => "doc" }
settings
end
def a_user_type_for(username)
user = mock 'user'
Puppet::Type.type(:user).expects(:new).with { |args| args[:name] == username }.returns user
user
end
it "should return false if there is no user setting" do
- settings.should_not be_service_user_available
+ expect(settings).not_to be_service_user_available
end
it "should return false if the user provider says the user is missing" do
settings[:user] = "foo"
a_user_type_for("foo").expects(:exists?).returns false
- settings.should_not be_service_user_available
+ expect(settings).not_to be_service_user_available
end
it "should return true if the user provider says the user is present" do
settings[:user] = "foo"
a_user_type_for("foo").expects(:exists?).returns true
- settings.should be_service_user_available
+ expect(settings).to be_service_user_available
end
it "caches the result of determining if the user is present" do
settings[:user] = "foo"
a_user_type_for("foo").expects(:exists?).returns true
- settings.should be_service_user_available
+ expect(settings).to be_service_user_available
- settings.should be_service_user_available
+ expect(settings).to be_service_user_available
end
end
describe "when determining if the service group is available" do
let(:settings) do
settings = Puppet::Settings.new
settings.define_settings :main, :group => { :default => nil, :desc => "doc" }
settings
end
def a_group_type_for(groupname)
group = mock 'group'
Puppet::Type.type(:group).expects(:new).with { |args| args[:name] == groupname }.returns group
group
end
it "should return false if there is no group setting" do
- settings.should_not be_service_group_available
+ expect(settings).not_to be_service_group_available
end
it "should return false if the group provider says the group is missing" do
settings[:group] = "foo"
a_group_type_for("foo").expects(:exists?).returns false
- settings.should_not be_service_group_available
+ expect(settings).not_to be_service_group_available
end
it "should return true if the group provider says the group is present" do
settings[:group] = "foo"
a_group_type_for("foo").expects(:exists?).returns true
- settings.should be_service_group_available
+ expect(settings).to be_service_group_available
end
it "caches the result of determining if the group is present" do
settings[:group] = "foo"
a_group_type_for("foo").expects(:exists?).returns true
- settings.should be_service_group_available
+ expect(settings).to be_service_group_available
- settings.should be_service_group_available
+ expect(settings).to be_service_group_available
end
end
describe "when dealing with command-line options" do
let(:settings) { Puppet::Settings.new }
it "should get options from Puppet.settings.optparse_addargs" do
settings.expects(:optparse_addargs).returns([])
settings.send(:parse_global_options, [])
end
it "should add options to OptionParser" do
settings.stubs(:optparse_addargs).returns( [["--option","-o", "Funny Option", :NONE]])
settings.expects(:handlearg).with("--option", true)
settings.send(:parse_global_options, ["--option"])
end
it "should not die if it sees an unrecognized option, because the app/face may handle it later" do
expect { settings.send(:parse_global_options, ["--topuppet", "value"]) } .to_not raise_error
end
it "should not pass an unrecognized option to handleargs" do
settings.expects(:handlearg).with("--topuppet", "value").never
expect { settings.send(:parse_global_options, ["--topuppet", "value"]) } .to_not raise_error
end
it "should pass valid puppet settings options to handlearg even if they appear after an unrecognized option" do
settings.stubs(:optparse_addargs).returns( [["--option","-o", "Funny Option", :NONE]])
settings.expects(:handlearg).with("--option", true)
settings.send(:parse_global_options, ["--invalidoption", "--option"])
end
it "should transform boolean option to normal form" do
- Puppet::Settings.clean_opt("--[no-]option", true).should == ["--option", true]
+ expect(Puppet::Settings.clean_opt("--[no-]option", true)).to eq(["--option", true])
end
it "should transform boolean option to no- form" do
- Puppet::Settings.clean_opt("--[no-]option", false).should == ["--no-option", false]
+ expect(Puppet::Settings.clean_opt("--[no-]option", false)).to eq(["--no-option", false])
end
it "should set preferred run mode from --run_mode <foo> string without error" do
args = ["--run_mode", "master"]
settings.expects(:handlearg).with("--run_mode", "master").never
expect { settings.send(:parse_global_options, args) } .to_not raise_error
- Puppet.settings.preferred_run_mode.should == :master
- args.empty?.should == true
+ expect(Puppet.settings.preferred_run_mode).to eq(:master)
+ expect(args.empty?).to eq(true)
end
it "should set preferred run mode from --run_mode=<foo> string without error" do
args = ["--run_mode=master"]
settings.expects(:handlearg).with("--run_mode", "master").never
expect { settings.send(:parse_global_options, args) } .to_not raise_error
- Puppet.settings.preferred_run_mode.should == :master
- args.empty?.should == true
+ expect(Puppet.settings.preferred_run_mode).to eq(:master)
+ expect(args.empty?).to eq(true)
end
end
describe "default_certname" do
describe "using hostname and domainname" do
before :each do
Puppet::Settings.stubs(:hostname_fact).returns("testhostname")
Puppet::Settings.stubs(:domain_fact).returns("domain.test.")
end
it "should use both to generate fqdn" do
- Puppet::Settings.default_certname.should =~ /testhostname\.domain\.test/
+ expect(Puppet::Settings.default_certname).to match(/testhostname\.domain\.test/)
end
it "should remove trailing dots from fqdn" do
- Puppet::Settings.default_certname.should == 'testhostname.domain.test'
+ expect(Puppet::Settings.default_certname).to eq('testhostname.domain.test')
end
end
describe "using just hostname" do
before :each do
Puppet::Settings.stubs(:hostname_fact).returns("testhostname")
Puppet::Settings.stubs(:domain_fact).returns("")
end
it "should use only hostname to generate fqdn" do
- Puppet::Settings.default_certname.should == "testhostname"
+ expect(Puppet::Settings.default_certname).to eq("testhostname")
end
it "should removing trailing dots from fqdn" do
- Puppet::Settings.default_certname.should == "testhostname"
+ expect(Puppet::Settings.default_certname).to eq("testhostname")
end
end
end
end
diff --git a/spec/unit/ssl/base_spec.rb b/spec/unit/ssl/base_spec.rb
index 3ca5a7492..c1c47208b 100755
--- a/spec/unit/ssl/base_spec.rb
+++ b/spec/unit/ssl/base_spec.rb
@@ -1,85 +1,85 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/certificate'
class TestCertificate < Puppet::SSL::Base
wraps(Puppet::SSL::Certificate)
end
describe Puppet::SSL::Certificate do
before :each do
@base = TestCertificate.new("name")
@class = TestCertificate
end
describe "when creating new instances" do
it "should fail if given an object that is not an instance of the wrapped class" do
obj = stub 'obj', :is_a? => false
- lambda { @class.from_instance(obj) }.should raise_error(ArgumentError)
+ expect { @class.from_instance(obj) }.to raise_error(ArgumentError)
end
it "should fail if a name is not supplied and can't be determined from the object" do
obj = stub 'obj', :is_a? => true
- lambda { @class.from_instance(obj) }.should raise_error(ArgumentError)
+ expect { @class.from_instance(obj) }.to raise_error(ArgumentError)
end
it "should determine the name from the object if it has a subject" do
obj = stub 'obj', :is_a? => true, :subject => '/CN=foo'
inst = stub 'base'
inst.expects(:content=).with(obj)
@class.expects(:new).with('foo').returns inst
@class.expects(:name_from_subject).with('/CN=foo').returns('foo')
- @class.from_instance(obj).should == inst
+ expect(@class.from_instance(obj)).to eq(inst)
end
end
describe "when determining a name from a certificate subject" do
it "should extract only the CN and not any other components" do
subject = stub 'sub'
Puppet::Util::SSL.expects(:cn_from_subject).with(subject).returns 'host.domain.com'
- @class.name_from_subject(subject).should == 'host.domain.com'
+ expect(@class.name_from_subject(subject)).to eq('host.domain.com')
end
end
describe "#digest_algorithm" do
let(:content) { stub 'content' }
let(:base) {
b = Puppet::SSL::Base.new('base')
b.content = content
b
}
# Some known signature algorithms taken from RFC 3279, 5758, and browsing
# objs_dat.h in openssl
{
'md5WithRSAEncryption' => 'md5',
'sha1WithRSAEncryption' => 'sha1',
'md4WithRSAEncryption' => 'md4',
'sha256WithRSAEncryption' => 'sha256',
'ripemd160WithRSA' => 'ripemd160',
'ecdsa-with-SHA1' => 'sha1',
'ecdsa-with-SHA224' => 'sha224',
'ecdsa-with-SHA256' => 'sha256',
'ecdsa-with-SHA384' => 'sha384',
'ecdsa-with-SHA512' => 'sha512',
'dsa_with_SHA224' => 'sha224',
'dsaWithSHA1' => 'sha1',
}.each do |signature, digest|
it "returns '#{digest}' for signature algorithm '#{signature}'" do
content.stubs(:signature_algorithm).returns(signature)
- base.digest_algorithm.should == digest
+ expect(base.digest_algorithm).to eq(digest)
end
end
it "raises an error on an unknown signature algorithm" do
content.stubs(:signature_algorithm).returns("nonsense")
expect {
base.digest_algorithm
}.to raise_error(Puppet::Error, "Unknown signature algorithm 'nonsense'")
end
end
end
diff --git a/spec/unit/ssl/certificate_authority/autosign_command_spec.rb b/spec/unit/ssl/certificate_authority/autosign_command_spec.rb
index 5792bb4f5..1ae49851b 100644
--- a/spec/unit/ssl/certificate_authority/autosign_command_spec.rb
+++ b/spec/unit/ssl/certificate_authority/autosign_command_spec.rb
@@ -1,30 +1,30 @@
require 'spec_helper'
require 'puppet/ssl/certificate_authority/autosign_command'
describe Puppet::SSL::CertificateAuthority::AutosignCommand do
let(:csr) { stub 'csr', :name => 'host', :to_s => 'CSR PEM goes here' }
let(:decider) { Puppet::SSL::CertificateAuthority::AutosignCommand.new('/autosign/command') }
it "returns true if the command succeeded" do
executes_the_command_resulting_in(0)
- decider.allowed?(csr).should == true
+ expect(decider.allowed?(csr)).to eq(true)
end
it "returns false if the command failed" do
executes_the_command_resulting_in(1)
- decider.allowed?(csr).should == false
+ expect(decider.allowed?(csr)).to eq(false)
end
def executes_the_command_resulting_in(exitstatus)
Puppet::Util::Execution.expects(:execute).
with(['/autosign/command', 'host'],
has_entries(:stdinfile => anything,
:combine => true,
:failonfail => false)).
returns(Puppet::Util::Execution::ProcessOutput.new('', exitstatus))
end
end
diff --git a/spec/unit/ssl/certificate_authority/interface_spec.rb b/spec/unit/ssl/certificate_authority/interface_spec.rb
index ec4dc6dfc..0ba1770ee 100755
--- a/spec/unit/ssl/certificate_authority/interface_spec.rb
+++ b/spec/unit/ssl/certificate_authority/interface_spec.rb
@@ -1,393 +1,393 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/certificate_authority'
shared_examples_for "a normal interface method" do
it "should call the method on the CA for each host specified if an array was provided" do
@ca.expects(@method).with("host1")
@ca.expects(@method).with("host2")
@applier = Puppet::SSL::CertificateAuthority::Interface.new(@method, :to => %w{host1 host2})
@applier.apply(@ca)
end
it "should call the method on the CA for all existing certificates if :all was provided" do
@ca.expects(:list).returns %w{host1 host2}
@ca.expects(@method).with("host1")
@ca.expects(@method).with("host2")
@applier = Puppet::SSL::CertificateAuthority::Interface.new(@method, :to => :all)
@applier.apply(@ca)
end
end
shared_examples_for "a destructive interface method" do
it "calls the method on the CA for each host specified if an array was provided" do
@ca.expects(@method).with("host1")
@ca.expects(@method).with("host2")
@applier = Puppet::SSL::CertificateAuthority::Interface.new(@method, :to => %w{host1 host2})
@applier.apply(@ca)
end
it "raises an error if :all was provided" do
@applier = Puppet::SSL::CertificateAuthority::Interface.new(@method, :to => :all)
expect {
@applier.apply(@ca)
}.to raise_error(ArgumentError, /Refusing to #{@method} all certs/)
end
it "raises an error if :signed was provided" do
@applier = Puppet::SSL::CertificateAuthority::Interface.new(@method, :to => :signed)
expect {
@applier.apply(@ca)
}.to raise_error(ArgumentError, /Refusing to #{@method} all signed certs/)
end
end
describe Puppet::SSL::CertificateAuthority::Interface do
before do
@class = Puppet::SSL::CertificateAuthority::Interface
end
describe "when initializing" do
it "should set its method using its settor" do
instance = @class.new(:generate, :to => :all)
- instance.method.should == :generate
+ expect(instance.method).to eq(:generate)
end
it "should set its subjects using the settor" do
instance = @class.new(:generate, :to => :all)
- instance.subjects.should == :all
+ expect(instance.subjects).to eq(:all)
end
it "should set the digest if given" do
interface = @class.new(:generate, :to => :all, :digest => :digest)
- interface.digest.should == :digest
+ expect(interface.digest).to eq(:digest)
end
end
describe "when setting the method" do
it "should set the method" do
instance = @class.new(:generate, :to => :all)
instance.method = :list
- instance.method.should == :list
+ expect(instance.method).to eq(:list)
end
it "should fail if the method isn't a member of the INTERFACE_METHODS array" do
- lambda { @class.new(:thing, :to => :all) }.should raise_error(ArgumentError, /Invalid method thing to apply/)
+ expect { @class.new(:thing, :to => :all) }.to raise_error(ArgumentError, /Invalid method thing to apply/)
end
end
describe "when setting the subjects" do
it "should set the subjects" do
instance = @class.new(:generate, :to => :all)
instance.subjects = :signed
- instance.subjects.should == :signed
+ expect(instance.subjects).to eq(:signed)
end
it "should fail if the subjects setting isn't :all or an array" do
- lambda { @class.new(:generate, :to => "other") }.should raise_error(ArgumentError, /Subjects must be an array or :all; not other/)
+ expect { @class.new(:generate, :to => "other") }.to raise_error(ArgumentError, /Subjects must be an array or :all; not other/)
end
end
it "should have a method for triggering the application" do
- @class.new(:generate, :to => :all).should respond_to(:apply)
+ expect(@class.new(:generate, :to => :all)).to respond_to(:apply)
end
describe "when applying" do
before do
# We use a real object here, because :verify can't be stubbed, apparently.
@ca = Object.new
end
describe "with an empty array specified and the method is not list" do
it "should fail" do
@applier = @class.new(:sign, :to => [])
- lambda { @applier.apply(@ca) }.should raise_error(ArgumentError)
+ expect { @applier.apply(@ca) }.to raise_error(ArgumentError)
end
end
describe ":generate" do
it "should fail if :all was specified" do
@applier = @class.new(:generate, :to => :all)
- lambda { @applier.apply(@ca) }.should raise_error(ArgumentError)
+ expect { @applier.apply(@ca) }.to raise_error(ArgumentError)
end
it "should call :generate on the CA for each host specified" do
@applier = @class.new(:generate, :to => %w{host1 host2})
@ca.expects(:generate).with("host1", {})
@ca.expects(:generate).with("host2", {})
@applier.apply(@ca)
end
end
describe ":verify" do
before { @method = :verify }
#it_should_behave_like "a normal interface method"
it "should call the method on the CA for each host specified if an array was provided" do
# LAK:NOTE Mocha apparently doesn't allow you to mock :verify, but I'm confident this works in real life.
end
it "should call the method on the CA for all existing certificates if :all was provided" do
# LAK:NOTE Mocha apparently doesn't allow you to mock :verify, but I'm confident this works in real life.
end
end
describe ":destroy" do
before { @method = :destroy }
it_should_behave_like "a destructive interface method"
end
describe ":revoke" do
before { @method = :revoke }
it_should_behave_like "a destructive interface method"
end
describe ":sign" do
describe "and an array of names was provided" do
let(:applier) { @class.new(:sign, @options.merge(:to => %w{host1 host2})) }
it "should sign the specified waiting certificate requests" do
@options = {:allow_dns_alt_names => false}
@ca.expects(:sign).with("host1", false)
@ca.expects(:sign).with("host2", false)
applier.apply(@ca)
end
it "should sign the certificate requests with alt names if specified" do
@options = {:allow_dns_alt_names => true}
@ca.expects(:sign).with("host1", true)
@ca.expects(:sign).with("host2", true)
applier.apply(@ca)
end
end
describe "and :all was provided" do
it "should sign all waiting certificate requests" do
@ca.stubs(:waiting?).returns(%w{cert1 cert2})
@ca.expects(:sign).with("cert1", nil)
@ca.expects(:sign).with("cert2", nil)
@applier = @class.new(:sign, :to => :all)
@applier.apply(@ca)
end
it "should fail if there are no waiting certificate requests" do
@ca.stubs(:waiting?).returns([])
@applier = @class.new(:sign, :to => :all)
- lambda { @applier.apply(@ca) }.should raise_error(Puppet::SSL::CertificateAuthority::Interface::InterfaceError)
+ expect { @applier.apply(@ca) }.to raise_error(Puppet::SSL::CertificateAuthority::Interface::InterfaceError)
end
end
end
describe ":list" do
before :each do
@cert = Puppet::SSL::Certificate.new 'foo'
@csr = Puppet::SSL::CertificateRequest.new 'bar'
@cert.stubs(:subject_alt_names).returns []
@csr.stubs(:subject_alt_names).returns []
Puppet::SSL::Certificate.indirection.stubs(:find).returns @cert
Puppet::SSL::CertificateRequest.indirection.stubs(:find).returns @csr
@digest = mock("digest")
@digest.stubs(:to_s).returns("(fingerprint)")
@ca.expects(:waiting?).returns %w{host1 host2 host3}
@ca.expects(:list).returns(%w{host4 host5 host6}).at_most(1)
@csr.stubs(:digest).returns @digest
@cert.stubs(:digest).returns @digest
@ca.stubs(:verify)
end
describe "and an empty array was provided" do
it "should print all certificate requests" do
applier = @class.new(:list, :to => [])
applier.expects(:puts).with(<<-OUTPUT.chomp)
"host1" (fingerprint)
"host2" (fingerprint)
"host3" (fingerprint)
OUTPUT
applier.apply(@ca)
end
end
describe "and :all was provided" do
it "should print a string containing all certificate requests and certificates" do
@ca.expects(:list).returns %w{host4 host5 host6}
@ca.stubs(:verify).with("host4").raises(Puppet::SSL::CertificateAuthority::CertificateVerificationError.new(23), "certificate revoked")
applier = @class.new(:list, :to => :all)
applier.expects(:puts).with(<<-OUTPUT.chomp)
"host1" (fingerprint)
"host2" (fingerprint)
"host3" (fingerprint)
+ "host5" (fingerprint)
+ "host6" (fingerprint)
- "host4" (fingerprint) (certificate revoked)
OUTPUT
applier.apply(@ca)
end
end
describe "and :signed was provided" do
it "should print a string containing all signed certificate requests and certificates" do
@ca.expects(:list).returns %w{host4 host5 host6}
applier = @class.new(:list, :to => :signed)
applier.expects(:puts).with(<<-OUTPUT.chomp)
+ "host4" (fingerprint)
+ "host5" (fingerprint)
+ "host6" (fingerprint)
OUTPUT
applier.apply(@ca)
end
it "should include subject alt names if they are on the certificate request" do
@csr.stubs(:subject_alt_names).returns ["DNS:foo", "DNS:bar"]
applier = @class.new(:list, :to => ['host1'])
applier.expects(:puts).with(<<-OUTPUT.chomp)
"host1" (fingerprint) (alt names: "DNS:foo", "DNS:bar")
OUTPUT
applier.apply(@ca)
end
end
describe "and an array of names was provided" do
it "should print all named hosts" do
applier = @class.new(:list, :to => %w{host1 host2 host4 host5})
applier.expects(:puts).with(<<-OUTPUT.chomp)
"host1" (fingerprint)
"host2" (fingerprint)
+ "host4" (fingerprint)
+ "host5" (fingerprint)
OUTPUT
applier.apply(@ca)
end
end
end
describe ":print" do
describe "and :all was provided" do
it "should print all certificates" do
@ca.expects(:list).returns %w{host1 host2}
@applier = @class.new(:print, :to => :all)
@ca.expects(:print).with("host1").returns "h1"
@applier.expects(:puts).with "h1"
@ca.expects(:print).with("host2").returns "h2"
@applier.expects(:puts).with "h2"
@applier.apply(@ca)
end
end
describe "and an array of names was provided" do
it "should print each named certificate if found" do
@applier = @class.new(:print, :to => %w{host1 host2})
@ca.expects(:print).with("host1").returns "h1"
@applier.expects(:puts).with "h1"
@ca.expects(:print).with("host2").returns "h2"
@applier.expects(:puts).with "h2"
@applier.apply(@ca)
end
it "should log any named but not found certificates" do
@applier = @class.new(:print, :to => %w{host1 host2})
@ca.expects(:print).with("host1").returns "h1"
@applier.expects(:puts).with "h1"
@ca.expects(:print).with("host2").returns nil
Puppet.expects(:err).with { |msg| msg.include?("host2") }
@applier.apply(@ca)
end
end
end
describe ":fingerprint" do
before(:each) do
@cert = Puppet::SSL::Certificate.new 'foo'
@csr = Puppet::SSL::CertificateRequest.new 'bar'
Puppet::SSL::Certificate.indirection.stubs(:find)
Puppet::SSL::CertificateRequest.indirection.stubs(:find)
Puppet::SSL::Certificate.indirection.stubs(:find).with('host1').returns(@cert)
Puppet::SSL::CertificateRequest.indirection.stubs(:find).with('host2').returns(@csr)
end
it "should fingerprint with the set digest algorithm" do
@applier = @class.new(:fingerprint, :to => %w{host1}, :digest => :shaonemillion)
@cert.expects(:digest).with(:shaonemillion).returns("fingerprint1")
@applier.expects(:puts).with "host1 fingerprint1"
@applier.apply(@ca)
end
describe "and :all was provided" do
it "should fingerprint all certificates (including waiting ones)" do
@ca.expects(:list).returns %w{host1}
@ca.expects(:waiting?).returns %w{host2}
@applier = @class.new(:fingerprint, :to => :all)
@cert.expects(:digest).returns("fingerprint1")
@applier.expects(:puts).with "host1 fingerprint1"
@csr.expects(:digest).returns("fingerprint2")
@applier.expects(:puts).with "host2 fingerprint2"
@applier.apply(@ca)
end
end
describe "and an array of names was provided" do
it "should print each named certificate if found" do
@applier = @class.new(:fingerprint, :to => %w{host1 host2})
@cert.expects(:digest).returns("fingerprint1")
@applier.expects(:puts).with "host1 fingerprint1"
@csr.expects(:digest).returns("fingerprint2")
@applier.expects(:puts).with "host2 fingerprint2"
@applier.apply(@ca)
end
end
end
end
end
diff --git a/spec/unit/ssl/certificate_authority_spec.rb b/spec/unit/ssl/certificate_authority_spec.rb
index 2881b0a1e..7e3c23e56 100755
--- a/spec/unit/ssl/certificate_authority_spec.rb
+++ b/spec/unit/ssl/certificate_authority_spec.rb
@@ -1,1130 +1,1130 @@
#! /usr/bin/env ruby
# encoding: ASCII-8BIT
require 'spec_helper'
require 'puppet/ssl/certificate_authority'
describe Puppet::SSL::CertificateAuthority do
after do
Puppet::SSL::CertificateAuthority.instance_variable_set(:@singleton_instance, nil)
end
def stub_ca_host
@key = mock 'key'
@key.stubs(:content).returns "cakey"
@cacert = mock 'certificate'
@cacert.stubs(:content).returns "cacertificate"
@host = stub 'ssl_host', :key => @key, :certificate => @cacert, :name => Puppet::SSL::Host.ca_name
end
it "should have a class method for returning a singleton instance" do
- Puppet::SSL::CertificateAuthority.should respond_to(:instance)
+ expect(Puppet::SSL::CertificateAuthority).to respond_to(:instance)
end
describe "when finding an existing instance" do
describe "and the host is a CA host and the run_mode is master" do
before do
Puppet[:ca] = true
Puppet.run_mode.stubs(:master?).returns true
@ca = mock('ca')
Puppet::SSL::CertificateAuthority.stubs(:new).returns @ca
end
it "should return an instance" do
- Puppet::SSL::CertificateAuthority.instance.should equal(@ca)
+ expect(Puppet::SSL::CertificateAuthority.instance).to equal(@ca)
end
it "should always return the same instance" do
- Puppet::SSL::CertificateAuthority.instance.should equal(Puppet::SSL::CertificateAuthority.instance)
+ expect(Puppet::SSL::CertificateAuthority.instance).to equal(Puppet::SSL::CertificateAuthority.instance)
end
end
describe "and the host is not a CA host" do
it "should return nil" do
Puppet[:ca] = false
Puppet.run_mode.stubs(:master?).returns true
ca = mock('ca')
Puppet::SSL::CertificateAuthority.expects(:new).never
- Puppet::SSL::CertificateAuthority.instance.should be_nil
+ expect(Puppet::SSL::CertificateAuthority.instance).to be_nil
end
end
describe "and the run_mode is not master" do
it "should return nil" do
Puppet[:ca] = true
Puppet.run_mode.stubs(:master?).returns false
ca = mock('ca')
Puppet::SSL::CertificateAuthority.expects(:new).never
- Puppet::SSL::CertificateAuthority.instance.should be_nil
+ expect(Puppet::SSL::CertificateAuthority.instance).to be_nil
end
end
end
describe "when initializing" do
before do
Puppet.settings.stubs(:use)
Puppet::SSL::CertificateAuthority.any_instance.stubs(:setup)
end
it "should always set its name to the value of :certname" do
Puppet[:certname] = "ca_testing"
- Puppet::SSL::CertificateAuthority.new.name.should == "ca_testing"
+ expect(Puppet::SSL::CertificateAuthority.new.name).to eq("ca_testing")
end
it "should create an SSL::Host instance whose name is the 'ca_name'" do
Puppet::SSL::Host.expects(:ca_name).returns "caname"
host = stub 'host'
Puppet::SSL::Host.expects(:new).with("caname").returns host
Puppet::SSL::CertificateAuthority.new
end
it "should use the :main, :ca, and :ssl settings sections" do
Puppet.settings.expects(:use).with(:main, :ssl, :ca)
Puppet::SSL::CertificateAuthority.new
end
it "should make sure the CA is set up" do
Puppet::SSL::CertificateAuthority.any_instance.expects(:setup)
Puppet::SSL::CertificateAuthority.new
end
end
describe "when setting itself up" do
it "should generate the CA certificate if it does not have one" do
Puppet.settings.stubs :use
host = stub 'host'
Puppet::SSL::Host.stubs(:new).returns host
host.expects(:certificate).returns nil
Puppet::SSL::CertificateAuthority.any_instance.expects(:generate_ca_certificate)
Puppet::SSL::CertificateAuthority.new
end
end
describe "when retrieving the certificate revocation list" do
before do
Puppet.settings.stubs(:use)
Puppet[:cacrl] = "/my/crl"
cert = stub("certificate", :content => "real_cert")
key = stub("key", :content => "real_key")
@host = stub 'host', :certificate => cert, :name => "hostname", :key => key
Puppet::SSL::CertificateAuthority.any_instance.stubs(:setup)
@ca = Puppet::SSL::CertificateAuthority.new
@ca.stubs(:host).returns @host
end
it "should return any found CRL instance" do
crl = mock 'crl'
Puppet::SSL::CertificateRevocationList.indirection.expects(:find).returns crl
- @ca.crl.should equal(crl)
+ expect(@ca.crl).to equal(crl)
end
it "should create, generate, and save a new CRL instance of no CRL can be found" do
crl = Puppet::SSL::CertificateRevocationList.new("fakename")
Puppet::SSL::CertificateRevocationList.indirection.expects(:find).returns nil
Puppet::SSL::CertificateRevocationList.expects(:new).returns crl
crl.expects(:generate).with(@ca.host.certificate.content, @ca.host.key.content)
Puppet::SSL::CertificateRevocationList.indirection.expects(:save).with(crl)
- @ca.crl.should equal(crl)
+ expect(@ca.crl).to equal(crl)
end
end
describe "when generating a self-signed CA certificate" do
before do
Puppet.settings.stubs(:use)
Puppet::SSL::CertificateAuthority.any_instance.stubs(:setup)
Puppet::SSL::CertificateAuthority.any_instance.stubs(:crl)
@ca = Puppet::SSL::CertificateAuthority.new
@host = stub 'host', :key => mock("key"), :name => "hostname", :certificate => mock('certificate')
Puppet::SSL::CertificateRequest.any_instance.stubs(:generate)
@ca.stubs(:host).returns @host
end
it "should create and store a password at :capass" do
Puppet[:capass] = File.expand_path("/path/to/pass")
Puppet::FileSystem.expects(:exist?).with(Puppet[:capass]).returns false
fh = StringIO.new
Puppet.settings.setting(:capass).expects(:open).with('w').yields fh
@ca.stubs(:sign)
@ca.generate_ca_certificate
expect(fh.string.length).to be > 18
end
it "should generate a key if one does not exist" do
@ca.stubs :generate_password
@ca.stubs :sign
@ca.host.expects(:key).returns nil
@ca.host.expects(:generate_key)
@ca.generate_ca_certificate
end
it "should create and sign a self-signed cert using the CA name" do
request = mock 'request'
Puppet::SSL::CertificateRequest.expects(:new).with(@ca.host.name).returns request
request.expects(:generate).with(@ca.host.key)
request.stubs(:request_extensions => [])
@ca.expects(:sign).with(@host.name, false, request)
@ca.stubs :generate_password
@ca.generate_ca_certificate
end
it "should generate its CRL" do
@ca.stubs :generate_password
@ca.stubs :sign
@ca.host.expects(:key).returns nil
@ca.host.expects(:generate_key)
@ca.expects(:crl)
@ca.generate_ca_certificate
end
end
describe "when signing" do
before do
Puppet.settings.stubs(:use)
Puppet::SSL::CertificateAuthority.any_instance.stubs(:password?).returns true
stub_ca_host
Puppet::SSL::Host.expects(:new).with(Puppet::SSL::Host.ca_name).returns @host
@ca = Puppet::SSL::CertificateAuthority.new
@name = "myhost"
@real_cert = stub 'realcert', :sign => nil
@cert = Puppet::SSL::Certificate.new(@name)
@cert.content = @real_cert
Puppet::SSL::Certificate.stubs(:new).returns @cert
Puppet::SSL::Certificate.indirection.stubs(:save)
# Stub out the factory
Puppet::SSL::CertificateFactory.stubs(:build).returns @cert.content
@request_content = stub "request content stub", :subject => OpenSSL::X509::Name.new([['CN', @name]]), :public_key => stub('public_key')
@request = stub 'request', :name => @name, :request_extensions => [], :subject_alt_names => [], :content => @request_content
@request_content.stubs(:verify).returns(true)
# And the inventory
@inventory = stub 'inventory', :add => nil
@ca.stubs(:inventory).returns @inventory
Puppet::SSL::CertificateRequest.indirection.stubs(:destroy)
end
describe "its own certificate" do
before do
@serial = 10
@ca.stubs(:next_serial).returns @serial
end
it "should not look up a certificate request for the host" do
Puppet::SSL::CertificateRequest.indirection.expects(:find).never
@ca.sign(@name, true, @request)
end
it "should use a certificate type of :ca" do
Puppet::SSL::CertificateFactory.expects(:build).with do |*args|
- args[0].should == :ca
+ expect(args[0]).to eq(:ca)
end.returns @cert.content
@ca.sign(@name, :ca, @request)
end
it "should pass the provided CSR as the CSR" do
Puppet::SSL::CertificateFactory.expects(:build).with do |*args|
- args[1].should == @request
+ expect(args[1]).to eq(@request)
end.returns @cert.content
@ca.sign(@name, :ca, @request)
end
it "should use the provided CSR's content as the issuer" do
Puppet::SSL::CertificateFactory.expects(:build).with do |*args|
- args[2].subject.to_s.should == "/CN=myhost"
+ expect(args[2].subject.to_s).to eq("/CN=myhost")
end.returns @cert.content
@ca.sign(@name, :ca, @request)
end
it "should pass the next serial as the serial number" do
Puppet::SSL::CertificateFactory.expects(:build).with do |*args|
- args[3].should == @serial
+ expect(args[3]).to eq(@serial)
end.returns @cert.content
@ca.sign(@name, :ca, @request)
end
it "should sign the certificate request even if it contains alt names" do
@request.stubs(:subject_alt_names).returns %w[DNS:foo DNS:bar DNS:baz]
expect do
@ca.sign(@name, false, @request)
end.not_to raise_error
end
it "should save the resulting certificate" do
Puppet::SSL::Certificate.indirection.expects(:save).with(@cert)
@ca.sign(@name, :ca, @request)
end
end
describe "another host's certificate" do
before do
@serial = 10
@ca.stubs(:next_serial).returns @serial
Puppet::SSL::CertificateRequest.indirection.stubs(:find).with(@name).returns @request
Puppet::SSL::CertificateRequest.indirection.stubs :save
end
it "should use a certificate type of :server" do
Puppet::SSL::CertificateFactory.expects(:build).with do |*args|
args[0] == :server
end.returns @cert.content
@ca.sign(@name)
end
it "should use look up a CSR for the host in the :ca_file terminus" do
Puppet::SSL::CertificateRequest.indirection.expects(:find).with(@name).returns @request
@ca.sign(@name)
end
it "should fail if no CSR can be found for the host" do
Puppet::SSL::CertificateRequest.indirection.expects(:find).with(@name).returns nil
expect { @ca.sign(@name) }.to raise_error(ArgumentError)
end
it "should fail if an unknown request extension is present" do
@request.stubs :request_extensions => [{ "oid" => "bananas",
"value" => "delicious" }]
expect {
@ca.sign(@name)
}.to raise_error(/CSR has request extensions that are not permitted/)
end
it "should fail if the CSR contains alt names and they are not expected" do
@request.stubs(:subject_alt_names).returns %w[DNS:foo DNS:bar DNS:baz]
expect do
@ca.sign(@name, false)
end.to raise_error(Puppet::SSL::CertificateAuthority::CertificateSigningError, /CSR '#{@name}' contains subject alternative names \(.*?\), which are disallowed. Use `puppet cert --allow-dns-alt-names sign #{@name}` to sign this request./)
end
it "should not fail if the CSR does not contain alt names and they are expected" do
@request.stubs(:subject_alt_names).returns []
expect { @ca.sign(@name, true) }.to_not raise_error
end
it "should reject alt names by default" do
@request.stubs(:subject_alt_names).returns %w[DNS:foo DNS:bar DNS:baz]
expect do
@ca.sign(@name)
end.to raise_error(Puppet::SSL::CertificateAuthority::CertificateSigningError, /CSR '#{@name}' contains subject alternative names \(.*?\), which are disallowed. Use `puppet cert --allow-dns-alt-names sign #{@name}` to sign this request./)
end
it "should use the CA certificate as the issuer" do
Puppet::SSL::CertificateFactory.expects(:build).with do |*args|
args[2] == @cacert.content
end.returns @cert.content
signed = @ca.sign(@name)
end
it "should pass the next serial as the serial number" do
Puppet::SSL::CertificateFactory.expects(:build).with do |*args|
args[3] == @serial
end.returns @cert.content
@ca.sign(@name)
end
it "should sign the resulting certificate using its real key and a digest" do
digest = mock 'digest'
OpenSSL::Digest::SHA256.expects(:new).returns digest
key = stub 'key', :content => "real_key"
@ca.host.stubs(:key).returns key
@cert.content.expects(:sign).with("real_key", digest)
@ca.sign(@name)
end
it "should save the resulting certificate" do
Puppet::SSL::Certificate.indirection.stubs(:save).with(@cert)
@ca.sign(@name)
end
it "should remove the host's certificate request" do
Puppet::SSL::CertificateRequest.indirection.expects(:destroy).with(@name)
@ca.sign(@name)
end
it "should check the internal signing policies" do
@ca.expects(:check_internal_signing_policies).returns true
@ca.sign(@name)
end
end
context "#check_internal_signing_policies" do
before do
@serial = 10
@ca.stubs(:next_serial).returns @serial
Puppet::SSL::CertificateRequest.indirection.stubs(:find).with(@name).returns @request
@cert.stubs :save
end
it "should reject CSRs whose CN doesn't match the name for which we're signing them" do
# Shorten this so the test doesn't take too long
Puppet[:keylength] = 1024
key = Puppet::SSL::Key.new('the_certname')
key.generate
csr = Puppet::SSL::CertificateRequest.new('the_certname')
csr.generate(key)
expect do
@ca.check_internal_signing_policies('not_the_certname', csr, false)
end.to raise_error(
Puppet::SSL::CertificateAuthority::CertificateSigningError,
/common name "the_certname" does not match expected certname "not_the_certname"/
)
end
describe "when validating the CN" do
before :all do
Puppet[:keylength] = 1024
Puppet[:passfile] = '/f00'
@signing_key = Puppet::SSL::Key.new('my_signing_key')
@signing_key.generate
end
[
'completely_okay',
'sure, why not? :)',
'so+many(things)-are=allowed.',
'this"is#just&madness%you[see]',
'and even a (an?) \\!',
'waltz, nymph, for quick jigs vex bud.',
'{552c04ca-bb1b-11e1-874b-60334b04494e}'
].each do |name|
it "should accept #{name.inspect}" do
csr = Puppet::SSL::CertificateRequest.new(name)
csr.generate(@signing_key)
@ca.check_internal_signing_policies(name, csr, false)
end
end
[
'super/bad',
"not\neven\tkind\rof",
"ding\adong\a",
"hidden\b\b\b\b\b\bmessage",
"\xE2\x98\x83 :("
].each do |name|
it "should reject #{name.inspect}" do
# We aren't even allowed to make objects with these names, so let's
# stub that to simulate an invalid one coming from outside Puppet
Puppet::SSL::CertificateRequest.stubs(:validate_certname)
csr = Puppet::SSL::CertificateRequest.new(name)
csr.generate(@signing_key)
expect do
@ca.check_internal_signing_policies(name, csr, false)
end.to raise_error(
Puppet::SSL::CertificateAuthority::CertificateSigningError,
/subject contains unprintable or non-ASCII characters/
)
end
end
end
it "accepts numeric OIDs under the ppRegCertExt subtree" do
exts = [{ 'oid' => '1.3.6.1.4.1.34380.1.1.1',
'value' => '657e4780-4cf5-11e3-8f96-0800200c9a66'}]
@request.stubs(:request_extensions).returns exts
expect {
@ca.check_internal_signing_policies(@name, @request, false)
}.to_not raise_error
end
it "accepts short name OIDs under the ppRegCertExt subtree" do
exts = [{ 'oid' => 'pp_uuid',
'value' => '657e4780-4cf5-11e3-8f96-0800200c9a66'}]
@request.stubs(:request_extensions).returns exts
expect {
@ca.check_internal_signing_policies(@name, @request, false)
}.to_not raise_error
end
it "accepts OIDs under the ppPrivCertAttrs subtree" do
exts = [{ 'oid' => '1.3.6.1.4.1.34380.1.2.1',
'value' => 'private extension'}]
@request.stubs(:request_extensions).returns exts
expect {
@ca.check_internal_signing_policies(@name, @request, false)
}.to_not raise_error
end
it "should reject a critical extension that isn't on the whitelist" do
@request.stubs(:request_extensions).returns [{ "oid" => "banana",
"value" => "yumm",
"critical" => true }]
expect { @ca.check_internal_signing_policies(@name, @request, false) }.to raise_error(
Puppet::SSL::CertificateAuthority::CertificateSigningError,
/request extensions that are not permitted/
)
end
it "should reject a non-critical extension that isn't on the whitelist" do
@request.stubs(:request_extensions).returns [{ "oid" => "peach",
"value" => "meh",
"critical" => false }]
expect { @ca.check_internal_signing_policies(@name, @request, false) }.to raise_error(
Puppet::SSL::CertificateAuthority::CertificateSigningError,
/request extensions that are not permitted/
)
end
it "should reject non-whitelist extensions even if a valid extension is present" do
@request.stubs(:request_extensions).returns [{ "oid" => "peach",
"value" => "meh",
"critical" => false },
{ "oid" => "subjectAltName",
"value" => "DNS:foo",
"critical" => true }]
expect { @ca.check_internal_signing_policies(@name, @request, false) }.to raise_error(
Puppet::SSL::CertificateAuthority::CertificateSigningError,
/request extensions that are not permitted/
)
end
it "should reject a subjectAltName for a non-DNS value" do
@request.stubs(:subject_alt_names).returns ['DNS:foo', 'email:bar@example.com']
expect { @ca.check_internal_signing_policies(@name, @request, true) }.to raise_error(
Puppet::SSL::CertificateAuthority::CertificateSigningError,
/subjectAltName outside the DNS label space/
)
end
it "should reject a wildcard subject" do
@request.content.stubs(:subject).
returns(OpenSSL::X509::Name.new([["CN", "*.local"]]))
expect { @ca.check_internal_signing_policies('*.local', @request, false) }.to raise_error(
Puppet::SSL::CertificateAuthority::CertificateSigningError,
/subject contains a wildcard/
)
end
it "should reject a wildcard subjectAltName" do
@request.stubs(:subject_alt_names).returns ['DNS:foo', 'DNS:*.bar']
expect { @ca.check_internal_signing_policies(@name, @request, true) }.to raise_error(
Puppet::SSL::CertificateAuthority::CertificateSigningError,
/subjectAltName contains a wildcard/
)
end
end
it "should create a certificate instance with the content set to the newly signed x509 certificate" do
@serial = 10
@ca.stubs(:next_serial).returns @serial
Puppet::SSL::CertificateRequest.indirection.stubs(:find).with(@name).returns @request
Puppet::SSL::Certificate.indirection.stubs :save
Puppet::SSL::Certificate.expects(:new).with(@name).returns @cert
@ca.sign(@name)
end
it "should return the certificate instance" do
@ca.stubs(:next_serial).returns @serial
Puppet::SSL::CertificateRequest.indirection.stubs(:find).with(@name).returns @request
Puppet::SSL::Certificate.indirection.stubs :save
- @ca.sign(@name).should equal(@cert)
+ expect(@ca.sign(@name)).to equal(@cert)
end
it "should add the certificate to its inventory" do
@ca.stubs(:next_serial).returns @serial
@inventory.expects(:add).with(@cert)
Puppet::SSL::CertificateRequest.indirection.stubs(:find).with(@name).returns @request
Puppet::SSL::Certificate.indirection.stubs :save
@ca.sign(@name)
end
it "should have a method for triggering autosigning of available CSRs" do
- @ca.should respond_to(:autosign)
+ expect(@ca).to respond_to(:autosign)
end
describe "when autosigning certificates" do
let(:csr) { Puppet::SSL::CertificateRequest.new("host") }
describe "using the autosign setting" do
let(:autosign) { File.expand_path("/auto/sign") }
it "should do nothing if autosign is disabled" do
Puppet[:autosign] = false
@ca.expects(:sign).never
@ca.autosign(csr)
end
it "should do nothing if no autosign.conf exists" do
Puppet[:autosign] = autosign
non_existent_file = Puppet::FileSystem::MemoryFile.a_missing_file(autosign)
Puppet::FileSystem.overlay(non_existent_file) do
@ca.expects(:sign).never
@ca.autosign(csr)
end
end
describe "and autosign is enabled and the autosign.conf file exists" do
let(:store) { stub 'store', :allow => nil, :allowed? => false }
before do
Puppet[:autosign] = autosign
end
describe "when creating the AuthStore instance to verify autosigning" do
it "should create an AuthStore with each line in the configuration file allowed to be autosigned" do
Puppet::FileSystem.overlay(Puppet::FileSystem::MemoryFile.a_regular_file_containing(autosign, "one\ntwo\n")) do
Puppet::Network::AuthStore.stubs(:new).returns store
store.expects(:allow).with("one")
store.expects(:allow).with("two")
@ca.autosign(csr)
end
end
it "should reparse the autosign configuration on each call" do
Puppet::FileSystem.overlay(Puppet::FileSystem::MemoryFile.a_regular_file_containing(autosign, "one")) do
Puppet::Network::AuthStore.stubs(:new).times(2).returns store
@ca.autosign(csr)
@ca.autosign(csr)
end
end
it "should ignore comments" do
Puppet::FileSystem.overlay(Puppet::FileSystem::MemoryFile.a_regular_file_containing(autosign, "one\n#two\n")) do
Puppet::Network::AuthStore.stubs(:new).returns store
store.expects(:allow).with("one")
@ca.autosign(csr)
end
end
it "should ignore blank lines" do
Puppet::FileSystem.overlay(Puppet::FileSystem::MemoryFile.a_regular_file_containing(autosign, "one\n\n")) do
Puppet::Network::AuthStore.stubs(:new).returns store
store.expects(:allow).with("one")
@ca.autosign(csr)
end
end
end
end
end
describe "using the autosign command setting" do
let(:cmd) { File.expand_path('/autosign_cmd') }
let(:autosign_cmd) { mock 'autosign_command' }
let(:autosign_executable) { Puppet::FileSystem::MemoryFile.an_executable(cmd) }
before do
Puppet[:autosign] = cmd
Puppet::SSL::CertificateAuthority::AutosignCommand.stubs(:new).returns autosign_cmd
end
it "autosigns the CSR if the autosign command returned true" do
Puppet::FileSystem.overlay(autosign_executable) do
autosign_cmd.expects(:allowed?).with(csr).returns true
@ca.expects(:sign).with('host')
@ca.autosign(csr)
end
end
it "doesn't autosign the CSR if the autosign_command returned false" do
Puppet::FileSystem.overlay(autosign_executable) do
autosign_cmd.expects(:allowed?).with(csr).returns false
@ca.expects(:sign).never
@ca.autosign(csr)
end
end
end
end
end
describe "when managing certificate clients" do
before do
Puppet.settings.stubs(:use)
Puppet::SSL::CertificateAuthority.any_instance.stubs(:password?).returns true
stub_ca_host
Puppet::SSL::Host.expects(:new).returns @host
Puppet::SSL::CertificateAuthority.any_instance.stubs(:host).returns @host
@cacert = mock 'certificate'
@cacert.stubs(:content).returns "cacertificate"
@ca = Puppet::SSL::CertificateAuthority.new
end
it "should be able to list waiting certificate requests" do
req1 = stub 'req1', :name => "one"
req2 = stub 'req2', :name => "two"
Puppet::SSL::CertificateRequest.indirection.expects(:search).with("*").returns [req1, req2]
- @ca.waiting?.should == %w{one two}
+ expect(@ca.waiting?).to eq(%w{one two})
end
it "should delegate removing hosts to the Host class" do
Puppet::SSL::Host.expects(:destroy).with("myhost")
@ca.destroy("myhost")
end
it "should be able to verify certificates" do
- @ca.should respond_to(:verify)
+ expect(@ca).to respond_to(:verify)
end
it "should list certificates as the sorted list of all existing signed certificates" do
cert1 = stub 'cert1', :name => "cert1"
cert2 = stub 'cert2', :name => "cert2"
Puppet::SSL::Certificate.indirection.expects(:search).with("*").returns [cert1, cert2]
- @ca.list.should == %w{cert1 cert2}
+ expect(@ca.list).to eq(%w{cert1 cert2})
end
it "should list the full certificates" do
cert1 = stub 'cert1', :name => "cert1"
cert2 = stub 'cert2', :name => "cert2"
Puppet::SSL::Certificate.indirection.expects(:search).with("*").returns [cert1, cert2]
- @ca.list_certificates.should == [cert1, cert2]
+ expect(@ca.list_certificates).to eq([cert1, cert2])
end
describe "and printing certificates" do
it "should return nil if the certificate cannot be found" do
Puppet::SSL::Certificate.indirection.expects(:find).with("myhost").returns nil
- @ca.print("myhost").should be_nil
+ expect(@ca.print("myhost")).to be_nil
end
it "should print certificates by calling :to_text on the host's certificate" do
cert1 = stub 'cert1', :name => "cert1", :to_text => "mytext"
Puppet::SSL::Certificate.indirection.expects(:find).with("myhost").returns cert1
- @ca.print("myhost").should == "mytext"
+ expect(@ca.print("myhost")).to eq("mytext")
end
end
describe "and fingerprinting certificates" do
before :each do
@cert = stub 'cert', :name => "cert", :fingerprint => "DIGEST"
Puppet::SSL::Certificate.indirection.stubs(:find).with("myhost").returns @cert
Puppet::SSL::CertificateRequest.indirection.stubs(:find).with("myhost")
end
it "should raise an error if the certificate or CSR cannot be found" do
Puppet::SSL::Certificate.indirection.expects(:find).with("myhost").returns nil
Puppet::SSL::CertificateRequest.indirection.expects(:find).with("myhost").returns nil
expect { @ca.fingerprint("myhost") }.to raise_error
end
it "should try to find a CSR if no certificate can be found" do
Puppet::SSL::Certificate.indirection.expects(:find).with("myhost").returns nil
Puppet::SSL::CertificateRequest.indirection.expects(:find).with("myhost").returns @cert
@cert.expects(:fingerprint)
@ca.fingerprint("myhost")
end
it "should delegate to the certificate fingerprinting" do
@cert.expects(:fingerprint)
@ca.fingerprint("myhost")
end
it "should propagate the digest algorithm to the certificate fingerprinting system" do
@cert.expects(:fingerprint).with(:digest)
@ca.fingerprint("myhost", :digest)
end
end
describe "and verifying certificates" do
let(:cacert) { File.expand_path("/ca/cert") }
before do
@store = stub 'store', :verify => true, :add_file => nil, :purpose= => nil, :add_crl => true, :flags= => nil
OpenSSL::X509::Store.stubs(:new).returns @store
@cert = stub 'cert', :content => "mycert"
Puppet::SSL::Certificate.indirection.stubs(:find).returns @cert
@crl = stub('crl', :content => "mycrl")
@ca.stubs(:crl).returns @crl
end
it "should fail if the host's certificate cannot be found" do
Puppet::SSL::Certificate.indirection.expects(:find).with("me").returns(nil)
expect { @ca.verify("me") }.to raise_error(ArgumentError)
end
it "should create an SSL Store to verify" do
OpenSSL::X509::Store.expects(:new).returns @store
@ca.verify("me")
end
it "should add the CA Certificate to the store" do
Puppet[:cacert] = cacert
@store.expects(:add_file).with cacert
@ca.verify("me")
end
it "should add the CRL to the store if the crl is enabled" do
@store.expects(:add_crl).with "mycrl"
@ca.verify("me")
end
it "should set the store purpose to OpenSSL::X509::PURPOSE_SSL_CLIENT" do
Puppet[:cacert] = cacert
@store.expects(:add_file).with cacert
@ca.verify("me")
end
it "should set the store flags to check the crl" do
@store.expects(:flags=).with OpenSSL::X509::V_FLAG_CRL_CHECK_ALL|OpenSSL::X509::V_FLAG_CRL_CHECK
@ca.verify("me")
end
it "should use the store to verify the certificate" do
@cert.expects(:content).returns "mycert"
@store.expects(:verify).with("mycert").returns true
@ca.verify("me")
end
it "should fail if the verification returns false" do
@cert.expects(:content).returns "mycert"
@store.expects(:verify).with("mycert").returns false
expect { @ca.verify("me") }.to raise_error
end
describe "certificate_is_alive?" do
it "should return false if verification fails" do
@cert.expects(:content).returns "mycert"
@store.expects(:verify).with("mycert").returns false
- @ca.certificate_is_alive?(@cert).should be_false
+ expect(@ca.certificate_is_alive?(@cert)).to be_falsey
end
it "should return true if verification passes" do
@cert.expects(:content).returns "mycert"
@store.expects(:verify).with("mycert").returns true
- @ca.certificate_is_alive?(@cert).should be_true
+ expect(@ca.certificate_is_alive?(@cert)).to be_truthy
end
it "should used a cached instance of the x509 store" do
OpenSSL::X509::Store.stubs(:new).returns(@store).once
@cert.expects(:content).returns "mycert"
@store.expects(:verify).with("mycert").returns true
@ca.certificate_is_alive?(@cert)
@ca.certificate_is_alive?(@cert)
end
end
end
describe "and revoking certificates" do
before do
@crl = mock 'crl'
@ca.stubs(:crl).returns @crl
@ca.stubs(:next_serial).returns 10
@real_cert = stub 'real_cert', :serial => 15
@cert = stub 'cert', :content => @real_cert
Puppet::SSL::Certificate.indirection.stubs(:find).returns @cert
end
it "should fail if the certificate revocation list is disabled" do
@ca.stubs(:crl).returns false
expect { @ca.revoke('ca_testing') }.to raise_error(ArgumentError)
end
it "should delegate the revocation to its CRL" do
@ca.crl.expects(:revoke)
@ca.revoke('host')
end
it "should get the serial number from the local certificate if it exists" do
@ca.crl.expects(:revoke).with { |serial, key| serial == 15 }
Puppet::SSL::Certificate.indirection.expects(:find).with("host").returns @cert
@ca.revoke('host')
end
it "should get the serial number from inventory if no local certificate exists" do
real_cert = stub 'real_cert', :serial => 15
cert = stub 'cert', :content => real_cert
Puppet::SSL::Certificate.indirection.expects(:find).with("host").returns nil
@ca.inventory.expects(:serials).with("host").returns [16]
@ca.crl.expects(:revoke).with { |serial, key| serial == 16 }
@ca.revoke('host')
end
it "should revoke all serials matching a name" do
real_cert = stub 'real_cert', :serial => 15
cert = stub 'cert', :content => real_cert
Puppet::SSL::Certificate.indirection.expects(:find).with("host").returns nil
@ca.inventory.expects(:serials).with("host").returns [16, 20, 25]
@ca.crl.expects(:revoke).with { |serial, key| serial == 16 }
@ca.crl.expects(:revoke).with { |serial, key| serial == 20 }
@ca.crl.expects(:revoke).with { |serial, key| serial == 25 }
@ca.revoke('host')
end
it "should raise an error if no certificate match" do
real_cert = stub 'real_cert', :serial => 15
cert = stub 'cert', :content => real_cert
Puppet::SSL::Certificate.indirection.expects(:find).with("host").returns nil
@ca.inventory.expects(:serials).with("host").returns []
@ca.crl.expects(:revoke).never
expect { @ca.revoke('host') }.to raise_error
end
context "revocation by serial number (#16798)" do
it "revokes when given a lower case hexadecimal formatted string" do
@ca.crl.expects(:revoke).with { |serial, key| serial == 15 }
Puppet::SSL::Certificate.indirection.expects(:find).with("0xf").returns nil
@ca.revoke('0xf')
end
it "revokes when given an upper case hexadecimal formatted string" do
@ca.crl.expects(:revoke).with { |serial, key| serial == 15 }
Puppet::SSL::Certificate.indirection.expects(:find).with("0xF").returns nil
@ca.revoke('0xF')
end
it "handles very large serial numbers" do
bighex = '0x4000000000000000000000000000000000000000'
bighex_int = 365375409332725729550921208179070754913983135744
@ca.crl.expects(:revoke).with(bighex_int, anything)
Puppet::SSL::Certificate.indirection.expects(:find).with(bighex).returns nil
@ca.revoke(bighex)
end
end
end
it "should be able to generate a complete new SSL host" do
- @ca.should respond_to(:generate)
+ expect(@ca).to respond_to(:generate)
end
end
end
require 'puppet/indirector/memory'
module CertificateAuthorityGenerateSpecs
describe "CertificateAuthority.generate" do
def expect_to_increment_serial_file
Puppet.settings.setting(:serial).expects(:exclusive_open)
end
def expect_to_sign_a_cert
expect_to_increment_serial_file
end
def expect_to_write_the_ca_password
Puppet.settings.setting(:capass).expects(:open).with('w')
end
def expect_ca_initialization
expect_to_write_the_ca_password
expect_to_sign_a_cert
end
INDIRECTED_CLASSES = [
Puppet::SSL::Certificate,
Puppet::SSL::CertificateRequest,
Puppet::SSL::CertificateRevocationList,
Puppet::SSL::Key,
]
INDIRECTED_CLASSES.each do |const|
class const::Memory < Puppet::Indirector::Memory
# @return Array of all the indirector's values
#
# This mirrors Puppet::Indirector::SslFile#search which returns all files
# in the directory.
def search(request)
return @instances.values
end
end
end
before do
Puppet::SSL::Inventory.stubs(:new).returns(stub("Inventory", :add => nil))
INDIRECTED_CLASSES.each { |const| const.indirection.terminus_class = :memory }
end
after do
INDIRECTED_CLASSES.each do |const|
const.indirection.terminus_class = :file
const.indirection.termini.clear
end
end
describe "when generating certificates" do
let(:ca) { Puppet::SSL::CertificateAuthority.new }
before do
expect_ca_initialization
end
it "should fail if a certificate already exists for the host" do
cert = Puppet::SSL::Certificate.new('pre.existing')
Puppet::SSL::Certificate.indirection.save(cert)
expect { ca.generate(cert.name) }.to raise_error(ArgumentError, /a certificate already exists/i)
end
describe "that do not yet exist" do
let(:cn) { "new.host" }
def expect_cert_does_not_exist(cn)
expect( Puppet::SSL::Certificate.indirection.find(cn) ).to be_nil
end
before do
expect_to_sign_a_cert
expect_cert_does_not_exist(cn)
end
it "should return the created certificate" do
cert = ca.generate(cn)
expect( cert ).to be_kind_of(Puppet::SSL::Certificate)
expect( cert.name ).to eq(cn)
end
it "should not have any subject_alt_names by default" do
cert = ca.generate(cn)
expect( cert.subject_alt_names ).to be_empty
end
it "should have subject_alt_names if passed dns_alt_names" do
cert = ca.generate(cn, :dns_alt_names => 'foo,bar')
expect( cert.subject_alt_names ).to match_array(["DNS:#{cn}",'DNS:foo','DNS:bar'])
end
context "if autosign is false" do
before do
Puppet[:autosign] = false
end
it "should still generate and explicitly sign the request" do
cert = nil
cert = ca.generate(cn)
expect(cert.name).to eq(cn)
end
end
context "if autosign is true (Redmine #6112)" do
def run_mode_must_be_master_for_autosign_to_be_attempted
Puppet.stubs(:run_mode).returns(Puppet::Util::RunMode[:master])
end
before do
Puppet[:autosign] = true
run_mode_must_be_master_for_autosign_to_be_attempted
Puppet::Util::Log.level = :info
end
it "should generate a cert without attempting to sign again" do
cert = ca.generate(cn)
expect(cert.name).to eq(cn)
expect(@logs.map(&:message)).to include("Autosigning #{cn}")
end
end
end
end
end
end
diff --git a/spec/unit/ssl/certificate_factory_spec.rb b/spec/unit/ssl/certificate_factory_spec.rb
index b87aaee63..30c0b75f8 100755
--- a/spec/unit/ssl/certificate_factory_spec.rb
+++ b/spec/unit/ssl/certificate_factory_spec.rb
@@ -1,177 +1,181 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/certificate_factory'
describe Puppet::SSL::CertificateFactory do
let :serial do OpenSSL::BN.new('12') end
let :name do "example.local" end
let :x509_name do OpenSSL::X509::Name.new([['CN', name]]) end
let :key do Puppet::SSL::Key.new(name).generate end
let :csr do
csr = Puppet::SSL::CertificateRequest.new(name)
csr.generate(key)
csr
end
let :issuer do
cert = Puppet::SSL::CertificateAuthority.new
cert.generate_ca_certificate
cert.host.certificate.content
end
describe "when generating the certificate" do
it "should return a new X509 certificate" do
- subject.build(:server, csr, issuer, serial).should_not ==
+ expect(subject.build(:server, csr, issuer, serial)).not_to eq(
subject.build(:server, csr, issuer, serial)
+ )
end
it "should set the certificate's version to 2" do
- subject.build(:server, csr, issuer, serial).version.should == 2
+ expect(subject.build(:server, csr, issuer, serial).version).to eq(2)
end
it "should set the certificate's subject to the CSR's subject" do
cert = subject.build(:server, csr, issuer, serial)
- cert.subject.should eql x509_name
+ expect(cert.subject).to eql x509_name
end
it "should set the certificate's issuer to the Issuer's subject" do
cert = subject.build(:server, csr, issuer, serial)
- cert.issuer.should eql issuer.subject
+ expect(cert.issuer).to eql issuer.subject
end
it "should set the certificate's public key to the CSR's public key" do
cert = subject.build(:server, csr, issuer, serial)
- cert.public_key.should be_public
- cert.public_key.to_s.should == csr.content.public_key.to_s
+ expect(cert.public_key).to be_public
+ expect(cert.public_key.to_s).to eq(csr.content.public_key.to_s)
end
it "should set the certificate's serial number to the provided serial number" do
cert = subject.build(:server, csr, issuer, serial)
- cert.serial.should == serial
+ expect(cert.serial).to eq(serial)
end
it "should have 24 hours grace on the start of the cert" do
cert = subject.build(:server, csr, issuer, serial)
- cert.not_before.should be_within(30).of(Time.now - 24*60*60)
+ expect(cert.not_before).to be_within(30).of(Time.now - 24*60*60)
end
it "should set the default TTL of the certificate to the `ca_ttl` setting" do
Puppet[:ca_ttl] = 12
now = Time.now.utc
Time.expects(:now).at_least_once.returns(now)
cert = subject.build(:server, csr, issuer, serial)
- cert.not_after.to_i.should == now.to_i + 12
+ expect(cert.not_after.to_i).to eq(now.to_i + 12)
end
it "should not allow a non-integer TTL" do
[ 'foo', 1.2, Time.now, true ].each do |ttl|
expect { subject.build(:server, csr, issuer, serial, ttl) }.to raise_error(ArgumentError)
end
end
it "should respect a custom TTL for the CA" do
now = Time.now.utc
Time.expects(:now).at_least_once.returns(now)
cert = subject.build(:server, csr, issuer, serial, 12)
- cert.not_after.to_i.should == now.to_i + 12
+ expect(cert.not_after.to_i).to eq(now.to_i + 12)
end
it "should adds an extension for the nsComment" do
cert = subject.build(:server, csr, issuer, serial)
- cert.extensions.map {|x| x.to_h }.find {|x| x["oid"] == "nsComment" }.should ==
+ expect(cert.extensions.map {|x| x.to_h }.find {|x| x["oid"] == "nsComment" }).to eq(
{ "oid" => "nsComment",
# Note that this output is due to a bug in OpenSSL::X509::Extensions
# where the values of some extensions are not properly decoded
"value" => ".(Puppet Ruby/OpenSSL Internal Certificate",
"critical" => false }
+ )
end
it "should add an extension for the subjectKeyIdentifer" do
cert = subject.build(:server, csr, issuer, serial)
ef = OpenSSL::X509::ExtensionFactory.new(issuer, cert)
- cert.extensions.map { |x| x.to_h }.find {|x| x["oid"] == "subjectKeyIdentifier" }.should ==
+ expect(cert.extensions.map { |x| x.to_h }.find {|x| x["oid"] == "subjectKeyIdentifier" }).to eq(
ef.create_extension("subjectKeyIdentifier", "hash", false).to_h
+ )
end
it "should add an extension for the authorityKeyIdentifer" do
cert = subject.build(:server, csr, issuer, serial)
ef = OpenSSL::X509::ExtensionFactory.new(issuer, cert)
- cert.extensions.map { |x| x.to_h }.find {|x| x["oid"] == "authorityKeyIdentifier" }.should ==
+ expect(cert.extensions.map { |x| x.to_h }.find {|x| x["oid"] == "authorityKeyIdentifier" }).to eq(
ef.create_extension("authorityKeyIdentifier", "keyid:always", false).to_h
+ )
end
# See #2848 for why we are doing this: we need to make sure that
# subjectAltName is set if the CSR has it, but *not* if it is set when the
# certificate is built!
it "should not add subjectAltNames from dns_alt_names" do
Puppet[:dns_alt_names] = 'one, two'
# Verify the CSR still has no extReq, just in case...
- csr.request_extensions.should == []
+ expect(csr.request_extensions).to eq([])
cert = subject.build(:server, csr, issuer, serial)
- cert.extensions.find {|x| x.oid == 'subjectAltName' }.should be_nil
+ expect(cert.extensions.find {|x| x.oid == 'subjectAltName' }).to be_nil
end
it "should add subjectAltName when the CSR requests them" do
Puppet[:dns_alt_names] = ''
expect = %w{one two} + [name]
csr = Puppet::SSL::CertificateRequest.new(name)
csr.generate(key, :dns_alt_names => expect.join(', '))
- csr.request_extensions.should_not be_nil
- csr.subject_alt_names.should =~ expect.map{|x| "DNS:#{x}"}
+ expect(csr.request_extensions).not_to be_nil
+ expect(csr.subject_alt_names).to match_array(expect.map{|x| "DNS:#{x}"})
cert = subject.build(:server, csr, issuer, serial)
san = cert.extensions.find {|x| x.oid == 'subjectAltName' }
- san.should_not be_nil
+ expect(san).not_to be_nil
expect.each do |name|
- san.value.should =~ /DNS:#{name}\b/i
+ expect(san.value).to match(/DNS:#{name}\b/i)
end
end
it "can add custom extension requests" do
csr = Puppet::SSL::CertificateRequest.new(name)
csr.generate(key)
csr.stubs(:request_extensions).returns([
{'oid' => '1.3.6.1.4.1.34380.1.2.1', 'value' => 'some-value'},
{'oid' => 'pp_uuid', 'value' => 'some-uuid'},
])
cert = subject.build(:client, csr, issuer, serial)
# The cert must be signed before being later DER-decoding
signer = Puppet::SSL::CertificateSigner.new
signer.sign(cert, key)
wrapped_cert = Puppet::SSL::Certificate.from_instance cert
priv_ext = wrapped_cert.custom_extensions.find {|ext| ext['oid'] == '1.3.6.1.4.1.34380.1.2.1'}
uuid_ext = wrapped_cert.custom_extensions.find {|ext| ext['oid'] == 'pp_uuid'}
# The expected results should be DER encoded, the Puppet cert wrapper will turn
# these into normal strings.
expect(priv_ext['value']).to eq 'some-value'
expect(uuid_ext['value']).to eq 'some-uuid'
end
# Can't check the CA here, since that requires way more infrastructure
# that I want to build up at this time. We can verify the critical
# values, though, which are non-CA certs. --daniel 2011-10-11
{ :ca => 'CA:TRUE',
:terminalsubca => ['CA:TRUE', 'pathlen:0'],
:server => 'CA:FALSE',
:ocsp => 'CA:FALSE',
:client => 'CA:FALSE',
}.each do |name, value|
it "should set basicConstraints for #{name} #{value.inspect}" do
cert = subject.build(name, csr, issuer, serial)
bc = cert.extensions.find {|x| x.oid == 'basicConstraints' }
- bc.should be
- bc.value.split(/\s*,\s*/).should =~ Array(value)
+ expect(bc).to be
+ expect(bc.value.split(/\s*,\s*/)).to match_array(Array(value))
end
end
end
end
diff --git a/spec/unit/ssl/certificate_request_attributes_spec.rb b/spec/unit/ssl/certificate_request_attributes_spec.rb
index 5c8f93b1b..c1662c2ad 100644
--- a/spec/unit/ssl/certificate_request_attributes_spec.rb
+++ b/spec/unit/ssl/certificate_request_attributes_spec.rb
@@ -1,61 +1,61 @@
require 'spec_helper'
require 'puppet/ssl/certificate_request_attributes'
describe Puppet::SSL::CertificateRequestAttributes do
let(:expected) do
{
"custom_attributes" => {
"1.3.6.1.4.1.34380.2.2"=>[3232235521, 3232235777], # system IPs in hex
"1.3.6.1.4.1.34380.2.0"=>"hostname.domain.com",
}
}
end
let(:csr_attributes_hash) { expected.dup }
let(:csr_attributes_path) { '/some/where/csr_attributes.yaml' }
let(:csr_attributes) { Puppet::SSL::CertificateRequestAttributes.new(csr_attributes_path) }
it "initializes with a path" do
expect(csr_attributes.path).to eq(csr_attributes_path)
end
describe "loading" do
it "returns nil when loading from a non-existent file" do
- expect(csr_attributes.load).to be_false
+ expect(csr_attributes.load).to be_falsey
end
context "with an available attributes file" do
before do
Puppet::FileSystem.expects(:exist?).with(csr_attributes_path).returns(true)
Puppet::Util::Yaml.expects(:load_file).with(csr_attributes_path, {}).returns(csr_attributes_hash)
end
it "loads csr attributes from a file when the file is present" do
- expect(csr_attributes.load).to be_true
+ expect(csr_attributes.load).to be_truthy
end
it "exposes custom_attributes" do
csr_attributes.load
expect(csr_attributes.custom_attributes).to eq(expected['custom_attributes'])
end
it "returns an empty hash if custom_attributes points to nil" do
csr_attributes_hash["custom_attributes"] = nil
csr_attributes.load
expect(csr_attributes.custom_attributes).to eq({})
end
it "returns an empty hash if custom_attributes key is not present" do
csr_attributes_hash.delete("custom_attributes")
csr_attributes.load
expect(csr_attributes.custom_attributes).to eq({})
end
it "raise a Puppet::Error if an unexpected root key is defined" do
csr_attributes_hash['unintentional'] = 'data'
expect { csr_attributes.load }.to raise_error(Puppet::Error, /unexpected attributes.*unintentional/)
end
end
end
end
diff --git a/spec/unit/ssl/certificate_request_spec.rb b/spec/unit/ssl/certificate_request_spec.rb
index ff65eef78..ffc54de9c 100755
--- a/spec/unit/ssl/certificate_request_spec.rb
+++ b/spec/unit/ssl/certificate_request_spec.rb
@@ -1,381 +1,381 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/certificate_request'
require 'puppet/ssl/key'
describe Puppet::SSL::CertificateRequest do
let(:request) { described_class.new("myname") }
let(:key) {
k = Puppet::SSL::Key.new("myname")
k.generate
k
}
it "should be extended with the Indirector module" do
- described_class.singleton_class.should be_include(Puppet::Indirector)
+ expect(described_class.singleton_class).to be_include(Puppet::Indirector)
end
it "should indirect certificate_request" do
- described_class.indirection.name.should == :certificate_request
+ expect(described_class.indirection.name).to eq(:certificate_request)
end
it "should use any provided name as its name" do
- described_class.new("myname").name.should == "myname"
+ expect(described_class.new("myname").name).to eq("myname")
end
it "should only support the text format" do
- described_class.supported_formats.should == [:s]
+ expect(described_class.supported_formats).to eq([:s])
end
describe "when converting from a string" do
it "should create a CSR instance with its name set to the CSR subject and its content set to the extracted CSR" do
csr = stub 'csr',
:subject => OpenSSL::X509::Name.parse("/CN=Foo.madstop.com"),
:is_a? => true
OpenSSL::X509::Request.expects(:new).with("my csr").returns(csr)
mycsr = stub 'sslcsr'
mycsr.expects(:content=).with(csr)
described_class.expects(:new).with("Foo.madstop.com").returns mycsr
described_class.from_s("my csr")
end
end
describe "when managing instances" do
it "should have a name attribute" do
- request.name.should == "myname"
+ expect(request.name).to eq("myname")
end
it "should downcase its name" do
- described_class.new("MyName").name.should == "myname"
+ expect(described_class.new("MyName").name).to eq("myname")
end
it "should have a content attribute" do
- request.should respond_to(:content)
+ expect(request).to respond_to(:content)
end
it "should be able to read requests from disk" do
path = "/my/path"
File.expects(:read).with(path).returns("my request")
my_req = mock 'request'
OpenSSL::X509::Request.expects(:new).with("my request").returns(my_req)
- request.read(path).should equal(my_req)
- request.content.should equal(my_req)
+ expect(request.read(path)).to equal(my_req)
+ expect(request.content).to equal(my_req)
end
it "should return an empty string when converted to a string with no request" do
- request.to_s.should == ""
+ expect(request.to_s).to eq("")
end
it "should convert the request to pem format when converted to a string" do
request.generate(key)
- request.to_s.should == request.content.to_pem
+ expect(request.to_s).to eq(request.content.to_pem)
end
it "should have a :to_text method that it delegates to the actual key" do
real_request = mock 'request'
real_request.expects(:to_text).returns "requesttext"
request.content = real_request
- request.to_text.should == "requesttext"
+ expect(request.to_text).to eq("requesttext")
end
end
describe "when generating" do
it "should use the content of the provided key if the key is a Puppet::SSL::Key instance" do
request.generate(key)
- request.content.verify(key.content.public_key).should be_true
+ expect(request.content.verify(key.content.public_key)).to be_truthy
end
it "should set the subject to [CN, name]" do
request.generate(key)
# OpenSSL::X509::Name only implements equality as `eql?`
- request.content.subject.should eql OpenSSL::X509::Name.new([['CN', key.name]])
+ expect(request.content.subject).to eql OpenSSL::X509::Name.new([['CN', key.name]])
end
it "should set the CN to the :ca_name setting when the CSR is for a CA" do
Puppet[:ca_name] = "mycertname"
request = described_class.new(Puppet::SSL::CA_NAME).generate(key)
- request.subject.should eql OpenSSL::X509::Name.new([['CN', Puppet[:ca_name]]])
+ expect(request.subject).to eql OpenSSL::X509::Name.new([['CN', Puppet[:ca_name]]])
end
it "should set the version to 0" do
request.generate(key)
- request.content.version.should == 0
+ expect(request.content.version).to eq(0)
end
it "should set the public key to the provided key's public key" do
request.generate(key)
# The openssl bindings do not define equality on keys so we use to_s
- request.content.public_key.to_s.should == key.content.public_key.to_s
+ expect(request.content.public_key.to_s).to eq(key.content.public_key.to_s)
end
context "without subjectAltName / dns_alt_names" do
before :each do
Puppet[:dns_alt_names] = ""
end
["extreq", "msExtReq"].each do |name|
it "should not add any #{name} attribute" do
request.generate(key)
- request.content.attributes.find do |attr|
+ expect(request.content.attributes.find do |attr|
attr.oid == name
- end.should_not be
+ end).not_to be
end
it "should return no subjectAltNames" do
request.generate(key)
- request.subject_alt_names.should be_empty
+ expect(request.subject_alt_names).to be_empty
end
end
end
context "with dns_alt_names" do
before :each do
Puppet[:dns_alt_names] = "one, two, three"
end
["extreq", "msExtReq"].each do |name|
it "should not add any #{name} attribute" do
request.generate(key)
- request.content.attributes.find do |attr|
+ expect(request.content.attributes.find do |attr|
attr.oid == name
- end.should_not be
+ end).not_to be
end
it "should return no subjectAltNames" do
request.generate(key)
- request.subject_alt_names.should be_empty
+ expect(request.subject_alt_names).to be_empty
end
end
end
context "with subjectAltName to generate request" do
before :each do
Puppet[:dns_alt_names] = ""
end
it "should add an extreq attribute" do
request.generate(key, :dns_alt_names => 'one, two')
extReq = request.content.attributes.find do |attr|
attr.oid == 'extReq'
end
- extReq.should be
+ expect(extReq).to be
extReq.value.value.all? do |x|
x.value.all? do |y|
- y.value[0].value.should == "subjectAltName"
+ expect(y.value[0].value).to eq("subjectAltName")
end
end
end
it "should return the subjectAltName values" do
request.generate(key, :dns_alt_names => 'one,two')
- request.subject_alt_names.should =~ ["DNS:myname", "DNS:one", "DNS:two"]
+ expect(request.subject_alt_names).to match_array(["DNS:myname", "DNS:one", "DNS:two"])
end
end
context "with custom CSR attributes" do
it "adds attributes with single values" do
csr_attributes = {
'1.3.6.1.4.1.34380.1.2.1' => 'CSR specific info',
'1.3.6.1.4.1.34380.1.2.2' => 'more CSR specific info',
}
request.generate(key, :csr_attributes => csr_attributes)
attrs = request.custom_attributes
- attrs.should include({'oid' => '1.3.6.1.4.1.34380.1.2.1', 'value' => 'CSR specific info'})
- attrs.should include({'oid' => '1.3.6.1.4.1.34380.1.2.2', 'value' => 'more CSR specific info'})
+ expect(attrs).to include({'oid' => '1.3.6.1.4.1.34380.1.2.1', 'value' => 'CSR specific info'})
+ expect(attrs).to include({'oid' => '1.3.6.1.4.1.34380.1.2.2', 'value' => 'more CSR specific info'})
end
['extReq', '1.2.840.113549.1.9.14'].each do |oid|
it "doesn't overwrite standard PKCS#9 CSR attribute '#{oid}'" do
expect do
request.generate(key, :csr_attributes => {oid => 'data'})
end.to raise_error ArgumentError, /Cannot specify.*#{oid}/
end
end
['msExtReq', '1.3.6.1.4.1.311.2.1.14'].each do |oid|
it "doesn't overwrite Microsoft extension request OID '#{oid}'" do
expect do
request.generate(key, :csr_attributes => {oid => 'data'})
end.to raise_error ArgumentError, /Cannot specify.*#{oid}/
end
end
it "raises an error if an attribute cannot be created" do
csr_attributes = { "thats.no.moon" => "death star" }
expect do
request.generate(key, :csr_attributes => csr_attributes)
end.to raise_error Puppet::Error, /Cannot create CSR with attribute thats\.no\.moon: first num too large/
end
it "should support old non-DER encoded extensions" do
csr = OpenSSL::X509::Request.new(File.read(my_fixture("old-style-cert-request.pem")))
wrapped_csr = Puppet::SSL::CertificateRequest.from_instance csr
exts = wrapped_csr.request_extensions()
- exts.find { |ext| ext['oid'] == 'pp_uuid' }['value'].should == 'I-AM-A-UUID'
- exts.find { |ext| ext['oid'] == 'pp_instance_id' }['value'].should == 'i_am_an_id'
- exts.find { |ext| ext['oid'] == 'pp_image_name' }['value'].should == 'i_am_an_image_name'
+ expect(exts.find { |ext| ext['oid'] == 'pp_uuid' }['value']).to eq('I-AM-A-UUID')
+ expect(exts.find { |ext| ext['oid'] == 'pp_instance_id' }['value']).to eq('i_am_an_id')
+ expect(exts.find { |ext| ext['oid'] == 'pp_image_name' }['value']).to eq('i_am_an_image_name')
end
end
context "with extension requests" do
let(:extension_data) do
{
'1.3.6.1.4.1.34380.1.1.31415' => 'pi',
'1.3.6.1.4.1.34380.1.1.2718' => 'e',
}
end
it "adds an extreq attribute to the CSR" do
request.generate(key, :extension_requests => extension_data)
exts = request.content.attributes.select { |attr| attr.oid = 'extReq' }
- exts.length.should == 1
+ expect(exts.length).to eq(1)
end
it "adds an extension for each entry in the extension request structure" do
request.generate(key, :extension_requests => extension_data)
exts = request.request_extensions
- exts.should include('oid' => '1.3.6.1.4.1.34380.1.1.31415', 'value' => 'pi')
- exts.should include('oid' => '1.3.6.1.4.1.34380.1.1.2718', 'value' => 'e')
+ expect(exts).to include('oid' => '1.3.6.1.4.1.34380.1.1.31415', 'value' => 'pi')
+ expect(exts).to include('oid' => '1.3.6.1.4.1.34380.1.1.2718', 'value' => 'e')
end
it "defines the extensions as non-critical" do
request.generate(key, :extension_requests => extension_data)
request.request_extensions.each do |ext|
- ext['critical'].should be_false
+ expect(ext['critical']).to be_falsey
end
end
it "rejects the subjectAltNames extension" do
san_names = ['subjectAltName', '2.5.29.17']
san_field = 'DNS:first.tld, DNS:second.tld'
san_names.each do |name|
expect do
request.generate(key, :extension_requests => {name => san_field})
end.to raise_error Puppet::Error, /conflicts with internally used extension/
end
end
it "merges the extReq attribute with the subjectAltNames extension" do
request.generate(key,
:dns_alt_names => 'first.tld, second.tld',
:extension_requests => extension_data)
exts = request.request_extensions
- exts.should include('oid' => '1.3.6.1.4.1.34380.1.1.31415', 'value' => 'pi')
- exts.should include('oid' => '1.3.6.1.4.1.34380.1.1.2718', 'value' => 'e')
- exts.should include('oid' => 'subjectAltName', 'value' => 'DNS:first.tld, DNS:myname, DNS:second.tld')
+ expect(exts).to include('oid' => '1.3.6.1.4.1.34380.1.1.31415', 'value' => 'pi')
+ expect(exts).to include('oid' => '1.3.6.1.4.1.34380.1.1.2718', 'value' => 'e')
+ expect(exts).to include('oid' => 'subjectAltName', 'value' => 'DNS:first.tld, DNS:myname, DNS:second.tld')
- request.subject_alt_names.should eq ['DNS:first.tld', 'DNS:myname', 'DNS:second.tld']
+ expect(request.subject_alt_names).to eq ['DNS:first.tld', 'DNS:myname', 'DNS:second.tld']
end
it "raises an error if the OID could not be created" do
exts = {"thats.no.moon" => "death star"}
expect do
request.generate(key, :extension_requests => exts)
end.to raise_error Puppet::Error, /Cannot create CSR with extension request thats\.no\.moon: first num too large/
end
end
it "should sign the csr with the provided key" do
request.generate(key)
- request.content.verify(key.content.public_key).should be_true
+ expect(request.content.verify(key.content.public_key)).to be_truthy
end
it "should verify the generated request using the public key" do
# Stupid keys don't have a competent == method.
OpenSSL::X509::Request.any_instance.expects(:verify).with { |public_key|
public_key.to_s == key.content.public_key.to_s
}.returns true
request.generate(key)
end
it "should fail if verification fails" do
OpenSSL::X509::Request.any_instance.expects(:verify).with { |public_key|
public_key.to_s == key.content.public_key.to_s
}.returns false
expect {
request.generate(key)
}.to raise_error(Puppet::Error, /CSR sign verification failed/)
end
it "should log the fingerprint" do
Puppet::SSL::Digest.any_instance.stubs(:to_hex).returns("FINGERPRINT")
Puppet.stubs(:info)
Puppet.expects(:info).with { |s| s =~ /FINGERPRINT/ }
request.generate(key)
end
it "should return the generated request" do
generated = request.generate(key)
- generated.should be_a(OpenSSL::X509::Request)
- generated.should be(request.content)
+ expect(generated).to be_a(OpenSSL::X509::Request)
+ expect(generated).to be(request.content)
end
it "should use SHA1 to sign the csr when SHA256 isn't available" do
csr = OpenSSL::X509::Request.new
OpenSSL::Digest.expects(:const_defined?).with("SHA256").returns(false)
OpenSSL::Digest.expects(:const_defined?).with("SHA1").returns(true)
signer = Puppet::SSL::CertificateSigner.new
signer.sign(csr, key.content)
- csr.verify(key.content).should be_true
+ expect(csr.verify(key.content)).to be_truthy
end
it "should raise an error if neither SHA256 nor SHA1 are available" do
csr = OpenSSL::X509::Request.new
OpenSSL::Digest.expects(:const_defined?).with("SHA256").returns(false)
OpenSSL::Digest.expects(:const_defined?).with("SHA1").returns(false)
expect {
signer = Puppet::SSL::CertificateSigner.new
}.to raise_error(Puppet::Error)
end
end
describe "when a CSR is saved" do
describe "and a CA is available" do
it "should save the CSR and trigger autosigning" do
ca = mock 'ca', :autosign
Puppet::SSL::CertificateAuthority.expects(:instance).returns ca
csr = Puppet::SSL::CertificateRequest.new("me")
terminus = mock 'terminus'
terminus.stubs(:validate)
Puppet::SSL::CertificateRequest.indirection.expects(:prepare).returns(terminus)
terminus.expects(:save).with { |request| request.instance == csr && request.key == "me" }
Puppet::SSL::CertificateRequest.indirection.save(csr)
end
end
describe "and a CA is not available" do
it "should save the CSR" do
Puppet::SSL::CertificateAuthority.expects(:instance).returns nil
csr = Puppet::SSL::CertificateRequest.new("me")
terminus = mock 'terminus'
terminus.stubs(:validate)
Puppet::SSL::CertificateRequest.indirection.expects(:prepare).returns(terminus)
terminus.expects(:save).with { |request| request.instance == csr && request.key == "me" }
Puppet::SSL::CertificateRequest.indirection.save(csr)
end
end
end
end
diff --git a/spec/unit/ssl/certificate_revocation_list_spec.rb b/spec/unit/ssl/certificate_revocation_list_spec.rb
index cf25022b0..bd4487531 100755
--- a/spec/unit/ssl/certificate_revocation_list_spec.rb
+++ b/spec/unit/ssl/certificate_revocation_list_spec.rb
@@ -1,196 +1,196 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/certificate_revocation_list'
describe Puppet::SSL::CertificateRevocationList do
before do
ca = Puppet::SSL::CertificateAuthority.new
ca.generate_ca_certificate
@cert = ca.host.certificate.content
@key = ca.host.key.content
@class = Puppet::SSL::CertificateRevocationList
end
def expects_time_close_to_now(time)
expect(time.to_i).to be_within(5*60).of(Time.now.to_i)
end
def expects_time_close_to_five_years(time)
future = Time.now + Puppet::SSL::CertificateRevocationList::FIVE_YEARS
expect(time.to_i).to be_within(5*60).of(future.to_i)
end
def expects_crlnumber_extension(crl, value)
crlNumber = crl.content.extensions.find { |ext| ext.oid == "crlNumber" }
expect(crlNumber.value).to eq(value.to_s)
expect(crlNumber).to_not be_critical
end
def expects_authkeyid_extension(crl, cert)
subjectKeyId = cert.extensions.find { |ext| ext.oid == 'subjectKeyIdentifier' }.value
authKeyId = crl.content.extensions.find { |ext| ext.oid == "authorityKeyIdentifier" }
expect(authKeyId.value.chomp).to eq("keyid:#{subjectKeyId}")
expect(authKeyId).to_not be_critical
end
def expects_crlreason_extension(crl, reason)
revoke = crl.content.revoked.first
crlNumber = crl.content.extensions.find { |ext| ext.oid == "crlNumber" }
expect(revoke.serial.to_s).to eq(crlNumber.value)
crlReason = revoke.extensions.find { |ext| ext.oid = 'CRLReason' }
expect(crlReason.value).to eq(reason)
expect(crlReason).to_not be_critical
end
it "should only support the text format" do
- @class.supported_formats.should == [:s]
+ expect(@class.supported_formats).to eq([:s])
end
describe "when converting from a string" do
it "deserializes a CRL" do
crl = @class.new('foo')
crl.generate(@cert, @key)
new_crl = @class.from_s(crl.to_s)
expect(new_crl.content.to_text).to eq(crl.content.to_text)
end
end
describe "when an instance" do
before do
@crl = @class.new("whatever")
end
it "should always use 'crl' for its name" do
- @crl.name.should == "crl"
+ expect(@crl.name).to eq("crl")
end
it "should have a content attribute" do
- @crl.should respond_to(:content)
+ expect(@crl).to respond_to(:content)
end
end
describe "when generating the crl" do
before do
@crl = @class.new("crl")
end
it "should set its issuer to the subject of the passed certificate" do
- @crl.generate(@cert, @key).issuer.to_s.should == @cert.subject.to_s
+ expect(@crl.generate(@cert, @key).issuer.to_s).to eq(@cert.subject.to_s)
end
it "should set its version to 1" do
- @crl.generate(@cert, @key).version.should == 1
+ expect(@crl.generate(@cert, @key).version).to eq(1)
end
it "should create an instance of OpenSSL::X509::CRL" do
- @crl.generate(@cert, @key).should be_an_instance_of(OpenSSL::X509::CRL)
+ expect(@crl.generate(@cert, @key)).to be_an_instance_of(OpenSSL::X509::CRL)
end
it "should add an extension for the CRL number" do
@crl.generate(@cert, @key)
expects_crlnumber_extension(@crl, 0)
end
it "should add an extension for the authority key identifier" do
@crl.generate(@cert, @key)
expects_authkeyid_extension(@crl, @cert)
end
it "returns the last update time in UTC" do
# http://tools.ietf.org/html/rfc5280#section-5.1.2.4
thisUpdate = @crl.generate(@cert, @key).last_update
- thisUpdate.should be_utc
+ expect(thisUpdate).to be_utc
expects_time_close_to_now(thisUpdate)
end
it "returns the next update time in UTC 5 years from now" do
# http://tools.ietf.org/html/rfc5280#section-5.1.2.5
nextUpdate = @crl.generate(@cert, @key).next_update
- nextUpdate.should be_utc
+ expect(nextUpdate).to be_utc
expects_time_close_to_five_years(nextUpdate)
end
it "should verify using the CA public_key" do
- @crl.generate(@cert, @key).verify(@key.public_key).should be_true
+ expect(@crl.generate(@cert, @key).verify(@key.public_key)).to be_truthy
end
it "should set the content to the generated crl" do
# this test shouldn't be needed since we test the return of generate() which should be the content field
@crl.generate(@cert, @key)
- @crl.content.should be_an_instance_of(OpenSSL::X509::CRL)
+ expect(@crl.content).to be_an_instance_of(OpenSSL::X509::CRL)
end
end
# This test suite isn't exactly complete, because the
# SSL stuff is very complicated. It just hits the high points.
describe "when revoking a certificate" do
before do
@crl = @class.new("crl")
@crl.generate(@cert, @key)
Puppet::SSL::CertificateRevocationList.indirection.stubs :save
end
it "should require a serial number and the CA's private key" do
expect { @crl.revoke }.to raise_error(ArgumentError)
end
it "should mark the CRL as updated at a time that makes it valid now" do
@crl.revoke(1, @key)
expects_time_close_to_now(@crl.content.last_update)
end
it "should mark the CRL valid for five years" do
@crl.revoke(1, @key)
expects_time_close_to_five_years(@crl.content.next_update)
end
it "should sign the CRL with the CA's private key and a digest instance" do
@crl.content.expects(:sign).with { |key, digest| key == @key and digest.is_a?(OpenSSL::Digest::SHA1) }
@crl.revoke(1, @key)
end
it "should save the CRL" do
Puppet::SSL::CertificateRevocationList.indirection.expects(:save).with(@crl, nil)
@crl.revoke(1, @key)
end
it "adds the crlNumber extension containing the serial number" do
serial = 1
@crl.revoke(serial, @key)
expects_crlnumber_extension(@crl, serial)
end
it "adds the CA cert's subjectKeyId as the authorityKeyIdentifier to the CRL" do
@crl.revoke(1, @key)
expects_authkeyid_extension(@crl, @cert)
end
it "adds a non-critical CRL reason specifying key compromise by default" do
# http://tools.ietf.org/html/rfc5280#section-5.3.1
serial = 1
@crl.revoke(serial, @key)
expects_crlreason_extension(@crl, 'Key Compromise')
end
it "allows alternate reasons to be specified" do
serial = 1
@crl.revoke(serial, @key, OpenSSL::OCSP::REVOKED_STATUS_CACOMPROMISE)
expects_crlreason_extension(@crl, 'CA Compromise')
end
end
end
diff --git a/spec/unit/ssl/certificate_spec.rb b/spec/unit/ssl/certificate_spec.rb
index fdfab5ee1..f3b39fb97 100755
--- a/spec/unit/ssl/certificate_spec.rb
+++ b/spec/unit/ssl/certificate_spec.rb
@@ -1,190 +1,190 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/certificate'
describe Puppet::SSL::Certificate do
let :key do Puppet::SSL::Key.new("test.localdomain").generate end
# Sign the provided cert so that it can be DER-decoded later
def sign_wrapped_cert(cert)
signer = Puppet::SSL::CertificateSigner.new
signer.sign(cert.content, key)
end
before do
@class = Puppet::SSL::Certificate
end
after do
@class.instance_variable_set("@ca_location", nil)
end
it "should be extended with the Indirector module" do
- @class.singleton_class.should be_include(Puppet::Indirector)
+ expect(@class.singleton_class).to be_include(Puppet::Indirector)
end
it "should indirect certificate" do
- @class.indirection.name.should == :certificate
+ expect(@class.indirection.name).to eq(:certificate)
end
it "should only support the text format" do
- @class.supported_formats.should == [:s]
+ expect(@class.supported_formats).to eq([:s])
end
describe "when converting from a string" do
it "should create a certificate instance with its name set to the certificate subject and its content set to the extracted certificate" do
cert = stub 'certificate',
:subject => OpenSSL::X509::Name.parse("/CN=Foo.madstop.com"),
:is_a? => true
OpenSSL::X509::Certificate.expects(:new).with("my certificate").returns(cert)
mycert = stub 'sslcert'
mycert.expects(:content=).with(cert)
@class.expects(:new).with("Foo.madstop.com").returns mycert
@class.from_s("my certificate")
end
it "should create multiple certificate instances when asked" do
cert1 = stub 'cert1'
@class.expects(:from_s).with("cert1").returns cert1
cert2 = stub 'cert2'
@class.expects(:from_s).with("cert2").returns cert2
- @class.from_multiple_s("cert1\n---\ncert2").should == [cert1, cert2]
+ expect(@class.from_multiple_s("cert1\n---\ncert2")).to eq([cert1, cert2])
end
end
describe "when converting to a string" do
before do
@certificate = @class.new("myname")
end
it "should return an empty string when it has no certificate" do
- @certificate.to_s.should == ""
+ expect(@certificate.to_s).to eq("")
end
it "should convert the certificate to pem format" do
certificate = mock 'certificate', :to_pem => "pem"
@certificate.content = certificate
- @certificate.to_s.should == "pem"
+ expect(@certificate.to_s).to eq("pem")
end
it "should be able to convert multiple instances to a string" do
cert2 = @class.new("foo")
@certificate.expects(:to_s).returns "cert1"
cert2.expects(:to_s).returns "cert2"
- @class.to_multiple_s([@certificate, cert2]).should == "cert1\n---\ncert2"
+ expect(@class.to_multiple_s([@certificate, cert2])).to eq("cert1\n---\ncert2")
end
end
describe "when managing instances" do
def build_cert(opts)
key = Puppet::SSL::Key.new('quux')
key.generate
csr = Puppet::SSL::CertificateRequest.new('quux')
csr.generate(key, opts)
raw_cert = Puppet::SSL::CertificateFactory.build('client', csr, csr.content, 14)
@class.from_instance(raw_cert)
end
before do
@certificate = @class.new("myname")
end
it "should have a name attribute" do
- @certificate.name.should == "myname"
+ expect(@certificate.name).to eq("myname")
end
it "should convert its name to a string and downcase it" do
- @class.new(:MyName).name.should == "myname"
+ expect(@class.new(:MyName).name).to eq("myname")
end
it "should have a content attribute" do
- @certificate.should respond_to(:content)
+ expect(@certificate).to respond_to(:content)
end
describe "#subject_alt_names" do
it "should list all alternate names when the extension is present" do
certificate = build_cert(:dns_alt_names => 'foo, bar,baz')
- certificate.subject_alt_names.
- should =~ ['DNS:foo', 'DNS:bar', 'DNS:baz', 'DNS:quux']
+ expect(certificate.subject_alt_names).
+ to match_array(['DNS:foo', 'DNS:bar', 'DNS:baz', 'DNS:quux'])
end
it "should return an empty list of names if the extension is absent" do
certificate = build_cert({})
- certificate.subject_alt_names.should be_empty
+ expect(certificate.subject_alt_names).to be_empty
end
end
describe "custom extensions" do
it "returns extensions under the ppRegCertExt" do
exts = {'pp_uuid' => 'abcdfd'}
cert = build_cert(:extension_requests => exts)
sign_wrapped_cert(cert)
expect(cert.custom_extensions).to include('oid' => 'pp_uuid', 'value' => 'abcdfd')
end
it "returns extensions under the ppPrivCertExt" do
exts = {'1.3.6.1.4.1.34380.1.2.1' => 'x509 :('}
cert = build_cert(:extension_requests => exts)
sign_wrapped_cert(cert)
expect(cert.custom_extensions).to include('oid' => '1.3.6.1.4.1.34380.1.2.1', 'value' => 'x509 :(')
end
it "doesn't return standard extensions" do
cert = build_cert(:dns_alt_names => 'foo')
expect(cert.custom_extensions).to be_empty
end
end
it "should return a nil expiration if there is no actual certificate" do
@certificate.stubs(:content).returns nil
- @certificate.expiration.should be_nil
+ expect(@certificate.expiration).to be_nil
end
it "should use the expiration of the certificate as its expiration date" do
cert = stub 'cert'
@certificate.stubs(:content).returns cert
cert.expects(:not_after).returns "sometime"
- @certificate.expiration.should == "sometime"
+ expect(@certificate.expiration).to eq("sometime")
end
it "should be able to read certificates from disk" do
path = "/my/path"
File.expects(:read).with(path).returns("my certificate")
certificate = mock 'certificate'
OpenSSL::X509::Certificate.expects(:new).with("my certificate").returns(certificate)
- @certificate.read(path).should equal(certificate)
- @certificate.content.should equal(certificate)
+ expect(@certificate.read(path)).to equal(certificate)
+ expect(@certificate.content).to equal(certificate)
end
it "should have a :to_text method that it delegates to the actual key" do
real_certificate = mock 'certificate'
real_certificate.expects(:to_text).returns "certificatetext"
@certificate.content = real_certificate
- @certificate.to_text.should == "certificatetext"
+ expect(@certificate.to_text).to eq("certificatetext")
end
it "should parse the old non-DER encoded extension values" do
cert = OpenSSL::X509::Certificate.new(File.read(my_fixture("old-style-cert-exts.pem")))
wrapped_cert = Puppet::SSL::Certificate.from_instance cert
exts = wrapped_cert.custom_extensions
expect(exts.find { |ext| ext['oid'] == 'pp_uuid'}['value']).to eq('I-AM-A-UUID')
expect(exts.find { |ext| ext['oid'] == 'pp_instance_id'}['value']).to eq('i_am_an_id')
expect(exts.find { |ext| ext['oid'] == 'pp_image_name'}['value']).to eq('i_am_an_image_name')
end
end
end
diff --git a/spec/unit/ssl/configuration_spec.rb b/spec/unit/ssl/configuration_spec.rb
index 09d99e468..2a00836ff 100755
--- a/spec/unit/ssl/configuration_spec.rb
+++ b/spec/unit/ssl/configuration_spec.rb
@@ -1,132 +1,132 @@
#! /usr/bin/env ruby
#
require 'spec_helper'
require 'puppet/ssl/configuration'
describe Puppet::SSL::Configuration do
let(:localcacert) { "/path/to/certs/ca.pem" }
let(:ssl_server_ca_auth) { "/path/to/certs/ssl_server_ca_auth.pem" }
it "should require the localcacert argument" do
- lambda { subject }.should raise_error ArgumentError
+ expect { subject }.to raise_error ArgumentError
end
context "Default configuration" do
subject do
described_class.new(localcacert)
end
it "#ca_chain_file == localcacert" do
- subject.ca_chain_file.should == localcacert
+ expect(subject.ca_chain_file).to eq(localcacert)
end
it "#ca_auth_file == localcacert" do
- subject.ca_auth_file.should == localcacert
+ expect(subject.ca_auth_file).to eq(localcacert)
end
end
context "Explicitly configured" do
subject do
options = {
:ca_auth_file => ssl_server_ca_auth,
}
Puppet::SSL::Configuration.new(localcacert, options)
end
it "#ca_chain_file == ssl_server_ca_chain" do
- subject.ca_chain_file.should == ssl_server_ca_auth
+ expect(subject.ca_chain_file).to eq(ssl_server_ca_auth)
end
it "#ca_auth_file == ssl_server_ca_auth" do
- subject.ca_auth_file.should == ssl_server_ca_auth
+ expect(subject.ca_auth_file).to eq(ssl_server_ca_auth)
end
it "#ca_auth_certificates returns an Array<OpenSSL::X509::Certificate>" do
subject.stubs(:read_file).returns(master_ca_pem + root_ca_pem)
certs = subject.ca_auth_certificates
- certs.each { |cert| cert.should be_a_kind_of OpenSSL::X509::Certificate }
+ certs.each { |cert| expect(cert).to be_a_kind_of OpenSSL::X509::Certificate }
end
end
context "Partially configured" do
describe "#ca_chain_file" do
subject do
described_class.new(localcacert, { :ca_auth_file => ssl_server_ca_auth })
end
it "should use ca_auth_file" do
- subject.ca_chain_file.should == ssl_server_ca_auth
+ expect(subject.ca_chain_file).to eq(ssl_server_ca_auth)
end
end
end
# This is the Intermediate CA specifically designated for issuing master
# certificates. It is signed by the Root CA.
def master_ca_pem
@master_ca_pem ||= <<-AUTH_BUNDLE
-----BEGIN CERTIFICATE-----
MIICljCCAf+gAwIBAgIBAjANBgkqhkiG9w0BAQUFADBJMRAwDgYDVQQDDAdSb290
IENBMRowGAYDVQQLDBFTZXJ2ZXIgT3BlcmF0aW9uczEZMBcGA1UECgwQRXhhbXBs
ZSBPcmcsIExMQzAeFw0xMzAzMzAwNTUwNDhaFw0zMzAzMjUwNTUwNDhaMH4xJDAi
BgNVBAMTG0ludGVybWVkaWF0ZSBDQSAobWFzdGVyLWNhKTEfMB0GCSqGSIb3DQEJ
ARYQdGVzdEBleGFtcGxlLm9yZzEZMBcGA1UEChMQRXhhbXBsZSBPcmcsIExMQzEa
MBgGA1UECxMRU2VydmVyIE9wZXJhdGlvbnMwXDANBgkqhkiG9w0BAQEFAANLADBI
AkEAvo/az3oR69SP92jGnUHMJLEyyD1Ui1BZ/rUABJcQTRQqn3RqtlfYePWZnUaZ
srKbXRS4q0w5Vqf1kx5w3q5tIwIDAQABo4GcMIGZMHkGA1UdIwRyMHCAFDBN1mqO
Nc4gUraE4zRtw6ueFDDaoU2kSzBJMRAwDgYDVQQDDAdSb290IENBMRowGAYDVQQL
DBFTZXJ2ZXIgT3BlcmF0aW9uczEZMBcGA1UECgwQRXhhbXBsZSBPcmcsIExMQ4IJ
ALf2Pk2HvtBzMA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMA0GCSqGSIb3
DQEBBQUAA4GBACRfa1YPS7RQUuhYovGgV0VYqxuATC7WwdIRihVh5FceSXKgSIbz
BKmOBAy/KixEhpnHTbkpaJ0d9ITkvjMTmj3M5YMahKaQA5niVPckQPecMMd6jg9U
l1k75xLLIcrlsDYo3999KOSSchH2K7bLT7TuQ2okdP6FHWmeWmudewlu
-----END CERTIFICATE-----
AUTH_BUNDLE
end
# This is the Root CA
def root_ca_pem
@root_ca_pem ||= <<-LOCALCACERT
-----BEGIN CERTIFICATE-----
MIICYDCCAcmgAwIBAgIJALf2Pk2HvtBzMA0GCSqGSIb3DQEBBQUAMEkxEDAOBgNV
BAMMB1Jvb3QgQ0ExGjAYBgNVBAsMEVNlcnZlciBPcGVyYXRpb25zMRkwFwYDVQQK
DBBFeGFtcGxlIE9yZywgTExDMB4XDTEzMDMzMDA1NTA0OFoXDTMzMDMyNTA1NTA0
OFowSTEQMA4GA1UEAwwHUm9vdCBDQTEaMBgGA1UECwwRU2VydmVyIE9wZXJhdGlv
bnMxGTAXBgNVBAoMEEV4YW1wbGUgT3JnLCBMTEMwgZ8wDQYJKoZIhvcNAQEBBQAD
gY0AMIGJAoGBAMGSpafR4lboYOPfPJC1wVHHl0gD49ZVRjOlJ9jidEUjBdFXK6SA
S1tecDv2G4tM1ANmfMKjZl0m+KaZ8O2oq0g6kxkq1Mg0eSNvlnEyehjmTLRzHC2i
a0biH2wMtCLzfAoXDKy4GPlciBPE9mup5I8Kien5s91t92tc7K8AJ8oBAgMBAAGj
UDBOMB0GA1UdDgQWBBQwTdZqjjXOIFK2hOM0bcOrnhQw2jAfBgNVHSMEGDAWgBQw
TdZqjjXOIFK2hOM0bcOrnhQw2jAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUA
A4GBACs8EZRrzgzAlcKC1Tz8GYlNHQg0XhpbEDm+p2mOV//PuDD190O+UBpWxo9Q
rrkkx8En0wXQZJf6iH3hwewwHLOq5yXZKbJN+SmvJvRNL95Yhyy08Y9N65tJveE7
rPsNU/Tx19jHC87oXlmAePLI4IaUHXrWb7CRbY9TEcPdmj1R
-----END CERTIFICATE-----
LOCALCACERT
end
# This is the intermediate CA designated to issue Agent SSL certs. It is
# signed by the Root CA.
def agent_ca_pem
@agent_ca_pem ||= <<-AGENT_CA
-----BEGIN CERTIFICATE-----
MIIClTCCAf6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBJMRAwDgYDVQQDDAdSb290
IENBMRowGAYDVQQLDBFTZXJ2ZXIgT3BlcmF0aW9uczEZMBcGA1UECgwQRXhhbXBs
ZSBPcmcsIExMQzAeFw0xMzAzMzAwNTUwNDhaFw0zMzAzMjUwNTUwNDhaMH0xIzAh
BgNVBAMTGkludGVybWVkaWF0ZSBDQSAoYWdlbnQtY2EpMR8wHQYJKoZIhvcNAQkB
FhB0ZXN0QGV4YW1wbGUub3JnMRkwFwYDVQQKExBFeGFtcGxlIE9yZywgTExDMRow
GAYDVQQLExFTZXJ2ZXIgT3BlcmF0aW9uczBcMA0GCSqGSIb3DQEBAQUAA0sAMEgC
QQDkEj/Msmi4hJImxP5+ocixMTHuYC1M1E2p4QcuzOkZYrfHf+5hJMcahfYhLiXU
jHBredOXhgSisHh6CLSb/rKzAgMBAAGjgZwwgZkweQYDVR0jBHIwcIAUME3Wao41
ziBStoTjNG3Dq54UMNqhTaRLMEkxEDAOBgNVBAMMB1Jvb3QgQ0ExGjAYBgNVBAsM
EVNlcnZlciBPcGVyYXRpb25zMRkwFwYDVQQKDBBFeGFtcGxlIE9yZywgTExDggkA
t/Y+TYe+0HMwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcN
AQEFBQADgYEAujSj9rxIxJHEuuYXb15L30yxs9Tdvy4OCLiKdjvs9Z7gG8Pbutls
ooCwyYAkmzKVs/8cYjZJnvJrPEW1gFwqX7Xknp85Cfrl+/pQEPYq5sZVa5BIm9tI
0EvlDax/Hd28jI6Bgq5fsTECNl9GDGknCy7vwRZem0h+hI56lzR3pYE=
-----END CERTIFICATE-----
AGENT_CA
end
end
diff --git a/spec/unit/ssl/digest_spec.rb b/spec/unit/ssl/digest_spec.rb
index effb029ea..8d17a2093 100644
--- a/spec/unit/ssl/digest_spec.rb
+++ b/spec/unit/ssl/digest_spec.rb
@@ -1,35 +1,35 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/digest'
describe Puppet::SSL::Digest do
it "defaults to sha256" do
digest = described_class.new(nil, 'blah')
- digest.name.should == 'SHA256'
- digest.digest.hexdigest.should == "8b7df143d91c716ecfa5fc1730022f6b421b05cedee8fd52b1fc65a96030ad52"
+ expect(digest.name).to eq('SHA256')
+ expect(digest.digest.hexdigest).to eq("8b7df143d91c716ecfa5fc1730022f6b421b05cedee8fd52b1fc65a96030ad52")
end
describe '#name' do
it "prints the hashing algorithm used by the openssl digest" do
- described_class.new('SHA224', 'blah').name.should == 'SHA224'
+ expect(described_class.new('SHA224', 'blah').name).to eq('SHA224')
end
it "upcases the hashing algorithm" do
- described_class.new('sha224', 'blah').name.should == 'SHA224'
+ expect(described_class.new('sha224', 'blah').name).to eq('SHA224')
end
end
describe '#to_hex' do
it "returns ':' separated upper case hex pairs" do
described_class.new(nil, 'blah').to_hex =~ /\A([A-Z0-9]:)+[A-Z0-9]\Z/
end
end
describe '#to_s' do
it "formats the digest algorithm and the digest as a string" do
digest = described_class.new('sha512', 'some content')
- digest.to_s.should == "(#{digest.name}) #{digest.to_hex}"
+ expect(digest.to_s).to eq("(#{digest.name}) #{digest.to_hex}")
end
end
end
diff --git a/spec/unit/ssl/host_spec.rb b/spec/unit/ssl/host_spec.rb
index 280880d1b..7454a4cb5 100755
--- a/spec/unit/ssl/host_spec.rb
+++ b/spec/unit/ssl/host_spec.rb
@@ -1,940 +1,940 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/host'
require 'matchers/json'
def base_pson_comparison(result, pson_hash)
- result["fingerprint"].should == pson_hash["fingerprint"]
- result["name"].should == pson_hash["name"]
- result["state"].should == pson_hash["desired_state"]
+ expect(result["fingerprint"]).to eq(pson_hash["fingerprint"])
+ expect(result["name"]).to eq(pson_hash["name"])
+ expect(result["state"]).to eq(pson_hash["desired_state"])
end
describe Puppet::SSL::Host do
include JSONMatchers
include PuppetSpec::Files
before do
Puppet::SSL::Host.indirection.terminus_class = :file
# Get a safe temporary file
dir = tmpdir("ssl_host_testing")
Puppet.settings[:confdir] = dir
Puppet.settings[:vardir] = dir
Puppet.settings.use :main, :ssl
@host = Puppet::SSL::Host.new("myname")
end
after do
# Cleaned out any cached localhost instance.
Puppet::SSL::Host.reset
Puppet::SSL::Host.ca_location = :none
end
it "should use any provided name as its name" do
- @host.name.should == "myname"
+ expect(@host.name).to eq("myname")
end
it "should retrieve its public key from its private key" do
realkey = mock 'realkey'
key = stub 'key', :content => realkey
Puppet::SSL::Key.indirection.stubs(:find).returns(key)
pubkey = mock 'public_key'
realkey.expects(:public_key).returns pubkey
- @host.public_key.should equal(pubkey)
+ expect(@host.public_key).to equal(pubkey)
end
it "should default to being a non-ca host" do
- @host.ca?.should be_false
+ expect(@host.ca?).to be_falsey
end
it "should be a ca host if its name matches the CA_NAME" do
Puppet::SSL::Host.stubs(:ca_name).returns "yayca"
- Puppet::SSL::Host.new("yayca").should be_ca
+ expect(Puppet::SSL::Host.new("yayca")).to be_ca
end
it "should have a method for determining the CA location" do
- Puppet::SSL::Host.should respond_to(:ca_location)
+ expect(Puppet::SSL::Host).to respond_to(:ca_location)
end
it "should have a method for specifying the CA location" do
- Puppet::SSL::Host.should respond_to(:ca_location=)
+ expect(Puppet::SSL::Host).to respond_to(:ca_location=)
end
it "should have a method for retrieving the default ssl host" do
- Puppet::SSL::Host.should respond_to(:ca_location=)
+ expect(Puppet::SSL::Host).to respond_to(:ca_location=)
end
it "should have a method for producing an instance to manage the local host's keys" do
- Puppet::SSL::Host.should respond_to(:localhost)
+ expect(Puppet::SSL::Host).to respond_to(:localhost)
end
it "should allow to reset localhost" do
previous_host = Puppet::SSL::Host.localhost
Puppet::SSL::Host.reset
- Puppet::SSL::Host.localhost.should_not == previous_host
+ expect(Puppet::SSL::Host.localhost).not_to eq(previous_host)
end
it "should generate the certificate for the localhost instance if no certificate is available" do
host = stub 'host', :key => nil
Puppet::SSL::Host.expects(:new).returns host
host.expects(:certificate).returns nil
host.expects(:generate)
- Puppet::SSL::Host.localhost.should equal(host)
+ expect(Puppet::SSL::Host.localhost).to equal(host)
end
it "should create a localhost cert if no cert is available and it is a CA with autosign and it is using DNS alt names", :unless => Puppet.features.microsoft_windows? do
Puppet[:autosign] = true
Puppet[:confdir] = tmpdir('conf')
Puppet[:dns_alt_names] = "foo,bar,baz"
ca = Puppet::SSL::CertificateAuthority.new
Puppet::SSL::CertificateAuthority.stubs(:instance).returns ca
localhost = Puppet::SSL::Host.localhost
cert = localhost.certificate
- cert.should be_a(Puppet::SSL::Certificate)
- cert.subject_alt_names.should =~ %W[DNS:#{Puppet[:certname]} DNS:foo DNS:bar DNS:baz]
+ expect(cert).to be_a(Puppet::SSL::Certificate)
+ expect(cert.subject_alt_names).to match_array(%W[DNS:#{Puppet[:certname]} DNS:foo DNS:bar DNS:baz])
end
context "with dns_alt_names" do
before :each do
@key = stub('key content')
key = stub('key', :generate => true, :content => @key)
Puppet::SSL::Key.stubs(:new).returns key
Puppet::SSL::Key.indirection.stubs(:save).with(key)
@cr = stub('certificate request')
Puppet::SSL::CertificateRequest.stubs(:new).returns @cr
Puppet::SSL::CertificateRequest.indirection.stubs(:save).with(@cr)
end
describe "explicitly specified" do
before :each do
Puppet[:dns_alt_names] = 'one, two'
end
it "should not include subjectAltName if not the local node" do
@cr.expects(:generate).with(@key, {})
Puppet::SSL::Host.new('not-the-' + Puppet[:certname]).generate
end
it "should include subjectAltName if I am a CA" do
@cr.expects(:generate).
with(@key, { :dns_alt_names => Puppet[:dns_alt_names] })
Puppet::SSL::Host.localhost
end
end
describe "implicitly defaulted" do
let(:ca) { stub('ca', :sign => nil) }
before :each do
Puppet[:dns_alt_names] = ''
Puppet::SSL::CertificateAuthority.stubs(:instance).returns ca
end
it "should not include defaults if we're not the CA" do
Puppet::SSL::CertificateAuthority.stubs(:ca?).returns false
@cr.expects(:generate).with(@key, {})
Puppet::SSL::Host.localhost
end
it "should not include defaults if not the local node" do
Puppet::SSL::CertificateAuthority.stubs(:ca?).returns true
@cr.expects(:generate).with(@key, {})
Puppet::SSL::Host.new('not-the-' + Puppet[:certname]).generate
end
it "should not include defaults if we can't resolve our fqdn" do
Puppet::SSL::CertificateAuthority.stubs(:ca?).returns true
Facter.stubs(:value).with(:fqdn).returns nil
@cr.expects(:generate).with(@key, {})
Puppet::SSL::Host.localhost
end
it "should provide defaults if we're bootstrapping the local master" do
Puppet::SSL::CertificateAuthority.stubs(:ca?).returns true
Facter.stubs(:value).with(:fqdn).returns 'web.foo.com'
Facter.stubs(:value).with(:domain).returns 'foo.com'
@cr.expects(:generate).with(@key, {:dns_alt_names => "puppet, web.foo.com, puppet.foo.com"})
Puppet::SSL::Host.localhost
end
end
end
it "should always read the key for the localhost instance in from disk" do
host = stub 'host', :certificate => "eh"
Puppet::SSL::Host.expects(:new).returns host
host.expects(:key)
Puppet::SSL::Host.localhost
end
it "should cache the localhost instance" do
host = stub 'host', :certificate => "eh", :key => 'foo'
Puppet::SSL::Host.expects(:new).once.returns host
- Puppet::SSL::Host.localhost.should == Puppet::SSL::Host.localhost
+ expect(Puppet::SSL::Host.localhost).to eq(Puppet::SSL::Host.localhost)
end
it "should be able to verify its certificate matches its key" do
- Puppet::SSL::Host.new("foo").should respond_to(:validate_certificate_with_key)
+ expect(Puppet::SSL::Host.new("foo")).to respond_to(:validate_certificate_with_key)
end
it "should consider the certificate invalid if it cannot find a key" do
host = Puppet::SSL::Host.new("foo")
certificate = mock('cert', :fingerprint => 'DEADBEEF')
host.expects(:certificate).twice.returns certificate
host.expects(:key).returns nil
- lambda { host.validate_certificate_with_key }.should raise_error(Puppet::Error, "No private key with which to validate certificate with fingerprint: DEADBEEF")
+ expect { host.validate_certificate_with_key }.to raise_error(Puppet::Error, "No private key with which to validate certificate with fingerprint: DEADBEEF")
end
it "should consider the certificate invalid if it cannot find a certificate" do
host = Puppet::SSL::Host.new("foo")
host.expects(:key).never
host.expects(:certificate).returns nil
- lambda { host.validate_certificate_with_key }.should raise_error(Puppet::Error, "No certificate to validate.")
+ expect { host.validate_certificate_with_key }.to raise_error(Puppet::Error, "No certificate to validate.")
end
it "should consider the certificate invalid if the SSL certificate's key verification fails" do
host = Puppet::SSL::Host.new("foo")
key = mock 'key', :content => "private_key"
sslcert = mock 'sslcert'
certificate = mock 'cert', {:content => sslcert, :fingerprint => 'DEADBEEF'}
host.stubs(:key).returns key
host.stubs(:certificate).returns certificate
sslcert.expects(:check_private_key).with("private_key").returns false
- lambda { host.validate_certificate_with_key }.should raise_error(Puppet::Error, /DEADBEEF/)
+ expect { host.validate_certificate_with_key }.to raise_error(Puppet::Error, /DEADBEEF/)
end
it "should consider the certificate valid if the SSL certificate's key verification succeeds" do
host = Puppet::SSL::Host.new("foo")
key = mock 'key', :content => "private_key"
sslcert = mock 'sslcert'
certificate = mock 'cert', :content => sslcert
host.stubs(:key).returns key
host.stubs(:certificate).returns certificate
sslcert.expects(:check_private_key).with("private_key").returns true
- lambda{ host.validate_certificate_with_key }.should_not raise_error
+ expect{ host.validate_certificate_with_key }.not_to raise_error
end
describe "when specifying the CA location" do
it "should support the location ':local'" do
- lambda { Puppet::SSL::Host.ca_location = :local }.should_not raise_error
+ expect { Puppet::SSL::Host.ca_location = :local }.not_to raise_error
end
it "should support the location ':remote'" do
- lambda { Puppet::SSL::Host.ca_location = :remote }.should_not raise_error
+ expect { Puppet::SSL::Host.ca_location = :remote }.not_to raise_error
end
it "should support the location ':none'" do
- lambda { Puppet::SSL::Host.ca_location = :none }.should_not raise_error
+ expect { Puppet::SSL::Host.ca_location = :none }.not_to raise_error
end
it "should support the location ':only'" do
- lambda { Puppet::SSL::Host.ca_location = :only }.should_not raise_error
+ expect { Puppet::SSL::Host.ca_location = :only }.not_to raise_error
end
it "should not support other modes" do
- lambda { Puppet::SSL::Host.ca_location = :whatever }.should raise_error(ArgumentError)
+ expect { Puppet::SSL::Host.ca_location = :whatever }.to raise_error(ArgumentError)
end
describe "as 'local'" do
before do
Puppet::SSL::Host.ca_location = :local
end
it "should set the cache class for Certificate, CertificateRevocationList, and CertificateRequest as :file" do
- Puppet::SSL::Certificate.indirection.cache_class.should == :file
- Puppet::SSL::CertificateRequest.indirection.cache_class.should == :file
- Puppet::SSL::CertificateRevocationList.indirection.cache_class.should == :file
+ expect(Puppet::SSL::Certificate.indirection.cache_class).to eq(:file)
+ expect(Puppet::SSL::CertificateRequest.indirection.cache_class).to eq(:file)
+ expect(Puppet::SSL::CertificateRevocationList.indirection.cache_class).to eq(:file)
end
it "should set the terminus class for Key and Host as :file" do
- Puppet::SSL::Key.indirection.terminus_class.should == :file
- Puppet::SSL::Host.indirection.terminus_class.should == :file
+ expect(Puppet::SSL::Key.indirection.terminus_class).to eq(:file)
+ expect(Puppet::SSL::Host.indirection.terminus_class).to eq(:file)
end
it "should set the terminus class for Certificate, CertificateRevocationList, and CertificateRequest as :ca" do
- Puppet::SSL::Certificate.indirection.terminus_class.should == :ca
- Puppet::SSL::CertificateRequest.indirection.terminus_class.should == :ca
- Puppet::SSL::CertificateRevocationList.indirection.terminus_class.should == :ca
+ expect(Puppet::SSL::Certificate.indirection.terminus_class).to eq(:ca)
+ expect(Puppet::SSL::CertificateRequest.indirection.terminus_class).to eq(:ca)
+ expect(Puppet::SSL::CertificateRevocationList.indirection.terminus_class).to eq(:ca)
end
end
describe "as 'remote'" do
before do
Puppet::SSL::Host.ca_location = :remote
end
it "should set the cache class for Certificate, CertificateRevocationList, and CertificateRequest as :file" do
- Puppet::SSL::Certificate.indirection.cache_class.should == :file
- Puppet::SSL::CertificateRequest.indirection.cache_class.should == :file
- Puppet::SSL::CertificateRevocationList.indirection.cache_class.should == :file
+ expect(Puppet::SSL::Certificate.indirection.cache_class).to eq(:file)
+ expect(Puppet::SSL::CertificateRequest.indirection.cache_class).to eq(:file)
+ expect(Puppet::SSL::CertificateRevocationList.indirection.cache_class).to eq(:file)
end
it "should set the terminus class for Key as :file" do
- Puppet::SSL::Key.indirection.terminus_class.should == :file
+ expect(Puppet::SSL::Key.indirection.terminus_class).to eq(:file)
end
it "should set the terminus class for Host, Certificate, CertificateRevocationList, and CertificateRequest as :rest" do
- Puppet::SSL::Host.indirection.terminus_class.should == :rest
- Puppet::SSL::Certificate.indirection.terminus_class.should == :rest
- Puppet::SSL::CertificateRequest.indirection.terminus_class.should == :rest
- Puppet::SSL::CertificateRevocationList.indirection.terminus_class.should == :rest
+ expect(Puppet::SSL::Host.indirection.terminus_class).to eq(:rest)
+ expect(Puppet::SSL::Certificate.indirection.terminus_class).to eq(:rest)
+ expect(Puppet::SSL::CertificateRequest.indirection.terminus_class).to eq(:rest)
+ expect(Puppet::SSL::CertificateRevocationList.indirection.terminus_class).to eq(:rest)
end
end
describe "as 'only'" do
before do
Puppet::SSL::Host.ca_location = :only
end
it "should set the terminus class for Key, Certificate, CertificateRevocationList, and CertificateRequest as :ca" do
- Puppet::SSL::Key.indirection.terminus_class.should == :ca
- Puppet::SSL::Certificate.indirection.terminus_class.should == :ca
- Puppet::SSL::CertificateRequest.indirection.terminus_class.should == :ca
- Puppet::SSL::CertificateRevocationList.indirection.terminus_class.should == :ca
+ expect(Puppet::SSL::Key.indirection.terminus_class).to eq(:ca)
+ expect(Puppet::SSL::Certificate.indirection.terminus_class).to eq(:ca)
+ expect(Puppet::SSL::CertificateRequest.indirection.terminus_class).to eq(:ca)
+ expect(Puppet::SSL::CertificateRevocationList.indirection.terminus_class).to eq(:ca)
end
it "should set the cache class for Certificate, CertificateRevocationList, and CertificateRequest to nil" do
- Puppet::SSL::Certificate.indirection.cache_class.should be_nil
- Puppet::SSL::CertificateRequest.indirection.cache_class.should be_nil
- Puppet::SSL::CertificateRevocationList.indirection.cache_class.should be_nil
+ expect(Puppet::SSL::Certificate.indirection.cache_class).to be_nil
+ expect(Puppet::SSL::CertificateRequest.indirection.cache_class).to be_nil
+ expect(Puppet::SSL::CertificateRevocationList.indirection.cache_class).to be_nil
end
it "should set the terminus class for Host to :file" do
- Puppet::SSL::Host.indirection.terminus_class.should == :file
+ expect(Puppet::SSL::Host.indirection.terminus_class).to eq(:file)
end
end
describe "as 'none'" do
before do
Puppet::SSL::Host.ca_location = :none
end
it "should set the terminus class for Key, Certificate, CertificateRevocationList, and CertificateRequest as :file" do
- Puppet::SSL::Key.indirection.terminus_class.should == :disabled_ca
- Puppet::SSL::Certificate.indirection.terminus_class.should == :disabled_ca
- Puppet::SSL::CertificateRequest.indirection.terminus_class.should == :disabled_ca
- Puppet::SSL::CertificateRevocationList.indirection.terminus_class.should == :disabled_ca
+ expect(Puppet::SSL::Key.indirection.terminus_class).to eq(:disabled_ca)
+ expect(Puppet::SSL::Certificate.indirection.terminus_class).to eq(:disabled_ca)
+ expect(Puppet::SSL::CertificateRequest.indirection.terminus_class).to eq(:disabled_ca)
+ expect(Puppet::SSL::CertificateRevocationList.indirection.terminus_class).to eq(:disabled_ca)
end
it "should set the terminus class for Host to 'none'" do
- lambda { Puppet::SSL::Host.indirection.terminus_class }.should raise_error(Puppet::DevError)
+ expect { Puppet::SSL::Host.indirection.terminus_class }.to raise_error(Puppet::DevError)
end
end
end
it "should have a class method for destroying all files related to a given host" do
- Puppet::SSL::Host.should respond_to(:destroy)
+ expect(Puppet::SSL::Host).to respond_to(:destroy)
end
describe "when destroying a host's SSL files" do
before do
Puppet::SSL::Key.indirection.stubs(:destroy).returns false
Puppet::SSL::Certificate.indirection.stubs(:destroy).returns false
Puppet::SSL::CertificateRequest.indirection.stubs(:destroy).returns false
end
it "should destroy its certificate, certificate request, and key" do
Puppet::SSL::Key.indirection.expects(:destroy).with("myhost")
Puppet::SSL::Certificate.indirection.expects(:destroy).with("myhost")
Puppet::SSL::CertificateRequest.indirection.expects(:destroy).with("myhost")
Puppet::SSL::Host.destroy("myhost")
end
it "should return true if any of the classes returned true" do
Puppet::SSL::Certificate.indirection.expects(:destroy).with("myhost").returns true
- Puppet::SSL::Host.destroy("myhost").should be_true
+ expect(Puppet::SSL::Host.destroy("myhost")).to be_truthy
end
it "should report that nothing was deleted if none of the classes returned true" do
- Puppet::SSL::Host.destroy("myhost").should == "Nothing was deleted"
+ expect(Puppet::SSL::Host.destroy("myhost")).to eq("Nothing was deleted")
end
end
describe "when initializing" do
it "should default its name to the :certname setting" do
Puppet[:certname] = "myname"
- Puppet::SSL::Host.new.name.should == "myname"
+ expect(Puppet::SSL::Host.new.name).to eq("myname")
end
it "should downcase a passed in name" do
- Puppet::SSL::Host.new("Host.Domain.Com").name.should == "host.domain.com"
+ expect(Puppet::SSL::Host.new("Host.Domain.Com").name).to eq("host.domain.com")
end
it "should indicate that it is a CA host if its name matches the ca_name constant" do
Puppet::SSL::Host.stubs(:ca_name).returns "myca"
- Puppet::SSL::Host.new("myca").should be_ca
+ expect(Puppet::SSL::Host.new("myca")).to be_ca
end
end
describe "when managing its private key" do
before do
@realkey = "mykey"
@key = Puppet::SSL::Key.new("mykey")
@key.content = @realkey
end
it "should return nil if the key is not set and cannot be found" do
Puppet::SSL::Key.indirection.expects(:find).with("myname").returns(nil)
- @host.key.should be_nil
+ expect(@host.key).to be_nil
end
it "should find the key in the Key class and return the Puppet instance" do
Puppet::SSL::Key.indirection.expects(:find).with("myname").returns(@key)
- @host.key.should equal(@key)
+ expect(@host.key).to equal(@key)
end
it "should be able to generate and save a new key" do
Puppet::SSL::Key.expects(:new).with("myname").returns(@key)
@key.expects(:generate)
Puppet::SSL::Key.indirection.expects(:save)
- @host.generate_key.should be_true
- @host.key.should equal(@key)
+ expect(@host.generate_key).to be_truthy
+ expect(@host.key).to equal(@key)
end
it "should not retain keys that could not be saved" do
Puppet::SSL::Key.expects(:new).with("myname").returns(@key)
@key.stubs(:generate)
Puppet::SSL::Key.indirection.expects(:save).raises "eh"
- lambda { @host.generate_key }.should raise_error
- @host.key.should be_nil
+ expect { @host.generate_key }.to raise_error
+ expect(@host.key).to be_nil
end
it "should return any previously found key without requerying" do
Puppet::SSL::Key.indirection.expects(:find).with("myname").returns(@key).once
- @host.key.should equal(@key)
- @host.key.should equal(@key)
+ expect(@host.key).to equal(@key)
+ expect(@host.key).to equal(@key)
end
end
describe "when managing its certificate request" do
before do
@realrequest = "real request"
@request = Puppet::SSL::CertificateRequest.new("myname")
@request.content = @realrequest
end
it "should return nil if the key is not set and cannot be found" do
Puppet::SSL::CertificateRequest.indirection.expects(:find).with("myname").returns(nil)
- @host.certificate_request.should be_nil
+ expect(@host.certificate_request).to be_nil
end
it "should find the request in the Key class and return it and return the Puppet SSL request" do
Puppet::SSL::CertificateRequest.indirection.expects(:find).with("myname").returns @request
- @host.certificate_request.should equal(@request)
+ expect(@host.certificate_request).to equal(@request)
end
it "should generate a new key when generating the cert request if no key exists" do
Puppet::SSL::CertificateRequest.expects(:new).with("myname").returns @request
key = stub 'key', :public_key => mock("public_key"), :content => "mycontent"
@host.expects(:key).times(2).returns(nil).then.returns(key)
@host.expects(:generate_key).returns(key)
@request.stubs(:generate)
Puppet::SSL::CertificateRequest.indirection.stubs(:save)
@host.generate_certificate_request
end
it "should be able to generate and save a new request using the private key" do
Puppet::SSL::CertificateRequest.expects(:new).with("myname").returns @request
key = stub 'key', :public_key => mock("public_key"), :content => "mycontent"
@host.stubs(:key).returns(key)
@request.expects(:generate).with("mycontent", {})
Puppet::SSL::CertificateRequest.indirection.expects(:save).with(@request)
- @host.generate_certificate_request.should be_true
- @host.certificate_request.should equal(@request)
+ expect(@host.generate_certificate_request).to be_truthy
+ expect(@host.certificate_request).to equal(@request)
end
it "should return any previously found request without requerying" do
Puppet::SSL::CertificateRequest.indirection.expects(:find).with("myname").returns(@request).once
- @host.certificate_request.should equal(@request)
- @host.certificate_request.should equal(@request)
+ expect(@host.certificate_request).to equal(@request)
+ expect(@host.certificate_request).to equal(@request)
end
it "should not keep its certificate request in memory if the request cannot be saved" do
Puppet::SSL::CertificateRequest.expects(:new).with("myname").returns @request
key = stub 'key', :public_key => mock("public_key"), :content => "mycontent"
@host.stubs(:key).returns(key)
@request.stubs(:generate)
@request.stubs(:name).returns("myname")
terminus = stub 'terminus'
terminus.stubs(:validate)
Puppet::SSL::CertificateRequest.indirection.expects(:prepare).returns(terminus)
terminus.expects(:save).with { |req| req.instance == @request && req.key == "myname" }.raises "eh"
- lambda { @host.generate_certificate_request }.should raise_error
+ expect { @host.generate_certificate_request }.to raise_error
- @host.instance_eval { @certificate_request }.should be_nil
+ expect(@host.instance_eval { @certificate_request }).to be_nil
end
end
describe "when managing its certificate" do
before do
@realcert = mock 'certificate'
@cert = stub 'cert', :content => @realcert
@host.stubs(:key).returns mock("key")
@host.stubs(:validate_certificate_with_key)
end
it "should find the CA certificate if it does not have a certificate" do
Puppet::SSL::Certificate.indirection.expects(:find).with(Puppet::SSL::CA_NAME, :fail_on_404 => true).returns mock("cacert")
Puppet::SSL::Certificate.indirection.stubs(:find).with("myname").returns @cert
@host.certificate
end
it "should not find the CA certificate if it is the CA host" do
@host.expects(:ca?).returns true
Puppet::SSL::Certificate.indirection.stubs(:find)
Puppet::SSL::Certificate.indirection.expects(:find).with(Puppet::SSL::CA_NAME, :fail_on_404 => true).never
@host.certificate
end
it "should return nil if it cannot find a CA certificate" do
Puppet::SSL::Certificate.indirection.expects(:find).with(Puppet::SSL::CA_NAME, :fail_on_404 => true).returns nil
Puppet::SSL::Certificate.indirection.expects(:find).with("myname").never
- @host.certificate.should be_nil
+ expect(@host.certificate).to be_nil
end
it "should find the key if it does not have one" do
Puppet::SSL::Certificate.indirection.stubs(:find)
@host.expects(:key).returns mock("key")
@host.certificate
end
it "should generate the key if one cannot be found" do
Puppet::SSL::Certificate.indirection.stubs(:find)
@host.expects(:key).returns nil
@host.expects(:generate_key)
@host.certificate
end
it "should find the certificate in the Certificate class and return the Puppet certificate instance" do
Puppet::SSL::Certificate.indirection.expects(:find).with(Puppet::SSL::CA_NAME, :fail_on_404 => true).returns mock("cacert")
Puppet::SSL::Certificate.indirection.expects(:find).with("myname").returns @cert
- @host.certificate.should equal(@cert)
+ expect(@host.certificate).to equal(@cert)
end
it "should return any previously found certificate" do
Puppet::SSL::Certificate.indirection.expects(:find).with(Puppet::SSL::CA_NAME, :fail_on_404 => true).returns mock("cacert")
Puppet::SSL::Certificate.indirection.expects(:find).with("myname").returns(@cert).once
- @host.certificate.should equal(@cert)
- @host.certificate.should equal(@cert)
+ expect(@host.certificate).to equal(@cert)
+ expect(@host.certificate).to equal(@cert)
end
end
it "should have a method for listing certificate hosts" do
- Puppet::SSL::Host.should respond_to(:search)
+ expect(Puppet::SSL::Host).to respond_to(:search)
end
describe "when listing certificate hosts" do
it "should default to listing all clients with any file types" do
Puppet::SSL::Key.indirection.expects(:search).returns []
Puppet::SSL::Certificate.indirection.expects(:search).returns []
Puppet::SSL::CertificateRequest.indirection.expects(:search).returns []
Puppet::SSL::Host.search
end
it "should be able to list only clients with a key" do
Puppet::SSL::Key.indirection.expects(:search).returns []
Puppet::SSL::Certificate.indirection.expects(:search).never
Puppet::SSL::CertificateRequest.indirection.expects(:search).never
Puppet::SSL::Host.search :for => Puppet::SSL::Key
end
it "should be able to list only clients with a certificate" do
Puppet::SSL::Key.indirection.expects(:search).never
Puppet::SSL::Certificate.indirection.expects(:search).returns []
Puppet::SSL::CertificateRequest.indirection.expects(:search).never
Puppet::SSL::Host.search :for => Puppet::SSL::Certificate
end
it "should be able to list only clients with a certificate request" do
Puppet::SSL::Key.indirection.expects(:search).never
Puppet::SSL::Certificate.indirection.expects(:search).never
Puppet::SSL::CertificateRequest.indirection.expects(:search).returns []
Puppet::SSL::Host.search :for => Puppet::SSL::CertificateRequest
end
it "should return a Host instance created with the name of each found instance" do
key = stub 'key', :name => "key", :to_ary => nil
cert = stub 'cert', :name => "cert", :to_ary => nil
csr = stub 'csr', :name => "csr", :to_ary => nil
Puppet::SSL::Key.indirection.expects(:search).returns [key]
Puppet::SSL::Certificate.indirection.expects(:search).returns [cert]
Puppet::SSL::CertificateRequest.indirection.expects(:search).returns [csr]
returned = []
%w{key cert csr}.each do |name|
result = mock(name)
returned << result
Puppet::SSL::Host.expects(:new).with(name).returns result
end
result = Puppet::SSL::Host.search
returned.each do |r|
- result.should be_include(r)
+ expect(result).to be_include(r)
end
end
end
it "should have a method for generating all necessary files" do
- Puppet::SSL::Host.new("me").should respond_to(:generate)
+ expect(Puppet::SSL::Host.new("me")).to respond_to(:generate)
end
describe "when generating files" do
before do
@host = Puppet::SSL::Host.new("me")
@host.stubs(:generate_key)
@host.stubs(:generate_certificate_request)
end
it "should generate a key if one is not present" do
@host.stubs(:key).returns nil
@host.expects(:generate_key)
@host.generate
end
it "should generate a certificate request if one is not present" do
@host.expects(:certificate_request).returns nil
@host.expects(:generate_certificate_request)
@host.generate
end
describe "and it can create a certificate authority" do
before do
@ca = mock 'ca'
Puppet::SSL::CertificateAuthority.stubs(:instance).returns @ca
end
it "should use the CA to sign its certificate request if it does not have a certificate" do
@host.expects(:certificate).returns nil
@ca.expects(:sign).with(@host.name, true)
@host.generate
end
end
describe "and it cannot create a certificate authority" do
before do
Puppet::SSL::CertificateAuthority.stubs(:instance).returns nil
end
it "should seek its certificate" do
@host.expects(:certificate)
@host.generate
end
end
end
it "should have a method for creating an SSL store" do
- Puppet::SSL::Host.new("me").should respond_to(:ssl_store)
+ expect(Puppet::SSL::Host.new("me")).to respond_to(:ssl_store)
end
it "should always return the same store" do
host = Puppet::SSL::Host.new("foo")
store = mock 'store'
store.stub_everything
OpenSSL::X509::Store.expects(:new).returns store
- host.ssl_store.should equal(host.ssl_store)
+ expect(host.ssl_store).to equal(host.ssl_store)
end
describe "when creating an SSL store" do
before do
@host = Puppet::SSL::Host.new("me")
@store = mock 'store'
@store.stub_everything
OpenSSL::X509::Store.stubs(:new).returns @store
Puppet[:localcacert] = "ssl_host_testing"
Puppet::SSL::CertificateRevocationList.indirection.stubs(:find).returns(nil)
end
it "should accept a purpose" do
@store.expects(:purpose=).with "my special purpose"
@host.ssl_store("my special purpose")
end
it "should default to OpenSSL::X509::PURPOSE_ANY as the purpose" do
@store.expects(:purpose=).with OpenSSL::X509::PURPOSE_ANY
@host.ssl_store
end
it "should add the local CA cert file" do
Puppet[:localcacert] = "/ca/cert/file"
@store.expects(:add_file).with Puppet[:localcacert]
@host.ssl_store
end
describe "and a CRL is available" do
before do
@crl = stub 'crl', :content => "real_crl"
Puppet::SSL::CertificateRevocationList.indirection.stubs(:find).returns @crl
end
describe "and 'certificate_revocation' is true" do
before do
Puppet[:certificate_revocation] = true
end
it "should add the CRL" do
@store.expects(:add_crl).with "real_crl"
@host.ssl_store
end
it "should set the flags to OpenSSL::X509::V_FLAG_CRL_CHECK_ALL|OpenSSL::X509::V_FLAG_CRL_CHECK" do
@store.expects(:flags=).with OpenSSL::X509::V_FLAG_CRL_CHECK_ALL|OpenSSL::X509::V_FLAG_CRL_CHECK
@host.ssl_store
end
end
describe "and 'certificate_revocation' is false" do
before do
Puppet[:certificate_revocation] = false
end
it "should not add the CRL" do
@store.expects(:add_crl).never
@host.ssl_store
end
it "should not set the flags" do
@store.expects(:flags=).never
@host.ssl_store
end
end
end
end
describe "when waiting for a cert" do
before do
@host = Puppet::SSL::Host.new("me")
end
it "should generate its certificate request and attempt to read the certificate again if no certificate is found" do
@host.expects(:certificate).times(2).returns(nil).then.returns "foo"
@host.expects(:generate)
@host.wait_for_cert(1)
end
it "should catch and log errors during CSR saving" do
@host.expects(:certificate).times(2).returns(nil).then.returns "foo"
@host.expects(:generate).raises(RuntimeError).then.returns nil
@host.stubs(:sleep)
@host.wait_for_cert(1)
end
it "should sleep and retry after failures saving the CSR if waitforcert is enabled" do
@host.expects(:certificate).times(2).returns(nil).then.returns "foo"
@host.expects(:generate).raises(RuntimeError).then.returns nil
@host.expects(:sleep).with(1)
@host.wait_for_cert(1)
end
it "should exit after failures saving the CSR of waitforcert is disabled" do
@host.expects(:certificate).returns(nil)
@host.expects(:generate).raises(RuntimeError)
@host.expects(:puts)
expect { @host.wait_for_cert(0) }.to exit_with 1
end
it "should exit if the wait time is 0 and it can neither find nor retrieve a certificate" do
@host.stubs(:certificate).returns nil
@host.expects(:generate)
@host.expects(:puts)
expect { @host.wait_for_cert(0) }.to exit_with 1
end
it "should sleep for the specified amount of time if no certificate is found after generating its certificate request" do
@host.expects(:certificate).times(3).returns(nil).then.returns(nil).then.returns "foo"
@host.expects(:generate)
@host.expects(:sleep).with(1)
@host.wait_for_cert(1)
end
it "should catch and log exceptions during certificate retrieval" do
@host.expects(:certificate).times(3).returns(nil).then.raises(RuntimeError).then.returns("foo")
@host.stubs(:generate)
@host.stubs(:sleep)
Puppet.expects(:err)
@host.wait_for_cert(1)
end
end
describe "when handling PSON", :unless => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
before do
Puppet[:vardir] = tmpdir("ssl_test_vardir")
Puppet[:ssldir] = tmpdir("ssl_test_ssldir")
# localcacert is where each client stores the CA certificate
# cacert is where the master stores the CA certificate
# Since we need to play the role of both for testing we need them to be the same and exist
Puppet[:cacert] = Puppet[:localcacert]
@ca=Puppet::SSL::CertificateAuthority.new
end
describe "when converting to PSON" do
let(:host) do
Puppet::SSL::Host.new("bazinga")
end
let(:pson_hash) do
{
"fingerprint" => host.certificate_request.fingerprint,
"desired_state" => 'requested',
"name" => host.name
}
end
it "should be able to identify a host with an unsigned certificate request" do
host.generate_certificate_request
result = PSON.parse(Puppet::SSL::Host.new(host.name).to_pson)
base_pson_comparison result, pson_hash
end
it "should validate against the schema" do
host.generate_certificate_request
expect(host.to_pson).to validate_against('api/schemas/host.json')
end
describe "explicit fingerprints" do
[:SHA1, :SHA256, :SHA512].each do |md|
it "should include #{md}" do
mds = md.to_s
host.generate_certificate_request
pson_hash["fingerprints"] = {}
pson_hash["fingerprints"][mds] = host.certificate_request.fingerprint(md)
result = PSON.parse(Puppet::SSL::Host.new(host.name).to_pson)
base_pson_comparison result, pson_hash
- result["fingerprints"][mds].should == pson_hash["fingerprints"][mds]
+ expect(result["fingerprints"][mds]).to eq(pson_hash["fingerprints"][mds])
end
end
end
describe "dns_alt_names" do
describe "when not specified" do
it "should include the dns_alt_names associated with the certificate" do
host.generate_certificate_request
pson_hash["desired_alt_names"] = host.certificate_request.subject_alt_names
result = PSON.parse(Puppet::SSL::Host.new(host.name).to_pson)
base_pson_comparison result, pson_hash
- result["dns_alt_names"].should == pson_hash["desired_alt_names"]
+ expect(result["dns_alt_names"]).to eq(pson_hash["desired_alt_names"])
end
end
[ "",
"test, alt, names"
].each do |alt_names|
describe "when #{alt_names}" do
before(:each) do
host.generate_certificate_request :dns_alt_names => alt_names
end
it "should include the dns_alt_names associated with the certificate" do
pson_hash["desired_alt_names"] = host.certificate_request.subject_alt_names
result = PSON.parse(Puppet::SSL::Host.new(host.name).to_pson)
base_pson_comparison result, pson_hash
- result["dns_alt_names"].should == pson_hash["desired_alt_names"]
+ expect(result["dns_alt_names"]).to eq(pson_hash["desired_alt_names"])
end
it "should validate against the schema" do
expect(host.to_pson).to validate_against('api/schemas/host.json')
end
end
end
end
it "should be able to identify a host with a signed certificate" do
host.generate_certificate_request
@ca.sign(host.name)
pson_hash = {
"fingerprint" => Puppet::SSL::Certificate.indirection.find(host.name).fingerprint,
"desired_state" => 'signed',
"name" => host.name,
}
result = PSON.parse(Puppet::SSL::Host.new(host.name).to_pson)
base_pson_comparison result, pson_hash
end
it "should be able to identify a host with a revoked certificate" do
host.generate_certificate_request
@ca.sign(host.name)
@ca.revoke(host.name)
pson_hash["fingerprint"] = Puppet::SSL::Certificate.indirection.find(host.name).fingerprint
pson_hash["desired_state"] = 'revoked'
result = PSON.parse(Puppet::SSL::Host.new(host.name).to_pson)
base_pson_comparison result, pson_hash
end
end
describe "when converting from PSON" do
it "should return a Puppet::SSL::Host object with the specified desired state" do
host = Puppet::SSL::Host.new("bazinga")
host.desired_state="signed"
pson_hash = {
"name" => host.name,
"desired_state" => host.desired_state,
}
generated_host = Puppet::SSL::Host.from_data_hash(pson_hash)
- generated_host.desired_state.should == host.desired_state
- generated_host.name.should == host.name
+ expect(generated_host.desired_state).to eq(host.desired_state)
+ expect(generated_host.name).to eq(host.name)
end
end
end
end
diff --git a/spec/unit/ssl/inventory_spec.rb b/spec/unit/ssl/inventory_spec.rb
index 70456e101..b3dd71a35 100755
--- a/spec/unit/ssl/inventory_spec.rb
+++ b/spec/unit/ssl/inventory_spec.rb
@@ -1,127 +1,127 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/inventory'
describe Puppet::SSL::Inventory, :unless => Puppet.features.microsoft_windows? do
let(:cert_inventory) { File.expand_path("/inven/tory") }
before do
@class = Puppet::SSL::Inventory
end
describe "when initializing" do
it "should set its path to the inventory file" do
Puppet[:cert_inventory] = cert_inventory
- @class.new.path.should == cert_inventory
+ expect(@class.new.path).to eq(cert_inventory)
end
end
describe "when managing an inventory" do
before do
Puppet[:cert_inventory] = cert_inventory
Puppet::FileSystem.stubs(:exist?).with(cert_inventory).returns true
@inventory = @class.new
@cert = mock 'cert'
end
describe "and creating the inventory file" do
it "re-adds all of the existing certificates" do
inventory_file = StringIO.new
Puppet.settings.setting(:cert_inventory).stubs(:open).yields(inventory_file)
cert1 = Puppet::SSL::Certificate.new("cert1")
cert1.content = stub 'cert1',
:serial => 2,
:not_before => Time.now,
:not_after => Time.now,
:subject => "/CN=smocking"
cert2 = Puppet::SSL::Certificate.new("cert2")
cert2.content = stub 'cert2',
:serial => 3,
:not_before => Time.now,
:not_after => Time.now,
:subject => "/CN=mocking bird"
Puppet::SSL::Certificate.indirection.expects(:search).with("*").returns [cert1, cert2]
@inventory.rebuild
expect(inventory_file.string).to match(/\/CN=smocking/)
expect(inventory_file.string).to match(/\/CN=mocking bird/)
end
end
describe "and adding a certificate" do
it "should use the Settings to write to the file" do
Puppet.settings.setting(:cert_inventory).expects(:open).with("a")
@inventory.add(@cert)
end
it "should add formatted certificate information to the end of the file" do
cert = Puppet::SSL::Certificate.new("mycert")
cert.content = @cert
fh = StringIO.new
Puppet.settings.setting(:cert_inventory).expects(:open).with("a").yields(fh)
@inventory.expects(:format).with(@cert).returns "myformat"
@inventory.add(@cert)
expect(fh.string).to eq("myformat")
end
end
describe "and formatting a certificate" do
before do
@cert = stub 'cert', :not_before => Time.now, :not_after => Time.now, :subject => "mycert", :serial => 15
end
it "should print the serial number as a 4 digit hex number in the first field" do
- @inventory.format(@cert).split[0].should == "0x000f" # 15 in hex
+ expect(@inventory.format(@cert).split[0]).to eq("0x000f") # 15 in hex
end
it "should print the not_before date in '%Y-%m-%dT%H:%M:%S%Z' format in the second field" do
@cert.not_before.expects(:strftime).with('%Y-%m-%dT%H:%M:%S%Z').returns "before_time"
- @inventory.format(@cert).split[1].should == "before_time"
+ expect(@inventory.format(@cert).split[1]).to eq("before_time")
end
it "should print the not_after date in '%Y-%m-%dT%H:%M:%S%Z' format in the third field" do
@cert.not_after.expects(:strftime).with('%Y-%m-%dT%H:%M:%S%Z').returns "after_time"
- @inventory.format(@cert).split[2].should == "after_time"
+ expect(@inventory.format(@cert).split[2]).to eq("after_time")
end
it "should print the subject in the fourth field" do
- @inventory.format(@cert).split[3].should == "mycert"
+ expect(@inventory.format(@cert).split[3]).to eq("mycert")
end
it "should add a carriage return" do
- @inventory.format(@cert).should =~ /\n$/
+ expect(@inventory.format(@cert)).to match(/\n$/)
end
it "should produce a line consisting of the serial number, start date, expiration date, and subject" do
# Just make sure our serial and subject bracket the lines.
- @inventory.format(@cert).should =~ /^0x.+mycert$/
+ expect(@inventory.format(@cert)).to match(/^0x.+mycert$/)
end
end
describe "and finding serial numbers" do
it "should return an empty array if the inventory file is missing" do
Puppet::FileSystem.expects(:exist?).with(cert_inventory).returns false
- @inventory.serials(:whatever).should be_empty
+ expect(@inventory.serials(:whatever)).to be_empty
end
it "should return the all the serial numbers from the lines matching the provided name" do
File.expects(:readlines).with(cert_inventory).returns ["0x00f blah blah /CN=me\n", "0x001 blah blah /CN=you\n", "0x002 blah blah /CN=me\n"]
- @inventory.serials("me").should == [15, 2]
+ expect(@inventory.serials("me")).to eq([15, 2])
end
end
end
end
diff --git a/spec/unit/ssl/key_spec.rb b/spec/unit/ssl/key_spec.rb
index c7f54ff5d..3d78a90b2 100755
--- a/spec/unit/ssl/key_spec.rb
+++ b/spec/unit/ssl/key_spec.rb
@@ -1,191 +1,191 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/ssl/key'
describe Puppet::SSL::Key do
before do
@class = Puppet::SSL::Key
end
it "should be extended with the Indirector module" do
- @class.singleton_class.should be_include(Puppet::Indirector)
+ expect(@class.singleton_class).to be_include(Puppet::Indirector)
end
it "should indirect key" do
- @class.indirection.name.should == :key
+ expect(@class.indirection.name).to eq(:key)
end
it "should only support the text format" do
- @class.supported_formats.should == [:s]
+ expect(@class.supported_formats).to eq([:s])
end
it "should have a method for determining whether it's a CA key" do
- @class.new("test").should respond_to(:ca?)
+ expect(@class.new("test")).to respond_to(:ca?)
end
it "should consider itself a ca key if its name matches the CA_NAME" do
- @class.new(Puppet::SSL::Host.ca_name).should be_ca
+ expect(@class.new(Puppet::SSL::Host.ca_name)).to be_ca
end
describe "when initializing" do
it "should set its password file to the :capass if it's a CA key" do
Puppet[:capass] = File.expand_path("/ca/pass")
key = Puppet::SSL::Key.new(Puppet::SSL::Host.ca_name)
- key.password_file.should == Puppet[:capass]
+ expect(key.password_file).to eq(Puppet[:capass])
end
it "should downcase its name" do
- @class.new("MyName").name.should == "myname"
+ expect(@class.new("MyName").name).to eq("myname")
end
it "should set its password file to the default password file if it is not the CA key" do
Puppet[:passfile] = File.expand_path("/normal/pass")
key = Puppet::SSL::Key.new("notca")
- key.password_file.should == Puppet[:passfile]
+ expect(key.password_file).to eq(Puppet[:passfile])
end
end
describe "when managing instances" do
before do
@key = @class.new("myname")
end
it "should have a name attribute" do
- @key.name.should == "myname"
+ expect(@key.name).to eq("myname")
end
it "should have a content attribute" do
- @key.should respond_to(:content)
+ expect(@key).to respond_to(:content)
end
it "should be able to read keys from disk" do
path = "/my/path"
File.expects(:read).with(path).returns("my key")
key = mock 'key'
OpenSSL::PKey::RSA.expects(:new).returns(key)
- @key.read(path).should equal(key)
- @key.content.should equal(key)
+ expect(@key.read(path)).to equal(key)
+ expect(@key.content).to equal(key)
end
it "should not try to use the provided password file if the file does not exist" do
Puppet::FileSystem.stubs(:exist?).returns false
@key.password_file = "/path/to/password"
path = "/my/path"
File.stubs(:read).with(path).returns("my key")
OpenSSL::PKey::RSA.expects(:new).with("my key", nil).returns(mock('key'))
File.expects(:read).with("/path/to/password").never
@key.read(path)
end
it "should read the key with the password retrieved from the password file if one is provided" do
Puppet::FileSystem.stubs(:exist?).returns true
@key.password_file = "/path/to/password"
path = "/my/path"
File.expects(:read).with(path).returns("my key")
File.expects(:read).with("/path/to/password").returns("my password")
key = mock 'key'
OpenSSL::PKey::RSA.expects(:new).with("my key", "my password").returns(key)
- @key.read(path).should equal(key)
- @key.content.should equal(key)
+ expect(@key.read(path)).to equal(key)
+ expect(@key.content).to equal(key)
end
it "should return an empty string when converted to a string with no key" do
- @key.to_s.should == ""
+ expect(@key.to_s).to eq("")
end
it "should convert the key to pem format when converted to a string" do
key = mock 'key', :to_pem => "pem"
@key.content = key
- @key.to_s.should == "pem"
+ expect(@key.to_s).to eq("pem")
end
it "should have a :to_text method that it delegates to the actual key" do
real_key = mock 'key'
real_key.expects(:to_text).returns "keytext"
@key.content = real_key
- @key.to_text.should == "keytext"
+ expect(@key.to_text).to eq("keytext")
end
end
describe "when generating the private key" do
before do
@instance = @class.new("test")
@key = mock 'key'
end
it "should create an instance of OpenSSL::PKey::RSA" do
OpenSSL::PKey::RSA.expects(:new).returns(@key)
@instance.generate
end
it "should create the private key with the keylength specified in the settings" do
Puppet[:keylength] = "50"
OpenSSL::PKey::RSA.expects(:new).with(50).returns(@key)
@instance.generate
end
it "should set the content to the generated key" do
OpenSSL::PKey::RSA.stubs(:new).returns(@key)
@instance.generate
- @instance.content.should equal(@key)
+ expect(@instance.content).to equal(@key)
end
it "should return the generated key" do
OpenSSL::PKey::RSA.stubs(:new).returns(@key)
- @instance.generate.should equal(@key)
+ expect(@instance.generate).to equal(@key)
end
it "should return the key in pem format" do
@instance.generate
@instance.content.expects(:to_pem).returns "my normal key"
- @instance.to_s.should == "my normal key"
+ expect(@instance.to_s).to eq("my normal key")
end
describe "with a password file set" do
it "should return a nil password if the password file does not exist" do
Puppet::FileSystem.expects(:exist?).with("/path/to/pass").returns false
File.expects(:read).with("/path/to/pass").never
@instance.password_file = "/path/to/pass"
- @instance.password.should be_nil
+ expect(@instance.password).to be_nil
end
it "should return the contents of the password file as its password" do
Puppet::FileSystem.expects(:exist?).with("/path/to/pass").returns true
File.expects(:read).with("/path/to/pass").returns "my password"
@instance.password_file = "/path/to/pass"
- @instance.password.should == "my password"
+ expect(@instance.password).to eq("my password")
end
it "should export the private key to text using the password" do
Puppet[:keylength] = "50"
@instance.password_file = "/path/to/pass"
@instance.stubs(:password).returns "my password"
OpenSSL::PKey::RSA.expects(:new).returns(@key)
@instance.generate
cipher = mock 'cipher'
OpenSSL::Cipher::DES.expects(:new).with(:EDE3, :CBC).returns cipher
@key.expects(:export).with(cipher, "my password").returns "my encrypted key"
- @instance.to_s.should == "my encrypted key"
+ expect(@instance.to_s).to eq("my encrypted key")
end
end
end
end
diff --git a/spec/unit/ssl/oids_spec.rb b/spec/unit/ssl/oids_spec.rb
index ee95bb942..549d7ecf2 100644
--- a/spec/unit/ssl/oids_spec.rb
+++ b/spec/unit/ssl/oids_spec.rb
@@ -1,48 +1,48 @@
require 'spec_helper'
require 'puppet/ssl/oids'
describe Puppet::SSL::Oids do
describe "defining application OIDs" do
{
'puppetlabs' => '1.3.6.1.4.1.34380',
'ppCertExt' => '1.3.6.1.4.1.34380.1',
'ppRegCertExt' => '1.3.6.1.4.1.34380.1.1',
'pp_uuid' => '1.3.6.1.4.1.34380.1.1.1',
'pp_instance_id' => '1.3.6.1.4.1.34380.1.1.2',
'pp_image_name' => '1.3.6.1.4.1.34380.1.1.3',
'pp_preshared_key' => '1.3.6.1.4.1.34380.1.1.4',
'ppPrivCertExt' => '1.3.6.1.4.1.34380.1.2',
}.each_pair do |sn, oid|
it "defines #{sn} as #{oid}" do
object_id = OpenSSL::ASN1::ObjectId.new(sn)
expect(object_id.oid).to eq oid
end
end
end
describe "checking if an OID is a subtree of another OID" do
it "can determine if an OID is contained in another OID" do
- described_class.subtree_of?('1.3.6.1', '1.3.6.1.4.1').should be_true
- described_class.subtree_of?('1.3.6.1.4.1', '1.3.6.1').should be_false
+ expect(described_class.subtree_of?('1.3.6.1', '1.3.6.1.4.1')).to be_truthy
+ expect(described_class.subtree_of?('1.3.6.1.4.1', '1.3.6.1')).to be_falsey
end
it "returns true if an OID is compared against itself and exclusive is false" do
- described_class.subtree_of?('1.3.6.1', '1.3.6.1', false).should be_true
+ expect(described_class.subtree_of?('1.3.6.1', '1.3.6.1', false)).to be_truthy
end
it "returns false if an OID is compared against itself and exclusive is true" do
- described_class.subtree_of?('1.3.6.1', '1.3.6.1', true).should be_false
+ expect(described_class.subtree_of?('1.3.6.1', '1.3.6.1', true)).to be_falsey
end
it "can compare OIDs defined as short names" do
- described_class.subtree_of?('IANA', '1.3.6.1.4.1').should be_true
- described_class.subtree_of?('1.3.6.1', 'enterprises').should be_true
+ expect(described_class.subtree_of?('IANA', '1.3.6.1.4.1')).to be_truthy
+ expect(described_class.subtree_of?('1.3.6.1', 'enterprises')).to be_truthy
end
it "returns false when an invalid OID shortname is passed" do
- described_class.subtree_of?('IANA', 'bananas').should be_false
+ expect(described_class.subtree_of?('IANA', 'bananas')).to be_falsey
end
end
end
diff --git a/spec/unit/ssl/validator_spec.rb b/spec/unit/ssl/validator_spec.rb
index b09242abc..a0b815540 100644
--- a/spec/unit/ssl/validator_spec.rb
+++ b/spec/unit/ssl/validator_spec.rb
@@ -1,418 +1,418 @@
require 'spec_helper'
require 'puppet/ssl'
describe Puppet::SSL::Validator::DefaultValidator do
let(:ssl_context) do
mock('OpenSSL::X509::StoreContext')
end
let(:ssl_configuration) do
Puppet::SSL::Configuration.new(
Puppet[:localcacert],
:ca_auth_file => Puppet[:ssl_client_ca_auth])
end
let(:ssl_host) do
stub('ssl_host',
:ssl_store => nil,
:certificate => stub('cert', :content => nil),
:key => stub('key', :content => nil))
end
subject do
described_class.new(ssl_configuration,
ssl_host)
end
before :each do
ssl_configuration.stubs(:read_file).
with(Puppet[:localcacert]).
returns(root_ca)
end
describe '#call' do
before :each do
ssl_context.stubs(:current_cert).returns(*cert_chain_in_callback_order)
ssl_context.stubs(:chain).returns(cert_chain)
end
context 'When pre-verification is not OK' do
context 'and the ssl_context is in an error state' do
let(:root_subject) { OpenSSL::X509::Certificate.new(root_ca).subject.to_s }
let(:code) { OpenSSL::X509::V_ERR_INVALID_CA }
it 'rejects the connection' do
ssl_context.stubs(:error_string).returns("Something went wrong")
ssl_context.stubs(:error).returns(code)
expect(subject.call(false, ssl_context)).to eq(false)
end
it 'makes the error available via #verify_errors' do
ssl_context.stubs(:error_string).returns("Something went wrong")
ssl_context.stubs(:error).returns(code)
subject.call(false, ssl_context)
expect(subject.verify_errors).to eq(["Something went wrong for #{root_subject}"])
end
it 'uses a generic message if error_string is nil' do
ssl_context.stubs(:error_string).returns(nil)
ssl_context.stubs(:error).returns(code)
subject.call(false, ssl_context)
expect(subject.verify_errors).to eq(["OpenSSL error #{code} for #{root_subject}"])
end
it 'uses 0 for nil error codes' do
ssl_context.stubs(:error_string).returns("Something went wrong")
ssl_context.stubs(:error).returns(nil)
subject.call(false, ssl_context)
expect(subject.verify_errors).to eq(["Something went wrong for #{root_subject}"])
end
context "when CRL is not yet valid" do
before :each do
ssl_context.stubs(:error_string).returns("CRL is not yet valid")
ssl_context.stubs(:error).returns(OpenSSL::X509::V_ERR_CRL_NOT_YET_VALID)
end
it 'rejects nil CRL' do
ssl_context.stubs(:current_crl).returns(nil)
expect(subject.call(false, ssl_context)).to eq(false)
expect(subject.verify_errors).to eq(["CRL is not yet valid"])
end
it 'includes the CRL issuer in the verify error message' do
crl = OpenSSL::X509::CRL.new
crl.issuer = OpenSSL::X509::Name.new([['CN','Puppet CA: puppetmaster.example.com']])
crl.last_update = Time.now + 24 * 60 * 60
ssl_context.stubs(:current_crl).returns(crl)
subject.call(false, ssl_context)
expect(subject.verify_errors).to eq(["CRL is not yet valid for /CN=Puppet CA: puppetmaster.example.com"])
end
it 'rejects CRLs whose last_update time is more than 5 minutes in the future' do
crl = OpenSSL::X509::CRL.new
crl.issuer = OpenSSL::X509::Name.new([['CN','Puppet CA: puppetmaster.example.com']])
crl.last_update = Time.now + 24 * 60 * 60
ssl_context.stubs(:current_crl).returns(crl)
expect(subject.call(false, ssl_context)).to eq(false)
end
it 'accepts CRLs whose last_update time is 10 seconds in the future' do
crl = OpenSSL::X509::CRL.new
crl.issuer = OpenSSL::X509::Name.new([['CN','Puppet CA: puppetmaster.example.com']])
crl.last_update = Time.now + 10
ssl_context.stubs(:current_crl).returns(crl)
expect(subject.call(false, ssl_context)).to eq(true)
end
end
end
end
context 'When pre-verification is OK' do
context 'and the ssl_context is in an error state' do
before :each do
ssl_context.stubs(:error_string).returns("Something went wrong")
end
it 'does not make the error available via #verify_errors' do
subject.call(true, ssl_context)
- subject.verify_errors.should == []
+ expect(subject.verify_errors).to eq([])
end
end
context 'and the chain is valid' do
it 'is true for each CA certificate in the chain' do
(cert_chain.length - 1).times do
- subject.call(true, ssl_context).should be_true
+ expect(subject.call(true, ssl_context)).to be_truthy
end
end
it 'is true for the SSL certificate ending the chain' do
(cert_chain.length - 1).times do
subject.call(true, ssl_context)
end
- subject.call(true, ssl_context).should be_true
+ expect(subject.call(true, ssl_context)).to be_truthy
end
end
context 'and the chain is invalid' do
before :each do
ssl_configuration.stubs(:read_file).
with(Puppet[:localcacert]).
returns(agent_ca)
end
it 'is true for each CA certificate in the chain' do
(cert_chain.length - 1).times do
- subject.call(true, ssl_context).should be_true
+ expect(subject.call(true, ssl_context)).to be_truthy
end
end
it 'is false for the SSL certificate ending the chain' do
(cert_chain.length - 1).times do
subject.call(true, ssl_context)
end
- subject.call(true, ssl_context).should be_false
+ expect(subject.call(true, ssl_context)).to be_falsey
end
end
context 'an error is raised inside of #call' do
before :each do
ssl_context.expects(:current_cert).raises(StandardError, "BOOM!")
end
it 'is false' do
- subject.call(true, ssl_context).should be_false
+ expect(subject.call(true, ssl_context)).to be_falsey
end
it 'makes the error available through #verify_errors' do
subject.call(true, ssl_context)
- subject.verify_errors.should == ["BOOM!"]
+ expect(subject.verify_errors).to eq(["BOOM!"])
end
end
end
end
describe '#setup_connection' do
it 'updates the connection for verification' do
subject.stubs(:ssl_certificates_are_present?).returns(true)
connection = mock('Net::HTTP')
connection.expects(:cert_store=).with(ssl_host.ssl_store)
connection.expects(:ca_file=).with(ssl_configuration.ca_auth_file)
connection.expects(:cert=).with(ssl_host.certificate.content)
connection.expects(:key=).with(ssl_host.key.content)
connection.expects(:verify_callback=).with(subject)
connection.expects(:verify_mode=).with(OpenSSL::SSL::VERIFY_PEER)
subject.setup_connection(connection)
end
it 'does not perform verification if certificate files are missing' do
subject.stubs(:ssl_certificates_are_present?).returns(false)
connection = mock('Net::HTTP')
connection.expects(:verify_mode=).with(OpenSSL::SSL::VERIFY_NONE)
subject.setup_connection(connection)
end
end
describe '#valid_peer?' do
before :each do
peer_certs = cert_chain_in_callback_order.map do |c|
Puppet::SSL::Certificate.from_instance(c)
end
subject.instance_variable_set(:@peer_certs, peer_certs)
end
context 'when the peer presents a valid chain' do
before :each do
subject.stubs(:has_authz_peer_cert).returns(true)
end
it 'is true' do
- subject.valid_peer?.should be_true
+ expect(subject.valid_peer?).to be_truthy
end
end
context 'when the peer presents an invalid chain' do
before :each do
subject.stubs(:has_authz_peer_cert).returns(false)
end
it 'is false' do
- subject.valid_peer?.should be_false
+ expect(subject.valid_peer?).to be_falsey
end
it 'makes a helpful error message available via #verify_errors' do
subject.valid_peer?
- subject.verify_errors.should == [expected_authz_error_msg]
+ expect(subject.verify_errors).to eq([expected_authz_error_msg])
end
end
end
describe '#has_authz_peer_cert' do
context 'when the Root CA is listed as authorized' do
it 'returns true when the SSL cert is issued by the Master CA' do
- subject.has_authz_peer_cert(cert_chain, [root_ca_cert]).should be_true
+ expect(subject.has_authz_peer_cert(cert_chain, [root_ca_cert])).to be_truthy
end
it 'returns true when the SSL cert is issued by the Agent CA' do
- subject.has_authz_peer_cert(cert_chain_agent_ca, [root_ca_cert]).should be_true
+ expect(subject.has_authz_peer_cert(cert_chain_agent_ca, [root_ca_cert])).to be_truthy
end
end
context 'when the Master CA is listed as authorized' do
it 'returns false when the SSL cert is issued by the Master CA' do
- subject.has_authz_peer_cert(cert_chain, [master_ca_cert]).should be_true
+ expect(subject.has_authz_peer_cert(cert_chain, [master_ca_cert])).to be_truthy
end
it 'returns true when the SSL cert is issued by the Agent CA' do
- subject.has_authz_peer_cert(cert_chain_agent_ca, [master_ca_cert]).should be_false
+ expect(subject.has_authz_peer_cert(cert_chain_agent_ca, [master_ca_cert])).to be_falsey
end
end
context 'when the Agent CA is listed as authorized' do
it 'returns true when the SSL cert is issued by the Master CA' do
- subject.has_authz_peer_cert(cert_chain, [agent_ca_cert]).should be_false
+ expect(subject.has_authz_peer_cert(cert_chain, [agent_ca_cert])).to be_falsey
end
it 'returns true when the SSL cert is issued by the Agent CA' do
- subject.has_authz_peer_cert(cert_chain_agent_ca, [agent_ca_cert]).should be_true
+ expect(subject.has_authz_peer_cert(cert_chain_agent_ca, [agent_ca_cert])).to be_truthy
end
end
end
def root_ca
<<-ROOT_CA
-----BEGIN CERTIFICATE-----
MIICYDCCAcmgAwIBAgIJALf2Pk2HvtBzMA0GCSqGSIb3DQEBBQUAMEkxEDAOBgNV
BAMMB1Jvb3QgQ0ExGjAYBgNVBAsMEVNlcnZlciBPcGVyYXRpb25zMRkwFwYDVQQK
DBBFeGFtcGxlIE9yZywgTExDMB4XDTEzMDMzMDA1NTA0OFoXDTMzMDMyNTA1NTA0
OFowSTEQMA4GA1UEAwwHUm9vdCBDQTEaMBgGA1UECwwRU2VydmVyIE9wZXJhdGlv
bnMxGTAXBgNVBAoMEEV4YW1wbGUgT3JnLCBMTEMwgZ8wDQYJKoZIhvcNAQEBBQAD
gY0AMIGJAoGBAMGSpafR4lboYOPfPJC1wVHHl0gD49ZVRjOlJ9jidEUjBdFXK6SA
S1tecDv2G4tM1ANmfMKjZl0m+KaZ8O2oq0g6kxkq1Mg0eSNvlnEyehjmTLRzHC2i
a0biH2wMtCLzfAoXDKy4GPlciBPE9mup5I8Kien5s91t92tc7K8AJ8oBAgMBAAGj
UDBOMB0GA1UdDgQWBBQwTdZqjjXOIFK2hOM0bcOrnhQw2jAfBgNVHSMEGDAWgBQw
TdZqjjXOIFK2hOM0bcOrnhQw2jAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUA
A4GBACs8EZRrzgzAlcKC1Tz8GYlNHQg0XhpbEDm+p2mOV//PuDD190O+UBpWxo9Q
rrkkx8En0wXQZJf6iH3hwewwHLOq5yXZKbJN+SmvJvRNL95Yhyy08Y9N65tJveE7
rPsNU/Tx19jHC87oXlmAePLI4IaUHXrWb7CRbY9TEcPdmj1R
-----END CERTIFICATE-----
ROOT_CA
end
def master_ca
<<-MASTER_CA
-----BEGIN CERTIFICATE-----
MIICljCCAf+gAwIBAgIBAjANBgkqhkiG9w0BAQUFADBJMRAwDgYDVQQDDAdSb290
IENBMRowGAYDVQQLDBFTZXJ2ZXIgT3BlcmF0aW9uczEZMBcGA1UECgwQRXhhbXBs
ZSBPcmcsIExMQzAeFw0xMzAzMzAwNTUwNDhaFw0zMzAzMjUwNTUwNDhaMH4xJDAi
BgNVBAMTG0ludGVybWVkaWF0ZSBDQSAobWFzdGVyLWNhKTEfMB0GCSqGSIb3DQEJ
ARYQdGVzdEBleGFtcGxlLm9yZzEZMBcGA1UEChMQRXhhbXBsZSBPcmcsIExMQzEa
MBgGA1UECxMRU2VydmVyIE9wZXJhdGlvbnMwXDANBgkqhkiG9w0BAQEFAANLADBI
AkEAvo/az3oR69SP92jGnUHMJLEyyD1Ui1BZ/rUABJcQTRQqn3RqtlfYePWZnUaZ
srKbXRS4q0w5Vqf1kx5w3q5tIwIDAQABo4GcMIGZMHkGA1UdIwRyMHCAFDBN1mqO
Nc4gUraE4zRtw6ueFDDaoU2kSzBJMRAwDgYDVQQDDAdSb290IENBMRowGAYDVQQL
DBFTZXJ2ZXIgT3BlcmF0aW9uczEZMBcGA1UECgwQRXhhbXBsZSBPcmcsIExMQ4IJ
ALf2Pk2HvtBzMA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMA0GCSqGSIb3
DQEBBQUAA4GBACRfa1YPS7RQUuhYovGgV0VYqxuATC7WwdIRihVh5FceSXKgSIbz
BKmOBAy/KixEhpnHTbkpaJ0d9ITkvjMTmj3M5YMahKaQA5niVPckQPecMMd6jg9U
l1k75xLLIcrlsDYo3999KOSSchH2K7bLT7TuQ2okdP6FHWmeWmudewlu
-----END CERTIFICATE-----
MASTER_CA
end
def agent_ca
<<-AGENT_CA
-----BEGIN CERTIFICATE-----
MIIClTCCAf6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBJMRAwDgYDVQQDDAdSb290
IENBMRowGAYDVQQLDBFTZXJ2ZXIgT3BlcmF0aW9uczEZMBcGA1UECgwQRXhhbXBs
ZSBPcmcsIExMQzAeFw0xMzAzMzAwNTUwNDhaFw0zMzAzMjUwNTUwNDhaMH0xIzAh
BgNVBAMTGkludGVybWVkaWF0ZSBDQSAoYWdlbnQtY2EpMR8wHQYJKoZIhvcNAQkB
FhB0ZXN0QGV4YW1wbGUub3JnMRkwFwYDVQQKExBFeGFtcGxlIE9yZywgTExDMRow
GAYDVQQLExFTZXJ2ZXIgT3BlcmF0aW9uczBcMA0GCSqGSIb3DQEBAQUAA0sAMEgC
QQDkEj/Msmi4hJImxP5+ocixMTHuYC1M1E2p4QcuzOkZYrfHf+5hJMcahfYhLiXU
jHBredOXhgSisHh6CLSb/rKzAgMBAAGjgZwwgZkweQYDVR0jBHIwcIAUME3Wao41
ziBStoTjNG3Dq54UMNqhTaRLMEkxEDAOBgNVBAMMB1Jvb3QgQ0ExGjAYBgNVBAsM
EVNlcnZlciBPcGVyYXRpb25zMRkwFwYDVQQKDBBFeGFtcGxlIE9yZywgTExDggkA
t/Y+TYe+0HMwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcN
AQEFBQADgYEAujSj9rxIxJHEuuYXb15L30yxs9Tdvy4OCLiKdjvs9Z7gG8Pbutls
ooCwyYAkmzKVs/8cYjZJnvJrPEW1gFwqX7Xknp85Cfrl+/pQEPYq5sZVa5BIm9tI
0EvlDax/Hd28jI6Bgq5fsTECNl9GDGknCy7vwRZem0h+hI56lzR3pYE=
-----END CERTIFICATE-----
AGENT_CA
end
# Signed by the master CA (Good)
def master_issued_by_master_ca
<<-GOOD_SSL_CERT
-----BEGIN CERTIFICATE-----
MIICZzCCAhGgAwIBAgIBATANBgkqhkiG9w0BAQUFADB+MSQwIgYDVQQDExtJbnRl
cm1lZGlhdGUgQ0EgKG1hc3Rlci1jYSkxHzAdBgkqhkiG9w0BCQEWEHRlc3RAZXhh
bXBsZS5vcmcxGTAXBgNVBAoTEEV4YW1wbGUgT3JnLCBMTEMxGjAYBgNVBAsTEVNl
cnZlciBPcGVyYXRpb25zMB4XDTEzMDMzMDA1NTA0OFoXDTMzMDMyNTA1NTA0OFow
HjEcMBoGA1UEAwwTbWFzdGVyMS5leGFtcGxlLm9yZzBcMA0GCSqGSIb3DQEBAQUA
A0sAMEgCQQDACW8fryVZH0dC7vYUASonVBKYcILnKN2O9QX7RenZGN1TWek9LQxr
yQFDyp7WJ8jUw6nENGniLU8J+QSSxryjAgMBAAGjgdkwgdYwWwYDVR0jBFQwUqFN
pEswSTEQMA4GA1UEAwwHUm9vdCBDQTEaMBgGA1UECwwRU2VydmVyIE9wZXJhdGlv
bnMxGTAXBgNVBAoMEEV4YW1wbGUgT3JnLCBMTEOCAQIwDAYDVR0TAQH/BAIwADAL
BgNVHQ8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMD0GA1Ud
EQQ2MDSCE21hc3RlcjEuZXhhbXBsZS5vcmeCB21hc3RlcjGCBnB1cHBldIIMcHVw
cGV0bWFzdGVyMA0GCSqGSIb3DQEBBQUAA0EAo8PvgLrah6jQVs6YCBxOTn13PDip
fVbcRsFd0dtIr00N61bCqr6Fa0aRwy424gh6bVJTNmk2zoaH7r025dZRhw==
-----END CERTIFICATE-----
GOOD_SSL_CERT
end
# Signed by the agent CA, not the master CA (Rogue)
def master_issued_by_agent_ca
<<-BAD_SSL_CERT
-----BEGIN CERTIFICATE-----
MIICZjCCAhCgAwIBAgIBBDANBgkqhkiG9w0BAQUFADB9MSMwIQYDVQQDExpJbnRl
cm1lZGlhdGUgQ0EgKGFnZW50LWNhKTEfMB0GCSqGSIb3DQEJARYQdGVzdEBleGFt
cGxlLm9yZzEZMBcGA1UEChMQRXhhbXBsZSBPcmcsIExMQzEaMBgGA1UECxMRU2Vy
dmVyIE9wZXJhdGlvbnMwHhcNMTMwMzMwMDU1MDQ4WhcNMzMwMzI1MDU1MDQ4WjAe
MRwwGgYDVQQDDBNtYXN0ZXIxLmV4YW1wbGUub3JnMFwwDQYJKoZIhvcNAQEBBQAD
SwAwSAJBAPnCDnryLLXWepGLqsdBWlytfeakE/yijM8GlE/yT0SbpJInIhJR1N1A
0RskriHrxTU5qQEhd0RIja7K5o4NYksCAwEAAaOB2TCB1jBbBgNVHSMEVDBSoU2k
SzBJMRAwDgYDVQQDDAdSb290IENBMRowGAYDVQQLDBFTZXJ2ZXIgT3BlcmF0aW9u
czEZMBcGA1UECgwQRXhhbXBsZSBPcmcsIExMQ4IBATAMBgNVHRMBAf8EAjAAMAsG
A1UdDwQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwPQYDVR0R
BDYwNIITbWFzdGVyMS5leGFtcGxlLm9yZ4IHbWFzdGVyMYIGcHVwcGV0ggxwdXBw
ZXRtYXN0ZXIwDQYJKoZIhvcNAQEFBQADQQA841IzHLlnn4RIJ0/BOZ/16iWC1dNr
jV9bELC5OxeMNSsVXbFNeTHwbHEYjDg5dQ6eUkxPdBSMWBeQwe2Mw+xG
-----END CERTIFICATE-----
BAD_SSL_CERT
end
def cert_chain
[ master_issued_by_master_ca, master_ca, root_ca ].map do |pem|
OpenSSL::X509::Certificate.new(pem)
end
end
def cert_chain_agent_ca
[ master_issued_by_agent_ca, agent_ca, root_ca ].map do |pem|
OpenSSL::X509::Certificate.new(pem)
end
end
def cert_chain_in_callback_order
cert_chain.reverse
end
let :authz_error_prefix do
"The server presented a SSL certificate chain which does not include a CA listed in the ssl_client_ca_auth file. "
end
let :expected_authz_error_msg do
authz_ca_certs = ssl_configuration.ca_auth_certificates
msg = authz_error_prefix
msg << "Authorized Issuers: #{authz_ca_certs.collect {|c| c.subject}.join(', ')} "
msg << "Peer Chain: #{cert_chain.collect {|c| c.subject}.join(' => ')}"
msg
end
let :root_ca_cert do
OpenSSL::X509::Certificate.new(root_ca)
end
let :master_ca_cert do
OpenSSL::X509::Certificate.new(master_ca)
end
let :agent_ca_cert do
OpenSSL::X509::Certificate.new(agent_ca)
end
end
diff --git a/spec/unit/status_spec.rb b/spec/unit/status_spec.rb
index 30c0b2892..5a6ad952d 100755
--- a/spec/unit/status_spec.rb
+++ b/spec/unit/status_spec.rb
@@ -1,45 +1,45 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'matchers/json'
describe Puppet::Status do
include JSONMatchers
it "should implement find" do
- Puppet::Status.indirection.find( :default ).should be_is_a(Puppet::Status)
- Puppet::Status.indirection.find( :default ).status["is_alive"].should == true
+ expect(Puppet::Status.indirection.find( :default )).to be_is_a(Puppet::Status)
+ expect(Puppet::Status.indirection.find( :default ).status["is_alive"]).to eq(true)
end
it "should default to is_alive is true" do
- Puppet::Status.new.status["is_alive"].should == true
+ expect(Puppet::Status.new.status["is_alive"]).to eq(true)
end
it "should return a pson hash" do
- Puppet::Status.new.status.to_pson.should == '{"is_alive":true}'
+ expect(Puppet::Status.new.status.to_pson).to eq('{"is_alive":true}')
end
it "should render to a pson hash" do
- PSON::pretty_generate(Puppet::Status.new).should =~ /"is_alive":\s*true/
+ expect(PSON::pretty_generate(Puppet::Status.new)).to match(/"is_alive":\s*true/)
end
it "should accept a hash from pson" do
status = Puppet::Status.new( { "is_alive" => false } )
- status.status.should == { "is_alive" => false }
+ expect(status.status).to eq({ "is_alive" => false })
end
it "should have a name" do
Puppet::Status.new.name
end
it "should allow a name to be set" do
Puppet::Status.new.name = "status"
end
it "serializes to PSON that conforms to the status schema" do
status = Puppet::Status.new
status.version = Puppet.version
expect(status.render('pson')).to validate_against('api/schemas/status.json')
end
end
diff --git a/spec/unit/transaction/additional_resource_generator_spec.rb b/spec/unit/transaction/additional_resource_generator_spec.rb
index 27dc3cbeb..f965bf759 100644
--- a/spec/unit/transaction/additional_resource_generator_spec.rb
+++ b/spec/unit/transaction/additional_resource_generator_spec.rb
@@ -1,411 +1,411 @@
require 'spec_helper'
require 'puppet/transaction'
require 'puppet_spec/compiler'
require 'matchers/relationship_graph_matchers'
require 'matchers/include_in_order'
require 'matchers/resource'
describe Puppet::Transaction::AdditionalResourceGenerator do
include PuppetSpec::Compiler
include PuppetSpec::Files
include RelationshipGraphMatchers
include Matchers::Resource
let(:prioritizer) { Puppet::Graph::SequentialPrioritizer.new }
def find_vertex(graph, type, title)
graph.vertices.find {|v| v.type == type and v.title == title}
end
Puppet::Type.newtype(:generator) do
include PuppetSpec::Compiler
newparam(:name) do
isnamevar
end
newparam(:kind) do
defaultto :eval_generate
newvalues(:eval_generate, :generate)
end
newparam(:code)
def respond_to?(method_name)
method_name == self[:kind] || super
end
def eval_generate
eval_code
end
def generate
eval_code
end
def eval_code
if self[:code]
compile_to_ral(self[:code]).resources.select { |r| r.ref =~ /Notify/ }
else
[]
end
end
end
context "when applying eval_generate" do
it "should add the generated resources to the catalog" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
eval_generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to have_resource('Notify[hello]')
end
it "should add a sentinel whit for the resource" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
- find_vertex(graph, :whit, "completed_thing").must be_a(Puppet::Type.type(:whit))
+ expect(find_vertex(graph, :whit, "completed_thing")).to be_a(Puppet::Type.type(:whit))
end
it "should replace dependencies on the resource with dependencies on the sentinel" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
notify { last: require => Generator['thing'] }
MANIFEST
expect(graph).to enforce_order_with_edge(
'Whit[completed_thing]', 'Notify[last]')
end
it "should add an edge from the nearest ancestor to the generated resource" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[hello]')
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[goodbye]')
end
it "should add an edge from each generated resource to the sentinel" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Notify[hello]', 'Whit[completed_thing]')
expect(graph).to enforce_order_with_edge(
'Notify[goodbye]', 'Whit[completed_thing]')
end
it "should add an edge from the resource to the sentinel" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Whit[completed_thing]')
end
it "should contain the generated resources in the same container as the generator" do
catalog = compile_to_ral(<<-MANIFEST)
class container {
generator { thing:
code => 'notify { hello: }'
}
}
include container
MANIFEST
eval_generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to contain_resources_equally('Generator[thing]', 'Notify[hello]')
end
it "should return false if an error occurred when generating resources" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'fail("not a good generation")'
}
MANIFEST
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph_for(catalog), prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(false)
end
it "should return true if resources were generated" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph_for(catalog), prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(true)
end
it "should not add a sentinel if no resources are generated" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing: }
MANIFEST
relationship_graph = relationship_graph_for(catalog)
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph, prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(false)
expect(find_vertex(relationship_graph, :whit, "completed_thing")).to be_nil
end
it "orders generated resources with the generator" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: }'
}
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[after]"))
end
it "orders the generator in manifest order with dependencies" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]",
"Generator[thing]",
"Notify[hello]",
"Notify[goodbye]",
"Notify[third]",
"Notify[after]"))
end
it "duplicate generated resources are made dependent on the generator" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
notify { hello: }
generator { thing:
code => 'notify { before: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[hello]", "Generator[thing]", "Notify[before]", "Notify[third]", "Notify[after]"))
end
it "preserves dependencies on duplicate generated resources" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: } notify { before: }',
require => 'Notify[before]'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[third]", "Notify[after]"))
end
def relationships_after_eval_generating(manifest, resource_to_generate)
catalog = compile_to_ral(manifest)
relationship_graph = relationship_graph_for(catalog)
eval_generate_resources_in(catalog, relationship_graph, resource_to_generate)
relationship_graph
end
def eval_generate_resources_in(catalog, relationship_graph, resource_to_generate)
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph, prioritizer)
generator.eval_generate(catalog.resource(resource_to_generate))
end
end
context "when applying generate" do
it "should add the generated resources to the catalog" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
MANIFEST
generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to have_resource('Notify[hello]')
end
it "should contain the generated resources in the same container as the generator" do
catalog = compile_to_ral(<<-MANIFEST)
class container {
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
}
include container
MANIFEST
generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to contain_resources_equally('Generator[thing]', 'Notify[hello]')
end
it "should add an edge from the nearest ancestor to the generated resource" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
kind => generate,
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[hello]')
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[goodbye]')
end
it "orders generated resources with the generator" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[after]"))
end
it "duplicate generated resources are made dependent on the generator" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
notify { hello: }
generator { thing:
kind => generate,
code => 'notify { before: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[hello]", "Generator[thing]", "Notify[before]", "Notify[third]", "Notify[after]"))
end
it "preserves dependencies on duplicate generated resources" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: } notify { before: }',
require => 'Notify[before]'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[third]", "Notify[after]"))
end
it "orders the generator in manifest order with dependencies" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: } notify { goodbye: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]",
"Generator[thing]",
"Notify[hello]",
"Notify[goodbye]",
"Notify[third]",
"Notify[after]"))
end
def relationships_after_generating(manifest, resource_to_generate)
catalog = compile_to_ral(manifest)
relationship_graph = relationship_graph_for(catalog)
generate_resources_in(catalog, relationship_graph, resource_to_generate)
relationship_graph
end
def generate_resources_in(catalog, relationship_graph, resource_to_generate)
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph, prioritizer)
generator.generate_additional_resources(catalog.resource(resource_to_generate))
end
end
def relationship_graph_for(catalog)
relationship_graph = Puppet::Graph::RelationshipGraph.new(prioritizer)
relationship_graph.populate_from(catalog)
relationship_graph
end
def order_resources_traversed_in(relationships)
order_seen = []
relationships.traverse { |resource| order_seen << resource.ref }
order_seen
end
RSpec::Matchers.define :contain_resources_equally do |*resource_refs|
match do |catalog|
@containers = resource_refs.collect do |resource_ref|
catalog.container_of(catalog.resource(resource_ref)).ref
end
@containers.all? { |resource_ref| resource_ref == @containers[0] }
end
- def failure_message_for_should
+ def failure_message
"expected #{@expected.join(', ')} to all be contained in the same resource but the containment was #{@expected.zip(@containers).collect { |(res, container)| res + ' => ' + container }.join(', ')}"
end
end
end
diff --git a/spec/unit/transaction/event_manager_spec.rb b/spec/unit/transaction/event_manager_spec.rb
index 5d53be3fa..76ba52c31 100755
--- a/spec/unit/transaction/event_manager_spec.rb
+++ b/spec/unit/transaction/event_manager_spec.rb
@@ -1,340 +1,340 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/transaction/event_manager'
describe Puppet::Transaction::EventManager do
include PuppetSpec::Files
describe "at initialization" do
it "should require a transaction" do
- Puppet::Transaction::EventManager.new("trans").transaction.should == "trans"
+ expect(Puppet::Transaction::EventManager.new("trans").transaction).to eq("trans")
end
end
it "should delegate its relationship graph to the transaction" do
transaction = stub 'transaction'
manager = Puppet::Transaction::EventManager.new(transaction)
transaction.expects(:relationship_graph).returns "mygraph"
- manager.relationship_graph.should == "mygraph"
+ expect(manager.relationship_graph).to eq("mygraph")
end
describe "when queueing events" do
before do
@manager = Puppet::Transaction::EventManager.new(@transaction)
@resource = Puppet::Type.type(:file).new :path => make_absolute("/my/file")
@graph = stub 'graph', :matching_edges => [], :resource => @resource
@manager.stubs(:relationship_graph).returns @graph
@event = Puppet::Transaction::Event.new(:name => :foo, :resource => @resource)
end
it "should store all of the events in its event list" do
@event2 = Puppet::Transaction::Event.new(:name => :bar, :resource => @resource)
@manager.queue_events(@resource, [@event, @event2])
- @manager.events.should include(@event)
- @manager.events.should include(@event2)
+ expect(@manager.events).to include(@event)
+ expect(@manager.events).to include(@event2)
end
it "should queue events for the target and callback of any matching edges" do
edge1 = stub("edge1", :callback => :c1, :source => stub("s1"), :target => stub("t1", :c1 => nil))
edge2 = stub("edge2", :callback => :c2, :source => stub("s2"), :target => stub("t2", :c2 => nil))
@graph.expects(:matching_edges).with { |event, resource| event == @event }.returns [edge1, edge2]
@manager.expects(:queue_events_for_resource).with(@resource, edge1.target, edge1.callback, [@event])
@manager.expects(:queue_events_for_resource).with(@resource, edge2.target, edge2.callback, [@event])
@manager.queue_events(@resource, [@event])
end
it "should queue events for the changed resource if the resource is self-refreshing and not being deleted" do
@graph.stubs(:matching_edges).returns []
@resource.expects(:self_refresh?).returns true
@resource.expects(:deleting?).returns false
@manager.expects(:queue_events_for_resource).with(@resource, @resource, :refresh, [@event])
@manager.queue_events(@resource, [@event])
end
it "should not queue events for the changed resource if the resource is not self-refreshing" do
@graph.stubs(:matching_edges).returns []
@resource.expects(:self_refresh?).returns false
@resource.stubs(:deleting?).returns false
@manager.expects(:queue_events_for_resource).never
@manager.queue_events(@resource, [@event])
end
it "should not queue events for the changed resource if the resource is being deleted" do
@graph.stubs(:matching_edges).returns []
@resource.expects(:self_refresh?).returns true
@resource.expects(:deleting?).returns true
@manager.expects(:queue_events_for_resource).never
@manager.queue_events(@resource, [@event])
end
it "should ignore edges that don't have a callback" do
edge1 = stub("edge1", :callback => :nil, :source => stub("s1"), :target => stub("t1", :c1 => nil))
@graph.expects(:matching_edges).returns [edge1]
@manager.expects(:queue_events_for_resource).never
@manager.queue_events(@resource, [@event])
end
it "should ignore targets that don't respond to the callback" do
edge1 = stub("edge1", :callback => :c1, :source => stub("s1"), :target => stub("t1"))
@graph.expects(:matching_edges).returns [edge1]
@manager.expects(:queue_events_for_resource).never
@manager.queue_events(@resource, [@event])
end
it "should dequeue events for the changed resource if an event with invalidate_refreshes is processed" do
@event2 = Puppet::Transaction::Event.new(:name => :foo, :resource => @resource, :invalidate_refreshes => true)
@graph.stubs(:matching_edges).returns []
@manager.expects(:dequeue_events_for_resource).with(@resource, :refresh)
@manager.queue_events(@resource, [@event, @event2])
end
end
describe "when queueing events for a resource" do
before do
@transaction = stub 'transaction'
@manager = Puppet::Transaction::EventManager.new(@transaction)
end
it "should do nothing if no events are queued" do
@manager.queued_events(stub("target")) { |callback, events| raise "should never reach this" }
end
it "should yield the callback and events for each callback" do
target = stub("target")
2.times do |i|
@manager.queue_events_for_resource(stub("source", :info => nil), target, "callback#{i}", ["event#{i}"])
end
@manager.queued_events(target) { |callback, events| }
end
it "should use the source to log that it's scheduling a refresh of the target" do
target = stub("target")
source = stub 'source'
source.expects(:info)
@manager.queue_events_for_resource(source, target, "callback", ["event"])
@manager.queued_events(target) { |callback, events| }
end
end
describe "when processing events for a given resource" do
before do
@transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil)
@manager = Puppet::Transaction::EventManager.new(@transaction)
@manager.stubs(:queue_events)
@resource = Puppet::Type.type(:file).new :path => make_absolute("/my/file")
@event = Puppet::Transaction::Event.new(:name => :event, :resource => @resource)
end
it "should call the required callback once for each set of associated events" do
@manager.expects(:queued_events).with(@resource).multiple_yields([:callback1, [@event]], [:callback2, [@event]])
@resource.expects(:callback1)
@resource.expects(:callback2)
@manager.process_events(@resource)
end
it "should set the 'restarted' state on the resource status" do
@manager.expects(:queued_events).with(@resource).yields(:callback1, [@event])
@resource.stubs(:callback1)
@manager.process_events(@resource)
- @transaction.resource_status(@resource).should be_restarted
+ expect(@transaction.resource_status(@resource)).to be_restarted
end
it "should queue a 'restarted' event generated by the resource" do
@manager.expects(:queued_events).with(@resource).yields(:callback1, [@event])
@resource.stubs(:callback1)
@resource.expects(:event).with(:name => :restarted, :status => "success").returns "myevent"
@manager.expects(:queue_events).with(@resource, ["myevent"])
@manager.process_events(@resource)
end
it "should log that it restarted" do
@manager.expects(:queued_events).with(@resource).yields(:callback1, [@event])
@resource.stubs(:callback1)
@resource.expects(:notice).with { |msg| msg.include?("Triggered 'callback1'") }
@manager.process_events(@resource)
end
describe "and the events include a noop event and at least one non-noop event" do
before do
@event.stubs(:status).returns "noop"
@event2 = Puppet::Transaction::Event.new(:name => :event, :resource => @resource)
@event2.status = "success"
@manager.expects(:queued_events).with(@resource).yields(:callback1, [@event, @event2])
end
it "should call the callback" do
@resource.expects(:callback1)
@manager.process_events(@resource)
end
end
describe "and the events are all noop events" do
before do
@event.stubs(:status).returns "noop"
@resource.stubs(:event).returns(Puppet::Transaction::Event.new)
@manager.expects(:queued_events).with(@resource).yields(:callback1, [@event])
end
it "should log" do
@resource.expects(:notice).with { |msg| msg.include?("Would have triggered 'callback1'") }
@manager.process_events(@resource)
end
it "should not call the callback" do
@resource.expects(:callback1).never
@manager.process_events(@resource)
end
it "should queue a new noop event generated from the resource" do
event = Puppet::Transaction::Event.new
@resource.expects(:event).with(:status => "noop", :name => :noop_restart).returns event
@manager.expects(:queue_events).with(@resource, [event])
@manager.process_events(@resource)
end
end
describe "and the resource has noop set to true" do
before do
@event.stubs(:status).returns "success"
@resource.stubs(:event).returns(Puppet::Transaction::Event.new)
@resource.stubs(:noop?).returns(true)
@manager.expects(:queued_events).with(@resource).yields(:callback1, [@event])
end
it "should log" do
@resource.expects(:notice).with { |msg| msg.include?("Would have triggered 'callback1'") }
@manager.process_events(@resource)
end
it "should not call the callback" do
@resource.expects(:callback1).never
@manager.process_events(@resource)
end
it "should queue a new noop event generated from the resource" do
event = Puppet::Transaction::Event.new
@resource.expects(:event).with(:status => "noop", :name => :noop_restart).returns event
@manager.expects(:queue_events).with(@resource, [event])
@manager.process_events(@resource)
end
end
describe "and the callback fails" do
before do
@resource.expects(:callback1).raises "a failure"
@resource.stubs(:err)
@manager.expects(:queued_events).yields(:callback1, [@event])
end
it "should log but not fail" do
@resource.expects(:err)
- lambda { @manager.process_events(@resource) }.should_not raise_error
+ expect { @manager.process_events(@resource) }.not_to raise_error
end
it "should set the 'failed_restarts' state on the resource status" do
@manager.process_events(@resource)
- @transaction.resource_status(@resource).should be_failed_to_restart
+ expect(@transaction.resource_status(@resource)).to be_failed_to_restart
end
it "should not queue a 'restarted' event" do
@manager.expects(:queue_events).never
@manager.process_events(@resource)
end
it "should set the 'restarted' state on the resource status" do
@manager.process_events(@resource)
- @transaction.resource_status(@resource).should_not be_restarted
+ expect(@transaction.resource_status(@resource)).not_to be_restarted
end
end
end
describe "when queueing then processing events for a given resource" do
before do
@transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil)
@manager = Puppet::Transaction::EventManager.new(@transaction)
@resource = Puppet::Type.type(:file).new :path => make_absolute("/my/file")
@target = Puppet::Type.type(:file).new :path => make_absolute("/your/file")
@graph = stub 'graph'
@graph.stubs(:matching_edges).returns []
@graph.stubs(:matching_edges).with(anything, @resource).returns [stub('edge', :target => @target, :callback => :refresh)]
@manager.stubs(:relationship_graph).returns @graph
@event = Puppet::Transaction::Event.new(:name => :notify, :resource => @target)
@event2 = Puppet::Transaction::Event.new(:name => :service_start, :resource => @target, :invalidate_refreshes => true)
end
it "should succeed when there's no invalidated event" do
@manager.queue_events(@target, [@event2])
end
describe "and the events were dequeued/invalidated" do
before do
@resource.expects(:info).with { |msg| msg.include?("Scheduling refresh") }
@target.expects(:info).with { |msg| msg.include?("Unscheduling") }
end
it "should not run an event or log" do
@target.expects(:notice).with { |msg| msg.include?("Would have triggered 'refresh'") }.never
@target.expects(:refresh).never
@manager.queue_events(@resource, [@event])
@manager.queue_events(@target, [@event2])
@manager.process_events(@resource)
@manager.process_events(@target)
end
end
end
end
diff --git a/spec/unit/transaction/event_spec.rb b/spec/unit/transaction/event_spec.rb
index 4781cbca1..536e5a5a5 100755
--- a/spec/unit/transaction/event_spec.rb
+++ b/spec/unit/transaction/event_spec.rb
@@ -1,192 +1,192 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/transaction/event'
class TestResource
def to_s
"Foo[bar]"
end
def [](v)
nil
end
end
describe Puppet::Transaction::Event do
include PuppetSpec::Files
it "should support resource" do
event = Puppet::Transaction::Event.new
event.resource = TestResource.new
- event.resource.should == "Foo[bar]"
+ expect(event.resource).to eq("Foo[bar]")
end
it "should always convert the property to a string" do
- Puppet::Transaction::Event.new(:property => :foo).property.should == "foo"
+ expect(Puppet::Transaction::Event.new(:property => :foo).property).to eq("foo")
end
it "should always convert the resource to a string" do
- Puppet::Transaction::Event.new(:resource => TestResource.new).resource.should == "Foo[bar]"
+ expect(Puppet::Transaction::Event.new(:resource => TestResource.new).resource).to eq("Foo[bar]")
end
it "should produce the message when converted to a string" do
event = Puppet::Transaction::Event.new
event.expects(:message).returns "my message"
- event.to_s.should == "my message"
+ expect(event.to_s).to eq("my message")
end
it "should support 'status'" do
event = Puppet::Transaction::Event.new
event.status = "success"
- event.status.should == "success"
+ expect(event.status).to eq("success")
end
it "should fail if the status is not to 'audit', 'noop', 'success', or 'failure" do
event = Puppet::Transaction::Event.new
- lambda { event.status = "foo" }.should raise_error(ArgumentError)
+ expect { event.status = "foo" }.to raise_error(ArgumentError)
end
it "should support tags" do
- Puppet::Transaction::Event.ancestors.should include(Puppet::Util::Tagging)
+ expect(Puppet::Transaction::Event.ancestors).to include(Puppet::Util::Tagging)
end
it "should create a timestamp at its creation time" do
- Puppet::Transaction::Event.new.time.should be_instance_of(Time)
+ expect(Puppet::Transaction::Event.new.time).to be_instance_of(Time)
end
describe "audit property" do
it "should default to false" do
- Puppet::Transaction::Event.new.audited.should == false
+ expect(Puppet::Transaction::Event.new.audited).to eq(false)
end
end
describe "when sending logs" do
before do
Puppet::Util::Log.stubs(:new)
end
it "should set the level to the resources's log level if the event status is 'success' and a resource is available" do
resource = stub 'resource'
resource.expects(:[]).with(:loglevel).returns :myloglevel
Puppet::Util::Log.expects(:create).with { |args| args[:level] == :myloglevel }
Puppet::Transaction::Event.new(:status => "success", :resource => resource).send_log
end
it "should set the level to 'notice' if the event status is 'success' and no resource is available" do
Puppet::Util::Log.expects(:new).with { |args| args[:level] == :notice }
Puppet::Transaction::Event.new(:status => "success").send_log
end
it "should set the level to 'notice' if the event status is 'noop'" do
Puppet::Util::Log.expects(:new).with { |args| args[:level] == :notice }
Puppet::Transaction::Event.new(:status => "noop").send_log
end
it "should set the level to 'err' if the event status is 'failure'" do
Puppet::Util::Log.expects(:new).with { |args| args[:level] == :err }
Puppet::Transaction::Event.new(:status => "failure").send_log
end
it "should set the 'message' to the event log" do
Puppet::Util::Log.expects(:new).with { |args| args[:message] == "my message" }
Puppet::Transaction::Event.new(:message => "my message").send_log
end
it "should set the tags to the event tags" do
- Puppet::Util::Log.expects(:new).with { |args| args[:tags].to_a.should =~ %w{one two} }
+ Puppet::Util::Log.expects(:new).with { |args| expect(args[:tags].to_a).to match_array(%w{one two}) }
Puppet::Transaction::Event.new(:tags => %w{one two}).send_log
end
[:file, :line].each do |attr|
it "should pass the #{attr}" do
Puppet::Util::Log.expects(:new).with { |args| args[attr] == "my val" }
Puppet::Transaction::Event.new(attr => "my val").send_log
end
end
it "should use the source description as the source if one is set" do
Puppet::Util::Log.expects(:new).with { |args| args[:source] == "/my/param" }
Puppet::Transaction::Event.new(:source_description => "/my/param", :resource => TestResource.new, :property => "foo").send_log
end
it "should use the property as the source if one is available and no source description is set" do
Puppet::Util::Log.expects(:new).with { |args| args[:source] == "foo" }
Puppet::Transaction::Event.new(:resource => TestResource.new, :property => "foo").send_log
end
it "should use the property as the source if one is available and no property or source description is set" do
Puppet::Util::Log.expects(:new).with { |args| args[:source] == "Foo[bar]" }
Puppet::Transaction::Event.new(:resource => TestResource.new).send_log
end
end
describe "When converting to YAML" do
it "should include only documented attributes" do
resource = Puppet::Type.type(:file).new(:title => make_absolute("/tmp/foo"))
event = Puppet::Transaction::Event.new(:source_description => "/my/param", :resource => resource,
:file => "/foo.rb", :line => 27, :tags => %w{one two},
:desired_value => 7, :historical_value => 'Brazil',
:message => "Help I'm trapped in a spec test",
:name => :mode_changed, :previous_value => 6, :property => :mode,
:status => 'success')
- event.to_yaml_properties.should =~ Puppet::Transaction::Event::YAML_ATTRIBUTES
+ expect(event.to_yaml_properties).to match_array(Puppet::Transaction::Event::YAML_ATTRIBUTES)
end
end
it "should round trip through pson" do
resource = Puppet::Type.type(:file).new(:title => make_absolute("/tmp/foo"))
event = Puppet::Transaction::Event.new(
:source_description => "/my/param",
:resource => resource,
:file => "/foo.rb",
:line => 27,
:tags => %w{one two},
:desired_value => 7,
:historical_value => 'Brazil',
:message => "Help I'm trapped in a spec test",
:name => :mode_changed,
:previous_value => 6,
:property => :mode,
:status => 'success')
tripped = Puppet::Transaction::Event.from_data_hash(PSON.parse(event.to_pson))
- tripped.audited.should == event.audited
- tripped.property.should == event.property
- tripped.previous_value.should == event.previous_value
- tripped.desired_value.should == event.desired_value
- tripped.historical_value.should == event.historical_value
- tripped.message.should == event.message
- tripped.name.should == event.name
- tripped.status.should == event.status
- tripped.time.should == event.time
+ expect(tripped.audited).to eq(event.audited)
+ expect(tripped.property).to eq(event.property)
+ expect(tripped.previous_value).to eq(event.previous_value)
+ expect(tripped.desired_value).to eq(event.desired_value)
+ expect(tripped.historical_value).to eq(event.historical_value)
+ expect(tripped.message).to eq(event.message)
+ expect(tripped.name).to eq(event.name)
+ expect(tripped.status).to eq(event.status)
+ expect(tripped.time).to eq(event.time)
end
it "should round trip an event for an inspect report through pson" do
resource = Puppet::Type.type(:file).new(:title => make_absolute("/tmp/foo"))
event = Puppet::Transaction::Event.new(
:audited => true,
:source_description => "/my/param",
:resource => resource,
:file => "/foo.rb",
:line => 27,
:tags => %w{one two},
:message => "Help I'm trapped in a spec test",
:previous_value => 6,
:property => :mode,
:status => 'success')
tripped = Puppet::Transaction::Event.from_data_hash(PSON.parse(event.to_pson))
- tripped.desired_value.should be_nil
- tripped.historical_value.should be_nil
- tripped.name.should be_nil
+ expect(tripped.desired_value).to be_nil
+ expect(tripped.historical_value).to be_nil
+ expect(tripped.name).to be_nil
- tripped.audited.should == event.audited
- tripped.property.should == event.property
- tripped.previous_value.should == event.previous_value
- tripped.message.should == event.message
- tripped.status.should == event.status
- tripped.time.should == event.time
+ expect(tripped.audited).to eq(event.audited)
+ expect(tripped.property).to eq(event.property)
+ expect(tripped.previous_value).to eq(event.previous_value)
+ expect(tripped.message).to eq(event.message)
+ expect(tripped.status).to eq(event.status)
+ expect(tripped.time).to eq(event.time)
end
end
diff --git a/spec/unit/transaction/report_spec.rb b/spec/unit/transaction/report_spec.rb
index a349374e6..1da1015ad 100755
--- a/spec/unit/transaction/report_spec.rb
+++ b/spec/unit/transaction/report_spec.rb
@@ -1,483 +1,483 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet'
require 'puppet/transaction/report'
require 'matchers/json'
describe Puppet::Transaction::Report do
include JSONMatchers
include PuppetSpec::Files
before do
Puppet::Util::Storage.stubs(:store)
end
it "should set its host name to the node_name_value" do
Puppet[:node_name_value] = 'mynode'
- Puppet::Transaction::Report.new("apply").host.should == "mynode"
+ expect(Puppet::Transaction::Report.new("apply").host).to eq("mynode")
end
it "should return its host name as its name" do
r = Puppet::Transaction::Report.new("apply")
- r.name.should == r.host
+ expect(r.name).to eq(r.host)
end
it "should create an initialization timestamp" do
Time.expects(:now).returns "mytime"
- Puppet::Transaction::Report.new("apply").time.should == "mytime"
+ expect(Puppet::Transaction::Report.new("apply").time).to eq("mytime")
end
it "should take a 'kind' as an argument" do
- Puppet::Transaction::Report.new("inspect").kind.should == "inspect"
+ expect(Puppet::Transaction::Report.new("inspect").kind).to eq("inspect")
end
it "should take a 'configuration_version' as an argument" do
- Puppet::Transaction::Report.new("inspect", "some configuration version", "some environment").configuration_version.should == "some configuration version"
+ expect(Puppet::Transaction::Report.new("inspect", "some configuration version", "some environment").configuration_version).to eq("some configuration version")
end
it "should take a 'transaction_uuid' as an argument" do
- Puppet::Transaction::Report.new("inspect", "some configuration version", "some environment", "some transaction uuid").transaction_uuid.should == "some transaction uuid"
+ expect(Puppet::Transaction::Report.new("inspect", "some configuration version", "some environment", "some transaction uuid").transaction_uuid).to eq("some transaction uuid")
end
it "should be able to set configuration_version" do
report = Puppet::Transaction::Report.new("inspect")
report.configuration_version = "some version"
- report.configuration_version.should == "some version"
+ expect(report.configuration_version).to eq("some version")
end
it "should be able to set transaction_uuid" do
report = Puppet::Transaction::Report.new("inspect")
report.transaction_uuid = "some transaction uuid"
- report.transaction_uuid.should == "some transaction uuid"
+ expect(report.transaction_uuid).to eq("some transaction uuid")
end
it "should take 'environment' as an argument" do
- Puppet::Transaction::Report.new("inspect", "some configuration version", "some environment").environment.should == "some environment"
+ expect(Puppet::Transaction::Report.new("inspect", "some configuration version", "some environment").environment).to eq("some environment")
end
it "should be able to set environment" do
report = Puppet::Transaction::Report.new("inspect")
report.environment = "some environment"
- report.environment.should == "some environment"
+ expect(report.environment).to eq("some environment")
end
it "should not include whits" do
Puppet::FileBucket::File.indirection.stubs(:save)
filename = tmpfile('whit_test')
file = Puppet::Type.type(:file).new(:path => filename)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource(file)
report = Puppet::Transaction::Report.new("apply")
catalog.apply(:report => report)
report.finalize_report
- report.resource_statuses.values.any? {|res| res.resource_type =~ /whit/i}.should be_false
- report.metrics['time'].values.any? {|metric| metric.first =~ /whit/i}.should be_false
+ expect(report.resource_statuses.values.any? {|res| res.resource_type =~ /whit/i}).to be_falsey
+ expect(report.metrics['time'].values.any? {|metric| metric.first =~ /whit/i}).to be_falsey
end
describe "when accepting logs" do
before do
@report = Puppet::Transaction::Report.new("apply")
end
it "should add new logs to the log list" do
@report << "log"
- @report.logs[-1].should == "log"
+ expect(@report.logs[-1]).to eq("log")
end
it "should return self" do
r = @report << "log"
- r.should equal(@report)
+ expect(r).to equal(@report)
end
end
describe "#as_logging_destination" do
it "makes the report collect logs during the block " do
log_string = 'Hello test report!'
report = Puppet::Transaction::Report.new('test')
report.as_logging_destination do
Puppet.err(log_string)
end
expect(report.logs.collect(&:message)).to include(log_string)
end
end
describe "when accepting resource statuses" do
before do
@report = Puppet::Transaction::Report.new("apply")
end
it "should add each status to its status list" do
status = stub 'status', :resource => "foo"
@report.add_resource_status status
- @report.resource_statuses["foo"].should equal(status)
+ expect(@report.resource_statuses["foo"]).to equal(status)
end
end
describe "when using the indirector" do
it "should redirect :save to the indirection" do
Facter.stubs(:value).returns("eh")
@indirection = stub 'indirection', :name => :report
Puppet::Transaction::Report.stubs(:indirection).returns(@indirection)
report = Puppet::Transaction::Report.new("apply")
@indirection.expects(:save)
Puppet::Transaction::Report.indirection.save(report)
end
it "should default to the 'processor' terminus" do
- Puppet::Transaction::Report.indirection.terminus_class.should == :processor
+ expect(Puppet::Transaction::Report.indirection.terminus_class).to eq(:processor)
end
it "should delegate its name attribute to its host method" do
report = Puppet::Transaction::Report.new("apply")
report.expects(:host).returns "me"
- report.name.should == "me"
+ expect(report.name).to eq("me")
end
end
describe "when computing exit status" do
it "should produce 2 if changes are present" do
report = Puppet::Transaction::Report.new("apply")
report.add_metric("changes", {"total" => 1})
report.add_metric("resources", {"failed" => 0})
- report.exit_status.should == 2
+ expect(report.exit_status).to eq(2)
end
it "should produce 4 if failures are present" do
report = Puppet::Transaction::Report.new("apply")
report.add_metric("changes", {"total" => 0})
report.add_metric("resources", {"failed" => 1})
- report.exit_status.should == 4
+ expect(report.exit_status).to eq(4)
end
it "should produce 4 if failures to restart are present" do
report = Puppet::Transaction::Report.new("apply")
report.add_metric("changes", {"total" => 0})
report.add_metric("resources", {"failed" => 0})
report.add_metric("resources", {"failed_to_restart" => 1})
- report.exit_status.should == 4
+ expect(report.exit_status).to eq(4)
end
it "should produce 6 if both changes and failures are present" do
report = Puppet::Transaction::Report.new("apply")
report.add_metric("changes", {"total" => 1})
report.add_metric("resources", {"failed" => 1})
- report.exit_status.should == 6
+ expect(report.exit_status).to eq(6)
end
end
describe "before finalizing the report" do
it "should have a status of 'failed'" do
report = Puppet::Transaction::Report.new("apply")
- report.status.should == 'failed'
+ expect(report.status).to eq('failed')
end
end
describe "when finalizing the report" do
before do
@report = Puppet::Transaction::Report.new("apply")
end
def metric(name, value)
if metric = @report.metrics[name.to_s]
metric[value]
else
nil
end
end
def add_statuses(count, type = :file)
count.times do |i|
status = Puppet::Resource::Status.new(Puppet::Type.type(type).new(:title => make_absolute("/my/path#{i}")))
yield status if block_given?
@report.add_resource_status status
end
end
[:time, :resources, :changes, :events].each do |type|
it "should add #{type} metrics" do
@report.finalize_report
- @report.metrics[type.to_s].should be_instance_of(Puppet::Transaction::Metric)
+ expect(@report.metrics[type.to_s]).to be_instance_of(Puppet::Transaction::Metric)
end
end
describe "for resources" do
it "should provide the total number of resources" do
add_statuses(3)
@report.finalize_report
- metric(:resources, "total").should == 3
+ expect(metric(:resources, "total")).to eq(3)
end
Puppet::Resource::Status::STATES.each do |state|
it "should provide the number of #{state} resources as determined by the status objects" do
add_statuses(3) { |status| status.send(state.to_s + "=", true) }
@report.finalize_report
- metric(:resources, state.to_s).should == 3
+ expect(metric(:resources, state.to_s)).to eq(3)
end
it "should provide 0 for states not in status" do
@report.finalize_report
- metric(:resources, state.to_s).should == 0
+ expect(metric(:resources, state.to_s)).to eq(0)
end
end
it "should mark the report as 'failed' if there are failing resources" do
add_statuses(1) { |status| status.failed = true }
@report.finalize_report
- @report.status.should == 'failed'
+ expect(@report.status).to eq('failed')
end
end
describe "for changes" do
it "should provide the number of changes from the resource statuses and mark the report as 'changed'" do
add_statuses(3) { |status| 3.times { status << Puppet::Transaction::Event.new(:status => 'success') } }
@report.finalize_report
- metric(:changes, "total").should == 9
- @report.status.should == 'changed'
+ expect(metric(:changes, "total")).to eq(9)
+ expect(@report.status).to eq('changed')
end
it "should provide a total even if there are no changes, and mark the report as 'unchanged'" do
@report.finalize_report
- metric(:changes, "total").should == 0
- @report.status.should == 'unchanged'
+ expect(metric(:changes, "total")).to eq(0)
+ expect(@report.status).to eq('unchanged')
end
end
describe "for times" do
it "should provide the total amount of time for each resource type" do
add_statuses(3, :file) do |status|
status.evaluation_time = 1
end
add_statuses(3, :exec) do |status|
status.evaluation_time = 2
end
add_statuses(3, :tidy) do |status|
status.evaluation_time = 3
end
@report.finalize_report
- metric(:time, "file").should == 3
- metric(:time, "exec").should == 6
- metric(:time, "tidy").should == 9
+ expect(metric(:time, "file")).to eq(3)
+ expect(metric(:time, "exec")).to eq(6)
+ expect(metric(:time, "tidy")).to eq(9)
end
it "should add any provided times from external sources" do
@report.add_times :foobar, 50
@report.finalize_report
- metric(:time, "foobar").should == 50
+ expect(metric(:time, "foobar")).to eq(50)
end
it "should have a total time" do
add_statuses(3, :file) do |status|
status.evaluation_time = 1.25
end
@report.add_times :config_retrieval, 0.5
@report.finalize_report
- metric(:time, "total").should == 4.25
+ expect(metric(:time, "total")).to eq(4.25)
end
end
describe "for events" do
it "should provide the total number of events" do
add_statuses(3) do |status|
3.times { |i| status.add_event(Puppet::Transaction::Event.new :status => 'success') }
end
@report.finalize_report
- metric(:events, "total").should == 9
+ expect(metric(:events, "total")).to eq(9)
end
it "should provide the total even if there are no events" do
@report.finalize_report
- metric(:events, "total").should == 0
+ expect(metric(:events, "total")).to eq(0)
end
Puppet::Transaction::Event::EVENT_STATUSES.each do |status_name|
it "should provide the number of #{status_name} events" do
add_statuses(3) do |status|
3.times do |i|
event = Puppet::Transaction::Event.new
event.status = status_name
status.add_event(event)
end
end
@report.finalize_report
- metric(:events, status_name).should == 9
+ expect(metric(:events, status_name)).to eq(9)
end
end
end
end
describe "when producing a summary" do
before do
resource = Puppet::Type.type(:notify).new(:name => "testing")
catalog = Puppet::Resource::Catalog.new
catalog.add_resource resource
catalog.version = 1234567
trans = catalog.apply
@report = trans.report
@report.finalize_report
end
%w{changes time resources events version}.each do |main|
it "should include the key #{main} in the raw summary hash" do
- @report.raw_summary.should be_key main
+ expect(@report.raw_summary).to be_key main
end
end
it "should include the last run time in the raw summary hash" do
Time.stubs(:now).returns(Time.utc(2010,11,10,12,0,24))
- @report.raw_summary["time"]["last_run"].should == 1289390424
+ expect(@report.raw_summary["time"]["last_run"]).to eq(1289390424)
end
it "should include all resource statuses" do
resources_report = @report.raw_summary["resources"]
Puppet::Resource::Status::STATES.each do |state|
- resources_report.should be_include(state.to_s)
+ expect(resources_report).to be_include(state.to_s)
end
end
%w{total failure success}.each do |r|
it "should include event #{r}" do
events_report = @report.raw_summary["events"]
- events_report.should be_include(r)
+ expect(events_report).to be_include(r)
end
end
it "should include config version" do
- @report.raw_summary["version"]["config"].should == 1234567
+ expect(@report.raw_summary["version"]["config"]).to eq(1234567)
end
it "should include puppet version" do
- @report.raw_summary["version"]["puppet"].should == Puppet.version
+ expect(@report.raw_summary["version"]["puppet"]).to eq(Puppet.version)
end
%w{Changes Total Resources Time Events}.each do |main|
it "should include information on #{main} in the textual summary" do
- @report.summary.should be_include(main)
+ expect(@report.summary).to be_include(main)
end
end
end
describe "when outputting yaml" do
it "should not include @external_times" do
report = Puppet::Transaction::Report.new('apply')
report.add_times('config_retrieval', 1.0)
- report.to_yaml_properties.should_not include('@external_times')
+ expect(report.to_yaml_properties).not_to include('@external_times')
end
end
it "defaults to serializing to pson" do
expect(Puppet::Transaction::Report.default_format).to eq(:pson)
end
it "supports both yaml and pson" do
expect(Puppet::Transaction::Report.supported_formats).to eq([:pson, :yaml])
end
it "can make a round trip through pson" do
report = generate_report
tripped = Puppet::Transaction::Report.convert_from(:pson, report.render)
expect_equivalent_reports(tripped, report)
end
it "generates pson which validates against the report schema" do
report = generate_report
expect(report.render).to validate_against('api/schemas/report.json')
end
it "generates pson for error report which validates against the report schema" do
error_report = generate_report_with_error
expect(error_report.render).to validate_against('api/schemas/report.json')
end
def expect_equivalent_reports(tripped, report)
- tripped.host.should == report.host
- tripped.time.to_i.should == report.time.to_i
- tripped.configuration_version.should == report.configuration_version
- tripped.transaction_uuid.should == report.transaction_uuid
- tripped.report_format.should == report.report_format
- tripped.puppet_version.should == report.puppet_version
- tripped.kind.should == report.kind
- tripped.status.should == report.status
- tripped.environment.should == report.environment
-
- logs_as_strings(tripped).should == logs_as_strings(report)
- metrics_as_hashes(tripped).should == metrics_as_hashes(report)
+ expect(tripped.host).to eq(report.host)
+ expect(tripped.time.to_i).to eq(report.time.to_i)
+ expect(tripped.configuration_version).to eq(report.configuration_version)
+ expect(tripped.transaction_uuid).to eq(report.transaction_uuid)
+ expect(tripped.report_format).to eq(report.report_format)
+ expect(tripped.puppet_version).to eq(report.puppet_version)
+ expect(tripped.kind).to eq(report.kind)
+ expect(tripped.status).to eq(report.status)
+ expect(tripped.environment).to eq(report.environment)
+
+ expect(logs_as_strings(tripped)).to eq(logs_as_strings(report))
+ expect(metrics_as_hashes(tripped)).to eq(metrics_as_hashes(report))
expect_equivalent_resource_statuses(tripped.resource_statuses, report.resource_statuses)
end
def logs_as_strings(report)
report.logs.map(&:to_report)
end
def metrics_as_hashes(report)
Hash[*report.metrics.collect do |name, m|
[name, { :name => m.name, :label => m.label, :value => m.value }]
end.flatten]
end
def expect_equivalent_resource_statuses(tripped, report)
- tripped.keys.sort.should == report.keys.sort
+ expect(tripped.keys.sort).to eq(report.keys.sort)
tripped.each_pair do |name, status|
expected = report[name]
- status.title.should == expected.title
- status.file.should == expected.file
- status.line.should == expected.line
- status.resource.should == expected.resource
- status.resource_type.should == expected.resource_type
- status.containment_path.should == expected.containment_path
- status.evaluation_time.should == expected.evaluation_time
- status.tags.should == expected.tags
- status.time.to_i.should == expected.time.to_i
- status.failed.should == expected.failed
- status.changed.should == expected.changed
- status.out_of_sync.should == expected.out_of_sync
- status.skipped.should == expected.skipped
- status.change_count.should == expected.change_count
- status.out_of_sync_count.should == expected.out_of_sync_count
- status.events.should == expected.events
+ expect(status.title).to eq(expected.title)
+ expect(status.file).to eq(expected.file)
+ expect(status.line).to eq(expected.line)
+ expect(status.resource).to eq(expected.resource)
+ expect(status.resource_type).to eq(expected.resource_type)
+ expect(status.containment_path).to eq(expected.containment_path)
+ expect(status.evaluation_time).to eq(expected.evaluation_time)
+ expect(status.tags).to eq(expected.tags)
+ expect(status.time.to_i).to eq(expected.time.to_i)
+ expect(status.failed).to eq(expected.failed)
+ expect(status.changed).to eq(expected.changed)
+ expect(status.out_of_sync).to eq(expected.out_of_sync)
+ expect(status.skipped).to eq(expected.skipped)
+ expect(status.change_count).to eq(expected.change_count)
+ expect(status.out_of_sync_count).to eq(expected.out_of_sync_count)
+ expect(status.events).to eq(expected.events)
end
end
def generate_report
status = Puppet::Resource::Status.new(Puppet::Type.type(:notify).new(:title => "a resource"))
status.changed = true
report = Puppet::Transaction::Report.new('apply', 1357986, 'test_environment', "df34516e-4050-402d-a166-05b03b940749")
report << Puppet::Util::Log.new(:level => :warning, :message => "log message")
report.add_times("timing", 4)
report.add_resource_status(status)
report.finalize_report
report
end
def generate_report_with_error
status = Puppet::Resource::Status.new(Puppet::Type.type(:notify).new(:title => "a resource"))
status.changed = true
status.failed_because("bad stuff happened")
report = Puppet::Transaction::Report.new('apply', 1357986, 'test_environment', "df34516e-4050-402d-a166-05b03b940749")
report << Puppet::Util::Log.new(:level => :warning, :message => "log message")
report.add_times("timing", 4)
report.add_resource_status(status)
report.finalize_report
report
end
end
diff --git a/spec/unit/transaction/resource_harness_spec.rb b/spec/unit/transaction/resource_harness_spec.rb
index 7d9c6f439..801ab3ce4 100755
--- a/spec/unit/transaction/resource_harness_spec.rb
+++ b/spec/unit/transaction/resource_harness_spec.rb
@@ -1,542 +1,542 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/transaction/resource_harness'
describe Puppet::Transaction::ResourceHarness do
include PuppetSpec::Files
before do
@mode_750 = Puppet.features.microsoft_windows? ? '644' : '750'
@mode_755 = Puppet.features.microsoft_windows? ? '644' : '755'
path = make_absolute("/my/file")
@transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil)
@resource = Puppet::Type.type(:file).new :path => path
@harness = Puppet::Transaction::ResourceHarness.new(@transaction)
@current_state = Puppet::Resource.new(:file, path)
@resource.stubs(:retrieve).returns @current_state
end
it "should accept a transaction at initialization" do
harness = Puppet::Transaction::ResourceHarness.new(@transaction)
- harness.transaction.should equal(@transaction)
+ expect(harness.transaction).to equal(@transaction)
end
it "should delegate to the transaction for its relationship graph" do
@transaction.expects(:relationship_graph).returns "relgraph"
- Puppet::Transaction::ResourceHarness.new(@transaction).relationship_graph.should == "relgraph"
+ expect(Puppet::Transaction::ResourceHarness.new(@transaction).relationship_graph).to eq("relgraph")
end
describe "when evaluating a resource" do
it "produces a resource state that describes what happened with the resource" do
status = @harness.evaluate(@resource)
- status.resource.should == @resource.ref
- status.should_not be_failed
- status.events.should be_empty
+ expect(status.resource).to eq(@resource.ref)
+ expect(status).not_to be_failed
+ expect(status.events).to be_empty
end
it "retrieves the current state of the resource" do
@resource.expects(:retrieve).returns @current_state
@harness.evaluate(@resource)
end
it "produces a failure status for the resource when an error occurs" do
the_message = "retrieve failed in testing"
@resource.expects(:retrieve).raises(ArgumentError.new(the_message))
status = @harness.evaluate(@resource)
- status.should be_failed
- events_to_hash(status.events).collect do |event|
+ expect(status).to be_failed
+ expect(events_to_hash(status.events).collect do |event|
{ :@status => event[:@status], :@message => event[:@message] }
- end.should == [{ :@status => "failure", :@message => the_message }]
+ end).to eq([{ :@status => "failure", :@message => the_message }])
end
it "records the time it took to evaluate the resource" do
before = Time.now
status = @harness.evaluate(@resource)
after = Time.now
- status.evaluation_time.should be <= after - before
+ expect(status.evaluation_time).to be <= after - before
end
end
def events_to_hash(events)
events.map do |event|
hash = {}
event.instance_variables.each do |varname|
hash[varname.to_sym] = event.instance_variable_get(varname)
end
hash
end
end
def make_stub_provider
stubProvider = Class.new(Puppet::Type)
stubProvider.instance_eval do
initvars
newparam(:name) do
desc "The name var"
isnamevar
end
newproperty(:foo) do
desc "A property that can be changed successfully"
def sync
end
def retrieve
:absent
end
def insync?(reference_value)
false
end
end
newproperty(:bar) do
desc "A property that raises an exception when you try to change it"
def sync
raise ZeroDivisionError.new('bar')
end
def retrieve
:absent
end
def insync?(reference_value)
false
end
end
newproperty(:baz) do
desc "A property that raises an Exception (not StandardError) when you try to change it"
def sync
raise Exception.new('baz')
end
def retrieve
:absent
end
def insync?(reference_value)
false
end
end
newproperty(:brillig) do
desc "A property that raises a StandardError exception when you test if it's insync?"
def sync
end
def retrieve
:absent
end
def insync?(reference_value)
raise ZeroDivisionError.new('brillig')
end
end
newproperty(:slithy) do
desc "A property that raises an Exception when you test if it's insync?"
def sync
end
def retrieve
:absent
end
def insync?(reference_value)
raise Exception.new('slithy')
end
end
end
stubProvider
end
context "interaction of ensure with other properties" do
def an_ensurable_resource_reacting_as(behaviors)
stub_type = Class.new(Puppet::Type)
stub_type.class_eval do
initvars
ensurable do
def sync
(@resource.behaviors[:on_ensure] || proc {}).call
end
def insync?(value)
@resource.behaviors[:ensure_insync?]
end
end
newparam(:name) do
desc "The name var"
isnamevar
end
newproperty(:prop) do
newvalue("new") do
#noop
end
def retrieve
"old"
end
end
attr_reader :behaviors
def initialize(options)
@behaviors = options.delete(:behaviors)
super
end
def exists?
@behaviors[:present?]
end
def present?(resource)
@behaviors[:present?]
end
def self.name
"Testing"
end
end
stub_type.new(:behaviors => behaviors,
:ensure => :present,
:name => "testing",
:prop => "new")
end
it "ensure errors means that the rest doesn't happen" do
resource = an_ensurable_resource_reacting_as(:ensure_insync? => false, :on_ensure => proc { raise StandardError }, :present? => true)
status = @harness.evaluate(resource)
expect(status.events.length).to eq(1)
expect(status.events[0].property).to eq('ensure')
expect(status.events[0].name.to_s).to eq('Testing_created')
expect(status.events[0].status).to eq('failure')
end
it "ensure fails completely means that the rest doesn't happen" do
resource = an_ensurable_resource_reacting_as(:ensure_insync? => false, :on_ensure => proc { raise Exception }, :present? => false)
expect do
@harness.evaluate(resource)
end.to raise_error(Exception)
- @logs.first.message.should == "change from absent to present failed: Exception"
- @logs.first.level.should == :err
+ expect(@logs.first.message).to eq("change from absent to present failed: Exception")
+ expect(@logs.first.level).to eq(:err)
end
it "ensure succeeds means that the rest doesn't happen" do
resource = an_ensurable_resource_reacting_as(:ensure_insync? => false, :on_ensure => proc { }, :present? => true)
status = @harness.evaluate(resource)
expect(status.events.length).to eq(1)
expect(status.events[0].property).to eq('ensure')
expect(status.events[0].name.to_s).to eq('Testing_created')
expect(status.events[0].status).to eq('success')
end
it "ensure is in sync means that the rest *does* happen" do
resource = an_ensurable_resource_reacting_as(:ensure_insync? => true, :present? => true)
status = @harness.evaluate(resource)
expect(status.events.length).to eq(1)
expect(status.events[0].property).to eq('prop')
expect(status.events[0].name.to_s).to eq('prop_changed')
expect(status.events[0].status).to eq('success')
end
it "ensure is in sync but resource not present, means that the rest doesn't happen" do
resource = an_ensurable_resource_reacting_as(:ensure_insync? => true, :present? => false)
status = @harness.evaluate(resource)
expect(status.events).to be_empty
end
end
describe "when a caught error occurs" do
before :each do
stub_provider = make_stub_provider
resource = stub_provider.new :name => 'name', :foo => 1, :bar => 2
resource.expects(:err).never
@status = @harness.evaluate(resource)
end
it "should record previous successful events" do
- @status.events[0].property.should == 'foo'
- @status.events[0].status.should == 'success'
+ expect(@status.events[0].property).to eq('foo')
+ expect(@status.events[0].status).to eq('success')
end
it "should record a failure event" do
- @status.events[1].property.should == 'bar'
- @status.events[1].status.should == 'failure'
+ expect(@status.events[1].property).to eq('bar')
+ expect(@status.events[1].status).to eq('failure')
end
end
describe "when an Exception occurs during sync" do
before :each do
stub_provider = make_stub_provider
@resource = stub_provider.new :name => 'name', :baz => 1
@resource.expects(:err).never
end
it "should log and pass the exception through" do
- lambda { @harness.evaluate(@resource) }.should raise_error(Exception, /baz/)
- @logs.first.message.should == "change from absent to 1 failed: baz"
- @logs.first.level.should == :err
+ expect { @harness.evaluate(@resource) }.to raise_error(Exception, /baz/)
+ expect(@logs.first.message).to eq("change from absent to 1 failed: baz")
+ expect(@logs.first.level).to eq(:err)
end
end
describe "when a StandardError exception occurs during insync?" do
before :each do
stub_provider = make_stub_provider
@resource = stub_provider.new :name => 'name', :brillig => 1
@resource.expects(:err).never
end
it "should record a failure event" do
@status = @harness.evaluate(@resource)
- @status.events[0].name.to_s.should == 'brillig_changed'
- @status.events[0].property.should == 'brillig'
- @status.events[0].status.should == 'failure'
+ expect(@status.events[0].name.to_s).to eq('brillig_changed')
+ expect(@status.events[0].property).to eq('brillig')
+ expect(@status.events[0].status).to eq('failure')
end
end
describe "when an Exception occurs during insync?" do
before :each do
stub_provider = make_stub_provider
@resource = stub_provider.new :name => 'name', :slithy => 1
@resource.expects(:err).never
end
it "should log and pass the exception through" do
- lambda { @harness.evaluate(@resource) }.should raise_error(Exception, /slithy/)
- @logs.first.message.should == "change from absent to 1 failed: slithy"
- @logs.first.level.should == :err
+ expect { @harness.evaluate(@resource) }.to raise_error(Exception, /slithy/)
+ expect(@logs.first.message).to eq("change from absent to 1 failed: slithy")
+ expect(@logs.first.level).to eq(:err)
end
end
describe "when auditing" do
it "should not call insync? on parameters that are merely audited" do
stub_provider = make_stub_provider
resource = stub_provider.new :name => 'name', :audit => ['foo']
resource.property(:foo).expects(:insync?).never
status = @harness.evaluate(resource)
expect(status.events).to be_empty
end
it "should be able to audit a file's group" do # see bug #5710
test_file = tmpfile('foo')
File.open(test_file, 'w').close
resource = Puppet::Type.type(:file).new :path => test_file, :audit => ['group'], :backup => false
resource.expects(:err).never # make sure no exceptions get swallowed
status = @harness.evaluate(resource)
status.events.each do |event|
- event.status.should != 'failure'
+ expect(event.status).to != 'failure'
end
end
it "should not ignore microseconds when auditing a file's mtime" do
test_file = tmpfile('foo')
File.open(test_file, 'w').close
resource = Puppet::Type.type(:file).new :path => test_file, :audit => ['mtime'], :backup => false
# construct a property hash with nanosecond resolution as would be
# found on an ext4 file system
time_with_nsec_resolution = Time.at(1000, 123456.999)
current_from_filesystem = {:mtime => time_with_nsec_resolution}
# construct a property hash with a 1 microsecond difference from above
time_with_usec_resolution = Time.at(1000, 123457.000)
historical_from_state_yaml = {:mtime => time_with_usec_resolution}
# set up the sequence of stubs; yeah, this is pretty
# brittle, so this might need to be adjusted if the
# resource_harness logic changes
resource.expects(:retrieve).returns(current_from_filesystem)
Puppet::Util::Storage.stubs(:cache).with(resource).
returns(historical_from_state_yaml).then.
returns(current_from_filesystem).then.
returns(current_from_filesystem)
# there should be an audit change recorded, since the two
# timestamps differ by at least 1 microsecond
status = @harness.evaluate(resource)
- status.events.should_not be_empty
+ expect(status.events).not_to be_empty
status.events.each do |event|
- event.message.should =~ /audit change: previously recorded/
+ expect(event.message).to match(/audit change: previously recorded/)
end
end
it "should ignore nanoseconds when auditing a file's mtime" do
test_file = tmpfile('foo')
File.open(test_file, 'w').close
resource = Puppet::Type.type(:file).new :path => test_file, :audit => ['mtime'], :backup => false
# construct a property hash with nanosecond resolution as would be
# found on an ext4 file system
time_with_nsec_resolution = Time.at(1000, 123456.789)
current_from_filesystem = {:mtime => time_with_nsec_resolution}
# construct a property hash with the same timestamp as above,
# truncated to microseconds, as would be read back from state.yaml
time_with_usec_resolution = Time.at(1000, 123456.000)
historical_from_state_yaml = {:mtime => time_with_usec_resolution}
# set up the sequence of stubs; yeah, this is pretty
# brittle, so this might need to be adjusted if the
# resource_harness logic changes
resource.expects(:retrieve).returns(current_from_filesystem)
Puppet::Util::Storage.stubs(:cache).with(resource).
returns(historical_from_state_yaml).then.
returns(current_from_filesystem).then.
returns(current_from_filesystem)
# there should be no audit change recorded, despite the
# slight difference in the two timestamps
status = @harness.evaluate(resource)
status.events.each do |event|
- event.message.should_not =~ /audit change: previously recorded/
+ expect(event.message).not_to match(/audit change: previously recorded/)
end
end
end
describe "when applying changes" do
it "should not apply changes if allow_changes?() returns false" do
test_file = tmpfile('foo')
resource = Puppet::Type.type(:file).new :path => test_file, :backup => false, :ensure => :file
resource.expects(:err).never # make sure no exceptions get swallowed
@harness.expects(:allow_changes?).with(resource).returns false
status = @harness.evaluate(resource)
- Puppet::FileSystem.exist?(test_file).should == false
+ expect(Puppet::FileSystem.exist?(test_file)).to eq(false)
end
end
describe "when determining whether the resource can be changed" do
before do
@resource.stubs(:purging?).returns true
@resource.stubs(:deleting?).returns true
end
it "should be true if the resource is not being purged" do
@resource.expects(:purging?).returns false
- @harness.should be_allow_changes(@resource)
+ expect(@harness).to be_allow_changes(@resource)
end
it "should be true if the resource is not being deleted" do
@resource.expects(:deleting?).returns false
- @harness.should be_allow_changes(@resource)
+ expect(@harness).to be_allow_changes(@resource)
end
it "should be true if the resource has no dependents" do
@harness.relationship_graph.expects(:dependents).with(@resource).returns []
- @harness.should be_allow_changes(@resource)
+ expect(@harness).to be_allow_changes(@resource)
end
it "should be true if all dependents are being deleted" do
dep = stub 'dependent', :deleting? => true
@harness.relationship_graph.expects(:dependents).with(@resource).returns [dep]
@resource.expects(:purging?).returns true
- @harness.should be_allow_changes(@resource)
+ expect(@harness).to be_allow_changes(@resource)
end
it "should be false if the resource's dependents are not being deleted" do
dep = stub 'dependent', :deleting? => false, :ref => "myres"
@resource.expects(:warning)
@harness.relationship_graph.expects(:dependents).with(@resource).returns [dep]
- @harness.should_not be_allow_changes(@resource)
+ expect(@harness).not_to be_allow_changes(@resource)
end
end
describe "when finding the schedule" do
before do
@catalog = Puppet::Resource::Catalog.new
@resource.catalog = @catalog
end
it "should warn and return nil if the resource has no catalog" do
@resource.catalog = nil
@resource.expects(:warning)
- @harness.schedule(@resource).should be_nil
+ expect(@harness.schedule(@resource)).to be_nil
end
it "should return nil if the resource specifies no schedule" do
- @harness.schedule(@resource).should be_nil
+ expect(@harness.schedule(@resource)).to be_nil
end
it "should fail if the named schedule cannot be found" do
@resource[:schedule] = "whatever"
@resource.expects(:fail)
@harness.schedule(@resource)
end
it "should return the named schedule if it exists" do
sched = Puppet::Type.type(:schedule).new(:name => "sched")
@catalog.add_resource(sched)
@resource[:schedule] = "sched"
- @harness.schedule(@resource).to_s.should == sched.to_s
+ expect(@harness.schedule(@resource).to_s).to eq(sched.to_s)
end
end
describe "when determining if a resource is scheduled" do
before do
@catalog = Puppet::Resource::Catalog.new
@resource.catalog = @catalog
end
it "should return true if 'ignoreschedules' is set" do
Puppet[:ignoreschedules] = true
@resource[:schedule] = "meh"
- @harness.should be_scheduled(@resource)
+ expect(@harness).to be_scheduled(@resource)
end
it "should return true if the resource has no schedule set" do
- @harness.should be_scheduled(@resource)
+ expect(@harness).to be_scheduled(@resource)
end
it "should return the result of matching the schedule with the cached 'checked' time if a schedule is set" do
t = Time.now
@harness.expects(:cached).with(@resource, :checked).returns(t)
sched = Puppet::Type.type(:schedule).new(:name => "sched")
@catalog.add_resource(sched)
@resource[:schedule] = "sched"
sched.expects(:match?).with(t.to_i).returns "feh"
- @harness.scheduled?(@resource).should == "feh"
+ expect(@harness.scheduled?(@resource)).to eq("feh")
end
end
it "should be able to cache data in the Storage module" do
data = {}
Puppet::Util::Storage.expects(:cache).with(@resource).returns data
@harness.cache(@resource, :foo, "something")
- data[:foo].should == "something"
+ expect(data[:foo]).to eq("something")
end
it "should be able to retrieve data from the cache" do
data = {:foo => "other"}
Puppet::Util::Storage.expects(:cache).with(@resource).returns data
- @harness.cached(@resource, :foo).should == "other"
+ expect(@harness.cached(@resource, :foo)).to eq("other")
end
end
diff --git a/spec/unit/transaction_spec.rb b/spec/unit/transaction_spec.rb
index e608a5d6b..debf3ad68 100755
--- a/spec/unit/transaction_spec.rb
+++ b/spec/unit/transaction_spec.rb
@@ -1,736 +1,736 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'matchers/include_in_order'
require 'puppet_spec/compiler'
require 'puppet/transaction'
require 'fileutils'
describe Puppet::Transaction do
include PuppetSpec::Files
include PuppetSpec::Compiler
def catalog_with_resource(resource)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource(resource)
catalog
end
def transaction_with_resource(resource)
transaction = Puppet::Transaction.new(catalog_with_resource(resource), nil, Puppet::Graph::RandomPrioritizer.new)
transaction
end
before do
@basepath = make_absolute("/what/ever")
@transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, Puppet::Graph::RandomPrioritizer.new)
end
it "should be able to look resource status up by resource reference" do
resource = Puppet::Type.type(:notify).new :title => "foobar"
transaction = transaction_with_resource(resource)
transaction.evaluate
- transaction.resource_status(resource.to_s).should be_changed
+ expect(transaction.resource_status(resource.to_s)).to be_changed
end
# This will basically only ever be used during testing.
it "should automatically create resource statuses if asked for a non-existent status" do
resource = Puppet::Type.type(:notify).new :title => "foobar"
transaction = transaction_with_resource(resource)
- transaction.resource_status(resource).should be_instance_of(Puppet::Resource::Status)
+ expect(transaction.resource_status(resource)).to be_instance_of(Puppet::Resource::Status)
end
it "should add provided resource statuses to its report" do
resource = Puppet::Type.type(:notify).new :title => "foobar"
transaction = transaction_with_resource(resource)
transaction.evaluate
status = transaction.resource_status(resource)
- transaction.report.resource_statuses[resource.to_s].should equal(status)
+ expect(transaction.report.resource_statuses[resource.to_s]).to equal(status)
end
it "should not consider there to be failed resources if no statuses are marked failed" do
resource = Puppet::Type.type(:notify).new :title => "foobar"
transaction = transaction_with_resource(resource)
transaction.evaluate
- transaction.should_not be_any_failed
+ expect(transaction).not_to be_any_failed
end
it "should use the provided report object" do
report = Puppet::Transaction::Report.new("apply")
transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, report, nil)
- transaction.report.should == report
+ expect(transaction.report).to eq(report)
end
it "should create a report if none is provided" do
transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil)
- transaction.report.should be_kind_of Puppet::Transaction::Report
+ expect(transaction.report).to be_kind_of Puppet::Transaction::Report
end
describe "when initializing" do
it "should create an event manager" do
transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil)
- transaction.event_manager.should be_instance_of(Puppet::Transaction::EventManager)
- transaction.event_manager.transaction.should equal(transaction)
+ expect(transaction.event_manager).to be_instance_of(Puppet::Transaction::EventManager)
+ expect(transaction.event_manager.transaction).to equal(transaction)
end
it "should create a resource harness" do
transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil)
- transaction.resource_harness.should be_instance_of(Puppet::Transaction::ResourceHarness)
- transaction.resource_harness.transaction.should equal(transaction)
+ expect(transaction.resource_harness).to be_instance_of(Puppet::Transaction::ResourceHarness)
+ expect(transaction.resource_harness.transaction).to equal(transaction)
end
it "should set retrieval time on the report" do
catalog = Puppet::Resource::Catalog.new
report = Puppet::Transaction::Report.new("apply")
catalog.retrieval_duration = 5
report.expects(:add_times).with(:config_retrieval, 5)
transaction = Puppet::Transaction.new(catalog, report, nil)
end
end
describe "when evaluating a resource" do
let(:resource) { Puppet::Type.type(:file).new :path => @basepath }
it "should process events" do
transaction = transaction_with_resource(resource)
transaction.expects(:skip?).with(resource).returns false
transaction.event_manager.expects(:process_events).with(resource)
transaction.evaluate
end
describe "and the resource should be skipped" do
it "should mark the resource's status as skipped" do
transaction = transaction_with_resource(resource)
transaction.expects(:skip?).with(resource).returns true
transaction.evaluate
- transaction.resource_status(resource).should be_skipped
+ expect(transaction.resource_status(resource)).to be_skipped
end
it "does not process any scheduled events" do
transaction = transaction_with_resource(resource)
transaction.expects(:skip?).with(resource).returns true
transaction.event_manager.expects(:process_events).with(resource).never
transaction.evaluate
end
it "dequeues all events scheduled on that resource" do
transaction = transaction_with_resource(resource)
transaction.expects(:skip?).with(resource).returns true
transaction.event_manager.expects(:dequeue_all_events_for_resource).with(resource)
transaction.evaluate
end
end
end
describe "when applying a resource" do
before do
@catalog = Puppet::Resource::Catalog.new
@resource = Puppet::Type.type(:file).new :path => @basepath
@catalog.add_resource(@resource)
@status = Puppet::Resource::Status.new(@resource)
@transaction = Puppet::Transaction.new(@catalog, nil, Puppet::Graph::RandomPrioritizer.new)
@transaction.event_manager.stubs(:queue_events)
end
it "should use its resource harness to apply the resource" do
@transaction.resource_harness.expects(:evaluate).with(@resource)
@transaction.evaluate
end
it "should add the resulting resource status to its status list" do
@transaction.resource_harness.stubs(:evaluate).returns(@status)
@transaction.evaluate
- @transaction.resource_status(@resource).should be_instance_of(Puppet::Resource::Status)
+ expect(@transaction.resource_status(@resource)).to be_instance_of(Puppet::Resource::Status)
end
it "should queue any events added to the resource status" do
@transaction.resource_harness.stubs(:evaluate).returns(@status)
@status.expects(:events).returns %w{a b}
@transaction.event_manager.expects(:queue_events).with(@resource, ["a", "b"])
@transaction.evaluate
end
it "should log and skip any resources that cannot be applied" do
@resource.expects(:properties).raises ArgumentError
@transaction.evaluate
- @transaction.report.resource_statuses[@resource.to_s].should be_failed
+ expect(@transaction.report.resource_statuses[@resource.to_s]).to be_failed
end
it "should report any_failed if any resources failed" do
@resource.expects(:properties).raises ArgumentError
@transaction.evaluate
expect(@transaction).to be_any_failed
end
end
describe "#unblock" do
let(:graph) { @transaction.relationship_graph }
let(:resource) { Puppet::Type.type(:notify).new(:name => 'foo') }
it "should calculate the number of blockers if it's not known" do
graph.add_vertex(resource)
3.times do |i|
other = Puppet::Type.type(:notify).new(:name => i.to_s)
graph.add_vertex(other)
graph.add_edge(other, resource)
end
graph.unblock(resource)
- graph.blockers[resource].should == 2
+ expect(graph.blockers[resource]).to eq(2)
end
it "should decrement the number of blockers if there are any" do
graph.blockers[resource] = 40
graph.unblock(resource)
- graph.blockers[resource].should == 39
+ expect(graph.blockers[resource]).to eq(39)
end
it "should warn if there are no blockers" do
vertex = stub('vertex')
vertex.expects(:warning).with "appears to have a negative number of dependencies"
graph.blockers[vertex] = 0
graph.unblock(vertex)
end
it "should return true if the resource is now unblocked" do
graph.blockers[resource] = 1
- graph.unblock(resource).should == true
+ expect(graph.unblock(resource)).to eq(true)
end
it "should return false if the resource is still blocked" do
graph.blockers[resource] = 2
- graph.unblock(resource).should == false
+ expect(graph.unblock(resource)).to eq(false)
end
end
describe "when traversing" do
let(:path) { tmpdir('eval_generate') }
let(:resource) { Puppet::Type.type(:file).new(:path => path, :recurse => true) }
before :each do
@transaction.catalog.add_resource(resource)
end
it "should yield the resource even if eval_generate is called" do
Puppet::Transaction::AdditionalResourceGenerator.any_instance.expects(:eval_generate).with(resource).returns true
yielded = false
@transaction.evaluate do |res|
yielded = true if res == resource
end
- yielded.should == true
+ expect(yielded).to eq(true)
end
it "should prefetch the provider if necessary" do
@transaction.expects(:prefetch_if_necessary).with(resource)
@transaction.evaluate {}
end
it "traverses independent resources before dependent resources" do
dependent = Puppet::Type.type(:notify).new(:name => "hello", :require => resource)
@transaction.catalog.add_resource(dependent)
seen = []
@transaction.evaluate do |res|
seen << res
end
expect(seen).to include_in_order(resource, dependent)
end
it "traverses completely independent resources in the order they appear in the catalog" do
independent = Puppet::Type.type(:notify).new(:name => "hello", :require => resource)
@transaction.catalog.add_resource(independent)
seen = []
@transaction.evaluate do |res|
seen << res
end
expect(seen).to include_in_order(resource, independent)
end
it "should fail unsuitable resources and go on if it gets blocked" do
dependent = Puppet::Type.type(:notify).new(:name => "hello", :require => resource)
@transaction.catalog.add_resource(dependent)
resource.stubs(:suitable?).returns false
evaluated = []
@transaction.evaluate do |res|
evaluated << res
end
# We should have gone on to evaluate the children
- evaluated.should == [dependent]
- @transaction.resource_status(resource).should be_failed
+ expect(evaluated).to eq([dependent])
+ expect(@transaction.resource_status(resource)).to be_failed
end
end
describe "when generating resources before traversal" do
let(:catalog) { Puppet::Resource::Catalog.new }
let(:transaction) { Puppet::Transaction.new(catalog, nil, Puppet::Graph::RandomPrioritizer.new) }
let(:generator) { Puppet::Type.type(:notify).new :title => "generator" }
let(:generated) do
%w[a b c].map { |name| Puppet::Type.type(:notify).new(:name => name) }
end
before :each do
catalog.add_resource generator
generator.stubs(:generate).returns generated
# avoid crude failures because of nil resources that result
# from implicit containment and lacking containers
catalog.stubs(:container_of).returns generator
end
it "should call 'generate' on all created resources" do
generated.each { |res| res.expects(:generate) }
transaction.evaluate
end
it "should finish all resources" do
generated.each { |res| res.expects(:finish) }
transaction.evaluate
end
it "should copy all tags to the newly generated resources" do
generator.tag('one', 'two')
transaction.evaluate
generated.each do |res|
- res.must be_tagged(*generator.tags)
+ expect(res).to be_tagged(*generator.tags)
end
end
end
describe "when performing pre-run checks" do
let(:resource) { Puppet::Type.type(:notify).new(:title => "spec") }
let(:transaction) { transaction_with_resource(resource) }
let(:spec_exception) { 'spec-exception' }
it "should invoke each resource's hook and apply the catalog after no failures" do
resource.expects(:pre_run_check)
transaction.evaluate
end
it "should abort the transaction on failure" do
resource.expects(:pre_run_check).raises(Puppet::Error, spec_exception)
expect { transaction.evaluate }.to raise_error(Puppet::Error, /Some pre-run checks failed/)
end
it "should log the resource-specific exception" do
resource.expects(:pre_run_check).raises(Puppet::Error, spec_exception)
resource.expects(:log_exception).with(responds_with(:message, spec_exception))
expect { transaction.evaluate }.to raise_error(Puppet::Error)
end
end
describe "when skipping a resource" do
before :each do
@resource = Puppet::Type.type(:notify).new :name => "foo"
@catalog = Puppet::Resource::Catalog.new
@resource.catalog = @catalog
@transaction = Puppet::Transaction.new(@catalog, nil, nil)
end
it "should skip resource with missing tags" do
@transaction.stubs(:missing_tags?).returns(true)
- @transaction.should be_skip(@resource)
+ expect(@transaction).to be_skip(@resource)
end
it "should skip unscheduled resources" do
@transaction.stubs(:scheduled?).returns(false)
- @transaction.should be_skip(@resource)
+ expect(@transaction).to be_skip(@resource)
end
it "should skip resources with failed dependencies" do
@transaction.stubs(:failed_dependencies?).returns(true)
- @transaction.should be_skip(@resource)
+ expect(@transaction).to be_skip(@resource)
end
it "should skip virtual resource" do
@resource.stubs(:virtual?).returns true
- @transaction.should be_skip(@resource)
+ expect(@transaction).to be_skip(@resource)
end
it "should skip device only resouce on normal host" do
@resource.stubs(:appliable_to_host?).returns false
@resource.stubs(:appliable_to_device?).returns true
@transaction.for_network_device = false
- @transaction.should be_skip(@resource)
+ expect(@transaction).to be_skip(@resource)
end
it "should not skip device only resouce on remote device" do
@resource.stubs(:appliable_to_host?).returns false
@resource.stubs(:appliable_to_device?).returns true
@transaction.for_network_device = true
- @transaction.should_not be_skip(@resource)
+ expect(@transaction).not_to be_skip(@resource)
end
it "should skip host resouce on device" do
@resource.stubs(:appliable_to_host?).returns true
@resource.stubs(:appliable_to_device?).returns false
@transaction.for_network_device = true
- @transaction.should be_skip(@resource)
+ expect(@transaction).to be_skip(@resource)
end
it "should not skip resouce available on both device and host when on device" do
@resource.stubs(:appliable_to_host?).returns true
@resource.stubs(:appliable_to_device?).returns true
@transaction.for_network_device = true
- @transaction.should_not be_skip(@resource)
+ expect(@transaction).not_to be_skip(@resource)
end
it "should not skip resouce available on both device and host when on host" do
@resource.stubs(:appliable_to_host?).returns true
@resource.stubs(:appliable_to_device?).returns true
@transaction.for_network_device = false
- @transaction.should_not be_skip(@resource)
+ expect(@transaction).not_to be_skip(@resource)
end
end
describe "when determining if tags are missing" do
before :each do
@resource = Puppet::Type.type(:notify).new :name => "foo"
@catalog = Puppet::Resource::Catalog.new
@resource.catalog = @catalog
@transaction = Puppet::Transaction.new(@catalog, nil, nil)
@transaction.stubs(:ignore_tags?).returns false
end
it "should not be missing tags if tags are being ignored" do
@transaction.expects(:ignore_tags?).returns true
@resource.expects(:tagged?).never
- @transaction.should_not be_missing_tags(@resource)
+ expect(@transaction).not_to be_missing_tags(@resource)
end
it "should not be missing tags if the transaction tags are empty" do
@transaction.tags = []
@resource.expects(:tagged?).never
- @transaction.should_not be_missing_tags(@resource)
+ expect(@transaction).not_to be_missing_tags(@resource)
end
it "should otherwise let the resource determine if it is missing tags" do
tags = ['one', 'two']
@transaction.tags = tags
- @transaction.should be_missing_tags(@resource)
+ expect(@transaction).to be_missing_tags(@resource)
end
end
describe "when determining if a resource should be scheduled" do
before :each do
@resource = Puppet::Type.type(:notify).new :name => "foo"
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource(@resource)
@transaction = Puppet::Transaction.new(@catalog, nil, Puppet::Graph::RandomPrioritizer.new)
end
it "should always schedule resources if 'ignoreschedules' is set" do
@transaction.ignoreschedules = true
@transaction.resource_harness.expects(:scheduled?).never
@transaction.evaluate
- @transaction.resource_status(@resource).should be_changed
+ expect(@transaction.resource_status(@resource)).to be_changed
end
it "should let the resource harness determine whether the resource should be scheduled" do
@transaction.resource_harness.expects(:scheduled?).with(@resource).returns "feh"
@transaction.evaluate
end
end
describe "when prefetching" do
let(:catalog) { Puppet::Resource::Catalog.new }
let(:transaction) { Puppet::Transaction.new(catalog, nil, nil) }
let(:resource) { Puppet::Type.type(:sshkey).new :title => "foo", :name => "bar", :type => :dsa, :key => "eh", :provider => :parsed }
let(:resource2) { Puppet::Type.type(:package).new :title => "blah", :provider => "apt" }
before :each do
catalog.add_resource resource
catalog.add_resource resource2
end
it "should match resources by name, not title" do
resource.provider.class.expects(:prefetch).with("bar" => resource)
transaction.prefetch_if_necessary(resource)
end
it "should not prefetch a provider which has already been prefetched" do
transaction.prefetched_providers[:sshkey][:parsed] = true
resource.provider.class.expects(:prefetch).never
transaction.prefetch_if_necessary(resource)
end
it "should mark the provider prefetched" do
resource.provider.class.stubs(:prefetch)
transaction.prefetch_if_necessary(resource)
- transaction.prefetched_providers[:sshkey][:parsed].should be_true
+ expect(transaction.prefetched_providers[:sshkey][:parsed]).to be_truthy
end
it "should prefetch resources without a provider if prefetching the default provider" do
other = Puppet::Type.type(:sshkey).new :name => "other"
other.instance_variable_set(:@provider, nil)
catalog.add_resource other
resource.provider.class.expects(:prefetch).with('bar' => resource, 'other' => other)
transaction.prefetch_if_necessary(resource)
end
end
describe "during teardown" do
let(:catalog) { Puppet::Resource::Catalog.new }
let(:transaction) do
Puppet::Transaction.new(catalog, nil, Puppet::Graph::RandomPrioritizer.new)
end
let(:teardown_type) do
Puppet::Type.newtype(:teardown_test) do
newparam(:name) {}
end
end
before :each do
teardown_type.provide(:teardown_provider) do
class << self
attr_reader :result
def post_resource_eval
@result = 'passed'
end
end
end
end
it "should call ::post_resource_eval on provider classes that support it" do
resource = teardown_type.new(:title => "foo", :provider => :teardown_provider)
transaction = transaction_with_resource(resource)
transaction.evaluate
expect(resource.provider.class.result).to eq('passed')
end
it "should call ::post_resource_eval even if other providers' ::post_resource_eval fails" do
teardown_type.provide(:always_fails) do
class << self
attr_reader :result
def post_resource_eval
@result = 'failed'
raise Puppet::Error, "This provider always fails"
end
end
end
good_resource = teardown_type.new(:title => "bloo", :provider => :teardown_provider)
bad_resource = teardown_type.new(:title => "blob", :provider => :always_fails)
catalog.add_resource(bad_resource)
catalog.add_resource(good_resource)
transaction.evaluate
expect(good_resource.provider.class.result).to eq('passed')
expect(bad_resource.provider.class.result).to eq('failed')
end
it "should call ::post_resource_eval even if one of the resources fails" do
resource = teardown_type.new(:title => "foo", :provider => :teardown_provider)
resource.stubs(:retrieve_resource).raises
catalog.add_resource resource
resource.provider.class.expects(:post_resource_eval)
transaction.evaluate
end
end
describe 'when checking application run state' do
before do
@catalog = Puppet::Resource::Catalog.new
@transaction = Puppet::Transaction.new(@catalog, nil, Puppet::Graph::RandomPrioritizer.new)
end
context "when stop is requested" do
before :each do
Puppet::Application.stubs(:stop_requested?).returns(true)
end
it 'should return true for :stop_processing?' do
- @transaction.should be_stop_processing
+ expect(@transaction).to be_stop_processing
end
it 'always evaluates non-host_config catalogs' do
@catalog.host_config = false
- @transaction.should_not be_stop_processing
+ expect(@transaction).not_to be_stop_processing
end
end
it 'should return false for :stop_processing? if Puppet::Application.stop_requested? is false' do
Puppet::Application.stubs(:stop_requested?).returns(false)
- @transaction.stop_processing?.should be_false
+ expect(@transaction.stop_processing?).to be_falsey
end
describe 'within an evaluate call' do
before do
@resource = Puppet::Type.type(:notify).new :title => "foobar"
@catalog.add_resource @resource
@transaction.stubs(:add_dynamically_generated_resources)
end
it 'should stop processing if :stop_processing? is true' do
@transaction.stubs(:stop_processing?).returns(true)
@transaction.expects(:eval_resource).never
@transaction.evaluate
end
it 'should continue processing if :stop_processing? is false' do
@transaction.stubs(:stop_processing?).returns(false)
@transaction.expects(:eval_resource).returns(nil)
@transaction.evaluate
end
end
end
it "errors with a dependency cycle for a resource that requires itself" do
expect do
apply_compiled_manifest(<<-MANIFEST)
notify { cycle: require => Notify[cycle] }
MANIFEST
end.to raise_error(Puppet::Error, /Found 1 dependency cycle:.*\(Notify\[cycle\] => Notify\[cycle\]\)/m)
end
it "errors with a dependency cycle for a self-requiring resource also required by another resource" do
expect do
apply_compiled_manifest(<<-MANIFEST)
notify { cycle: require => Notify[cycle] }
notify { other: require => Notify[cycle] }
MANIFEST
end.to raise_error(Puppet::Error, /Found 1 dependency cycle:.*\(Notify\[cycle\] => Notify\[cycle\]\)/m)
end
it "errors with a dependency cycle for a resource that requires itself and another resource" do
expect do
apply_compiled_manifest(<<-MANIFEST)
notify { cycle:
require => [Notify[other], Notify[cycle]]
}
notify { other: }
MANIFEST
end.to raise_error(Puppet::Error, /Found 1 dependency cycle:.*\(Notify\[cycle\] => Notify\[cycle\]\)/m)
end
it "errors with a dependency cycle for a resource that is later modified to require itself" do
expect do
apply_compiled_manifest(<<-MANIFEST)
notify { cycle: }
Notify <| title == 'cycle' |> {
require => Notify[cycle]
}
MANIFEST
end.to raise_error(Puppet::Error, /Found 1 dependency cycle:.*\(Notify\[cycle\] => Notify\[cycle\]\)/m)
end
it "reports a changed resource with a successful run" do
transaction = apply_compiled_manifest("notify { one: }")
- transaction.report.status.should == 'changed'
- transaction.report.resource_statuses['Notify[one]'].should be_changed
+ expect(transaction.report.status).to eq('changed')
+ expect(transaction.report.resource_statuses['Notify[one]']).to be_changed
end
describe "when interrupted" do
it "marks unprocessed resources as skipped" do
Puppet::Application.stop!
transaction = apply_compiled_manifest(<<-MANIFEST)
notify { a: } ->
notify { b: }
MANIFEST
- transaction.report.resource_statuses['Notify[a]'].should be_skipped
- transaction.report.resource_statuses['Notify[b]'].should be_skipped
+ expect(transaction.report.resource_statuses['Notify[a]']).to be_skipped
+ expect(transaction.report.resource_statuses['Notify[b]']).to be_skipped
end
end
end
describe Puppet::Transaction, " when determining tags" do
before do
@config = Puppet::Resource::Catalog.new
@transaction = Puppet::Transaction.new(@config, nil, nil)
end
it "should default to the tags specified in the :tags setting" do
Puppet[:tags] = "one"
- @transaction.should be_tagged("one")
+ expect(@transaction).to be_tagged("one")
end
it "should split tags based on ','" do
Puppet[:tags] = "one,two"
- @transaction.should be_tagged("one")
- @transaction.should be_tagged("two")
+ expect(@transaction).to be_tagged("one")
+ expect(@transaction).to be_tagged("two")
end
it "should use any tags set after creation" do
Puppet[:tags] = ""
@transaction.tags = %w{one two}
- @transaction.should be_tagged("one")
- @transaction.should be_tagged("two")
+ expect(@transaction).to be_tagged("one")
+ expect(@transaction).to be_tagged("two")
end
it "should always convert assigned tags to an array" do
@transaction.tags = "one::two"
- @transaction.should be_tagged("one::two")
+ expect(@transaction).to be_tagged("one::two")
end
it "should accept a comma-delimited string" do
@transaction.tags = "one, two"
- @transaction.should be_tagged("one")
- @transaction.should be_tagged("two")
+ expect(@transaction).to be_tagged("one")
+ expect(@transaction).to be_tagged("two")
end
it "should accept an empty string" do
@transaction.tags = "one, two"
- @transaction.should be_tagged("one")
+ expect(@transaction).to be_tagged("one")
@transaction.tags = ""
- @transaction.should_not be_tagged("one")
+ expect(@transaction).not_to be_tagged("one")
end
end
diff --git a/spec/unit/type/augeas_spec.rb b/spec/unit/type/augeas_spec.rb
index ed510c974..a1f2f0f43 100755
--- a/spec/unit/type/augeas_spec.rb
+++ b/spec/unit/type/augeas_spec.rb
@@ -1,119 +1,119 @@
#! /usr/bin/env ruby
require 'spec_helper'
augeas = Puppet::Type.type(:augeas)
describe augeas do
describe "when augeas is present", :if => Puppet.features.augeas? do
it "should have a default provider inheriting from Puppet::Provider" do
- augeas.defaultprovider.ancestors.should be_include(Puppet::Provider)
+ expect(augeas.defaultprovider.ancestors).to be_include(Puppet::Provider)
end
it "should have a valid provider" do
- augeas.new(:name => "foo").provider.class.ancestors.should be_include(Puppet::Provider)
+ expect(augeas.new(:name => "foo").provider.class.ancestors).to be_include(Puppet::Provider)
end
end
describe "basic structure" do
it "should be able to create an instance" do
provider_class = Puppet::Type::Augeas.provider(Puppet::Type::Augeas.providers[0])
Puppet::Type::Augeas.expects(:defaultprovider).returns provider_class
- augeas.new(:name => "bar").should_not be_nil
+ expect(augeas.new(:name => "bar")).not_to be_nil
end
it "should have a parse_commands feature" do
- augeas.provider_feature(:parse_commands).should_not be_nil
+ expect(augeas.provider_feature(:parse_commands)).not_to be_nil
end
it "should have a need_to_run? feature" do
- augeas.provider_feature(:need_to_run?).should_not be_nil
+ expect(augeas.provider_feature(:need_to_run?)).not_to be_nil
end
it "should have an execute_changes feature" do
- augeas.provider_feature(:execute_changes).should_not be_nil
+ expect(augeas.provider_feature(:execute_changes)).not_to be_nil
end
properties = [:returns]
params = [:name, :context, :onlyif, :changes, :root, :load_path, :type_check, :show_diff]
properties.each do |property|
it "should have a #{property} property" do
- augeas.attrclass(property).ancestors.should be_include(Puppet::Property)
+ expect(augeas.attrclass(property).ancestors).to be_include(Puppet::Property)
end
it "should have documentation for its #{property} property" do
- augeas.attrclass(property).doc.should be_instance_of(String)
+ expect(augeas.attrclass(property).doc).to be_instance_of(String)
end
end
params.each do |param|
it "should have a #{param} parameter" do
- augeas.attrclass(param).ancestors.should be_include(Puppet::Parameter)
+ expect(augeas.attrclass(param).ancestors).to be_include(Puppet::Parameter)
end
it "should have documentation for its #{param} parameter" do
- augeas.attrclass(param).doc.should be_instance_of(String)
+ expect(augeas.attrclass(param).doc).to be_instance_of(String)
end
end
end
describe "default values" do
before do
provider_class = augeas.provider(augeas.providers[0])
augeas.expects(:defaultprovider).returns provider_class
end
it "should be blank for context" do
- augeas.new(:name => :context)[:context].should == ""
+ expect(augeas.new(:name => :context)[:context]).to eq("")
end
it "should be blank for onlyif" do
- augeas.new(:name => :onlyif)[:onlyif].should == ""
+ expect(augeas.new(:name => :onlyif)[:onlyif]).to eq("")
end
it "should be blank for load_path" do
- augeas.new(:name => :load_path)[:load_path].should == ""
+ expect(augeas.new(:name => :load_path)[:load_path]).to eq("")
end
it "should be / for root" do
- augeas.new(:name => :root)[:root].should == "/"
+ expect(augeas.new(:name => :root)[:root]).to eq("/")
end
it "should be false for type_check" do
- augeas.new(:name => :type_check)[:type_check].should == :false
+ expect(augeas.new(:name => :type_check)[:type_check]).to eq(:false)
end
end
describe "provider interaction" do
it "should return 0 if it does not need to run" do
provider = stub("provider", :need_to_run? => false)
resource = stub('resource', :resource => nil, :provider => provider, :line => nil, :file => nil)
changes = augeas.attrclass(:returns).new(:resource => resource)
- changes.retrieve.should == 0
+ expect(changes.retrieve).to eq(0)
end
it "should return :need_to_run if it needs to run" do
provider = stub("provider", :need_to_run? => true)
resource = stub('resource', :resource => nil, :provider => provider, :line => nil, :file => nil)
changes = augeas.attrclass(:returns).new(:resource => resource)
- changes.retrieve.should == :need_to_run
+ expect(changes.retrieve).to eq(:need_to_run)
end
end
describe "loading specific files" do
it "should require lens when incl is used" do
- lambda { augeas.new(:name => :no_lens, :incl => "/etc/hosts")}.should raise_error(Puppet::Error)
+ expect { augeas.new(:name => :no_lens, :incl => "/etc/hosts")}.to raise_error(Puppet::Error)
end
it "should require incl when lens is used" do
- lambda { augeas.new(:name => :no_incl, :lens => "Hosts.lns") }.should raise_error(Puppet::Error)
+ expect { augeas.new(:name => :no_incl, :lens => "Hosts.lns") }.to raise_error(Puppet::Error)
end
it "should set the context when a specific file is used" do
fake_provider = stub_everything "fake_provider"
augeas.stubs(:defaultprovider).returns fake_provider
- augeas.new(:name => :no_incl, :lens => "Hosts.lns", :incl => "/etc/hosts")[:context].should == "/files/etc/hosts"
+ expect(augeas.new(:name => :no_incl, :lens => "Hosts.lns", :incl => "/etc/hosts")[:context]).to eq("/files/etc/hosts")
end
end
end
diff --git a/spec/unit/type/component_spec.rb b/spec/unit/type/component_spec.rb
index f3326a161..35693b83e 100755
--- a/spec/unit/type/component_spec.rb
+++ b/spec/unit/type/component_spec.rb
@@ -1,53 +1,53 @@
#! /usr/bin/env ruby
require 'spec_helper'
component = Puppet::Type.type(:component)
describe component do
it "should have a :name attribute" do
- component.attrclass(:name).should_not be_nil
+ expect(component.attrclass(:name)).not_to be_nil
end
it "should use Class as its type when a normal string is provided as the title" do
- component.new(:name => "bar").ref.should == "Class[Bar]"
+ expect(component.new(:name => "bar").ref).to eq("Class[Bar]")
end
it "should always produce a resource reference string as its title" do
- component.new(:name => "bar").title.should == "Class[Bar]"
+ expect(component.new(:name => "bar").title).to eq("Class[Bar]")
end
it "should have a reference string equivalent to its title" do
comp = component.new(:name => "Foo[bar]")
- comp.title.should == comp.ref
+ expect(comp.title).to eq(comp.ref)
end
it "should not fail when provided an invalid value" do
comp = component.new(:name => "Foo[bar]")
- lambda { comp[:yayness] = "ey" }.should_not raise_error
+ expect { comp[:yayness] = "ey" }.not_to raise_error
end
it "should return previously provided invalid values" do
comp = component.new(:name => "Foo[bar]")
comp[:yayness] = "eh"
- comp[:yayness].should == "eh"
+ expect(comp[:yayness]).to eq("eh")
end
it "should correctly support metaparameters" do
comp = component.new(:name => "Foo[bar]", :require => "Foo[bar]")
- comp.parameter(:require).should be_instance_of(component.attrclass(:require))
+ expect(comp.parameter(:require)).to be_instance_of(component.attrclass(:require))
end
describe "when building up the path" do
it "should produce the class name if the component models a class" do
- component.new(:name => "Class[foo]").pathbuilder.must == ["Foo"]
+ expect(component.new(:name => "Class[foo]").pathbuilder).to eq(["Foo"])
end
it "should produce the class name even for the class named main" do
- component.new(:name => "Class[main]").pathbuilder.must == ["Main"]
+ expect(component.new(:name => "Class[main]").pathbuilder).to eq(["Main"])
end
it "should produce a resource reference if the component does not model a class" do
- component.new(:name => "Foo[bar]").pathbuilder.must == ["Foo[bar]"]
+ expect(component.new(:name => "Foo[bar]").pathbuilder).to eq(["Foo[bar]"])
end
end
end
diff --git a/spec/unit/type/computer_spec.rb b/spec/unit/type/computer_spec.rb
index dd01e47bd..ba61aafde 100755
--- a/spec/unit/type/computer_spec.rb
+++ b/spec/unit/type/computer_spec.rb
@@ -1,80 +1,80 @@
#! /usr/bin/env ruby
require 'spec_helper'
computer = Puppet::Type.type(:computer)
describe Puppet::Type.type(:computer), " when checking computer objects" do
before do
provider_class = Puppet::Type::Computer.provider(Puppet::Type::Computer.providers[0])
Puppet::Type::Computer.expects(:defaultprovider).returns provider_class
@resource = Puppet::Type::Computer.new(
:name => "puppetcomputertest",
:en_address => "aa:bb:cc:dd:ee:ff",
:ip_address => "1.2.3.4")
@properties = {}
@ensure = Puppet::Type::Computer.attrclass(:ensure).new(:resource => @resource)
end
it "should be able to create an instance" do
provider_class = Puppet::Type::Computer.provider(Puppet::Type::Computer.providers[0])
Puppet::Type::Computer.expects(:defaultprovider).returns provider_class
- computer.new(:name => "bar").should_not be_nil
+ expect(computer.new(:name => "bar")).not_to be_nil
end
properties = [:en_address, :ip_address]
params = [:name]
properties.each do |property|
it "should have a #{property} property" do
- computer.attrclass(property).ancestors.should be_include(Puppet::Property)
+ expect(computer.attrclass(property).ancestors).to be_include(Puppet::Property)
end
it "should have documentation for its #{property} property" do
- computer.attrclass(property).doc.should be_instance_of(String)
+ expect(computer.attrclass(property).doc).to be_instance_of(String)
end
it "should accept :absent as a value" do
prop = computer.attrclass(property).new(:resource => @resource)
prop.should = :absent
- prop.should.must == :absent
+ expect(prop.should).to eq(:absent)
end
end
params.each do |param|
it "should have a #{param} parameter" do
- computer.attrclass(param).ancestors.should be_include(Puppet::Parameter)
+ expect(computer.attrclass(param).ancestors).to be_include(Puppet::Parameter)
end
it "should have documentation for its #{param} parameter" do
- computer.attrclass(param).doc.should be_instance_of(String)
+ expect(computer.attrclass(param).doc).to be_instance_of(String)
end
end
describe "default values" do
before do
provider_class = computer.provider(computer.providers[0])
computer.expects(:defaultprovider).returns provider_class
end
it "should be nil for en_address" do
- computer.new(:name => :en_address)[:en_address].should == nil
+ expect(computer.new(:name => :en_address)[:en_address]).to eq(nil)
end
it "should be nil for ip_address" do
- computer.new(:name => :ip_address)[:ip_address].should == nil
+ expect(computer.new(:name => :ip_address)[:ip_address]).to eq(nil)
end
end
describe "when managing the ensure property" do
it "should support a :present value" do
- lambda { @ensure.should = :present }.should_not raise_error
+ expect { @ensure.should = :present }.not_to raise_error
end
it "should support an :absent value" do
- lambda { @ensure.should = :absent }.should_not raise_error
+ expect { @ensure.should = :absent }.not_to raise_error
end
end
end
diff --git a/spec/unit/type/cron_spec.rb b/spec/unit/type/cron_spec.rb
index 37be5cbcc..4241e5173 100755
--- a/spec/unit/type/cron_spec.rb
+++ b/spec/unit/type/cron_spec.rb
@@ -1,543 +1,543 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:cron), :unless => Puppet.features.microsoft_windows? do
let(:simple_provider) do
@provider_class = described_class.provide(:simple) { mk_resource_methods }
@provider_class.stubs(:suitable?).returns true
@provider_class
end
before :each do
described_class.stubs(:defaultprovider).returns @provider_class
end
after :each do
described_class.unprovide(:simple)
end
it "should have :name be its namevar" do
- described_class.key_attributes.should == [:name]
+ expect(described_class.key_attributes).to eq([:name])
end
describe "when validating attributes" do
[:name, :provider].each do |param|
it "should have a #{param} parameter" do
- described_class.attrtype(param).should == :param
+ expect(described_class.attrtype(param)).to eq(:param)
end
end
[:command, :special, :minute, :hour, :weekday, :month, :monthday, :environment, :user, :target].each do |property|
it "should have a #{property} property" do
- described_class.attrtype(property).should == :property
+ expect(described_class.attrtype(property)).to eq(:property)
end
end
[:command, :minute, :hour, :weekday, :month, :monthday].each do |cronparam|
it "should have #{cronparam} of type CronParam" do
- described_class.attrclass(cronparam).ancestors.should include CronParam
+ expect(described_class.attrclass(cronparam).ancestors).to include CronParam
end
end
end
describe "when validating values" do
describe "ensure" do
it "should support present as a value for ensure" do
expect { described_class.new(:name => 'foo', :ensure => :present) }.to_not raise_error
end
it "should support absent as a value for ensure" do
expect { described_class.new(:name => 'foo', :ensure => :present) }.to_not raise_error
end
it "should not support other values" do
expect { described_class.new(:name => 'foo', :ensure => :foo) }.to raise_error(Puppet::Error, /Invalid value/)
end
end
describe "command" do
it "should discard leading spaces" do
- described_class.new(:name => 'foo', :command => " /bin/true")[:command].should_not match Regexp.new(" ")
+ expect(described_class.new(:name => 'foo', :command => " /bin/true")[:command]).not_to match Regexp.new(" ")
end
it "should discard trailing spaces" do
- described_class.new(:name => 'foo', :command => "/bin/true ")[:command].should_not match Regexp.new(" ")
+ expect(described_class.new(:name => 'foo', :command => "/bin/true ")[:command]).not_to match Regexp.new(" ")
end
end
describe "minute" do
it "should support absent" do
expect { described_class.new(:name => 'foo', :minute => 'absent') }.to_not raise_error
end
it "should support *" do
expect { described_class.new(:name => 'foo', :minute => '*') }.to_not raise_error
end
it "should translate absent to :absent" do
- described_class.new(:name => 'foo', :minute => 'absent')[:minute].should == :absent
+ expect(described_class.new(:name => 'foo', :minute => 'absent')[:minute]).to eq(:absent)
end
it "should translate * to :absent" do
- described_class.new(:name => 'foo', :minute => '*')[:minute].should == :absent
+ expect(described_class.new(:name => 'foo', :minute => '*')[:minute]).to eq(:absent)
end
it "should support valid single values" do
expect { described_class.new(:name => 'foo', :minute => '0') }.to_not raise_error
expect { described_class.new(:name => 'foo', :minute => '1') }.to_not raise_error
expect { described_class.new(:name => 'foo', :minute => '59') }.to_not raise_error
end
it "should not support non numeric characters" do
expect { described_class.new(:name => 'foo', :minute => 'z59') }.to raise_error(Puppet::Error, /z59 is not a valid minute/)
expect { described_class.new(:name => 'foo', :minute => '5z9') }.to raise_error(Puppet::Error, /5z9 is not a valid minute/)
expect { described_class.new(:name => 'foo', :minute => '59z') }.to raise_error(Puppet::Error, /59z is not a valid minute/)
end
it "should not support single values out of range" do
expect { described_class.new(:name => 'foo', :minute => '-1') }.to raise_error(Puppet::Error, /-1 is not a valid minute/)
expect { described_class.new(:name => 'foo', :minute => '60') }.to raise_error(Puppet::Error, /60 is not a valid minute/)
expect { described_class.new(:name => 'foo', :minute => '61') }.to raise_error(Puppet::Error, /61 is not a valid minute/)
expect { described_class.new(:name => 'foo', :minute => '120') }.to raise_error(Puppet::Error, /120 is not a valid minute/)
end
it "should support valid multiple values" do
expect { described_class.new(:name => 'foo', :minute => ['0','1','59'] ) }.to_not raise_error
expect { described_class.new(:name => 'foo', :minute => ['40','30','20'] ) }.to_not raise_error
expect { described_class.new(:name => 'foo', :minute => ['10','30','20'] ) }.to_not raise_error
end
it "should not support multiple values if at least one is invalid" do
# one invalid
expect { described_class.new(:name => 'foo', :minute => ['0','1','60'] ) }.to raise_error(Puppet::Error, /60 is not a valid minute/)
expect { described_class.new(:name => 'foo', :minute => ['0','120','59'] ) }.to raise_error(Puppet::Error, /120 is not a valid minute/)
expect { described_class.new(:name => 'foo', :minute => ['-1','1','59'] ) }.to raise_error(Puppet::Error, /-1 is not a valid minute/)
# two invalid
expect { described_class.new(:name => 'foo', :minute => ['0','61','62'] ) }.to raise_error(Puppet::Error, /(61|62) is not a valid minute/)
# all invalid
expect { described_class.new(:name => 'foo', :minute => ['-1','61','62'] ) }.to raise_error(Puppet::Error, /(-1|61|62) is not a valid minute/)
end
it "should support valid step syntax" do
expect { described_class.new(:name => 'foo', :minute => '*/2' ) }.to_not raise_error
expect { described_class.new(:name => 'foo', :minute => '10-16/2' ) }.to_not raise_error
end
it "should not support invalid steps" do
expect { described_class.new(:name => 'foo', :minute => '*/A' ) }.to raise_error(Puppet::Error, /\*\/A is not a valid minute/)
expect { described_class.new(:name => 'foo', :minute => '*/2A' ) }.to raise_error(Puppet::Error, /\*\/2A is not a valid minute/)
# As it turns out cron does not complaining about steps that exceed the valid range
# expect { described_class.new(:name => 'foo', :minute => '*/120' ) }.to raise_error(Puppet::Error, /is not a valid minute/)
end
end
describe "hour" do
it "should support absent" do
expect { described_class.new(:name => 'foo', :hour => 'absent') }.to_not raise_error
end
it "should support *" do
expect { described_class.new(:name => 'foo', :hour => '*') }.to_not raise_error
end
it "should translate absent to :absent" do
- described_class.new(:name => 'foo', :hour => 'absent')[:hour].should == :absent
+ expect(described_class.new(:name => 'foo', :hour => 'absent')[:hour]).to eq(:absent)
end
it "should translate * to :absent" do
- described_class.new(:name => 'foo', :hour => '*')[:hour].should == :absent
+ expect(described_class.new(:name => 'foo', :hour => '*')[:hour]).to eq(:absent)
end
it "should support valid single values" do
expect { described_class.new(:name => 'foo', :hour => '0') }.to_not raise_error
expect { described_class.new(:name => 'foo', :hour => '11') }.to_not raise_error
expect { described_class.new(:name => 'foo', :hour => '12') }.to_not raise_error
expect { described_class.new(:name => 'foo', :hour => '13') }.to_not raise_error
expect { described_class.new(:name => 'foo', :hour => '23') }.to_not raise_error
end
it "should not support non numeric characters" do
expect { described_class.new(:name => 'foo', :hour => 'z15') }.to raise_error(Puppet::Error, /z15 is not a valid hour/)
expect { described_class.new(:name => 'foo', :hour => '1z5') }.to raise_error(Puppet::Error, /1z5 is not a valid hour/)
expect { described_class.new(:name => 'foo', :hour => '15z') }.to raise_error(Puppet::Error, /15z is not a valid hour/)
end
it "should not support single values out of range" do
expect { described_class.new(:name => 'foo', :hour => '-1') }.to raise_error(Puppet::Error, /-1 is not a valid hour/)
expect { described_class.new(:name => 'foo', :hour => '24') }.to raise_error(Puppet::Error, /24 is not a valid hour/)
expect { described_class.new(:name => 'foo', :hour => '120') }.to raise_error(Puppet::Error, /120 is not a valid hour/)
end
it "should support valid multiple values" do
expect { described_class.new(:name => 'foo', :hour => ['0','1','23'] ) }.to_not raise_error
expect { described_class.new(:name => 'foo', :hour => ['5','16','14'] ) }.to_not raise_error
expect { described_class.new(:name => 'foo', :hour => ['16','13','9'] ) }.to_not raise_error
end
it "should not support multiple values if at least one is invalid" do
# one invalid
expect { described_class.new(:name => 'foo', :hour => ['0','1','24'] ) }.to raise_error(Puppet::Error, /24 is not a valid hour/)
expect { described_class.new(:name => 'foo', :hour => ['0','-1','5'] ) }.to raise_error(Puppet::Error, /-1 is not a valid hour/)
expect { described_class.new(:name => 'foo', :hour => ['-1','1','23'] ) }.to raise_error(Puppet::Error, /-1 is not a valid hour/)
# two invalid
expect { described_class.new(:name => 'foo', :hour => ['0','25','26'] ) }.to raise_error(Puppet::Error, /(25|26) is not a valid hour/)
# all invalid
expect { described_class.new(:name => 'foo', :hour => ['-1','24','120'] ) }.to raise_error(Puppet::Error, /(-1|24|120) is not a valid hour/)
end
it "should support valid step syntax" do
expect { described_class.new(:name => 'foo', :hour => '*/2' ) }.to_not raise_error
expect { described_class.new(:name => 'foo', :hour => '10-18/4' ) }.to_not raise_error
end
it "should not support invalid steps" do
expect { described_class.new(:name => 'foo', :hour => '*/A' ) }.to raise_error(Puppet::Error, /\*\/A is not a valid hour/)
expect { described_class.new(:name => 'foo', :hour => '*/2A' ) }.to raise_error(Puppet::Error, /\*\/2A is not a valid hour/)
# As it turns out cron does not complaining about steps that exceed the valid range
# expect { described_class.new(:name => 'foo', :hour => '*/26' ) }.to raise_error(Puppet::Error, /is not a valid hour/)
end
end
describe "weekday" do
it "should support absent" do
expect { described_class.new(:name => 'foo', :weekday => 'absent') }.to_not raise_error
end
it "should support *" do
expect { described_class.new(:name => 'foo', :weekday => '*') }.to_not raise_error
end
it "should translate absent to :absent" do
- described_class.new(:name => 'foo', :weekday => 'absent')[:weekday].should == :absent
+ expect(described_class.new(:name => 'foo', :weekday => 'absent')[:weekday]).to eq(:absent)
end
it "should translate * to :absent" do
- described_class.new(:name => 'foo', :weekday => '*')[:weekday].should == :absent
+ expect(described_class.new(:name => 'foo', :weekday => '*')[:weekday]).to eq(:absent)
end
it "should support valid numeric weekdays" do
expect { described_class.new(:name => 'foo', :weekday => '0') }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => '1') }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => '6') }.to_not raise_error
# According to http://www.manpagez.com/man/5/crontab 7 is also valid (Sunday)
expect { described_class.new(:name => 'foo', :weekday => '7') }.to_not raise_error
end
it "should support valid weekdays as words (long version)" do
expect { described_class.new(:name => 'foo', :weekday => 'Monday') }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => 'Tuesday') }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => 'Wednesday') }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => 'Thursday') }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => 'Friday') }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => 'Saturday') }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => 'Sunday') }.to_not raise_error
end
it "should support valid weekdays as words (3 character version)" do
expect { described_class.new(:name => 'foo', :weekday => 'Mon') }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => 'Tue') }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => 'Wed') }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => 'Thu') }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => 'Fri') }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => 'Sat') }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => 'Sun') }.to_not raise_error
end
it "should not support numeric values out of range" do
expect { described_class.new(:name => 'foo', :weekday => '-1') }.to raise_error(Puppet::Error, /-1 is not a valid weekday/)
expect { described_class.new(:name => 'foo', :weekday => '8') }.to raise_error(Puppet::Error, /8 is not a valid weekday/)
end
it "should not support invalid weekday names" do
expect { described_class.new(:name => 'foo', :weekday => 'Sar') }.to raise_error(Puppet::Error, /Sar is not a valid weekday/)
end
it "should support valid multiple values" do
expect { described_class.new(:name => 'foo', :weekday => ['0','1','6'] ) }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => ['Mon','Wed','Friday'] ) }.to_not raise_error
end
it "should not support multiple values if at least one is invalid" do
# one invalid
expect { described_class.new(:name => 'foo', :weekday => ['0','1','8'] ) }.to raise_error(Puppet::Error, /8 is not a valid weekday/)
expect { described_class.new(:name => 'foo', :weekday => ['Mon','Fii','Sat'] ) }.to raise_error(Puppet::Error, /Fii is not a valid weekday/)
# two invalid
expect { described_class.new(:name => 'foo', :weekday => ['Mos','Fii','Sat'] ) }.to raise_error(Puppet::Error, /(Mos|Fii) is not a valid weekday/)
# all invalid
expect { described_class.new(:name => 'foo', :weekday => ['Mos','Fii','Saa'] ) }.to raise_error(Puppet::Error, /(Mos|Fii|Saa) is not a valid weekday/)
expect { described_class.new(:name => 'foo', :weekday => ['-1','8','11'] ) }.to raise_error(Puppet::Error, /(-1|8|11) is not a valid weekday/)
end
it "should support valid step syntax" do
expect { described_class.new(:name => 'foo', :weekday => '*/2' ) }.to_not raise_error
expect { described_class.new(:name => 'foo', :weekday => '0-4/2' ) }.to_not raise_error
end
it "should not support invalid steps" do
expect { described_class.new(:name => 'foo', :weekday => '*/A' ) }.to raise_error(Puppet::Error, /\*\/A is not a valid weekday/)
expect { described_class.new(:name => 'foo', :weekday => '*/2A' ) }.to raise_error(Puppet::Error, /\*\/2A is not a valid weekday/)
# As it turns out cron does not complaining about steps that exceed the valid range
# expect { described_class.new(:name => 'foo', :weekday => '*/9' ) }.to raise_error(Puppet::Error, /is not a valid weekday/)
end
end
describe "month" do
it "should support absent" do
expect { described_class.new(:name => 'foo', :month => 'absent') }.to_not raise_error
end
it "should support *" do
expect { described_class.new(:name => 'foo', :month => '*') }.to_not raise_error
end
it "should translate absent to :absent" do
- described_class.new(:name => 'foo', :month => 'absent')[:month].should == :absent
+ expect(described_class.new(:name => 'foo', :month => 'absent')[:month]).to eq(:absent)
end
it "should translate * to :absent" do
- described_class.new(:name => 'foo', :month => '*')[:month].should == :absent
+ expect(described_class.new(:name => 'foo', :month => '*')[:month]).to eq(:absent)
end
it "should support valid numeric values" do
expect { described_class.new(:name => 'foo', :month => '1') }.to_not raise_error
expect { described_class.new(:name => 'foo', :month => '12') }.to_not raise_error
end
it "should support valid months as words" do
expect( described_class.new(:name => 'foo', :month => 'January')[:month] ).to eq(['1'])
expect( described_class.new(:name => 'foo', :month => 'February')[:month] ).to eq(['2'])
expect( described_class.new(:name => 'foo', :month => 'March')[:month] ).to eq(['3'])
expect( described_class.new(:name => 'foo', :month => 'April')[:month] ).to eq(['4'])
expect( described_class.new(:name => 'foo', :month => 'May')[:month] ).to eq(['5'])
expect( described_class.new(:name => 'foo', :month => 'June')[:month] ).to eq(['6'])
expect( described_class.new(:name => 'foo', :month => 'July')[:month] ).to eq(['7'])
expect( described_class.new(:name => 'foo', :month => 'August')[:month] ).to eq(['8'])
expect( described_class.new(:name => 'foo', :month => 'September')[:month] ).to eq(['9'])
expect( described_class.new(:name => 'foo', :month => 'October')[:month] ).to eq(['10'])
expect( described_class.new(:name => 'foo', :month => 'November')[:month] ).to eq(['11'])
expect( described_class.new(:name => 'foo', :month => 'December')[:month] ).to eq(['12'])
end
it "should support valid months as words (3 character short version)" do
expect( described_class.new(:name => 'foo', :month => 'Jan')[:month] ).to eq(['1'])
expect( described_class.new(:name => 'foo', :month => 'Feb')[:month] ).to eq(['2'])
expect( described_class.new(:name => 'foo', :month => 'Mar')[:month] ).to eq(['3'])
expect( described_class.new(:name => 'foo', :month => 'Apr')[:month] ).to eq(['4'])
expect( described_class.new(:name => 'foo', :month => 'May')[:month] ).to eq(['5'])
expect( described_class.new(:name => 'foo', :month => 'Jun')[:month] ).to eq(['6'])
expect( described_class.new(:name => 'foo', :month => 'Jul')[:month] ).to eq(['7'])
expect( described_class.new(:name => 'foo', :month => 'Aug')[:month] ).to eq(['8'])
expect( described_class.new(:name => 'foo', :month => 'Sep')[:month] ).to eq(['9'])
expect( described_class.new(:name => 'foo', :month => 'Oct')[:month] ).to eq(['10'])
expect( described_class.new(:name => 'foo', :month => 'Nov')[:month] ).to eq(['11'])
expect( described_class.new(:name => 'foo', :month => 'Dec')[:month] ).to eq(['12'])
end
it "should not support numeric values out of range" do
expect { described_class.new(:name => 'foo', :month => '-1') }.to raise_error(Puppet::Error, /-1 is not a valid month/)
expect { described_class.new(:name => 'foo', :month => '0') }.to raise_error(Puppet::Error, /0 is not a valid month/)
expect { described_class.new(:name => 'foo', :month => '13') }.to raise_error(Puppet::Error, /13 is not a valid month/)
end
it "should not support words that are not valid months" do
expect { described_class.new(:name => 'foo', :month => 'Jal') }.to raise_error(Puppet::Error, /Jal is not a valid month/)
end
it "should not support single values out of range" do
expect { described_class.new(:name => 'foo', :month => '-1') }.to raise_error(Puppet::Error, /-1 is not a valid month/)
expect { described_class.new(:name => 'foo', :month => '60') }.to raise_error(Puppet::Error, /60 is not a valid month/)
expect { described_class.new(:name => 'foo', :month => '61') }.to raise_error(Puppet::Error, /61 is not a valid month/)
expect { described_class.new(:name => 'foo', :month => '120') }.to raise_error(Puppet::Error, /120 is not a valid month/)
end
it "should support valid multiple values" do
expect { described_class.new(:name => 'foo', :month => ['1','9','12'] ) }.to_not raise_error
expect { described_class.new(:name => 'foo', :month => ['Jan','March','Jul'] ) }.to_not raise_error
end
it "should not support multiple values if at least one is invalid" do
# one invalid
expect { described_class.new(:name => 'foo', :month => ['0','1','12'] ) }.to raise_error(Puppet::Error, /0 is not a valid month/)
expect { described_class.new(:name => 'foo', :month => ['1','13','10'] ) }.to raise_error(Puppet::Error, /13 is not a valid month/)
expect { described_class.new(:name => 'foo', :month => ['Jan','Feb','Jxx'] ) }.to raise_error(Puppet::Error, /Jxx is not a valid month/)
# two invalid
expect { described_class.new(:name => 'foo', :month => ['Jan','Fex','Jux'] ) }.to raise_error(Puppet::Error, /(Fex|Jux) is not a valid month/)
# all invalid
expect { described_class.new(:name => 'foo', :month => ['-1','0','13'] ) }.to raise_error(Puppet::Error, /(-1|0|13) is not a valid month/)
expect { described_class.new(:name => 'foo', :month => ['Jax','Fex','Aux'] ) }.to raise_error(Puppet::Error, /(Jax|Fex|Aux) is not a valid month/)
end
it "should support valid step syntax" do
expect { described_class.new(:name => 'foo', :month => '*/2' ) }.to_not raise_error
expect { described_class.new(:name => 'foo', :month => '1-12/3' ) }.to_not raise_error
end
it "should not support invalid steps" do
expect { described_class.new(:name => 'foo', :month => '*/A' ) }.to raise_error(Puppet::Error, /\*\/A is not a valid month/)
expect { described_class.new(:name => 'foo', :month => '*/2A' ) }.to raise_error(Puppet::Error, /\*\/2A is not a valid month/)
# As it turns out cron does not complaining about steps that exceed the valid range
# expect { described_class.new(:name => 'foo', :month => '*/13' ) }.to raise_error(Puppet::Error, /is not a valid month/)
end
end
describe "monthday" do
it "should support absent" do
expect { described_class.new(:name => 'foo', :monthday => 'absent') }.to_not raise_error
end
it "should support *" do
expect { described_class.new(:name => 'foo', :monthday => '*') }.to_not raise_error
end
it "should translate absent to :absent" do
- described_class.new(:name => 'foo', :monthday => 'absent')[:monthday].should == :absent
+ expect(described_class.new(:name => 'foo', :monthday => 'absent')[:monthday]).to eq(:absent)
end
it "should translate * to :absent" do
- described_class.new(:name => 'foo', :monthday => '*')[:monthday].should == :absent
+ expect(described_class.new(:name => 'foo', :monthday => '*')[:monthday]).to eq(:absent)
end
it "should support valid single values" do
expect { described_class.new(:name => 'foo', :monthday => '1') }.to_not raise_error
expect { described_class.new(:name => 'foo', :monthday => '30') }.to_not raise_error
expect { described_class.new(:name => 'foo', :monthday => '31') }.to_not raise_error
end
it "should not support non numeric characters" do
expect { described_class.new(:name => 'foo', :monthday => 'z23') }.to raise_error(Puppet::Error, /z23 is not a valid monthday/)
expect { described_class.new(:name => 'foo', :monthday => '2z3') }.to raise_error(Puppet::Error, /2z3 is not a valid monthday/)
expect { described_class.new(:name => 'foo', :monthday => '23z') }.to raise_error(Puppet::Error, /23z is not a valid monthday/)
end
it "should not support single values out of range" do
expect { described_class.new(:name => 'foo', :monthday => '-1') }.to raise_error(Puppet::Error, /-1 is not a valid monthday/)
expect { described_class.new(:name => 'foo', :monthday => '0') }.to raise_error(Puppet::Error, /0 is not a valid monthday/)
expect { described_class.new(:name => 'foo', :monthday => '32') }.to raise_error(Puppet::Error, /32 is not a valid monthday/)
end
it "should support valid multiple values" do
expect { described_class.new(:name => 'foo', :monthday => ['1','23','31'] ) }.to_not raise_error
expect { described_class.new(:name => 'foo', :monthday => ['31','23','1'] ) }.to_not raise_error
expect { described_class.new(:name => 'foo', :monthday => ['1','31','23'] ) }.to_not raise_error
end
it "should not support multiple values if at least one is invalid" do
# one invalid
expect { described_class.new(:name => 'foo', :monthday => ['1','23','32'] ) }.to raise_error(Puppet::Error, /32 is not a valid monthday/)
expect { described_class.new(:name => 'foo', :monthday => ['-1','12','23'] ) }.to raise_error(Puppet::Error, /-1 is not a valid monthday/)
expect { described_class.new(:name => 'foo', :monthday => ['13','32','30'] ) }.to raise_error(Puppet::Error, /32 is not a valid monthday/)
# two invalid
expect { described_class.new(:name => 'foo', :monthday => ['-1','0','23'] ) }.to raise_error(Puppet::Error, /(-1|0) is not a valid monthday/)
# all invalid
expect { described_class.new(:name => 'foo', :monthday => ['-1','0','32'] ) }.to raise_error(Puppet::Error, /(-1|0|32) is not a valid monthday/)
end
it "should support valid step syntax" do
expect { described_class.new(:name => 'foo', :monthday => '*/2' ) }.to_not raise_error
expect { described_class.new(:name => 'foo', :monthday => '10-16/2' ) }.to_not raise_error
end
it "should not support invalid steps" do
expect { described_class.new(:name => 'foo', :monthday => '*/A' ) }.to raise_error(Puppet::Error, /\*\/A is not a valid monthday/)
expect { described_class.new(:name => 'foo', :monthday => '*/2A' ) }.to raise_error(Puppet::Error, /\*\/2A is not a valid monthday/)
# As it turns out cron does not complaining about steps that exceed the valid range
# expect { described_class.new(:name => 'foo', :monthday => '*/32' ) }.to raise_error(Puppet::Error, /is not a valid monthday/)
end
end
describe "special" do
%w(reboot yearly annually monthly weekly daily midnight hourly).each do |value|
it "should support the value '#{value}'" do
expect { described_class.new(:name => 'foo', :special => value ) }.to_not raise_error
end
end
context "when combined with numeric schedule fields" do
context "which are 'absent'" do
[ %w(reboot yearly annually monthly weekly daily midnight hourly), :absent ].flatten.each { |value|
it "should accept the value '#{value}' for special" do
expect {
described_class.new(:name => 'foo', :minute => :absent, :special => value )
}.to_not raise_error
end
}
end
context "which are not absent" do
%w(reboot yearly annually monthly weekly daily midnight hourly).each { |value|
it "should not accept the value '#{value}' for special" do
expect {
described_class.new(:name => 'foo', :minute => "1", :special => value )
}.to raise_error(Puppet::Error, /cannot specify both a special schedule and a value/)
end
}
it "should accept the 'absent' value for special" do
expect {
described_class.new(:name => 'foo', :minute => "1", :special => :absent )
}.to_not raise_error
end
end
end
end
describe "environment" do
it "it should accept an :environment that looks like a path" do
expect do
described_class.new(:name => 'foo',:environment => 'PATH=/bin:/usr/bin:/usr/sbin')
end.to_not raise_error
end
it "should not accept environment variables that do not contain '='" do
expect do
described_class.new(:name => 'foo',:environment => 'INVALID')
end.to raise_error(Puppet::Error, /Invalid environment setting "INVALID"/)
end
it "should accept empty environment variables that do not contain '='" do
expect do
described_class.new(:name => 'foo',:environment => 'MAILTO=')
end.to_not raise_error
end
it "should accept 'absent'" do
expect do
described_class.new(:name => 'foo',:environment => 'absent')
end.to_not raise_error
end
end
end
describe "when autorequiring resources" do
before :each do
@user_bob = Puppet::Type.type(:user).new(:name => 'bob', :ensure => :present)
@user_alice = Puppet::Type.type(:user).new(:name => 'alice', :ensure => :present)
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource @user_bob, @user_alice
end
it "should autorequire the user" do
@resource = described_class.new(:name => 'dummy', :command => '/usr/bin/uptime', :user => 'alice')
@catalog.add_resource @resource
req = @resource.autorequire
- req.size.should == 1
- req[0].target.must == @resource
- req[0].source.must == @user_alice
+ expect(req.size).to eq(1)
+ expect(req[0].target).to eq(@resource)
+ expect(req[0].source).to eq(@user_alice)
end
end
it "should not require a command when removing an entry" do
entry = described_class.new(:name => "test_entry", :ensure => :absent)
- entry.value(:command).should == nil
+ expect(entry.value(:command)).to eq(nil)
end
it "should default to user => root if Etc.getpwuid(Process.uid) returns nil (#12357)" do
Etc.expects(:getpwuid).returns(nil)
entry = described_class.new(:name => "test_entry", :ensure => :present)
- entry.value(:user).should eql "root"
+ expect(entry.value(:user)).to eql "root"
end
end
diff --git a/spec/unit/type/exec_spec.rb b/spec/unit/type/exec_spec.rb
index 681cae429..48c740468 100755
--- a/spec/unit/type/exec_spec.rb
+++ b/spec/unit/type/exec_spec.rb
@@ -1,772 +1,772 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:exec) do
include PuppetSpec::Files
def exec_tester(command, exitstatus = 0, rest = {})
Puppet.features.stubs(:root?).returns(true)
output = rest.delete(:output) || ''
output = Puppet::Util::Execution::ProcessOutput.new(output, exitstatus)
tries = rest[:tries] || 1
args = {
:name => command,
:path => @example_path,
:logoutput => false,
:loglevel => :err,
:returns => 0
}.merge(rest)
exec = Puppet::Type.type(:exec).new(args)
status = stub "process", :exitstatus => exitstatus
Puppet::Util::Execution.expects(:execute).times(tries).
with() { |*args|
args[0] == command &&
args[1][:override_locale] == false &&
args[1].has_key?(:custom_environment)
}.returns(output)
return exec
end
before do
@command = make_absolute('/bin/true whatever')
@executable = make_absolute('/bin/true')
@bogus_cmd = make_absolute('/bogus/cmd')
end
describe "when not stubbing the provider" do
before do
path = tmpdir('path')
ext = Puppet.features.microsoft_windows? ? '.exe' : ''
true_cmd = File.join(path, "true#{ext}")
false_cmd = File.join(path, "false#{ext}")
FileUtils.touch(true_cmd)
FileUtils.touch(false_cmd)
File.chmod(0755, true_cmd)
File.chmod(0755, false_cmd)
@example_path = [path]
end
it "should return :executed_command as its event" do
resource = Puppet::Type.type(:exec).new :command => @command
- resource.parameter(:returns).event.name.should == :executed_command
+ expect(resource.parameter(:returns).event.name).to eq(:executed_command)
end
describe "when execing" do
it "should use the 'execute' method to exec" do
- exec_tester("true").refresh.should == :executed_command
+ expect(exec_tester("true").refresh).to eq(:executed_command)
end
it "should report a failure" do
expect { exec_tester('false', 1).refresh }.
to raise_error(Puppet::Error, /^false returned 1 instead of/)
end
it "should not report a failure if the exit status is specified in a returns array" do
expect { exec_tester("false", 1, :returns => [0, 1]).refresh }.to_not raise_error
end
it "should report a failure if the exit status is not specified in a returns array" do
expect { exec_tester('false', 1, :returns => [0, 100]).refresh }.
to raise_error(Puppet::Error, /^false returned 1 instead of/)
end
it "should log the output on success" do
output = "output1\noutput2\n"
exec_tester('false', 0, :output => output, :logoutput => true).refresh
output.split("\n").each do |line|
log = @logs.shift
- log.level.should == :err
- log.message.should == line
+ expect(log.level).to eq(:err)
+ expect(log.message).to eq(line)
end
end
it "should log the output on failure" do
output = "output1\noutput2\n"
expect { exec_tester('false', 1, :output => output, :logoutput => true).refresh }.
to raise_error(Puppet::Error)
output.split("\n").each do |line|
log = @logs.shift
- log.level.should == :err
- log.message.should == line
+ expect(log.level).to eq(:err)
+ expect(log.message).to eq(line)
end
end
end
describe "when logoutput=>on_failure is set" do
it "should log the output on failure" do
output = "output1\noutput2\n"
expect { exec_tester('false', 1, :output => output, :logoutput => :on_failure).refresh }.
to raise_error(Puppet::Error, /^false returned 1 instead of/)
output.split("\n").each do |line|
log = @logs.shift
- log.level.should == :err
- log.message.should == line
+ expect(log.level).to eq(:err)
+ expect(log.message).to eq(line)
end
end
it "should log the output on failure when returns is specified as an array" do
output = "output1\noutput2\n"
expect {
exec_tester('false', 1, :output => output, :returns => [0, 100],
:logoutput => :on_failure).refresh
}.to raise_error(Puppet::Error, /^false returned 1 instead of/)
output.split("\n").each do |line|
log = @logs.shift
- log.level.should == :err
- log.message.should == line
+ expect(log.level).to eq(:err)
+ expect(log.message).to eq(line)
end
end
it "shouldn't log the output on success" do
exec_tester('true', 0, :output => "a\nb\nc\n", :logoutput => :on_failure).refresh
- @logs.should == []
+ expect(@logs).to eq([])
end
end
it "shouldn't log the output on success when non-zero exit status is in a returns array" do
exec_tester("true", 100, :output => "a\n", :logoutput => :on_failure, :returns => [1, 100]).refresh
- @logs.should == []
+ expect(@logs).to eq([])
end
describe " when multiple tries are set," do
it "should repeat the command attempt 'tries' times on failure and produce an error" do
tries = 5
resource = exec_tester("false", 1, :tries => tries, :try_sleep => 0)
expect { resource.refresh }.to raise_error(Puppet::Error)
end
end
end
it "should be able to autorequire files mentioned in the command" do
foo = make_absolute('/bin/foo')
catalog = Puppet::Resource::Catalog.new
tmp = Puppet::Type.type(:file).new(:name => foo)
execer = Puppet::Type.type(:exec).new(:name => foo)
catalog.add_resource tmp
catalog.add_resource execer
dependencies = execer.autorequire(catalog)
- dependencies.collect(&:to_s).should == [Puppet::Relationship.new(tmp, execer).to_s]
+ expect(dependencies.collect(&:to_s)).to eq([Puppet::Relationship.new(tmp, execer).to_s])
end
describe "when handling the path parameter" do
expect = %w{one two three four}
{ "an array" => expect,
"a path-separator delimited list" => expect.join(File::PATH_SEPARATOR),
"both array and path-separator delimited lists" => ["one", "two#{File::PATH_SEPARATOR}three", "four"],
}.each do |test, input|
it "should accept #{test}" do
type = Puppet::Type.type(:exec).new(:name => @command, :path => input)
- type[:path].should == expect
+ expect(type[:path]).to eq(expect)
end
end
describe "on platforms where path separator is not :" do
before :each do
@old_verbosity = $VERBOSE
$VERBOSE = nil
@old_separator = File::PATH_SEPARATOR
File::PATH_SEPARATOR = 'q'
end
after :each do
File::PATH_SEPARATOR = @old_separator
$VERBOSE = @old_verbosity
end
it "should use the path separator of the current platform" do
type = Puppet::Type.type(:exec).new(:name => @command, :path => "fooqbarqbaz")
- type[:path].should == %w[foo bar baz]
+ expect(type[:path]).to eq(%w[foo bar baz])
end
end
end
describe "when setting user" do
describe "on POSIX systems", :if => Puppet.features.posix? do
it "should fail if we are not root" do
Puppet.features.stubs(:root?).returns(false)
expect {
Puppet::Type.type(:exec).new(:name => '/bin/true whatever', :user => 'input')
}.to raise_error Puppet::Error, /Parameter user failed/
end
it "accepts the current user" do
Puppet.features.stubs(:root?).returns(false)
Etc.stubs(:getpwuid).returns(Struct::Passwd.new('input'))
type = Puppet::Type.type(:exec).new(:name => '/bin/true whatever', :user => 'input')
expect(type[:user]).to eq('input')
end
['one', 2, 'root', 4294967295, 4294967296].each do |value|
it "should accept '#{value}' as user if we are root" do
Puppet.features.stubs(:root?).returns(true)
type = Puppet::Type.type(:exec).new(:name => '/bin/true whatever', :user => value)
- type[:user].should == value
+ expect(type[:user]).to eq(value)
end
end
end
describe "on Windows systems", :if => Puppet.features.microsoft_windows? do
before :each do
Puppet.features.stubs(:root?).returns(true)
end
it "should reject user parameter" do
expect {
Puppet::Type.type(:exec).new(:name => 'c:\windows\notepad.exe', :user => 'input')
}.to raise_error Puppet::Error, /Unable to execute commands as other users on Windows/
end
end
end
describe "when setting group" do
shared_examples_for "exec[:group]" do
['one', 2, 'wheel', 4294967295, 4294967296].each do |value|
it "should accept '#{value}' without error or judgement" do
type = Puppet::Type.type(:exec).new(:name => @command, :group => value)
- type[:group].should == value
+ expect(type[:group]).to eq(value)
end
end
end
describe "when running as root" do
before :each do Puppet.features.stubs(:root?).returns(true) end
it_behaves_like "exec[:group]"
end
describe "when not running as root" do
before :each do Puppet.features.stubs(:root?).returns(false) end
it_behaves_like "exec[:group]"
end
end
describe "when setting cwd" do
it_should_behave_like "all path parameters", :cwd, :array => false do
def instance(path)
# Specify shell provider so we don't have to care about command validation
Puppet::Type.type(:exec).new(:name => @executable, :cwd => path, :provider => :shell)
end
end
end
shared_examples_for "all exec command parameters" do |param|
{ "relative" => "example", "absolute" => "/bin/example" }.sort.each do |name, command|
describe "if command is #{name}" do
before :each do
@param = param
end
def test(command, valid)
if @param == :name then
instance = Puppet::Type.type(:exec).new()
else
instance = Puppet::Type.type(:exec).new(:name => @executable)
end
if valid then
instance.provider.expects(:validatecmd).returns(true)
else
instance.provider.expects(:validatecmd).raises(Puppet::Error, "from a stub")
end
instance[@param] = command
end
it "should work if the provider calls the command valid" do
expect { test(command, true) }.to_not raise_error
end
it "should fail if the provider calls the command invalid" do
expect { test(command, false) }.
to raise_error Puppet::Error, /Parameter #{@param} failed on Exec\[.*\]: from a stub/
end
end
end
end
shared_examples_for "all exec command parameters that take arrays" do |param|
describe "when given an array of inputs" do
before :each do
@test = Puppet::Type.type(:exec).new(:name => @executable)
end
it "should accept the array when all commands return valid" do
input = %w{one two three}
@test.provider.expects(:validatecmd).times(input.length).returns(true)
@test[param] = input
- @test[param].should == input
+ expect(@test[param]).to eq(input)
end
it "should reject the array when any commands return invalid" do
input = %w{one two three}
@test.provider.expects(:validatecmd).with(input.first).returns(false)
input[1..-1].each do |cmd|
@test.provider.expects(:validatecmd).with(cmd).returns(true)
end
@test[param] = input
- @test[param].should == input
+ expect(@test[param]).to eq(input)
end
it "should reject the array when all commands return invalid" do
input = %w{one two three}
@test.provider.expects(:validatecmd).times(input.length).returns(false)
@test[param] = input
- @test[param].should == input
+ expect(@test[param]).to eq(input)
end
end
end
describe "when setting command" do
subject { described_class.new(:name => @command) }
it "fails when passed an Array" do
expect { subject[:command] = [] }.to raise_error Puppet::Error, /Command must be a String/
end
it "fails when passed a Hash" do
expect { subject[:command] = {} }.to raise_error Puppet::Error, /Command must be a String/
end
end
describe "when setting refresh" do
it_should_behave_like "all exec command parameters", :refresh
end
describe "for simple parameters" do
before :each do
@exec = Puppet::Type.type(:exec).new(:name => @executable)
end
describe "when setting environment" do
{ "single values" => "foo=bar",
"multiple values" => ["foo=bar", "baz=quux"],
}.each do |name, data|
it "should accept #{name}" do
@exec[:environment] = data
- @exec[:environment].should == data
+ expect(@exec[:environment]).to eq(data)
end
end
{ "single values" => "foo",
"only values" => ["foo", "bar"],
"any values" => ["foo=bar", "baz"]
}.each do |name, data|
it "should reject #{name} without assignment" do
expect { @exec[:environment] = data }.
to raise_error Puppet::Error, /Invalid environment setting/
end
end
end
describe "when setting timeout" do
[0, 0.1, 1, 10, 4294967295].each do |valid|
it "should accept '#{valid}' as valid" do
@exec[:timeout] = valid
- @exec[:timeout].should == valid
+ expect(@exec[:timeout]).to eq(valid)
end
it "should accept '#{valid}' in an array as valid" do
@exec[:timeout] = [valid]
- @exec[:timeout].should == valid
+ expect(@exec[:timeout]).to eq(valid)
end
end
['1/2', '', 'foo', '5foo'].each do |invalid|
it "should reject '#{invalid}' as invalid" do
expect { @exec[:timeout] = invalid }.
to raise_error Puppet::Error, /The timeout must be a number/
end
it "should reject '#{invalid}' in an array as invalid" do
expect { @exec[:timeout] = [invalid] }.
to raise_error Puppet::Error, /The timeout must be a number/
end
end
it "should fail if timeout is exceeded" do
ruby_path = Puppet::Util::Execution.ruby_path()
## Leaving this commented version in here because it fails on windows, due to what appears to be
## an assumption about hash iteration order in lib/puppet/type.rb#hash2resource, where
## resource[]= will overwrite the namevar with ":name" if the iteration is in the wrong order
#sleep_exec = Puppet::Type.type(:exec).new(:name => 'exec_spec sleep command', :command => "#{ruby_path} -e 'sleep 0.02'", :timeout => '0.01')
sleep_exec = Puppet::Type.type(:exec).new(:name => "#{ruby_path} -e 'sleep 0.02'", :timeout => '0.01')
expect { sleep_exec.refresh }.to raise_error Puppet::Error, "Command exceeded timeout"
end
it "should convert timeout to a float" do
command = make_absolute('/bin/false')
resource = Puppet::Type.type(:exec).new :command => command, :timeout => "12"
- resource[:timeout].should be_a(Float)
- resource[:timeout].should == 12.0
+ expect(resource[:timeout]).to be_a(Float)
+ expect(resource[:timeout]).to eq(12.0)
end
it "should munge negative timeouts to 0.0" do
command = make_absolute('/bin/false')
resource = Puppet::Type.type(:exec).new :command => command, :timeout => "-12.0"
- resource.parameter(:timeout).value.should be_a(Float)
- resource.parameter(:timeout).value.should == 0.0
+ expect(resource.parameter(:timeout).value).to be_a(Float)
+ expect(resource.parameter(:timeout).value).to eq(0.0)
end
end
describe "when setting tries" do
[1, 10, 4294967295].each do |valid|
it "should accept '#{valid}' as valid" do
@exec[:tries] = valid
- @exec[:tries].should == valid
+ expect(@exec[:tries]).to eq(valid)
end
if "REVISIT: too much test log spam" == "a good thing" then
it "should accept '#{valid}' in an array as valid" do
pending "inconsistent, but this is not supporting arrays, unlike timeout"
@exec[:tries] = [valid]
- @exec[:tries].should == valid
+ expect(@exec[:tries]).to eq(valid)
end
end
end
[-3.5, -1, 0, 0.2, '1/2', '1_000_000', '+12', '', 'foo'].each do |invalid|
it "should reject '#{invalid}' as invalid" do
expect { @exec[:tries] = invalid }.
to raise_error Puppet::Error, /Tries must be an integer/
end
if "REVISIT: too much test log spam" == "a good thing" then
it "should reject '#{invalid}' in an array as invalid" do
pending "inconsistent, but this is not supporting arrays, unlike timeout"
expect { @exec[:tries] = [invalid] }.
to raise_error Puppet::Error, /Tries must be an integer/
end
end
end
end
describe "when setting try_sleep" do
[0, 0.2, 1, 10, 4294967295].each do |valid|
it "should accept '#{valid}' as valid" do
@exec[:try_sleep] = valid
- @exec[:try_sleep].should == valid
+ expect(@exec[:try_sleep]).to eq(valid)
end
if "REVISIT: too much test log spam" == "a good thing" then
it "should accept '#{valid}' in an array as valid" do
pending "inconsistent, but this is not supporting arrays, unlike timeout"
@exec[:try_sleep] = [valid]
- @exec[:try_sleep].should == valid
+ expect(@exec[:try_sleep]).to eq(valid)
end
end
end
{ -3.5 => "cannot be a negative number",
-1 => "cannot be a negative number",
'1/2' => 'must be a number',
'1_000_000' => 'must be a number',
'+12' => 'must be a number',
'' => 'must be a number',
'foo' => 'must be a number',
}.each do |invalid, error|
it "should reject '#{invalid}' as invalid" do
expect { @exec[:try_sleep] = invalid }.
to raise_error Puppet::Error, /try_sleep #{error}/
end
if "REVISIT: too much test log spam" == "a good thing" then
it "should reject '#{invalid}' in an array as invalid" do
pending "inconsistent, but this is not supporting arrays, unlike timeout"
expect { @exec[:try_sleep] = [invalid] }.
to raise_error Puppet::Error, /try_sleep #{error}/
end
end
end
end
describe "when setting refreshonly" do
[:true, :false].each do |value|
it "should accept '#{value}'" do
@exec[:refreshonly] = value
- @exec[:refreshonly].should == value
+ expect(@exec[:refreshonly]).to eq(value)
end
end
[1, 0, "1", "0", "yes", "y", "no", "n"].each do |value|
it "should reject '#{value}'" do
expect { @exec[:refreshonly] = value }.
to raise_error(Puppet::Error,
/Invalid value #{value.inspect}\. Valid values are true, false/
)
end
end
end
end
describe "when setting creates" do
it_should_behave_like "all path parameters", :creates, :array => true do
def instance(path)
# Specify shell provider so we don't have to care about command validation
Puppet::Type.type(:exec).new(:name => @executable, :creates => path, :provider => :shell)
end
end
end
describe "when setting unless" do
it_should_behave_like "all exec command parameters", :unless
it_should_behave_like "all exec command parameters that take arrays", :unless
end
describe "when setting onlyif" do
it_should_behave_like "all exec command parameters", :onlyif
it_should_behave_like "all exec command parameters that take arrays", :onlyif
end
describe "#check" do
before :each do
@test = Puppet::Type.type(:exec).new(:name => @executable)
end
describe ":refreshonly" do
{ :true => false, :false => true }.each do |input, result|
it "should return '#{result}' when given '#{input}'" do
@test[:refreshonly] = input
- @test.check_all_attributes.should == result
+ expect(@test.check_all_attributes).to eq(result)
end
end
end
describe ":creates" do
before :each do
@exist = tmpfile('exist')
FileUtils.touch(@exist)
@unexist = tmpfile('unexist')
end
context "with a single item" do
it "should run when the item does not exist" do
@test[:creates] = @unexist
- @test.check_all_attributes.should == true
+ expect(@test.check_all_attributes).to eq(true)
end
it "should not run when the item exists" do
@test[:creates] = @exist
- @test.check_all_attributes.should == false
+ expect(@test.check_all_attributes).to eq(false)
end
end
context "with an array with one item" do
it "should run when the item does not exist" do
@test[:creates] = [@unexist]
- @test.check_all_attributes.should == true
+ expect(@test.check_all_attributes).to eq(true)
end
it "should not run when the item exists" do
@test[:creates] = [@exist]
- @test.check_all_attributes.should == false
+ expect(@test.check_all_attributes).to eq(false)
end
end
context "with an array with multiple items" do
it "should run when all items do not exist" do
@test[:creates] = [@unexist] * 3
- @test.check_all_attributes.should == true
+ expect(@test.check_all_attributes).to eq(true)
end
it "should not run when one item exists" do
@test[:creates] = [@unexist, @exist, @unexist]
- @test.check_all_attributes.should == false
+ expect(@test.check_all_attributes).to eq(false)
end
it "should not run when all items exist" do
@test[:creates] = [@exist] * 3
end
end
end
{ :onlyif => { :pass => false, :fail => true },
:unless => { :pass => true, :fail => false },
}.each do |param, sense|
describe ":#{param}" do
before :each do
@pass = make_absolute("/magic/pass")
@fail = make_absolute("/magic/fail")
@pass_status = stub('status', :exitstatus => sense[:pass] ? 0 : 1)
@fail_status = stub('status', :exitstatus => sense[:fail] ? 0 : 1)
@test.provider.stubs(:checkexe).returns(true)
[true, false].each do |check|
@test.provider.stubs(:run).with(@pass, check).
returns(['test output', @pass_status])
@test.provider.stubs(:run).with(@fail, check).
returns(['test output', @fail_status])
end
end
context "with a single item" do
it "should run if the command exits non-zero" do
@test[param] = @fail
- @test.check_all_attributes.should == true
+ expect(@test.check_all_attributes).to eq(true)
end
it "should not run if the command exits zero" do
@test[param] = @pass
- @test.check_all_attributes.should == false
+ expect(@test.check_all_attributes).to eq(false)
end
end
context "with an array with a single item" do
it "should run if the command exits non-zero" do
@test[param] = [@fail]
- @test.check_all_attributes.should == true
+ expect(@test.check_all_attributes).to eq(true)
end
it "should not run if the command exits zero" do
@test[param] = [@pass]
- @test.check_all_attributes.should == false
+ expect(@test.check_all_attributes).to eq(false)
end
end
context "with an array with multiple items" do
it "should run if all the commands exits non-zero" do
@test[param] = [@fail] * 3
- @test.check_all_attributes.should == true
+ expect(@test.check_all_attributes).to eq(true)
end
it "should not run if one command exits zero" do
@test[param] = [@pass, @fail, @pass]
- @test.check_all_attributes.should == false
+ expect(@test.check_all_attributes).to eq(false)
end
it "should not run if all command exits zero" do
@test[param] = [@pass] * 3
- @test.check_all_attributes.should == false
+ expect(@test.check_all_attributes).to eq(false)
end
end
it "should emit output to debug" do
Puppet::Util::Log.level = :debug
@test[param] = @fail
- @test.check_all_attributes.should == true
- @logs.shift.message.should == "test output"
+ expect(@test.check_all_attributes).to eq(true)
+ expect(@logs.shift.message).to eq("test output")
end
end
end
end
describe "#retrieve" do
before :each do
@exec_resource = Puppet::Type.type(:exec).new(:name => @bogus_cmd)
end
it "should return :notrun when check_all_attributes returns true" do
@exec_resource.stubs(:check_all_attributes).returns true
- @exec_resource.retrieve[:returns].should == :notrun
+ expect(@exec_resource.retrieve[:returns]).to eq(:notrun)
end
it "should return default exit code 0 when check_all_attributes returns false" do
@exec_resource.stubs(:check_all_attributes).returns false
- @exec_resource.retrieve[:returns].should == ['0']
+ expect(@exec_resource.retrieve[:returns]).to eq(['0'])
end
it "should return the specified exit code when check_all_attributes returns false" do
@exec_resource.stubs(:check_all_attributes).returns false
@exec_resource[:returns] = 42
- @exec_resource.retrieve[:returns].should == ["42"]
+ expect(@exec_resource.retrieve[:returns]).to eq(["42"])
end
end
describe "#output" do
before :each do
@exec_resource = Puppet::Type.type(:exec).new(:name => @bogus_cmd)
end
it "should return the provider's run output" do
provider = stub 'provider'
status = stubs "process_status"
status.stubs(:exitstatus).returns("0")
provider.expects(:run).returns(["silly output", status])
@exec_resource.stubs(:provider).returns(provider)
@exec_resource.refresh
- @exec_resource.output.should == 'silly output'
+ expect(@exec_resource.output).to eq('silly output')
end
end
describe "#refresh" do
before :each do
@exec_resource = Puppet::Type.type(:exec).new(:name => @bogus_cmd)
end
it "should call provider run with the refresh parameter if it is set" do
myother_bogus_cmd = make_absolute('/myother/bogus/cmd')
provider = stub 'provider'
@exec_resource.stubs(:provider).returns(provider)
@exec_resource.stubs(:[]).with(:refresh).returns(myother_bogus_cmd)
provider.expects(:run).with(myother_bogus_cmd)
@exec_resource.refresh
end
it "should call provider run with the specified command if the refresh parameter is not set" do
provider = stub 'provider'
status = stubs "process_status"
status.stubs(:exitstatus).returns("0")
provider.expects(:run).with(@bogus_cmd).returns(["silly output", status])
@exec_resource.stubs(:provider).returns(provider)
@exec_resource.refresh
end
it "should not run the provider if check_all_attributes is false" do
@exec_resource.stubs(:check_all_attributes).returns false
provider = stub 'provider'
provider.expects(:run).never
@exec_resource.stubs(:provider).returns(provider)
@exec_resource.refresh
end
end
describe "relative and absolute commands vs path" do
let :type do Puppet::Type.type(:exec) end
let :rel do 'echo' end
let :abs do make_absolute('/bin/echo') end
let :path do make_absolute('/bin') end
it "should fail with relative command and no path" do
expect { type.new(:command => rel) }.
to raise_error Puppet::Error, /no path was specified/
end
it "should accept a relative command with a path" do
- type.new(:command => rel, :path => path).must be
+ expect(type.new(:command => rel, :path => path)).to be
end
it "should accept an absolute command with no path" do
- type.new(:command => abs).must be
+ expect(type.new(:command => abs)).to be
end
it "should accept an absolute command with a path" do
- type.new(:command => abs, :path => path).must be
+ expect(type.new(:command => abs, :path => path)).to be
end
end
describe "when providing a umask" do
it "should fail if an invalid umask is used" do
resource = Puppet::Type.type(:exec).new :command => @command
expect { resource[:umask] = '0028'}.to raise_error(Puppet::ResourceError, /umask specification is invalid/)
expect { resource[:umask] = '28' }.to raise_error(Puppet::ResourceError, /umask specification is invalid/)
end
end
end
diff --git a/spec/unit/type/file/checksum_spec.rb b/spec/unit/type/file/checksum_spec.rb
index 6a68b8b0c..7d903e55b 100755
--- a/spec/unit/type/file/checksum_spec.rb
+++ b/spec/unit/type/file/checksum_spec.rb
@@ -1,79 +1,79 @@
#! /usr/bin/env ruby
require 'spec_helper'
checksum = Puppet::Type.type(:file).attrclass(:checksum)
describe checksum do
before do
@path = Puppet.features.microsoft_windows? ? "c:/foo/bar" : "/foo/bar"
@resource = Puppet::Type.type(:file).new :path => @path
@checksum = @resource.parameter(:checksum)
end
it "should be a parameter" do
- checksum.superclass.must == Puppet::Parameter
+ expect(checksum.superclass).to eq(Puppet::Parameter)
end
it "should use its current value when asked to sum content" do
@checksum.value = :md5lite
@checksum.expects(:md5lite).with("foobar").returns "yay"
@checksum.sum("foobar")
end
it "should use :md5 to sum when no value is set" do
@checksum.expects(:md5).with("foobar").returns "yay"
@checksum.sum("foobar")
end
it "should return the summed contents with a checksum label" do
sum = Digest::MD5.hexdigest("foobar")
@resource[:checksum] = :md5
- @checksum.sum("foobar").should == "{md5}#{sum}"
+ expect(@checksum.sum("foobar")).to eq("{md5}#{sum}")
end
it "when using digest_algorithm 'sha256' should return the summed contents with a checksum label" do
sum = Digest::SHA256.hexdigest("foobar")
@resource[:checksum] = :sha256
- @checksum.sum("foobar").should == "{sha256}#{sum}"
+ expect(@checksum.sum("foobar")).to eq("{sha256}#{sum}")
end
it "should use :md5 as its default type" do
- @checksum.default.should == :md5
+ expect(@checksum.default).to eq(:md5)
end
it "should use its current value when asked to sum a file's content" do
@checksum.value = :md5lite
@checksum.expects(:md5lite_file).with(@path).returns "yay"
@checksum.sum_file(@path)
end
it "should use :md5 to sum a file when no value is set" do
@checksum.expects(:md5_file).with(@path).returns "yay"
@checksum.sum_file(@path)
end
it "should convert all sums to strings when summing files" do
@checksum.value = :mtime
@checksum.expects(:mtime_file).with(@path).returns Time.now
- lambda { @checksum.sum_file(@path) }.should_not raise_error
+ expect { @checksum.sum_file(@path) }.not_to raise_error
end
it "should return the summed contents of a file with a checksum label" do
@resource[:checksum] = :md5
@checksum.expects(:md5_file).returns "mysum"
- @checksum.sum_file(@path).should == "{md5}mysum"
+ expect(@checksum.sum_file(@path)).to eq("{md5}mysum")
end
it "should return the summed contents of a stream with a checksum label" do
@resource[:checksum] = :md5
@checksum.expects(:md5_stream).returns "mysum"
- @checksum.sum_stream.should == "{md5}mysum"
+ expect(@checksum.sum_stream).to eq("{md5}mysum")
end
it "should yield the sum_stream block to the underlying checksum" do
@resource[:checksum] = :md5
@checksum.expects(:md5_stream).yields("something").returns("mysum")
@checksum.sum_stream do |sum|
- sum.should == "something"
+ expect(sum).to eq("something")
end
end
end
diff --git a/spec/unit/type/file/content_spec.rb b/spec/unit/type/file/content_spec.rb
index c9570955b..dfd880063 100755
--- a/spec/unit/type/file/content_spec.rb
+++ b/spec/unit/type/file/content_spec.rb
@@ -1,521 +1,521 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/http_pool'
require 'puppet/network/resolver'
describe Puppet::Type.type(:file).attrclass(:content), :uses_checksums => true do
include PuppetSpec::Files
let(:filename) { tmpfile('testfile') }
let(:environment) { Puppet::Node::Environment.create(:testing, []) }
let(:catalog) { Puppet::Resource::Catalog.new(:test, environment) }
let(:resource) { Puppet::Type.type(:file).new :path => filename, :catalog => catalog }
before do
File.open(filename, 'w') {|f| f.write "initial file content"}
described_class.stubs(:standalone?).returns(false)
end
around do |example|
Puppet.override(:environments => Puppet::Environments::Static.new(environment)) do
example.run
end
end
describe "when determining the checksum type" do
let(:content) { described_class.new(:resource => resource) }
it "should use the type specified in the source checksum if a source is set" do
resource[:source] = File.expand_path("/foo")
resource.parameter(:source).expects(:checksum).returns "{md5lite}eh"
- content.checksum_type.should == :md5lite
+ expect(content.checksum_type).to eq(:md5lite)
end
it "should use the type specified by the checksum parameter if no source is set" do
resource[:checksum] = :md5lite
- content.checksum_type.should == :md5lite
+ expect(content.checksum_type).to eq(:md5lite)
end
with_digest_algorithms do
it "should use the type specified by digest_algorithm by default" do
- content.checksum_type.should == digest_algorithm.intern
+ expect(content.checksum_type).to eq(digest_algorithm.intern)
end
end
end
describe "when determining the actual content to write" do
let(:content) { described_class.new(:resource => resource) }
it "should use the set content if available" do
content.should = "ehness"
- content.actual_content.should == "ehness"
+ expect(content.actual_content).to eq("ehness")
end
it "should not use the content from the source if the source is set" do
source = mock 'source'
resource.expects(:parameter).never.with(:source).returns source
- content.actual_content.should be_nil
+ expect(content.actual_content).to be_nil
end
end
describe "when setting the desired content" do
let(:content) { described_class.new(:resource => resource) }
it "should make the actual content available via an attribute" do
content.stubs(:checksum_type).returns "md5"
content.should = "this is some content"
- content.actual_content.should == "this is some content"
+ expect(content.actual_content).to eq("this is some content")
end
with_digest_algorithms do
it "should store the checksum as the desired content" do
d = digest("this is some content")
content.stubs(:checksum_type).returns digest_algorithm
content.should = "this is some content"
- content.should.must == "{#{digest_algorithm}}#{d}"
+ expect(content.should).to eq("{#{digest_algorithm}}#{d}")
end
it "should not checksum 'absent'" do
content.should = :absent
- content.should.must == :absent
+ expect(content.should).to eq(:absent)
end
it "should accept a checksum as the desired content" do
d = digest("this is some content")
string = "{#{digest_algorithm}}#{d}"
content.should = string
- content.should.must == string
+ expect(content.should).to eq(string)
end
end
it "should convert the value to ASCII-8BIT", :if => "".respond_to?(:encode) do
content.should= "Let's make a \u{2603}"
- content.actual_content.should == "Let's make a \xE2\x98\x83".force_encoding(Encoding::ASCII_8BIT)
+ expect(content.actual_content).to eq("Let's make a \xE2\x98\x83".force_encoding(Encoding::ASCII_8BIT))
end
end
describe "when retrieving the current content" do
let(:content) { described_class.new(:resource => resource) }
it "should return :absent if the file does not exist" do
resource.expects(:stat).returns nil
- content.retrieve.should == :absent
+ expect(content.retrieve).to eq(:absent)
end
it "should not manage content on directories" do
stat = mock 'stat', :ftype => "directory"
resource.expects(:stat).returns stat
- content.retrieve.should be_nil
+ expect(content.retrieve).to be_nil
end
it "should not manage content on links" do
stat = mock 'stat', :ftype => "link"
resource.expects(:stat).returns stat
- content.retrieve.should be_nil
+ expect(content.retrieve).to be_nil
end
it "should always return the checksum as a string" do
resource[:checksum] = :mtime
stat = mock 'stat', :ftype => "file"
resource.expects(:stat).returns stat
time = Time.now
resource.parameter(:checksum).expects(:mtime_file).with(resource[:path]).returns time
- content.retrieve.should == "{mtime}#{time}"
+ expect(content.retrieve).to eq("{mtime}#{time}")
end
with_digest_algorithms do
it "should return the checksum of the file if it exists and is a normal file" do
stat = mock 'stat', :ftype => "file"
resource.expects(:stat).returns stat
resource.parameter(:checksum).expects("#{digest_algorithm}_file".intern).with(resource[:path]).returns "mysum"
- content.retrieve.should == "{#{digest_algorithm}}mysum"
+ expect(content.retrieve).to eq("{#{digest_algorithm}}mysum")
end
end
end
describe "when testing whether the content is in sync" do
let(:content) { described_class.new(:resource => resource) }
before do
resource[:ensure] = :file
end
it "should return true if the resource shouldn't be a regular file" do
resource.expects(:should_be_file?).returns false
content.should = "foo"
- content.must be_safe_insync("whatever")
+ expect(content).to be_safe_insync("whatever")
end
it "should warn that no content will be synced to links when ensure is :present" do
resource[:ensure] = :present
resource[:content] = 'foo'
resource.stubs(:should_be_file?).returns false
resource.stubs(:stat).returns mock("stat", :ftype => "link")
resource.expects(:warning).with {|msg| msg =~ /Ensure set to :present but file type is/}
content.insync? :present
end
it "should return false if the current content is :absent" do
content.should = "foo"
- content.should_not be_safe_insync(:absent)
+ expect(content).not_to be_safe_insync(:absent)
end
it "should return false if the file should be a file but is not present" do
resource.expects(:should_be_file?).returns true
content.should = "foo"
- content.should_not be_safe_insync(:absent)
+ expect(content).not_to be_safe_insync(:absent)
end
describe "and the file exists" do
with_digest_algorithms do
before do
resource.stubs(:stat).returns mock("stat")
resource[:checksum] = digest_algorithm
content.should = "some content"
end
it "should return false if the current contents are different from the desired content" do
- content.should_not be_safe_insync("other content")
+ expect(content).not_to be_safe_insync("other content")
end
it "should return true if the sum for the current contents is the same as the sum for the desired content" do
- content.must be_safe_insync("{#{digest_algorithm}}" + digest("some content"))
+ expect(content).to be_safe_insync("{#{digest_algorithm}}" + digest("some content"))
end
[true, false].product([true, false]).each do |cfg, param|
describe "and Puppet[:show_diff] is #{cfg} and show_diff => #{param}" do
before do
Puppet[:show_diff] = cfg
resource.stubs(:show_diff?).returns param
resource[:loglevel] = "debug"
end
if cfg and param
it "should display a diff" do
content.expects(:diff).returns("my diff").once
content.expects(:debug).with("\nmy diff").once
- content.should_not be_safe_insync("other content")
+ expect(content).not_to be_safe_insync("other content")
end
else
it "should not display a diff" do
content.expects(:diff).never
- content.should_not be_safe_insync("other content")
+ expect(content).not_to be_safe_insync("other content")
end
end
end
end
end
end
describe "and :replace is false" do
before do
resource.stubs(:replace?).returns false
end
it "should be insync if the file exists and the content is different" do
resource.stubs(:stat).returns mock('stat')
- content.must be_safe_insync("whatever")
+ expect(content).to be_safe_insync("whatever")
end
it "should be insync if the file exists and the content is right" do
resource.stubs(:stat).returns mock('stat')
- content.must be_safe_insync("something")
+ expect(content).to be_safe_insync("something")
end
it "should not be insync if the file does not exist" do
content.should = "foo"
- content.should_not be_safe_insync(:absent)
+ expect(content).not_to be_safe_insync(:absent)
end
end
end
describe "when changing the content" do
let(:content) { described_class.new(:resource => resource) }
before do
resource.stubs(:[]).with(:path).returns "/boo"
resource.stubs(:stat).returns "eh"
end
it "should use the file's :write method to write the content" do
resource.expects(:write).with(:content)
content.sync
end
it "should return :file_changed if the file already existed" do
resource.expects(:stat).returns "something"
resource.stubs(:write)
- content.sync.should == :file_changed
+ expect(content.sync).to eq(:file_changed)
end
it "should return :file_created if the file did not exist" do
resource.expects(:stat).returns nil
resource.stubs(:write)
- content.sync.should == :file_created
+ expect(content.sync).to eq(:file_created)
end
end
describe "when writing" do
let(:content) { described_class.new(:resource => resource) }
let(:fh) { File.open(filename, 'wb') }
it "should attempt to read from the filebucket if no actual content nor source exists" do
content.should = "{md5}foo"
content.resource.bucket.class.any_instance.stubs(:getfile).returns "foo"
content.write(fh)
fh.close
end
describe "from actual content" do
before(:each) do
content.stubs(:actual_content).returns("this is content")
end
it "should write to the given file handle" do
fh = mock 'filehandle'
fh.expects(:print).with("this is content")
content.write(fh)
end
it "should return the current checksum value" do
resource.parameter(:checksum).expects(:sum_stream).returns "checksum"
- content.write(fh).should == "checksum"
+ expect(content.write(fh)).to eq("checksum")
end
end
describe "from a file bucket" do
it "should fail if a file bucket cannot be retrieved" do
content.should = "{md5}foo"
content.resource.expects(:bucket).returns nil
expect { content.write(fh) }.to raise_error(Puppet::Error)
end
it "should fail if the file bucket cannot find any content" do
content.should = "{md5}foo"
bucket = stub 'bucket'
content.resource.expects(:bucket).returns bucket
bucket.expects(:getfile).with("foo").raises "foobar"
expect { content.write(fh) }.to raise_error(Puppet::Error)
end
it "should write the returned content to the file" do
content.should = "{md5}foo"
bucket = stub 'bucket'
content.resource.expects(:bucket).returns bucket
bucket.expects(:getfile).with("foo").returns "mycontent"
fh = mock 'filehandle'
fh.expects(:print).with("mycontent")
content.write(fh)
end
end
describe "from local source" do
let(:source_content) { "source file content\r\n"*10 }
before(:each) do
sourcename = tmpfile('source')
resource[:backup] = false
resource[:source] = sourcename
File.open(sourcename, 'wb') {|f| f.write source_content}
# This needs to be invoked to properly initialize the content property,
# or attempting to write a file will fail.
resource.newattr(:content)
end
it "should copy content from the source to the file" do
source = resource.parameter(:source)
resource.write(source)
- Puppet::FileSystem.binread(filename).should == source_content
+ expect(Puppet::FileSystem.binread(filename)).to eq(source_content)
end
with_digest_algorithms do
it "should return the checksum computed" do
File.open(filename, 'wb') do |file|
resource[:checksum] = digest_algorithm
- content.write(file).should == "{#{digest_algorithm}}#{digest(source_content)}"
+ expect(content.write(file)).to eq("{#{digest_algorithm}}#{digest(source_content)}")
end
end
end
end
describe 'from remote source' do
let(:source_content) { "source file content\n"*10 }
let(:source) { resource.newattr(:source) }
let(:response) { stub_everything('response') }
let(:conn) { mock('connection') }
before(:each) do
resource[:backup] = false
# This needs to be invoked to properly initialize the content property,
# or attempting to write a file will fail.
resource.newattr(:content)
response.stubs(:read_body).multiple_yields(*source_content.lines)
conn.stubs(:request_get).yields(response)
end
it 'should use an explicit fileserver if source starts with puppet://' do
response.stubs(:code).returns('200')
source.stubs(:metadata).returns stub_everything('metadata', :source => 'puppet://somehostname/test/foo', :ftype => 'file')
Puppet::Network::HttpPool.expects(:http_instance).with('somehostname', anything).returns(conn)
resource.write(source)
end
it 'should use the default fileserver if source starts with puppet:///' do
response.stubs(:code).returns('200')
source.stubs(:metadata).returns stub_everything('metadata', :source => 'puppet:///test/foo', :ftype => 'file')
Puppet::Network::HttpPool.expects(:http_instance).with(Puppet.settings[:server], anything).returns(conn)
resource.write(source)
end
it 'should percent encode reserved characters' do
response.stubs(:code).returns('200')
Puppet::Network::HttpPool.stubs(:http_instance).returns(conn)
source.stubs(:metadata).returns stub_everything('metadata', :source => 'puppet:///test/foo bar', :ftype => 'file')
conn.unstub(:request_get)
conn.expects(:request_get).with("#{Puppet::Network::HTTP::MASTER_URL_PREFIX}/v3/file_content/test/foo%20bar?environment=testing&", anything).yields(response)
resource.write(source)
end
describe 'when handling file_content responses' do
before(:each) do
Puppet::Network::HttpPool.stubs(:http_instance).returns(conn)
source.stubs(:metadata).returns stub_everything('metadata', :source => 'puppet:///test/foo', :ftype => 'file')
end
it 'should not write anything if source is not found' do
response.stubs(:code).returns('404')
expect { resource.write(source) }.to raise_error(Net::HTTPError, /404/)
expect(File.read(filename)).to eq('initial file content')
end
it 'should raise an HTTP error in case of server error' do
response.stubs(:code).returns('500')
expect { resource.write(source) }.to raise_error(Net::HTTPError, /500/)
end
context 'and the request was successful' do
before(:each) { response.stubs(:code).returns '200' }
it 'should write the contents to the file' do
resource.write(source)
expect(Puppet::FileSystem.binread(filename)).to eq(source_content)
end
with_digest_algorithms do
it 'should return the checksum computed' do
File.open(filename, 'w') do |file|
resource[:checksum] = digest_algorithm
expect(content.write(file)).to eq("{#{digest_algorithm}}#{digest(source_content)}")
end
end
end
end
end
end
# These are testing the implementation rather than the desired behaviour; while that bites, there are a whole
# pile of other methods in the File type that depend on intimate details of this implementation and vice-versa.
# If these blow up, you are gonna have to review the callers to make sure they don't explode! --daniel 2011-02-01
describe "each_chunk_from should work" do
it "when content is a string" do
- content.each_chunk_from('i_am_a_string') { |chunk| chunk.should == 'i_am_a_string' }
+ content.each_chunk_from('i_am_a_string') { |chunk| expect(chunk).to eq('i_am_a_string') }
end
# The following manifest is a case where source and content.should are both set
# file { "/tmp/mydir" :
# source => '/tmp/sourcedir',
# recurse => true,
# }
it "when content checksum comes from source" do
source_param = Puppet::Type.type(:file).attrclass(:source)
source = source_param.new(:resource => resource)
content.should = "{md5}123abcd"
content.expects(:chunk_file_from_source).returns('from_source')
- content.each_chunk_from(source) { |chunk| chunk.should == 'from_source' }
+ content.each_chunk_from(source) { |chunk| expect(chunk).to eq('from_source') }
end
it "when no content, source, but ensure present" do
resource[:ensure] = :present
- content.each_chunk_from(nil) { |chunk| chunk.should == '' }
+ content.each_chunk_from(nil) { |chunk| expect(chunk).to eq('') }
end
# you might do this if you were just auditing
it "when no content, source, but ensure file" do
resource[:ensure] = :file
- content.each_chunk_from(nil) { |chunk| chunk.should == '' }
+ content.each_chunk_from(nil) { |chunk| expect(chunk).to eq('') }
end
it "when source_or_content is nil and content not a checksum" do
- content.each_chunk_from(nil) { |chunk| chunk.should == '' }
+ content.each_chunk_from(nil) { |chunk| expect(chunk).to eq('') }
end
# the content is munged so that if it's a checksum nil gets passed in
it "when content is a checksum it should try to read from filebucket" do
content.should = "{md5}123abcd"
content.expects(:read_file_from_filebucket).once.returns('im_a_filebucket')
- content.each_chunk_from(nil) { |chunk| chunk.should == 'im_a_filebucket' }
+ content.each_chunk_from(nil) { |chunk| expect(chunk).to eq('im_a_filebucket') }
end
it "when running as puppet apply" do
Puppet[:default_file_terminus] = "file_server"
source_or_content = stubs('source_or_content')
source_or_content.expects(:content).once.returns :whoo
- content.each_chunk_from(source_or_content) { |chunk| chunk.should == :whoo }
+ content.each_chunk_from(source_or_content) { |chunk| expect(chunk).to eq(:whoo) }
end
it "when running from source with a local file" do
source_or_content = stubs('source_or_content')
source_or_content.expects(:local?).returns true
content.expects(:chunk_file_from_disk).with(source_or_content).once.yields 'woot'
- content.each_chunk_from(source_or_content) { |chunk| chunk.should == 'woot' }
+ content.each_chunk_from(source_or_content) { |chunk| expect(chunk).to eq('woot') }
end
it "when running from source with a remote file" do
source_or_content = stubs('source_or_content')
source_or_content.expects(:local?).returns false
content.expects(:chunk_file_from_source).with(source_or_content).once.yields 'woot'
- content.each_chunk_from(source_or_content) { |chunk| chunk.should == 'woot' }
+ content.each_chunk_from(source_or_content) { |chunk| expect(chunk).to eq('woot') }
end
end
end
end
diff --git a/spec/unit/type/file/ctime_spec.rb b/spec/unit/type/file/ctime_spec.rb
index ecb7458bc..733883473 100755
--- a/spec/unit/type/file/ctime_spec.rb
+++ b/spec/unit/type/file/ctime_spec.rb
@@ -1,34 +1,34 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:ctime) do
require 'puppet_spec/files'
include PuppetSpec::Files
before do
@filename = tmpfile('ctime')
@resource = Puppet::Type.type(:file).new({:name => @filename})
end
it "should be able to audit the file's ctime" do
File.open(@filename, "w"){ }
@resource[:audit] = [:ctime]
# this .to_resource audit behavior is magical :-(
- @resource.to_resource[:ctime].should == Puppet::FileSystem.stat(@filename).ctime
+ expect(@resource.to_resource[:ctime]).to eq(Puppet::FileSystem.stat(@filename).ctime)
end
it "should return absent if auditing an absent file" do
@resource[:audit] = [:ctime]
- @resource.to_resource[:ctime].should == :absent
+ expect(@resource.to_resource[:ctime]).to eq(:absent)
end
it "should prevent the user from trying to set the ctime" do
- lambda {
+ expect {
@resource[:ctime] = Time.now.to_s
- }.should raise_error(Puppet::Error, /ctime is read-only/)
+ }.to raise_error(Puppet::Error, /ctime is read-only/)
end
end
diff --git a/spec/unit/type/file/ensure_spec.rb b/spec/unit/type/file/ensure_spec.rb
index 0198b06d3..91049c2b4 100755
--- a/spec/unit/type/file/ensure_spec.rb
+++ b/spec/unit/type/file/ensure_spec.rb
@@ -1,123 +1,123 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/type/file/ensure'
describe Puppet::Type::File::Ensure do
include PuppetSpec::Files
let(:path) { tmpfile('file_ensure') }
let(:resource) { Puppet::Type.type(:file).new(:ensure => 'file', :path => path, :replace => true) }
let(:property) { resource.property(:ensure) }
it "should be a subclass of Ensure" do
- described_class.superclass.must == Puppet::Property::Ensure
+ expect(described_class.superclass).to eq(Puppet::Property::Ensure)
end
describe "when retrieving the current state" do
it "should return :absent if the file does not exist" do
resource.expects(:stat).returns nil
- property.retrieve.should == :absent
+ expect(property.retrieve).to eq(:absent)
end
it "should return the current file type if the file exists" do
stat = mock 'stat', :ftype => "directory"
resource.expects(:stat).returns stat
- property.retrieve.should == :directory
+ expect(property.retrieve).to eq(:directory)
end
end
describe "when testing whether :ensure is in sync" do
it "should always be in sync if replace is 'false' unless the file is missing" do
property.should = :file
resource.expects(:replace?).returns false
- property.safe_insync?(:link).should be_true
+ expect(property.safe_insync?(:link)).to be_truthy
end
it "should be in sync if :ensure is set to :absent and the file does not exist" do
property.should = :absent
- property.must be_safe_insync(:absent)
+ expect(property).to be_safe_insync(:absent)
end
it "should not be in sync if :ensure is set to :absent and the file exists" do
property.should = :absent
- property.should_not be_safe_insync(:file)
+ expect(property).not_to be_safe_insync(:file)
end
it "should be in sync if a normal file exists and :ensure is set to :present" do
property.should = :present
- property.must be_safe_insync(:file)
+ expect(property).to be_safe_insync(:file)
end
it "should be in sync if a directory exists and :ensure is set to :present" do
property.should = :present
- property.must be_safe_insync(:directory)
+ expect(property).to be_safe_insync(:directory)
end
it "should be in sync if a symlink exists and :ensure is set to :present" do
property.should = :present
- property.must be_safe_insync(:link)
+ expect(property).to be_safe_insync(:link)
end
it "should not be in sync if :ensure is set to :file and a directory exists" do
property.should = :file
- property.should_not be_safe_insync(:directory)
+ expect(property).not_to be_safe_insync(:directory)
end
end
describe "#sync" do
context "directory" do
before :each do
resource[:ensure] = :directory
end
it "should raise if the parent directory doesn't exist" do
newpath = File.join(path, 'nonexistentparent', 'newdir')
resource[:path] = newpath
expect {
property.sync
}.to raise_error(Puppet::Error, /Cannot create #{newpath}; parent directory #{File.dirname(newpath)} does not exist/)
end
it "should accept octal mode as fixnum" do
resource[:mode] = '0700'
resource.expects(:property_fix)
Dir.expects(:mkdir).with(path, 0700)
property.sync
end
it "should accept octal mode as string" do
resource[:mode] = "700"
resource.expects(:property_fix)
Dir.expects(:mkdir).with(path, 0700)
property.sync
end
it "should accept octal mode as string with leading zero" do
resource[:mode] = "0700"
resource.expects(:property_fix)
Dir.expects(:mkdir).with(path, 0700)
property.sync
end
it "should accept symbolic mode" do
resource[:mode] = "u=rwx,go=x"
resource.expects(:property_fix)
Dir.expects(:mkdir).with(path, 0711)
property.sync
end
end
end
end
diff --git a/spec/unit/type/file/group_spec.rb b/spec/unit/type/file/group_spec.rb
index c2a38d07b..031c01ad4 100755
--- a/spec/unit/type/file/group_spec.rb
+++ b/spec/unit/type/file/group_spec.rb
@@ -1,60 +1,60 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:group) do
include PuppetSpec::Files
let(:path) { tmpfile('mode_spec') }
let(:resource) { Puppet::Type.type(:file).new :path => path, :group => 'users' }
let(:group) { resource.property(:group) }
before :each do
# If the provider was already loaded without root, it won't have the
# feature, so we have to add it here to test.
Puppet::Type.type(:file).defaultprovider.has_feature :manages_ownership
end
describe "#insync?" do
before :each do
resource[:group] = ['foos', 'bars']
resource.provider.stubs(:name2gid).with('foos').returns 1001
resource.provider.stubs(:name2gid).with('bars').returns 1002
end
it "should fail if a group's id can't be found by name" do
resource.provider.stubs(:name2gid).returns nil
expect { group.insync?(5) }.to raise_error(/Could not find group foos/)
end
it "should use the id for comparisons, not the name" do
- group.insync?('foos').should be_false
+ expect(group.insync?('foos')).to be_falsey
end
it "should return true if the current group is one of the desired group" do
- group.insync?(1001).should be_true
+ expect(group.insync?(1001)).to be_truthy
end
it "should return false if the current group is not one of the desired group" do
- group.insync?(1003).should be_false
+ expect(group.insync?(1003)).to be_falsey
end
end
%w[is_to_s should_to_s].each do |prop_to_s|
describe "##{prop_to_s}" do
it "should use the name of the user if it can find it" do
resource.provider.stubs(:gid2name).with(1001).returns 'foos'
- group.send(prop_to_s, 1001).should == 'foos'
+ expect(group.send(prop_to_s, 1001)).to eq('foos')
end
it "should use the id of the user if it can't" do
resource.provider.stubs(:gid2name).with(1001).returns nil
- group.send(prop_to_s, 1001).should == 1001
+ expect(group.send(prop_to_s, 1001)).to eq(1001)
end
end
end
end
diff --git a/spec/unit/type/file/mode_spec.rb b/spec/unit/type/file/mode_spec.rb
index 536138510..038c9e13c 100755
--- a/spec/unit/type/file/mode_spec.rb
+++ b/spec/unit/type/file/mode_spec.rb
@@ -1,222 +1,222 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:mode) do
include PuppetSpec::Files
let(:path) { tmpfile('mode_spec') }
let(:resource) { Puppet::Type.type(:file).new :path => path, :mode => '0644' }
let(:mode) { resource.property(:mode) }
describe "#validate" do
it "should reject non-string values" do
expect {
mode.value = 0755
}.to raise_error(Puppet::Error, /The file mode specification must be a string, not 'Fixnum'/)
end
it "should accept values specified as octal numbers in strings" do
expect { mode.value = '0755' }.not_to raise_error
end
it "should accept valid symbolic strings" do
expect { mode.value = 'g+w,u-x' }.not_to raise_error
end
it "should not accept strings other than octal numbers" do
expect do
mode.value = 'readable please!'
end.to raise_error(Puppet::Error, /The file mode specification is invalid/)
end
end
describe "#munge" do
# This is sort of a redundant test, but its spec is important.
it "should return the value as a string" do
- mode.munge('0644').should be_a(String)
+ expect(mode.munge('0644')).to be_a(String)
end
it "should accept strings as arguments" do
- mode.munge('0644').should == '644'
+ expect(mode.munge('0644')).to eq('644')
end
it "should accept symbolic strings as arguments and return them intact" do
- mode.munge('u=rw,go=r').should == 'u=rw,go=r'
+ expect(mode.munge('u=rw,go=r')).to eq('u=rw,go=r')
end
it "should accept integers are arguments" do
- mode.munge(0644).should == '644'
+ expect(mode.munge(0644)).to eq('644')
end
end
describe "#dirmask" do
before :each do
Dir.mkdir(path)
end
it "should add execute bits corresponding to read bits for directories" do
- mode.dirmask('0644').should == '755'
+ expect(mode.dirmask('0644')).to eq('755')
end
it "should not add an execute bit when there is no read bit" do
- mode.dirmask('0600').should == '700'
+ expect(mode.dirmask('0600')).to eq('700')
end
it "should not add execute bits for files that aren't directories" do
resource[:path] = tmpfile('other_file')
- mode.dirmask('0644').should == '0644'
+ expect(mode.dirmask('0644')).to eq('0644')
end
end
describe "#insync?" do
it "should return true if the mode is correct" do
FileUtils.touch(path)
- mode.must be_insync('644')
+ expect(mode).to be_insync('644')
end
it "should return false if the mode is incorrect" do
FileUtils.touch(path)
- mode.must_not be_insync('755')
+ expect(mode).to_not be_insync('755')
end
it "should return true if the file is a link and we are managing links", :if => Puppet.features.manages_symlinks? do
Puppet::FileSystem.symlink('anything', path)
- mode.must be_insync('644')
+ expect(mode).to be_insync('644')
end
describe "with a symbolic mode" do
let(:resource_sym) { Puppet::Type.type(:file).new :path => path, :mode => 'u+w,g-w' }
let(:mode_sym) { resource_sym.property(:mode) }
it "should return true if the mode matches, regardless of other bits" do
FileUtils.touch(path)
- mode_sym.must be_insync('644')
+ expect(mode_sym).to be_insync('644')
end
it "should return false if the mode requires 0's where there are 1's" do
FileUtils.touch(path)
- mode_sym.must_not be_insync('624')
+ expect(mode_sym).to_not be_insync('624')
end
it "should return false if the mode requires 1's where there are 0's" do
FileUtils.touch(path)
- mode_sym.must_not be_insync('044')
+ expect(mode_sym).to_not be_insync('044')
end
end
end
describe "#retrieve" do
it "should return absent if the resource doesn't exist" do
resource[:path] = File.expand_path("/does/not/exist")
- mode.retrieve.should == :absent
+ expect(mode.retrieve).to eq(:absent)
end
it "should retrieve the directory mode from the provider" do
Dir.mkdir(path)
mode.expects(:dirmask).with('644').returns '755'
resource.provider.expects(:mode).returns '755'
- mode.retrieve.should == '755'
+ expect(mode.retrieve).to eq('755')
end
it "should retrieve the file mode from the provider" do
FileUtils.touch(path)
mode.expects(:dirmask).with('644').returns '644'
resource.provider.expects(:mode).returns '644'
- mode.retrieve.should == '644'
+ expect(mode.retrieve).to eq('644')
end
end
describe '#should_to_s' do
describe 'with a 3-digit mode' do
it 'returns a 4-digit mode with a leading zero' do
- mode.should_to_s('755').should == '0755'
+ expect(mode.should_to_s('755')).to eq('0755')
end
end
describe 'with a 4-digit mode' do
it 'returns the 4-digit mode when the first digit is a zero' do
- mode.should_to_s('0755').should == '0755'
+ expect(mode.should_to_s('0755')).to eq('0755')
end
it 'returns the 4-digit mode when the first digit is not a zero' do
- mode.should_to_s('1755').should == '1755'
+ expect(mode.should_to_s('1755')).to eq('1755')
end
end
end
describe '#is_to_s' do
describe 'with a 3-digit mode' do
it 'returns a 4-digit mode with a leading zero' do
- mode.is_to_s('755').should == '0755'
+ expect(mode.is_to_s('755')).to eq('0755')
end
end
describe 'with a 4-digit mode' do
it 'returns the 4-digit mode when the first digit is a zero' do
- mode.is_to_s('0755').should == '0755'
+ expect(mode.is_to_s('0755')).to eq('0755')
end
it 'returns the 4-digit mode when the first digit is not a zero' do
- mode.is_to_s('1755').should == '1755'
+ expect(mode.is_to_s('1755')).to eq('1755')
end
end
describe 'when passed :absent' do
it 'returns :absent' do
- mode.is_to_s(:absent).should == :absent
+ expect(mode.is_to_s(:absent)).to eq(:absent)
end
end
end
describe "#sync with a symbolic mode" do
let(:resource_sym) { Puppet::Type.type(:file).new :path => path, :mode => 'u+w,g-w' }
let(:mode_sym) { resource_sym.property(:mode) }
before { FileUtils.touch(path) }
it "changes only the requested bits" do
# lower nibble must be set to 4 for the sake of passing on Windows
Puppet::FileSystem.chmod(0464, path)
mode_sym.sync
stat = Puppet::FileSystem.stat(path)
- (stat.mode & 0777).to_s(8).should == "644"
+ expect((stat.mode & 0777).to_s(8)).to eq("644")
end
end
describe '#sync with a symbolic mode of +X for a file' do
let(:resource_sym) { Puppet::Type.type(:file).new :path => path, :mode => 'g+wX' }
let(:mode_sym) { resource_sym.property(:mode) }
before { FileUtils.touch(path) }
it 'does not change executable bit if no executable bit is set' do
Puppet::FileSystem.chmod(0644, path)
mode_sym.sync
stat = Puppet::FileSystem.stat(path)
- (stat.mode & 0777).to_s(8).should == '664'
+ expect((stat.mode & 0777).to_s(8)).to eq('664')
end
it 'does change executable bit if an executable bit is set' do
Puppet::FileSystem.chmod(0744, path)
mode_sym.sync
stat = Puppet::FileSystem.stat(path)
- (stat.mode & 0777).to_s(8).should == '774'
+ expect((stat.mode & 0777).to_s(8)).to eq('774')
end
end
end
diff --git a/spec/unit/type/file/mtime_spec.rb b/spec/unit/type/file/mtime_spec.rb
index 5456ec38b..836a71d8b 100755
--- a/spec/unit/type/file/mtime_spec.rb
+++ b/spec/unit/type/file/mtime_spec.rb
@@ -1,34 +1,34 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:mtime) do
require 'puppet_spec/files'
include PuppetSpec::Files
before do
@filename = tmpfile('mtime')
@resource = Puppet::Type.type(:file).new({:name => @filename})
end
it "should be able to audit the file's mtime" do
File.open(@filename, "w"){ }
@resource[:audit] = [:mtime]
# this .to_resource audit behavior is magical :-(
- @resource.to_resource[:mtime].should == Puppet::FileSystem.stat(@filename).mtime
+ expect(@resource.to_resource[:mtime]).to eq(Puppet::FileSystem.stat(@filename).mtime)
end
it "should return absent if auditing an absent file" do
@resource[:audit] = [:mtime]
- @resource.to_resource[:mtime].should == :absent
+ expect(@resource.to_resource[:mtime]).to eq(:absent)
end
it "should prevent the user from trying to set the mtime" do
- lambda {
+ expect {
@resource[:mtime] = Time.now.to_s
- }.should raise_error(Puppet::Error, /mtime is read-only/)
+ }.to raise_error(Puppet::Error, /mtime is read-only/)
end
end
diff --git a/spec/unit/type/file/owner_spec.rb b/spec/unit/type/file/owner_spec.rb
index 3a628b2c4..ea193a6be 100755
--- a/spec/unit/type/file/owner_spec.rb
+++ b/spec/unit/type/file/owner_spec.rb
@@ -1,58 +1,58 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:owner) do
include PuppetSpec::Files
let(:path) { tmpfile('mode_spec') }
let(:resource) { Puppet::Type.type(:file).new :path => path, :owner => 'joeuser' }
let(:owner) { resource.property(:owner) }
before :each do
Puppet.features.stubs(:root?).returns(true)
end
describe "#insync?" do
before :each do
resource[:owner] = ['foo', 'bar']
resource.provider.stubs(:name2uid).with('foo').returns 1001
resource.provider.stubs(:name2uid).with('bar').returns 1002
end
it "should fail if an owner's id can't be found by name" do
resource.provider.stubs(:name2uid).returns nil
expect { owner.insync?(5) }.to raise_error(/Could not find user foo/)
end
it "should use the id for comparisons, not the name" do
- owner.insync?('foo').should be_false
+ expect(owner.insync?('foo')).to be_falsey
end
it "should return true if the current owner is one of the desired owners" do
- owner.insync?(1001).should be_true
+ expect(owner.insync?(1001)).to be_truthy
end
it "should return false if the current owner is not one of the desired owners" do
- owner.insync?(1003).should be_false
+ expect(owner.insync?(1003)).to be_falsey
end
end
%w[is_to_s should_to_s].each do |prop_to_s|
describe "##{prop_to_s}" do
it "should use the name of the user if it can find it" do
resource.provider.stubs(:uid2name).with(1001).returns 'foo'
- owner.send(prop_to_s, 1001).should == 'foo'
+ expect(owner.send(prop_to_s, 1001)).to eq('foo')
end
it "should use the id of the user if it can't" do
resource.provider.stubs(:uid2name).with(1001).returns nil
- owner.send(prop_to_s, 1001).should == 1001
+ expect(owner.send(prop_to_s, 1001)).to eq(1001)
end
end
end
end
diff --git a/spec/unit/type/file/selinux_spec.rb b/spec/unit/type/file/selinux_spec.rb
index e9973c535..6a77b2627 100755
--- a/spec/unit/type/file/selinux_spec.rb
+++ b/spec/unit/type/file/selinux_spec.rb
@@ -1,89 +1,89 @@
#! /usr/bin/env ruby
require 'spec_helper'
[:seluser, :selrole, :seltype, :selrange].each do |param|
property = Puppet::Type.type(:file).attrclass(param)
describe property do
include PuppetSpec::Files
before do
@path = make_absolute("/my/file")
@resource = Puppet::Type.type(:file).new :path => @path
@sel = property.new :resource => @resource
end
it "retrieve on #{param} should return :absent if the file isn't statable" do
@resource.expects(:stat).returns nil
- @sel.retrieve.should == :absent
+ expect(@sel.retrieve).to eq(:absent)
end
it "should retrieve nil for #{param} if there is no SELinux support" do
stat = stub 'stat', :ftype => "foo"
@resource.expects(:stat).returns stat
@sel.expects(:get_selinux_current_context).with(@path).returns nil
- @sel.retrieve.should be_nil
+ expect(@sel.retrieve).to be_nil
end
it "should retrieve #{param} if a SELinux context is found with a range" do
stat = stub 'stat', :ftype => "foo"
@resource.expects(:stat).returns stat
@sel.expects(:get_selinux_current_context).with(@path).returns "user_u:role_r:type_t:s0"
expectedresult = case param
when :seluser; "user_u"
when :selrole; "role_r"
when :seltype; "type_t"
when :selrange; "s0"
end
- @sel.retrieve.should == expectedresult
+ expect(@sel.retrieve).to eq(expectedresult)
end
it "should retrieve #{param} if a SELinux context is found without a range" do
stat = stub 'stat', :ftype => "foo"
@resource.expects(:stat).returns stat
@sel.expects(:get_selinux_current_context).with(@path).returns "user_u:role_r:type_t"
expectedresult = case param
when :seluser; "user_u"
when :selrole; "role_r"
when :seltype; "type_t"
when :selrange; nil
end
- @sel.retrieve.should == expectedresult
+ expect(@sel.retrieve).to eq(expectedresult)
end
it "should handle no default gracefully" do
@sel.expects(:get_selinux_default_context).with(@path).returns nil
- @sel.default.must be_nil
+ expect(@sel.default).to be_nil
end
it "should be able to detect matchpathcon defaults" do
@sel.stubs(:debug)
@sel.expects(:get_selinux_default_context).with(@path).returns "user_u:role_r:type_t:s0"
expectedresult = case param
when :seluser; "user_u"
when :selrole; "role_r"
when :seltype; "type_t"
when :selrange; "s0"
end
- @sel.default.must == expectedresult
+ expect(@sel.default).to eq(expectedresult)
end
it "should return nil for defaults if selinux_ignore_defaults is true" do
@resource[:selinux_ignore_defaults] = :true
- @sel.default.must be_nil
+ expect(@sel.default).to be_nil
end
it "should be able to set a new context" do
stat = stub 'stat', :ftype => "foo"
@sel.should = %w{newone}
@sel.expects(:set_selinux_context).with(@path, ["newone"], param)
@sel.sync
end
it "should do nothing for safe_insync? if no SELinux support" do
@sel.should = %{newcontext}
@sel.expects(:selinux_support?).returns false
- @sel.safe_insync?("oldcontext").should == true
+ expect(@sel.safe_insync?("oldcontext")).to eq(true)
end
end
end
diff --git a/spec/unit/type/file/source_spec.rb b/spec/unit/type/file/source_spec.rb
index 26fc4a8b0..451b3d9d1 100755
--- a/spec/unit/type/file/source_spec.rb
+++ b/spec/unit/type/file/source_spec.rb
@@ -1,560 +1,560 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'uri'
source = Puppet::Type.type(:file).attrclass(:source)
describe Puppet::Type.type(:file).attrclass(:source) do
include PuppetSpec::Files
around :each do |example|
Puppet.override(:environments => Puppet::Environments::Static.new) do
example.run
end
end
before do
# Wow that's a messy interface to the resource.
@environment = Puppet::Node::Environment.remote("myenv")
@resource = stub 'resource', :[]= => nil, :property => nil, :catalog => Puppet::Resource::Catalog.new(nil, @environment), :line => 0, :file => ''
@foobar = make_absolute("/foo/bar baz")
@feebooz = make_absolute("/fee/booz baz")
@foobar_uri = URI.unescape(Puppet::Util.path_to_uri(@foobar).to_s)
@feebooz_uri = URI.unescape(Puppet::Util.path_to_uri(@feebooz).to_s)
end
it "should be a subclass of Parameter" do
- source.superclass.must == Puppet::Parameter
+ expect(source.superclass).to eq(Puppet::Parameter)
end
describe "#validate" do
let(:path) { tmpfile('file_source_validate') }
let(:resource) { Puppet::Type.type(:file).new(:path => path) }
it "should fail if the set values are not URLs" do
URI.expects(:parse).with('foo').raises RuntimeError
- lambda { resource[:source] = %w{foo} }.must raise_error(Puppet::Error)
+ expect(lambda { resource[:source] = %w{foo} }).to raise_error(Puppet::Error)
end
it "should fail if the URI is not a local file, file URI, or puppet URI" do
- lambda { resource[:source] = %w{http://foo/bar} }.must raise_error(Puppet::Error, /Cannot use URLs of type 'http' as source for fileserving/)
+ expect(lambda { resource[:source] = %w{http://foo/bar} }).to raise_error(Puppet::Error, /Cannot use URLs of type 'http' as source for fileserving/)
end
it "should strip trailing forward slashes", :unless => Puppet.features.microsoft_windows? do
resource[:source] = "/foo/bar\\//"
- resource[:source].should == %w{file:/foo/bar\\}
+ expect(resource[:source]).to eq(%w{file:/foo/bar\\})
end
it "should strip trailing forward and backslashes", :if => Puppet.features.microsoft_windows? do
resource[:source] = "X:/foo/bar\\//"
- resource[:source].should == %w{file:/X:/foo/bar}
+ expect(resource[:source]).to eq(%w{file:/X:/foo/bar})
end
it "should accept an array of sources" do
resource[:source] = %w{file:///foo/bar puppet://host:8140/foo/bar}
- resource[:source].should == %w{file:///foo/bar puppet://host:8140/foo/bar}
+ expect(resource[:source]).to eq(%w{file:///foo/bar puppet://host:8140/foo/bar})
end
it "should accept file path characters that are not valid in URI" do
resource[:source] = 'file:///foo bar'
end
it "should reject relative URI sources" do
- lambda { resource[:source] = 'foo/bar' }.must raise_error(Puppet::Error)
+ expect(lambda { resource[:source] = 'foo/bar' }).to raise_error(Puppet::Error)
end
it "should reject opaque sources" do
- lambda { resource[:source] = 'mailto:foo@com' }.must raise_error(Puppet::Error)
+ expect(lambda { resource[:source] = 'mailto:foo@com' }).to raise_error(Puppet::Error)
end
it "should accept URI authority component" do
resource[:source] = 'file://host/foo'
- resource[:source].should == %w{file://host/foo}
+ expect(resource[:source]).to eq(%w{file://host/foo})
end
it "should accept when URI authority is absent" do
resource[:source] = 'file:///foo/bar'
- resource[:source].should == %w{file:///foo/bar}
+ expect(resource[:source]).to eq(%w{file:///foo/bar})
end
end
describe "#munge" do
let(:path) { tmpfile('file_source_munge') }
let(:resource) { Puppet::Type.type(:file).new(:path => path) }
it "should prefix file scheme to absolute paths" do
resource[:source] = path
- resource[:source].should == [URI.unescape(Puppet::Util.path_to_uri(path).to_s)]
+ expect(resource[:source]).to eq([URI.unescape(Puppet::Util.path_to_uri(path).to_s)])
end
%w[file puppet].each do |scheme|
it "should not prefix valid #{scheme} URIs" do
resource[:source] = "#{scheme}:///foo bar"
- resource[:source].should == ["#{scheme}:///foo bar"]
+ expect(resource[:source]).to eq(["#{scheme}:///foo bar"])
end
end
end
describe "when returning the metadata" do
before do
@metadata = stub 'metadata', :source= => nil
@resource.stubs(:[]).with(:links).returns :manage
@resource.stubs(:[]).with(:source_permissions).returns :use
end
it "should return already-available metadata" do
@source = source.new(:resource => @resource)
@source.metadata = "foo"
- @source.metadata.should == "foo"
+ expect(@source.metadata).to eq("foo")
end
it "should return nil if no @should value is set and no metadata is available" do
@source = source.new(:resource => @resource)
- @source.metadata.should be_nil
+ expect(@source.metadata).to be_nil
end
it "should collect its metadata using the Metadata class if it is not already set" do
@source = source.new(:resource => @resource, :value => @foobar)
Puppet::FileServing::Metadata.indirection.expects(:find).with do |uri, options|
expect(uri).to eq @foobar_uri
expect(options[:environment]).to eq @environment
expect(options[:links]).to eq :manage
end.returns @metadata
@source.metadata
end
it "should use the metadata from the first found source" do
metadata = stub 'metadata', :source= => nil
@source = source.new(:resource => @resource, :value => [@foobar, @feebooz])
options = {
:environment => @environment,
:links => :manage,
:source_permissions => :use
}
Puppet::FileServing::Metadata.indirection.expects(:find).with(@foobar_uri, options).returns nil
Puppet::FileServing::Metadata.indirection.expects(:find).with(@feebooz_uri, options).returns metadata
- @source.metadata.should equal(metadata)
+ expect(@source.metadata).to equal(metadata)
end
it "should store the found source as the metadata's source" do
metadata = mock 'metadata'
@source = source.new(:resource => @resource, :value => @foobar)
Puppet::FileServing::Metadata.indirection.expects(:find).with do |uri, options|
expect(uri).to eq @foobar_uri
expect(options[:environment]).to eq @environment
expect(options[:links]).to eq :manage
end.returns metadata
metadata.expects(:source=).with(@foobar_uri)
@source.metadata
end
it "should fail intelligently if an exception is encountered while querying for metadata" do
@source = source.new(:resource => @resource, :value => @foobar)
Puppet::FileServing::Metadata.indirection.expects(:find).with do |uri, options|
expect(uri).to eq @foobar_uri
expect(options[:environment]).to eq @environment
expect(options[:links]).to eq :manage
end.raises RuntimeError
@source.expects(:fail).raises ArgumentError
- lambda { @source.metadata }.should raise_error(ArgumentError)
+ expect { @source.metadata }.to raise_error(ArgumentError)
end
it "should fail if no specified sources can be found" do
@source = source.new(:resource => @resource, :value => @foobar)
Puppet::FileServing::Metadata.indirection.expects(:find).with do |uri, options|
expect(uri).to eq @foobar_uri
expect(options[:environment]).to eq @environment
expect(options[:links]).to eq :manage
end.returns nil
@source.expects(:fail).raises RuntimeError
- lambda { @source.metadata }.should raise_error(RuntimeError)
+ expect { @source.metadata }.to raise_error(RuntimeError)
end
end
it "should have a method for setting the desired values on the resource" do
- source.new(:resource => @resource).must respond_to(:copy_source_values)
+ expect(source.new(:resource => @resource)).to respond_to(:copy_source_values)
end
describe "when copying the source values" do
before :each do
@resource = Puppet::Type.type(:file).new :path => @foobar
@source = source.new(:resource => @resource)
@metadata = stub 'metadata', :owner => 100, :group => 200, :mode => "173", :checksum => "{md5}asdfasdf", :ftype => "file", :source => @foobar
@source.stubs(:metadata).returns @metadata
Puppet.features.stubs(:root?).returns true
end
it "should not issue an error - except on Windows - if the source mode value is a Numeric" do
@metadata.stubs(:mode).returns 0173
@resource[:source_permissions] = :use
if Puppet::Util::Platform.windows?
expect { @source.copy_source_values }.to raise_error("Copying owner/mode/group from the source file on Windows is not supported; use source_permissions => ignore.")
else
expect { @source.copy_source_values }.not_to raise_error
end
end
it "should not issue an error - except on Windows - if the source mode value is a String" do
@metadata.stubs(:mode).returns "173"
@resource[:source_permissions] = :use
if Puppet::Util::Platform.windows?
expect { @source.copy_source_values }.to raise_error("Copying owner/mode/group from the source file on Windows is not supported; use source_permissions => ignore.")
else
expect { @source.copy_source_values }.not_to raise_error
end
end
it "should fail if there is no metadata" do
@source.stubs(:metadata).returns nil
@source.expects(:devfail).raises ArgumentError
- lambda { @source.copy_source_values }.should raise_error(ArgumentError)
+ expect { @source.copy_source_values }.to raise_error(ArgumentError)
end
it "should set :ensure to the file type" do
@metadata.stubs(:ftype).returns "file"
@source.copy_source_values
- @resource[:ensure].must == :file
+ expect(@resource[:ensure]).to eq(:file)
end
it "should not set 'ensure' if it is already set to 'absent'" do
@metadata.stubs(:ftype).returns "file"
@resource[:ensure] = :absent
@source.copy_source_values
- @resource[:ensure].must == :absent
+ expect(@resource[:ensure]).to eq(:absent)
end
describe "and the source is a file" do
before do
@metadata.stubs(:ftype).returns "file"
Puppet.features.stubs(:microsoft_windows?).returns false
end
context "when source_permissions is `use`" do
before :each do
@resource[:source_permissions] = "use"
end
it "should copy the metadata's owner, group, checksum, and mode to the resource if they are not set on the resource" do
@source.copy_source_values
- @resource[:owner].must == 100
- @resource[:group].must == 200
- @resource[:mode].must == "173"
+ expect(@resource[:owner]).to eq(100)
+ expect(@resource[:group]).to eq(200)
+ expect(@resource[:mode]).to eq("173")
# Metadata calls it checksum, we call it content.
- @resource[:content].must == @metadata.checksum
+ expect(@resource[:content]).to eq(@metadata.checksum)
end
it "should not copy the metadata's owner, group, checksum and mode to the resource if they are already set" do
@resource[:owner] = 1
@resource[:group] = 2
@resource[:mode] = '173'
@resource[:content] = "foobar"
@source.copy_source_values
- @resource[:owner].must == 1
- @resource[:group].must == 2
- @resource[:mode].must == '173'
- @resource[:content].should_not == @metadata.checksum
+ expect(@resource[:owner]).to eq(1)
+ expect(@resource[:group]).to eq(2)
+ expect(@resource[:mode]).to eq('173')
+ expect(@resource[:content]).not_to eq(@metadata.checksum)
end
describe "and puppet is not running as root" do
before do
Puppet.features.stubs(:root?).returns false
end
it "should not try to set the owner" do
@source.copy_source_values
- @resource[:owner].should be_nil
+ expect(@resource[:owner]).to be_nil
end
it "should not try to set the group" do
@source.copy_source_values
- @resource[:group].should be_nil
+ expect(@resource[:group]).to be_nil
end
end
end
context "when source_permissions is `use_when_creating`" do
before :each do
@resource[:source_permissions] = "use_when_creating"
Puppet.features.expects(:root?).returns true
@source.stubs(:local?).returns(false)
end
context "when managing a new file" do
it "should copy owner and group from local sources" do
@source.stubs(:local?).returns true
@source.copy_source_values
- @resource[:owner].must == 100
- @resource[:group].must == 200
- @resource[:mode].must == "173"
+ expect(@resource[:owner]).to eq(100)
+ expect(@resource[:group]).to eq(200)
+ expect(@resource[:mode]).to eq("173")
end
it "copies the remote owner" do
@source.copy_source_values
- @resource[:owner].must == 100
+ expect(@resource[:owner]).to eq(100)
end
it "copies the remote group" do
@source.copy_source_values
- @resource[:group].must == 200
+ expect(@resource[:group]).to eq(200)
end
it "copies the remote mode" do
@source.copy_source_values
- @resource[:mode].must == "173"
+ expect(@resource[:mode]).to eq("173")
end
end
context "when managing an existing file" do
before :each do
Puppet::FileSystem.stubs(:exist?).with(@resource[:path]).returns(true)
end
it "should not copy owner, group or mode from local sources" do
@source.stubs(:local?).returns true
@source.copy_source_values
- @resource[:owner].must be_nil
- @resource[:group].must be_nil
- @resource[:mode].must be_nil
+ expect(@resource[:owner]).to be_nil
+ expect(@resource[:group]).to be_nil
+ expect(@resource[:mode]).to be_nil
end
it "preserves the local owner" do
@source.copy_source_values
- @resource[:owner].must be_nil
+ expect(@resource[:owner]).to be_nil
end
it "preserves the local group" do
@source.copy_source_values
- @resource[:group].must be_nil
+ expect(@resource[:group]).to be_nil
end
it "preserves the local mode" do
@source.copy_source_values
- @resource[:mode].must be_nil
+ expect(@resource[:mode]).to be_nil
end
end
end
context "when source_permissions is default" do
before :each do
@source.stubs(:local?).returns(false)
Puppet.features.expects(:root?).returns true
end
it "should not copy owner, group or mode from local sources" do
@source.stubs(:local?).returns true
@source.copy_source_values
- @resource[:owner].must be_nil
- @resource[:group].must be_nil
- @resource[:mode].must be_nil
+ expect(@resource[:owner]).to be_nil
+ expect(@resource[:group]).to be_nil
+ expect(@resource[:mode]).to be_nil
end
it "preserves the local owner" do
@source.copy_source_values
- @resource[:owner].must be_nil
+ expect(@resource[:owner]).to be_nil
end
it "preserves the local group" do
@source.copy_source_values
- @resource[:group].must be_nil
+ expect(@resource[:group]).to be_nil
end
it "preserves the local mode" do
@source.copy_source_values
- @resource[:mode].must be_nil
+ expect(@resource[:mode]).to be_nil
end
end
describe "on Windows when source_permissions is `use`" do
before :each do
Puppet.features.stubs(:microsoft_windows?).returns true
@resource[:source_permissions] = "use"
end
let(:err_message) { "Copying owner/mode/group from the" <<
" source file on Windows is not supported;" <<
" use source_permissions => ignore." }
it "should issue error when copying from remote sources" do
@source.stubs(:local?).returns false
expect { @source.copy_source_values }.to raise_error(err_message)
end
it "should issue error when copying from local sources" do
@source.stubs(:local?).returns true
expect { @source.copy_source_values }.to raise_error(err_message)
end
it "should issue error when copying metadata from remote sources if only user is unspecified" do
@source.stubs(:local?).returns false
@resource[:group] = 2
@resource[:mode] = "0003"
expect { @source.copy_source_values }.to raise_error(err_message)
end
it "should issue error when copying metadata from remote sources if only group is unspecified" do
@source.stubs(:local?).returns false
@resource[:owner] = 1
@resource[:mode] = "0003"
expect { @source.copy_source_values }.to raise_error(err_message)
end
it "should issue error when copying metadata from remote sources if only mode is unspecified" do
@source.stubs(:local?).returns false
@resource[:owner] = 1
@resource[:group] = 2
expect { @source.copy_source_values }.to raise_error(err_message)
end
it "should not issue error when copying metadata from remote sources if group, owner, and mode are all specified" do
@source.stubs(:local?).returns false
@resource[:owner] = 1
@resource[:group] = 2
@resource[:mode] = "0003"
expect { @source.copy_source_values }.not_to raise_error
end
end
end
describe "and the source is a link" do
it "should set the target to the link destination" do
@metadata.stubs(:ftype).returns "link"
@metadata.stubs(:links).returns "manage"
@resource.stubs(:[])
@resource.stubs(:[]=)
@metadata.expects(:destination).returns "/path/to/symlink"
@resource.expects(:[]=).with(:target, "/path/to/symlink")
@source.copy_source_values
end
end
end
it "should have a local? method" do
- source.new(:resource => @resource).must be_respond_to(:local?)
+ expect(source.new(:resource => @resource)).to be_respond_to(:local?)
end
context "when accessing source properties" do
let(:catalog) { Puppet::Resource::Catalog.new }
let(:path) { tmpfile('file_resource') }
let(:resource) { Puppet::Type.type(:file).new(:path => path, :catalog => catalog) }
let(:sourcepath) { tmpfile('file_source') }
describe "for local sources" do
before :each do
FileUtils.touch(sourcepath)
end
describe "on POSIX systems", :if => Puppet.features.posix? do
['', "file:", "file://"].each do |prefix|
it "with prefix '#{prefix}' should be local" do
resource[:source] = "#{prefix}#{sourcepath}"
- resource.parameter(:source).must be_local
+ expect(resource.parameter(:source)).to be_local
end
it "should be able to return the metadata source full path" do
resource[:source] = "#{prefix}#{sourcepath}"
- resource.parameter(:source).full_path.should == sourcepath
+ expect(resource.parameter(:source).full_path).to eq(sourcepath)
end
end
end
describe "on Windows systems", :if => Puppet.features.microsoft_windows? do
['', "file:/", "file:///"].each do |prefix|
it "should be local with prefix '#{prefix}'" do
resource[:source] = "#{prefix}#{sourcepath}"
- resource.parameter(:source).must be_local
+ expect(resource.parameter(:source)).to be_local
end
it "should be able to return the metadata source full path" do
resource[:source] = "#{prefix}#{sourcepath}"
- resource.parameter(:source).full_path.should == sourcepath
+ expect(resource.parameter(:source).full_path).to eq(sourcepath)
end
it "should convert backslashes to forward slashes" do
resource[:source] = "#{prefix}#{sourcepath.gsub(/\\/, '/')}"
end
end
it "should be UNC with two slashes"
end
end
describe "for remote sources" do
let(:sourcepath) { "/path/to/source" }
let(:uri) { URI::Generic.build(:scheme => 'puppet', :host => 'server', :port => 8192, :path => sourcepath).to_s }
before(:each) do
metadata = Puppet::FileServing::Metadata.new(path, :source => uri, 'type' => 'file')
#metadata = stub('remote', :ftype => "file", :source => uri)
Puppet::FileServing::Metadata.indirection.stubs(:find).
with(uri,all_of(has_key(:environment), has_key(:links))).returns metadata
resource[:source] = uri
end
it "should not be local" do
- resource.parameter(:source).should_not be_local
+ expect(resource.parameter(:source)).not_to be_local
end
it "should be able to return the metadata source full path" do
- resource.parameter(:source).full_path.should == "/path/to/source"
+ expect(resource.parameter(:source).full_path).to eq("/path/to/source")
end
it "should be able to return the source server" do
- resource.parameter(:source).server.should == "server"
+ expect(resource.parameter(:source).server).to eq("server")
end
it "should be able to return the source port" do
- resource.parameter(:source).port.should == 8192
+ expect(resource.parameter(:source).port).to eq(8192)
end
describe "which don't specify server or port" do
let(:uri) { "puppet:///path/to/source" }
it "should return the default source server" do
Puppet[:server] = "myserver"
- resource.parameter(:source).server.should == "myserver"
+ expect(resource.parameter(:source).server).to eq("myserver")
end
it "should return the default source port" do
Puppet[:masterport] = 1234
- resource.parameter(:source).port.should == 1234
+ expect(resource.parameter(:source).port).to eq(1234)
end
end
end
end
end
diff --git a/spec/unit/type/file/type_spec.rb b/spec/unit/type/file/type_spec.rb
index f7cafc945..9f78d72f8 100755
--- a/spec/unit/type/file/type_spec.rb
+++ b/spec/unit/type/file/type_spec.rb
@@ -1,19 +1,19 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:type) do
require 'puppet_spec/files'
include PuppetSpec::Files
before do
@filename = tmpfile('type')
@resource = Puppet::Type.type(:file).new({:name => @filename})
end
it "should prevent the user from trying to set the type" do
- lambda {
+ expect {
@resource[:type] = "fifo"
- }.should raise_error(Puppet::Error, /type is read-only/)
+ }.to raise_error(Puppet::Error, /type is read-only/)
end
end
diff --git a/spec/unit/type/file_spec.rb b/spec/unit/type/file_spec.rb
index c99aec494..f57a0fba6 100755
--- a/spec/unit/type/file_spec.rb
+++ b/spec/unit/type/file_spec.rb
@@ -1,1504 +1,1509 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:file) do
include PuppetSpec::Files
let(:path) { tmpfile('file_testing') }
let(:file) { described_class.new(:path => path, :catalog => catalog) }
let(:provider) { file.provider }
let(:catalog) { Puppet::Resource::Catalog.new }
before do
Puppet.features.stubs("posix?").returns(true)
end
describe "the path parameter" do
describe "on POSIX systems", :if => Puppet.features.posix? do
it "should remove trailing slashes" do
file[:path] = "/foo/bar/baz/"
- file[:path].should == "/foo/bar/baz"
+ expect(file[:path]).to eq("/foo/bar/baz")
end
it "should remove double slashes" do
file[:path] = "/foo/bar//baz"
- file[:path].should == "/foo/bar/baz"
+ expect(file[:path]).to eq("/foo/bar/baz")
end
it "should remove triple slashes" do
file[:path] = "/foo/bar///baz"
- file[:path].should == "/foo/bar/baz"
+ expect(file[:path]).to eq("/foo/bar/baz")
end
it "should remove trailing double slashes" do
file[:path] = "/foo/bar/baz//"
- file[:path].should == "/foo/bar/baz"
+ expect(file[:path]).to eq("/foo/bar/baz")
end
it "should leave a single slash alone" do
file[:path] = "/"
- file[:path].should == "/"
+ expect(file[:path]).to eq("/")
end
it "should accept and collapse a double-slash at the start of the path" do
file[:path] = "//tmp/xxx"
- file[:path].should == '/tmp/xxx'
+ expect(file[:path]).to eq('/tmp/xxx')
end
it "should accept and collapse a triple-slash at the start of the path" do
file[:path] = "///tmp/xxx"
- file[:path].should == '/tmp/xxx'
+ expect(file[:path]).to eq('/tmp/xxx')
end
end
describe "on Windows systems", :if => Puppet.features.microsoft_windows? do
it "should remove trailing slashes" do
file[:path] = "X:/foo/bar/baz/"
- file[:path].should == "X:/foo/bar/baz"
+ expect(file[:path]).to eq("X:/foo/bar/baz")
end
it "should remove double slashes" do
file[:path] = "X:/foo/bar//baz"
- file[:path].should == "X:/foo/bar/baz"
+ expect(file[:path]).to eq("X:/foo/bar/baz")
end
it "should remove trailing double slashes" do
file[:path] = "X:/foo/bar/baz//"
- file[:path].should == "X:/foo/bar/baz"
+ expect(file[:path]).to eq("X:/foo/bar/baz")
end
it "should leave a drive letter with a slash alone" do
file[:path] = "X:/"
- file[:path].should == "X:/"
+ expect(file[:path]).to eq("X:/")
end
it "should not accept a drive letter without a slash" do
expect { file[:path] = "X:" }.to raise_error(/File paths must be fully qualified/)
end
describe "when using UNC filenames", :if => Puppet.features.microsoft_windows? do
it "should remove trailing slashes" do
file[:path] = "//localhost/foo/bar/baz/"
- file[:path].should == "//localhost/foo/bar/baz"
+ expect(file[:path]).to eq("//localhost/foo/bar/baz")
end
it "should remove double slashes" do
file[:path] = "//localhost/foo/bar//baz"
- file[:path].should == "//localhost/foo/bar/baz"
+ expect(file[:path]).to eq("//localhost/foo/bar/baz")
end
it "should remove trailing double slashes" do
file[:path] = "//localhost/foo/bar/baz//"
- file[:path].should == "//localhost/foo/bar/baz"
+ expect(file[:path]).to eq("//localhost/foo/bar/baz")
end
it "should remove a trailing slash from a sharename" do
file[:path] = "//localhost/foo/"
- file[:path].should == "//localhost/foo"
+ expect(file[:path]).to eq("//localhost/foo")
end
it "should not modify a sharename" do
file[:path] = "//localhost/foo"
- file[:path].should == "//localhost/foo"
+ expect(file[:path]).to eq("//localhost/foo")
end
end
end
end
describe "the backup parameter" do
[false, 'false', :false].each do |value|
it "should disable backup if the value is #{value.inspect}" do
file[:backup] = value
- file[:backup].should == false
+ expect(file[:backup]).to eq(false)
end
end
[true, 'true', '.puppet-bak'].each do |value|
it "should use .puppet-bak if the value is #{value.inspect}" do
file[:backup] = value
- file[:backup].should == '.puppet-bak'
+ expect(file[:backup]).to eq('.puppet-bak')
end
end
it "should use the provided value if it's any other string" do
file[:backup] = "over there"
- file[:backup].should == "over there"
+ expect(file[:backup]).to eq("over there")
end
it "should fail if backup is set to anything else" do
expect do
file[:backup] = 97
end.to raise_error(Puppet::Error, /Invalid backup type 97/)
end
end
describe "the recurse parameter" do
it "should default to recursion being disabled" do
- file[:recurse].should be_false
+ expect(file[:recurse]).to be_falsey
end
[true, "true", "remote"].each do |value|
it "should consider #{value} to enable recursion" do
file[:recurse] = value
- file[:recurse].should be_true
+ expect(file[:recurse]).to be_truthy
end
end
it "should not allow numbers" do
expect { file[:recurse] = 10 }.to raise_error(
Puppet::Error, /Parameter recurse failed on File\[[^\]]+\]: Invalid recurse value 10/)
end
[false, "false"].each do |value|
it "should consider #{value} to disable recursion" do
file[:recurse] = value
- file[:recurse].should be_false
+ expect(file[:recurse]).to be_falsey
end
end
end
describe "the recurselimit parameter" do
it "should accept integers" do
file[:recurselimit] = 12
- file[:recurselimit].should == 12
+ expect(file[:recurselimit]).to eq(12)
end
it "should munge string numbers to number numbers" do
file[:recurselimit] = '12'
- file[:recurselimit].should == 12
+ expect(file[:recurselimit]).to eq(12)
end
it "should fail if given a non-number" do
expect do
file[:recurselimit] = 'twelve'
end.to raise_error(Puppet::Error, /Invalid value "twelve"/)
end
end
describe "the replace parameter" do
[true, :true, :yes].each do |value|
it "should consider #{value} to be true" do
file[:replace] = value
- file[:replace].should be_true
+ expect(file[:replace]).to be_truthy
end
end
[false, :false, :no].each do |value|
it "should consider #{value} to be false" do
file[:replace] = value
- file[:replace].should be_false
+ expect(file[:replace]).to be_falsey
end
end
end
describe ".instances" do
it "should return an empty array" do
- described_class.instances.should == []
+ expect(described_class.instances).to eq([])
end
end
describe "#bucket" do
it "should return nil if backup is off" do
file[:backup] = false
- file.bucket.should == nil
+ expect(file.bucket).to eq(nil)
end
it "should not return a bucket if using a file extension for backup" do
file[:backup] = '.backup'
- file.bucket.should == nil
+ expect(file.bucket).to eq(nil)
end
it "should return the default filebucket if using the 'puppet' filebucket" do
file[:backup] = 'puppet'
bucket = stub('bucket')
file.stubs(:default_bucket).returns bucket
- file.bucket.should == bucket
+ expect(file.bucket).to eq(bucket)
end
it "should fail if using a remote filebucket and no catalog exists" do
file.catalog = nil
file[:backup] = 'my_bucket'
expect { file.bucket }.to raise_error(Puppet::Error, "Can not find filebucket for backups without a catalog")
end
it "should fail if the specified filebucket isn't in the catalog" do
file[:backup] = 'my_bucket'
expect { file.bucket }.to raise_error(Puppet::Error, "Could not find filebucket my_bucket specified in backup")
end
it "should use the specified filebucket if it is in the catalog" do
file[:backup] = 'my_bucket'
filebucket = Puppet::Type.type(:filebucket).new(:name => 'my_bucket')
catalog.add_resource(filebucket)
- file.bucket.should == filebucket.bucket
+ expect(file.bucket).to eq(filebucket.bucket)
end
end
describe "#asuser" do
before :each do
# Mocha won't let me just stub SUIDManager.asuser to yield and return,
# but it will do exactly that if we're not root.
Puppet::Util::SUIDManager.stubs(:root?).returns false
end
it "should return the desired owner if they can write to the parent directory" do
file[:owner] = 1001
FileTest.stubs(:writable?).with(File.dirname file[:path]).returns true
- file.asuser.should == 1001
+ expect(file.asuser).to eq(1001)
end
it "should return nil if the desired owner can't write to the parent directory" do
file[:owner] = 1001
FileTest.stubs(:writable?).with(File.dirname file[:path]).returns false
- file.asuser.should == nil
+ expect(file.asuser).to eq(nil)
end
it "should return nil if not managing owner" do
- file.asuser.should == nil
+ expect(file.asuser).to eq(nil)
end
end
describe "#exist?" do
it "should be considered existent if it can be stat'ed" do
file.expects(:stat).returns mock('stat')
- file.must be_exist
+ expect(file).to be_exist
end
it "should be considered nonexistent if it can not be stat'ed" do
file.expects(:stat).returns nil
- file.must_not be_exist
+ expect(file).to_not be_exist
end
end
describe "#eval_generate" do
before do
@graph = stub 'graph', :add_edge => nil
catalog.stubs(:relationship_graph).returns @graph
end
it "should recurse if recursion is enabled" do
resource = stub('resource', :[] => 'resource')
file.expects(:recurse).returns [resource]
file[:recurse] = true
- file.eval_generate.should == [resource]
+ expect(file.eval_generate).to eq([resource])
end
it "should not recurse if recursion is disabled" do
file.expects(:recurse).never
file[:recurse] = false
- file.eval_generate.should == []
+ expect(file.eval_generate).to eq([])
end
end
describe "#ancestors" do
it "should return the ancestors of the file, in ascending order" do
file = described_class.new(:path => make_absolute("/tmp/foo/bar/baz/qux"))
pieces = %W[#{make_absolute('/')} tmp foo bar baz]
ancestors = file.ancestors
- ancestors.should_not be_empty
+ expect(ancestors).not_to be_empty
ancestors.reverse.each_with_index do |path,i|
- path.should == File.join(*pieces[0..i])
+ expect(path).to eq(File.join(*pieces[0..i]))
end
end
end
describe "#flush" do
it "should flush all properties that respond to :flush" do
file[:source] = File.expand_path(__FILE__)
file.parameter(:source).expects(:flush)
file.flush
end
it "should reset its stat reference" do
FileUtils.touch(path)
stat1 = file.stat
- file.stat.should equal(stat1)
+ expect(file.stat).to equal(stat1)
file.flush
- file.stat.should_not equal(stat1)
+ expect(file.stat).not_to equal(stat1)
end
end
describe "#initialize" do
it "should remove a trailing slash from the title to create the path" do
title = File.expand_path("/abc/\n\tdef/")
file = described_class.new(:title => title)
- file[:path].should == title
+ expect(file[:path]).to eq(title)
end
it "should set a desired 'ensure' value if none is set and 'content' is set" do
file = described_class.new(:path => path, :content => "/foo/bar")
- file[:ensure].should == :file
+ expect(file[:ensure]).to eq(:file)
end
it "should set a desired 'ensure' value if none is set and 'target' is set", :if => described_class.defaultprovider.feature?(:manages_symlinks) do
file = described_class.new(:path => path, :target => File.expand_path(__FILE__))
- file[:ensure].should == :link
+ expect(file[:ensure]).to eq(:link)
end
end
describe "#mark_children_for_purging" do
it "should set each child's ensure to absent" do
paths = %w[foo bar baz]
children = paths.inject({}) do |children,child|
children.merge child => described_class.new(:path => File.join(path, child), :ensure => :present)
end
file.mark_children_for_purging(children)
- children.length.should == 3
+ expect(children.length).to eq(3)
children.values.each do |child|
- child[:ensure].should == :absent
+ expect(child[:ensure]).to eq(:absent)
end
end
it "should skip children which have a source" do
child = described_class.new(:path => path, :ensure => :present, :source => File.expand_path(__FILE__))
file.mark_children_for_purging('foo' => child)
- child[:ensure].should == :present
+ expect(child[:ensure]).to eq(:present)
end
end
describe "#newchild" do
it "should create a new resource relative to the parent" do
child = file.newchild('bar')
- child.must be_a(described_class)
- child[:path].should == File.join(file[:path], 'bar')
+ expect(child).to be_a(described_class)
+ expect(child[:path]).to eq(File.join(file[:path], 'bar'))
end
{
:ensure => :present,
:recurse => true,
:recurselimit => 5,
:target => "some_target",
:source => File.expand_path("some_source"),
}.each do |param, value|
it "should omit the #{param} parameter", :if => described_class.defaultprovider.feature?(:manages_symlinks) do
# Make a new file, because we have to set the param at initialization
# or it wouldn't be copied regardless.
file = described_class.new(:path => path, param => value)
child = file.newchild('bar')
- child[param].should_not == value
+ expect(child[param]).not_to eq(value)
end
end
it "should copy all of the parent resource's 'should' values that were set at initialization" do
parent = described_class.new(:path => path, :owner => 'root', :group => 'wheel')
child = parent.newchild("my/path")
- child[:owner].should == 'root'
- child[:group].should == 'wheel'
+ expect(child[:owner]).to eq('root')
+ expect(child[:group]).to eq('wheel')
end
it "should not copy default values to the new child" do
child = file.newchild("my/path")
- child.original_parameters.should_not include(:backup)
+ expect(child.original_parameters).not_to include(:backup)
end
it "should not copy values to the child which were set by the source" do
source = File.expand_path(__FILE__)
file[:source] = source
metadata = stub 'metadata', :owner => "root", :group => "root", :mode => '0755', :ftype => "file", :checksum => "{md5}whatever", :source => source
file.parameter(:source).stubs(:metadata).returns metadata
file.parameter(:source).copy_source_values
file.class.expects(:new).with { |params| params[:group].nil? }
file.newchild("my/path")
end
end
describe "#purge?" do
it "should return false if purge is not set" do
- file.must_not be_purge
+ expect(file).to_not be_purge
end
it "should return true if purge is set to true" do
file[:purge] = true
- file.must be_purge
+ expect(file).to be_purge
end
it "should return false if purge is set to false" do
file[:purge] = false
- file.must_not be_purge
+ expect(file).to_not be_purge
end
end
describe "#recurse" do
before do
file[:recurse] = true
@metadata = Puppet::FileServing::Metadata
end
describe "and a source is set" do
it "should pass the already-discovered resources to recurse_remote" do
file[:source] = File.expand_path(__FILE__)
file.stubs(:recurse_local).returns(:foo => "bar")
file.expects(:recurse_remote).with(:foo => "bar").returns []
file.recurse
end
end
describe "and a target is set" do
it "should use recurse_link" do
file[:target] = File.expand_path(__FILE__)
file.stubs(:recurse_local).returns(:foo => "bar")
file.expects(:recurse_link).with(:foo => "bar").returns []
file.recurse
end
end
it "should use recurse_local if recurse is not remote" do
file.expects(:recurse_local).returns({})
file.recurse
end
it "should not use recurse_local if recurse is remote" do
file[:recurse] = :remote
file.expects(:recurse_local).never
file.recurse
end
it "should return the generated resources as an array sorted by file path" do
one = stub 'one', :[] => "/one"
two = stub 'two', :[] => "/one/two"
three = stub 'three', :[] => "/three"
file.expects(:recurse_local).returns(:one => one, :two => two, :three => three)
- file.recurse.should == [one, two, three]
+ expect(file.recurse).to eq([one, two, three])
end
describe "and purging is enabled" do
before do
file[:purge] = true
end
it "should mark each file for removal" do
local = described_class.new(:path => path, :ensure => :present)
file.expects(:recurse_local).returns("local" => local)
file.recurse
- local[:ensure].should == :absent
+ expect(local[:ensure]).to eq(:absent)
end
it "should not remove files that exist in the remote repository" do
file[:source] = File.expand_path(__FILE__)
file.expects(:recurse_local).returns({})
remote = described_class.new(:path => path, :source => File.expand_path(__FILE__), :ensure => :present)
file.expects(:recurse_remote).with { |hash| hash["remote"] = remote }
file.recurse
- remote[:ensure].should_not == :absent
+ expect(remote[:ensure]).not_to eq(:absent)
end
end
end
describe "#remove_less_specific_files" do
it "should remove any nested files that are already in the catalog" do
foo = described_class.new :path => File.join(file[:path], 'foo')
bar = described_class.new :path => File.join(file[:path], 'bar')
baz = described_class.new :path => File.join(file[:path], 'baz')
catalog.add_resource(foo)
catalog.add_resource(bar)
- file.remove_less_specific_files([foo, bar, baz]).should == [baz]
+ expect(file.remove_less_specific_files([foo, bar, baz])).to eq([baz])
end
end
describe "#remove_less_specific_files" do
it "should remove any nested files that are already in the catalog" do
foo = described_class.new :path => File.join(file[:path], 'foo')
bar = described_class.new :path => File.join(file[:path], 'bar')
baz = described_class.new :path => File.join(file[:path], 'baz')
catalog.add_resource(foo)
catalog.add_resource(bar)
- file.remove_less_specific_files([foo, bar, baz]).should == [baz]
+ expect(file.remove_less_specific_files([foo, bar, baz])).to eq([baz])
end
end
describe "#recurse?" do
it "should be true if recurse is true" do
file[:recurse] = true
- file.must be_recurse
+ expect(file).to be_recurse
end
it "should be true if recurse is remote" do
file[:recurse] = :remote
- file.must be_recurse
+ expect(file).to be_recurse
end
it "should be false if recurse is false" do
file[:recurse] = false
- file.must_not be_recurse
+ expect(file).to_not be_recurse
end
end
describe "#recurse_link" do
before do
@first = stub 'first', :relative_path => "first", :full_path => "/my/first", :ftype => "directory"
@second = stub 'second', :relative_path => "second", :full_path => "/my/second", :ftype => "file"
@resource = stub 'file', :[]= => nil
end
it "should pass its target to the :perform_recursion method" do
file[:target] = "mylinks"
file.expects(:perform_recursion).with("mylinks").returns [@first]
file.stubs(:newchild).returns @resource
file.recurse_link({})
end
it "should ignore the recursively-found '.' file and configure the top-level file to create a directory" do
@first.stubs(:relative_path).returns "."
file[:target] = "mylinks"
file.expects(:perform_recursion).with("mylinks").returns [@first]
file.stubs(:newchild).never
file.expects(:[]=).with(:ensure, :directory)
file.recurse_link({})
end
it "should create a new child resource for each generated metadata instance's relative path that doesn't already exist in the children hash" do
file.expects(:perform_recursion).returns [@first, @second]
file.expects(:newchild).with(@first.relative_path).returns @resource
file.recurse_link("second" => @resource)
end
it "should not create a new child resource for paths that already exist in the children hash" do
file.expects(:perform_recursion).returns [@first]
file.expects(:newchild).never
file.recurse_link("first" => @resource)
end
it "should set the target to the full path of discovered file and set :ensure to :link if the file is not a directory", :if => described_class.defaultprovider.feature?(:manages_symlinks) do
file.stubs(:perform_recursion).returns [@first, @second]
file.recurse_link("first" => @resource, "second" => file)
- file[:ensure].should == :link
- file[:target].should == "/my/second"
+ expect(file[:ensure]).to eq(:link)
+ expect(file[:target]).to eq("/my/second")
end
it "should :ensure to :directory if the file is a directory" do
file.stubs(:perform_recursion).returns [@first, @second]
file.recurse_link("first" => file, "second" => @resource)
- file[:ensure].should == :directory
+ expect(file[:ensure]).to eq(:directory)
end
it "should return a hash with both created and existing resources with the relative paths as the hash keys" do
file.expects(:perform_recursion).returns [@first, @second]
file.stubs(:newchild).returns file
- file.recurse_link("second" => @resource).should == {"second" => @resource, "first" => file}
+ expect(file.recurse_link("second" => @resource)).to eq({"second" => @resource, "first" => file})
end
end
describe "#recurse_local" do
before do
@metadata = stub 'metadata', :relative_path => "my/file"
end
it "should pass its path to the :perform_recursion method" do
file.expects(:perform_recursion).with(file[:path]).returns [@metadata]
file.stubs(:newchild)
file.recurse_local
end
it "should return an empty hash if the recursion returns nothing" do
file.expects(:perform_recursion).returns nil
- file.recurse_local.should == {}
+ expect(file.recurse_local).to eq({})
end
it "should create a new child resource with each generated metadata instance's relative path" do
file.expects(:perform_recursion).returns [@metadata]
file.expects(:newchild).with(@metadata.relative_path).returns "fiebar"
file.recurse_local
end
it "should not create a new child resource for the '.' directory" do
@metadata.stubs(:relative_path).returns "."
file.expects(:perform_recursion).returns [@metadata]
file.expects(:newchild).never
file.recurse_local
end
it "should return a hash of the created resources with the relative paths as the hash keys" do
file.expects(:perform_recursion).returns [@metadata]
file.expects(:newchild).with("my/file").returns "fiebar"
- file.recurse_local.should == {"my/file" => "fiebar"}
+ expect(file.recurse_local).to eq({"my/file" => "fiebar"})
end
it "should set checksum_type to none if this file checksum is none" do
file[:checksum] = :none
Puppet::FileServing::Metadata.indirection.expects(:search).with { |path,params| params[:checksum_type] == :none }.returns [@metadata]
file.expects(:newchild).with("my/file").returns "fiebar"
file.recurse_local
end
end
describe "#recurse_remote", :uses_checksums => true do
let(:my) { File.expand_path('/my') }
before do
file[:source] = "puppet://foo/bar"
@first = Puppet::FileServing::Metadata.new(my, :relative_path => "first")
@second = Puppet::FileServing::Metadata.new(my, :relative_path => "second")
@first.stubs(:ftype).returns "directory"
@second.stubs(:ftype).returns "directory"
@parameter = stub 'property', :metadata= => nil
@resource = stub 'file', :[]= => nil, :parameter => @parameter
end
it "should pass its source to the :perform_recursion method" do
data = Puppet::FileServing::Metadata.new(File.expand_path("/whatever"), :relative_path => "foobar")
file.expects(:perform_recursion).with("puppet://foo/bar").returns [data]
file.stubs(:newchild).returns @resource
file.recurse_remote({})
end
it "should not recurse when the remote file is not a directory" do
data = Puppet::FileServing::Metadata.new(File.expand_path("/whatever"), :relative_path => ".")
data.stubs(:ftype).returns "file"
file.expects(:perform_recursion).with("puppet://foo/bar").returns [data]
file.expects(:newchild).never
file.recurse_remote({})
end
it "should set the source of each returned file to the searched-for URI plus the found relative path" do
@first.expects(:source=).with File.join("puppet://foo/bar", @first.relative_path)
file.expects(:perform_recursion).returns [@first]
file.stubs(:newchild).returns @resource
file.recurse_remote({})
end
it "should create a new resource for any relative file paths that do not already have a resource" do
file.stubs(:perform_recursion).returns [@first]
file.expects(:newchild).with("first").returns @resource
- file.recurse_remote({}).should == {"first" => @resource}
+ expect(file.recurse_remote({})).to eq({"first" => @resource})
end
it "should not create a new resource for any relative file paths that do already have a resource" do
file.stubs(:perform_recursion).returns [@first]
file.expects(:newchild).never
file.recurse_remote("first" => @resource)
end
it "should set the source of each resource to the source of the metadata" do
file.stubs(:perform_recursion).returns [@first]
@resource.stubs(:[]=)
@resource.expects(:[]=).with(:source, File.join("puppet://foo/bar", @first.relative_path))
file.recurse_remote("first" => @resource)
end
# LAK:FIXME This is a bug, but I can't think of a fix for it. Fortunately it's already
# filed, and when it's fixed, we'll just fix the whole flow.
with_digest_algorithms do
it "it should set the checksum type to #{metadata[:digest_algorithm]} if the remote file is a file" do
@first.stubs(:ftype).returns "file"
file.stubs(:perform_recursion).returns [@first]
@resource.stubs(:[]=)
@resource.expects(:[]=).with(:checksum, digest_algorithm.intern)
file.recurse_remote("first" => @resource)
end
end
it "should store the metadata in the source property for each resource so the source does not have to requery the metadata" do
file.stubs(:perform_recursion).returns [@first]
@resource.expects(:parameter).with(:source).returns @parameter
@parameter.expects(:metadata=).with(@first)
file.recurse_remote("first" => @resource)
end
it "should not create a new resource for the '.' file" do
@first.stubs(:relative_path).returns "."
file.stubs(:perform_recursion).returns [@first]
file.expects(:newchild).never
file.recurse_remote({})
end
it "should store the metadata in the main file's source property if the relative path is '.'" do
@first.stubs(:relative_path).returns "."
file.stubs(:perform_recursion).returns [@first]
file.parameter(:source).expects(:metadata=).with @first
file.recurse_remote("first" => @resource)
end
describe "and multiple sources are provided" do
let(:sources) do
h = {}
%w{/a /b /c /d}.each do |key|
h[key] = URI.unescape(Puppet::Util.path_to_uri(File.expand_path(key)).to_s)
end
h
end
describe "and :sourceselect is set to :first" do
it "should create file instances for the results for the first source to return any values" do
data = Puppet::FileServing::Metadata.new(File.expand_path("/whatever"), :relative_path => "foobar")
file[:source] = sources.keys.sort.map { |key| File.expand_path(key) }
file.expects(:perform_recursion).with(sources['/a']).returns nil
file.expects(:perform_recursion).with(sources['/b']).returns []
file.expects(:perform_recursion).with(sources['/c']).returns [data]
file.expects(:perform_recursion).with(sources['/d']).never
file.expects(:newchild).with("foobar").returns @resource
file.recurse_remote({})
end
end
describe "and :sourceselect is set to :all" do
before do
file[:sourceselect] = :all
end
it "should return every found file that is not in a previous source" do
klass = Puppet::FileServing::Metadata
file[:source] = abs_path = %w{/a /b /c /d}.map {|f| File.expand_path(f) }
file.stubs(:newchild).returns @resource
one = [klass.new(abs_path[0], :relative_path => "a")]
file.expects(:perform_recursion).with(sources['/a']).returns one
file.expects(:newchild).with("a").returns @resource
two = [klass.new(abs_path[1], :relative_path => "a"), klass.new(abs_path[1], :relative_path => "b")]
file.expects(:perform_recursion).with(sources['/b']).returns two
file.expects(:newchild).with("b").returns @resource
three = [klass.new(abs_path[2], :relative_path => "a"), klass.new(abs_path[2], :relative_path => "c")]
file.expects(:perform_recursion).with(sources['/c']).returns three
file.expects(:newchild).with("c").returns @resource
file.expects(:perform_recursion).with(sources['/d']).returns []
file.recurse_remote({})
end
end
end
end
describe "#perform_recursion" do
it "should use Metadata to do its recursion" do
Puppet::FileServing::Metadata.indirection.expects(:search)
file.perform_recursion(file[:path])
end
it "should use the provided path as the key to the search" do
Puppet::FileServing::Metadata.indirection.expects(:search).with { |key, options| key == "/foo" }
file.perform_recursion("/foo")
end
it "should return the results of the metadata search" do
Puppet::FileServing::Metadata.indirection.expects(:search).returns "foobar"
- file.perform_recursion(file[:path]).should == "foobar"
+ expect(file.perform_recursion(file[:path])).to eq("foobar")
end
it "should pass its recursion value to the search" do
file[:recurse] = true
Puppet::FileServing::Metadata.indirection.expects(:search).with { |key, options| options[:recurse] == true }
file.perform_recursion(file[:path])
end
it "should pass true if recursion is remote" do
file[:recurse] = :remote
Puppet::FileServing::Metadata.indirection.expects(:search).with { |key, options| options[:recurse] == true }
file.perform_recursion(file[:path])
end
it "should pass its recursion limit value to the search" do
file[:recurselimit] = 10
Puppet::FileServing::Metadata.indirection.expects(:search).with { |key, options| options[:recurselimit] == 10 }
file.perform_recursion(file[:path])
end
it "should configure the search to ignore or manage links" do
file[:links] = :manage
Puppet::FileServing::Metadata.indirection.expects(:search).with { |key, options| options[:links] == :manage }
file.perform_recursion(file[:path])
end
it "should pass its 'ignore' setting to the search if it has one" do
file[:ignore] = %w{.svn CVS}
Puppet::FileServing::Metadata.indirection.expects(:search).with { |key, options| options[:ignore] == %w{.svn CVS} }
file.perform_recursion(file[:path])
end
end
describe "#remove_existing" do
it "should do nothing if the file doesn't exist" do
- file.remove_existing(:file).should == false
+ expect(file.remove_existing(:file)).to eq(false)
end
it "should fail if it can't backup the file" do
file.stubs(:stat).returns stub('stat', :ftype => 'file')
file.stubs(:perform_backup).returns false
expect { file.remove_existing(:file) }.to raise_error(Puppet::Error, /Could not back up; will not replace/)
end
describe "backing up directories" do
it "should not backup directories if force is false" do
file[:force] = false
file.stubs(:stat).returns stub('stat', :ftype => 'directory')
file.expects(:perform_backup).never
- file.remove_existing(:file).should == false
+ expect(file.remove_existing(:file)).to eq(false)
end
it "should backup directories if force is true" do
file[:force] = true
FileUtils.expects(:rmtree).with(file[:path])
file.stubs(:stat).returns stub('stat', :ftype => 'directory')
file.expects(:perform_backup).once.returns(true)
- file.remove_existing(:file).should == true
+ expect(file.remove_existing(:file)).to eq(true)
end
end
it "should not do anything if the file is already the right type and not a link" do
file.stubs(:stat).returns stub('stat', :ftype => 'file')
- file.remove_existing(:file).should == false
+ expect(file.remove_existing(:file)).to eq(false)
end
it "should not remove directories and should not invalidate the stat unless force is set" do
# Actually call stat to set @needs_stat to nil
file.stat
file.stubs(:stat).returns stub('stat', :ftype => 'directory')
file.remove_existing(:file)
- file.instance_variable_get(:@stat).should == nil
- @logs.should be_any {|log| log.level == :notice and log.message =~ /Not removing directory; use 'force' to override/}
+ expect(file.instance_variable_get(:@stat)).to eq(nil)
+ expect(@logs).to be_any {|log| log.level == :notice and log.message =~ /Not removing directory; use 'force' to override/}
end
it "should remove a directory if force is set" do
file[:force] = true
file.stubs(:stat).returns stub('stat', :ftype => 'directory')
FileUtils.expects(:rmtree).with(file[:path])
- file.remove_existing(:file).should == true
+ expect(file.remove_existing(:file)).to eq(true)
end
it "should remove an existing file" do
file.stubs(:perform_backup).returns true
FileUtils.touch(path)
- file.remove_existing(:directory).should == true
+ expect(file.remove_existing(:directory)).to eq(true)
- Puppet::FileSystem.exist?(file[:path]).should == false
+ expect(Puppet::FileSystem.exist?(file[:path])).to eq(false)
end
it "should remove an existing link", :if => described_class.defaultprovider.feature?(:manages_symlinks) do
file.stubs(:perform_backup).returns true
target = tmpfile('link_target')
FileUtils.touch(target)
Puppet::FileSystem.symlink(target, path)
file[:target] = target
- file.remove_existing(:directory).should == true
+ expect(file.remove_existing(:directory)).to eq(true)
- Puppet::FileSystem.exist?(file[:path]).should == false
+ expect(Puppet::FileSystem.exist?(file[:path])).to eq(false)
end
it "should fail if the file is not a file, link, or directory" do
file.stubs(:stat).returns stub('stat', :ftype => 'socket')
expect { file.remove_existing(:file) }.to raise_error(Puppet::Error, /Could not back up files of type socket/)
end
it "should invalidate the existing stat of the file" do
# Actually call stat to set @needs_stat to nil
file.stat
file.stubs(:stat).returns stub('stat', :ftype => 'file')
Puppet::FileSystem.stubs(:unlink)
- file.remove_existing(:directory).should == true
- file.instance_variable_get(:@stat).should == :needs_stat
+ expect(file.remove_existing(:directory)).to eq(true)
+ expect(file.instance_variable_get(:@stat)).to eq(:needs_stat)
end
end
describe "#retrieve" do
it "should copy the source values if the 'source' parameter is set" do
file[:source] = File.expand_path('/foo/bar')
file.parameter(:source).expects(:copy_source_values)
file.retrieve
end
end
describe "#should_be_file?" do
it "should have a method for determining if the file should be a normal file" do
- file.must respond_to(:should_be_file?)
+ expect(file).to respond_to(:should_be_file?)
end
it "should be a file if :ensure is set to :file" do
file[:ensure] = :file
- file.must be_should_be_file
+ expect(file).to be_should_be_file
end
it "should be a file if :ensure is set to :present and the file exists as a normal file" do
file.stubs(:stat).returns(mock('stat', :ftype => "file"))
file[:ensure] = :present
- file.must be_should_be_file
+ expect(file).to be_should_be_file
end
it "should not be a file if :ensure is set to something other than :file" do
file[:ensure] = :directory
- file.must_not be_should_be_file
+ expect(file).to_not be_should_be_file
end
it "should not be a file if :ensure is set to :present and the file exists but is not a normal file" do
file.stubs(:stat).returns(mock('stat', :ftype => "directory"))
file[:ensure] = :present
- file.must_not be_should_be_file
+ expect(file).to_not be_should_be_file
end
it "should be a file if :ensure is not set and :content is" do
file[:content] = "foo"
- file.must be_should_be_file
+ expect(file).to be_should_be_file
end
it "should be a file if neither :ensure nor :content is set but the file exists as a normal file" do
file.stubs(:stat).returns(mock("stat", :ftype => "file"))
- file.must be_should_be_file
+ expect(file).to be_should_be_file
end
it "should not be a file if neither :ensure nor :content is set but the file exists but not as a normal file" do
file.stubs(:stat).returns(mock("stat", :ftype => "directory"))
- file.must_not be_should_be_file
+ expect(file).to_not be_should_be_file
end
end
describe "#stat", :if => described_class.defaultprovider.feature?(:manages_symlinks) do
before do
target = tmpfile('link_target')
FileUtils.touch(target)
Puppet::FileSystem.symlink(target, path)
file[:target] = target
file[:links] = :manage # so we always use :lstat
end
it "should stat the target if it is following links" do
file[:links] = :follow
- file.stat.ftype.should == 'file'
+ expect(file.stat.ftype).to eq('file')
end
it "should stat the link if is it not following links" do
file[:links] = :manage
- file.stat.ftype.should == 'link'
+ expect(file.stat.ftype).to eq('link')
end
it "should return nil if the file does not exist" do
file[:path] = make_absolute('/foo/bar/baz/non-existent')
- file.stat.should be_nil
+ expect(file.stat).to be_nil
end
it "should return nil if the file cannot be stat'ed" do
dir = tmpfile('link_test_dir')
child = File.join(dir, 'some_file')
Dir.mkdir(dir)
File.chmod(0, dir)
file[:path] = child
- file.stat.should be_nil
+ expect(file.stat).to be_nil
# chmod it back so we can clean it up
File.chmod(0777, dir)
end
it "should return nil if parts of path are no directories" do
regular_file = tmpfile('ENOTDIR_test')
FileUtils.touch(regular_file)
impossible_child = File.join(regular_file, 'some_file')
file[:path] = impossible_child
- file.stat.should be_nil
+ expect(file.stat).to be_nil
end
it "should return the stat instance" do
- file.stat.should be_a(File::Stat)
+ expect(file.stat).to be_a(File::Stat)
end
it "should cache the stat instance" do
- file.stat.should equal(file.stat)
+ expect(file.stat).to equal(file.stat)
end
end
describe "#write" do
describe "when validating the checksum" do
before { file.stubs(:validate_checksum?).returns(true) }
it "should fail if the checksum parameter and content checksums do not match" do
checksum = stub('checksum_parameter', :sum => 'checksum_b', :sum_file => 'checksum_b')
file.stubs(:parameter).with(:checksum).returns(checksum)
property = stub('content_property', :actual_content => "something", :length => "something".length, :write => 'checksum_a')
file.stubs(:property).with(:content).returns(property)
expect { file.write :NOTUSED }.to raise_error(Puppet::Error)
end
end
describe "when not validating the checksum" do
before { file.stubs(:validate_checksum?).returns(false) }
it "should not fail if the checksum property and content checksums do not match" do
checksum = stub('checksum_parameter', :sum => 'checksum_b')
file.stubs(:parameter).with(:checksum).returns(checksum)
property = stub('content_property', :actual_content => "something", :length => "something".length, :write => 'checksum_a')
file.stubs(:property).with(:content).returns(property)
expect { file.write :NOTUSED }.to_not raise_error
end
end
describe "when resource mode is supplied" do
before { file.stubs(:property_fix) }
context "and writing temporary files" do
before { file.stubs(:write_temporary_file?).returns(true) }
it "should convert symbolic mode to int" do
file[:mode] = 'oga=r'
Puppet::Util.expects(:replace_file).with(file[:path], 0444)
file.write :NOTUSED
end
it "should support int modes" do
file[:mode] = '0444'
Puppet::Util.expects(:replace_file).with(file[:path], 0444)
file.write :NOTUSED
end
end
context "and not writing temporary files" do
before { file.stubs(:write_temporary_file?).returns(false) }
it "should set a umask of 0" do
file[:mode] = 'oga=r'
Puppet::Util.expects(:withumask).with(0)
file.write :NOTUSED
end
it "should convert symbolic mode to int" do
file[:mode] = 'oga=r'
File.expects(:open).with(file[:path], anything, 0444)
file.write :NOTUSED
end
it "should support int modes" do
file[:mode] = '0444'
File.expects(:open).with(file[:path], anything, 0444)
file.write :NOTUSED
end
end
end
describe "when resource mode is not supplied" do
context "and content is supplied" do
it "should default to 0644 mode" do
file = described_class.new(:path => path, :content => "file content")
file.write :NOTUSED
expect(File.stat(file[:path]).mode & 0777).to eq(0644)
end
end
context "and no content is supplied" do
it "should use puppet's default umask of 022" do
file = described_class.new(:path => path)
umask_from_the_user = 0777
Puppet::Util.withumask(umask_from_the_user) do
file.write :NOTUSED
end
expect(File.stat(file[:path]).mode & 0777).to eq(0644)
end
end
end
end
describe "#fail_if_checksum_is_wrong" do
it "should fail if the checksum of the file doesn't match the expected one" do
expect do
file.instance_eval do
parameter(:checksum).stubs(:sum_file).returns('wrong!!')
fail_if_checksum_is_wrong(self[:path], 'anything!')
end
end.to raise_error(Puppet::Error, /File written to disk did not match checksum/)
end
it "should not fail if the checksum is correct" do
- file.instance_eval do
- parameter(:checksum).stubs(:sum_file).returns('anything!')
- fail_if_checksum_is_wrong(self[:path], 'anything!').should == nil
- end
+ expect do
+ file.instance_eval do
+ parameter(:checksum).stubs(:sum_file).returns('anything!')
+ fail_if_checksum_is_wrong(self[:path], 'anything!')
+ end
+ end.not_to raise_error
end
it "should not fail if the checksum is absent" do
- file.instance_eval do
- parameter(:checksum).stubs(:sum_file).returns(nil)
- fail_if_checksum_is_wrong(self[:path], 'anything!').should == nil
- end
+ expect do
+ file.instance_eval do
+ parameter(:checksum).stubs(:sum_file).returns(nil)
+ fail_if_checksum_is_wrong(self[:path], 'anything!')
+ end
+ end.not_to raise_error
end
end
describe "#write_content" do
it "should delegate writing the file to the content property" do
io = stub('io')
file[:content] = "some content here"
file.property(:content).expects(:write).with(io)
file.send(:write_content, io)
end
end
describe "#write_temporary_file?" do
it "should be true if the file has specified content" do
file[:content] = 'some content'
- file.send(:write_temporary_file?).should be_true
+ expect(file.send(:write_temporary_file?)).to be_truthy
end
it "should be true if the file has specified source" do
file[:source] = File.expand_path('/tmp/foo')
- file.send(:write_temporary_file?).should be_true
+ expect(file.send(:write_temporary_file?)).to be_truthy
end
it "should be false if the file has neither content nor source" do
- file.send(:write_temporary_file?).should be_false
+ expect(file.send(:write_temporary_file?)).to be_falsey
end
end
describe "#property_fix" do
{
:mode => '0777',
:owner => 'joeuser',
:group => 'joeusers',
:seluser => 'seluser',
:selrole => 'selrole',
:seltype => 'seltype',
:selrange => 'selrange'
}.each do |name,value|
it "should sync the #{name} property if it's not in sync" do
file[name] = value
prop = file.property(name)
prop.expects(:retrieve)
prop.expects(:safe_insync?).returns false
prop.expects(:sync)
file.send(:property_fix)
end
end
end
describe "when autorequiring" do
describe "target" do
it "should require file resource when specified with the target property", :if => described_class.defaultprovider.feature?(:manages_symlinks) do
file = described_class.new(:path => File.expand_path("/foo"), :ensure => :directory)
link = described_class.new(:path => File.expand_path("/bar"), :ensure => :link, :target => File.expand_path("/foo"))
catalog.add_resource file
catalog.add_resource link
reqs = link.autorequire
- reqs.size.must == 1
- reqs[0].source.must == file
- reqs[0].target.must == link
+ expect(reqs.size).to eq(1)
+ expect(reqs[0].source).to eq(file)
+ expect(reqs[0].target).to eq(link)
end
it "should require file resource when specified with the ensure property" do
file = described_class.new(:path => File.expand_path("/foo"), :ensure => :directory)
link = described_class.new(:path => File.expand_path("/bar"), :ensure => File.expand_path("/foo"))
catalog.add_resource file
catalog.add_resource link
reqs = link.autorequire
- reqs.size.must == 1
- reqs[0].source.must == file
- reqs[0].target.must == link
+ expect(reqs.size).to eq(1)
+ expect(reqs[0].source).to eq(file)
+ expect(reqs[0].target).to eq(link)
end
it "should not require target if target is not managed", :if => described_class.defaultprovider.feature?(:manages_symlinks) do
link = described_class.new(:path => File.expand_path('/foo'), :ensure => :link, :target => '/bar')
catalog.add_resource link
- link.autorequire.size.should == 0
+ expect(link.autorequire.size).to eq(0)
end
end
describe "directories" do
it "should autorequire its parent directory" do
dir = described_class.new(:path => File.dirname(path))
catalog.add_resource file
catalog.add_resource dir
reqs = file.autorequire
- reqs[0].source.must == dir
- reqs[0].target.must == file
+ expect(reqs[0].source).to eq(dir)
+ expect(reqs[0].target).to eq(file)
end
it "should autorequire its nearest ancestor directory" do
dir = described_class.new(:path => File.dirname(path))
grandparent = described_class.new(:path => File.dirname(File.dirname(path)))
catalog.add_resource file
catalog.add_resource dir
catalog.add_resource grandparent
reqs = file.autorequire
- reqs.length.must == 1
- reqs[0].source.must == dir
- reqs[0].target.must == file
+ expect(reqs.length).to eq(1)
+ expect(reqs[0].source).to eq(dir)
+ expect(reqs[0].target).to eq(file)
end
it "should not autorequire anything when there is no nearest ancestor directory" do
catalog.add_resource file
- file.autorequire.should be_empty
+ expect(file.autorequire).to be_empty
end
it "should not autorequire its parent dir if its parent dir is itself" do
file[:path] = File.expand_path('/')
catalog.add_resource file
- file.autorequire.should be_empty
+ expect(file.autorequire).to be_empty
end
describe "on Windows systems", :if => Puppet.features.microsoft_windows? do
describe "when using UNC filenames" do
it "should autorequire its parent directory" do
file[:path] = '//localhost/foo/bar/baz'
dir = described_class.new(:path => "//localhost/foo/bar")
catalog.add_resource file
catalog.add_resource dir
reqs = file.autorequire
- reqs[0].source.must == dir
- reqs[0].target.must == file
+ expect(reqs[0].source).to eq(dir)
+ expect(reqs[0].target).to eq(file)
end
it "should autorequire its nearest ancestor directory" do
file = described_class.new(:path => "//localhost/foo/bar/baz/qux")
dir = described_class.new(:path => "//localhost/foo/bar/baz")
grandparent = described_class.new(:path => "//localhost/foo/bar")
catalog.add_resource file
catalog.add_resource dir
catalog.add_resource grandparent
reqs = file.autorequire
- reqs.length.must == 1
- reqs[0].source.must == dir
- reqs[0].target.must == file
+ expect(reqs.length).to eq(1)
+ expect(reqs[0].source).to eq(dir)
+ expect(reqs[0].target).to eq(file)
end
it "should not autorequire anything when there is no nearest ancestor directory" do
file = described_class.new(:path => "//localhost/foo/bar/baz/qux")
catalog.add_resource file
- file.autorequire.should be_empty
+ expect(file.autorequire).to be_empty
end
it "should not autorequire its parent dir if its parent dir is itself" do
file = described_class.new(:path => "//localhost/foo")
catalog.add_resource file
puts file.autorequire
- file.autorequire.should be_empty
+ expect(file.autorequire).to be_empty
end
end
end
end
end
describe "when managing links", :if => Puppet.features.manages_symlinks? do
require 'tempfile'
before :each do
Dir.mkdir(path)
@target = File.join(path, "target")
@link = File.join(path, "link")
target = described_class.new(
:ensure => :file, :path => @target,
:catalog => catalog, :content => 'yayness',
:mode => '0644')
catalog.add_resource target
@link_resource = described_class.new(
:ensure => :link, :path => @link,
:target => @target, :catalog => catalog,
:mode => '0755')
catalog.add_resource @link_resource
# to prevent the catalog from trying to write state.yaml
Puppet::Util::Storage.stubs(:store)
end
it "should preserve the original file mode and ignore the one set by the link" do
@link_resource[:links] = :manage # default
catalog.apply
# I convert them to strings so they display correctly if there's an error.
- (Puppet::FileSystem.stat(@target).mode & 007777).to_s(8).should == '644'
+ expect((Puppet::FileSystem.stat(@target).mode & 007777).to_s(8)).to eq('644')
end
it "should manage the mode of the followed link" do
- pending("Windows cannot presently manage the mode when following symlinks",
- :if => Puppet.features.microsoft_windows?) do
+ if Puppet.features.microsoft_windows?
+ skip "Windows cannot presently manage the mode when following symlinks"
+ else
@link_resource[:links] = :follow
catalog.apply
- (Puppet::FileSystem.stat(@target).mode & 007777).to_s(8).should == '755'
+ expect((Puppet::FileSystem.stat(@target).mode & 007777).to_s(8)).to eq('755')
end
end
end
describe "when using source" do
before do
file[:source] = File.expand_path('/one')
end
Puppet::Type::File::ParameterChecksum.value_collection.values.reject {|v| v == :none}.each do |checksum_type|
describe "with checksum '#{checksum_type}'" do
before do
file[:checksum] = checksum_type
end
it 'should validate' do
expect { file.validate }.to_not raise_error
end
end
end
describe "with checksum 'none'" do
before do
file[:checksum] = :none
end
it 'should raise an exception when validating' do
expect { file.validate }.to raise_error(/You cannot specify source when using checksum 'none'/)
end
end
end
describe "when using content" do
before do
file[:content] = 'file contents'
end
(Puppet::Type::File::ParameterChecksum.value_collection.values - SOURCE_ONLY_CHECKSUMS).each do |checksum_type|
describe "with checksum '#{checksum_type}'" do
before do
file[:checksum] = checksum_type
end
it 'should validate' do
expect { file.validate }.to_not raise_error
end
end
end
SOURCE_ONLY_CHECKSUMS.each do |checksum_type|
describe "with checksum '#{checksum_type}'" do
it 'should raise an exception when validating' do
file[:checksum] = checksum_type
expect { file.validate }.to raise_error(/You cannot specify content when using checksum '#{checksum_type}'/)
end
end
end
end
describe "when auditing" do
before :each do
# to prevent the catalog from trying to write state.yaml
Puppet::Util::Storage.stubs(:store)
end
it "should not fail if creating a new file if group is not set" do
file = described_class.new(:path => path, :audit => 'all', :content => 'content')
catalog.add_resource(file)
report = catalog.apply.report
- report.resource_statuses["File[#{path}]"].should_not be_failed
- File.read(path).should == 'content'
+ expect(report.resource_statuses["File[#{path}]"]).not_to be_failed
+ expect(File.read(path)).to eq('content')
end
it "should not log errors if creating a new file with ensure present and no content" do
file[:audit] = 'content'
file[:ensure] = 'present'
catalog.add_resource(file)
catalog.apply
- Puppet::FileSystem.exist?(path).should be_true
- @logs.should_not be_any {|l| l.level != :notice }
+ expect(Puppet::FileSystem.exist?(path)).to be_truthy
+ expect(@logs).not_to be_any {|l| l.level != :notice }
end
end
describe "when specifying both source and checksum" do
it 'should use the specified checksum when source is first' do
file[:source] = File.expand_path('/foo')
file[:checksum] = :md5lite
- file[:checksum].should == :md5lite
+ expect(file[:checksum]).to eq(:md5lite)
end
it 'should use the specified checksum when source is last' do
file[:checksum] = :md5lite
file[:source] = File.expand_path('/foo')
- file[:checksum].should == :md5lite
+ expect(file[:checksum]).to eq(:md5lite)
end
end
describe "when validating" do
[[:source, :target], [:source, :content], [:target, :content]].each do |prop1,prop2|
it "should fail if both #{prop1} and #{prop2} are specified" do
file[prop1] = prop1 == :source ? File.expand_path("prop1 value") : "prop1 value"
file[prop2] = "prop2 value"
expect do
file.validate
end.to raise_error(Puppet::Error, /You cannot specify more than one of/)
end
end
end
end
diff --git a/spec/unit/type/filebucket_spec.rb b/spec/unit/type/filebucket_spec.rb
index 4c6fc42e2..b8c9c1489 100755
--- a/spec/unit/type/filebucket_spec.rb
+++ b/spec/unit/type/filebucket_spec.rb
@@ -1,103 +1,103 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:filebucket) do
include PuppetSpec::Files
describe "when validating attributes" do
%w{name server port path}.each do |attr|
it "should have a '#{attr}' parameter" do
- Puppet::Type.type(:filebucket).attrtype(attr.intern).should == :param
+ expect(Puppet::Type.type(:filebucket).attrtype(attr.intern)).to eq(:param)
end
end
it "should have its 'name' attribute set as its namevar" do
- Puppet::Type.type(:filebucket).key_attributes.should == [:name]
+ expect(Puppet::Type.type(:filebucket).key_attributes).to eq([:name])
end
end
it "should use the clientbucketdir as the path by default path" do
Puppet.settings[:clientbucketdir] = "/my/bucket"
- Puppet::Type.type(:filebucket).new(:name => "main")[:path].should == Puppet[:clientbucketdir]
+ expect(Puppet::Type.type(:filebucket).new(:name => "main")[:path]).to eq(Puppet[:clientbucketdir])
end
it "should use the masterport as the path by default port" do
Puppet.settings[:masterport] = 50
- Puppet::Type.type(:filebucket).new(:name => "main")[:port].should == Puppet[:masterport]
+ expect(Puppet::Type.type(:filebucket).new(:name => "main")[:port]).to eq(Puppet[:masterport])
end
it "should use the server as the path by default server" do
Puppet.settings[:server] = "myserver"
- Puppet::Type.type(:filebucket).new(:name => "main")[:server].should == Puppet[:server]
+ expect(Puppet::Type.type(:filebucket).new(:name => "main")[:server]).to eq(Puppet[:server])
end
it "be local by default" do
bucket = Puppet::Type.type(:filebucket).new :name => "main"
- bucket.bucket.should be_local
+ expect(bucket.bucket).to be_local
end
describe "path" do
def bucket(hash)
Puppet::Type.type(:filebucket).new({:name => 'main'}.merge(hash))
end
it "should accept false as a value" do
expect { bucket(:path => false) }.not_to raise_error
end
it "should accept true as a value" do
expect { bucket(:path => true) }.not_to raise_error
end
it "should fail when given an array of values" do
expect { bucket(:path => ['one', 'two']) }.
to raise_error Puppet::Error, /only have one filebucket path/
end
%w{one ../one one/two}.each do |path|
it "should fail if given a relative path of #{path.inspect}" do
expect { bucket(:path => path) }.
to raise_error Puppet::Error, /Filebucket paths must be absolute/
end
end
it "should succeed if given an absolute path" do
expect { bucket(:path => make_absolute('/tmp/bucket')) }.not_to raise_error
end
it "not be local if path is false" do
- bucket(:path => false).bucket.should_not be_local
+ expect(bucket(:path => false).bucket).not_to be_local
end
it "be local if both a path and a server are specified" do
- bucket(:server => "puppet", :path => make_absolute("/my/path")).bucket.should be_local
+ expect(bucket(:server => "puppet", :path => make_absolute("/my/path")).bucket).to be_local
end
end
describe "when creating the filebucket" do
before do
@bucket = stub 'bucket', :name= => nil
end
it "should use any provided path" do
path = make_absolute("/foo/bar")
bucket = Puppet::Type.type(:filebucket).new :name => "main", :path => path
Puppet::FileBucket::Dipper.expects(:new).with(:Path => path).returns @bucket
bucket.bucket
end
it "should use any provided server and port" do
bucket = Puppet::Type.type(:filebucket).new :name => "main", :server => "myserv", :port => "myport", :path => false
Puppet::FileBucket::Dipper.expects(:new).with(:Server => "myserv", :Port => "myport").returns @bucket
bucket.bucket
end
it "should use the default server if the path is unset and no server is provided" do
Puppet.settings[:server] = "myserv"
bucket = Puppet::Type.type(:filebucket).new :name => "main", :path => false
Puppet::FileBucket::Dipper.expects(:new).with { |args| args[:Server] == "myserv" }.returns @bucket
bucket.bucket
end
end
end
diff --git a/spec/unit/type/group_spec.rb b/spec/unit/type/group_spec.rb
index ffadfac26..656e86e36 100755
--- a/spec/unit/type/group_spec.rb
+++ b/spec/unit/type/group_spec.rb
@@ -1,84 +1,84 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:group) do
before do
@class = Puppet::Type.type(:group)
end
it "should have a system_groups feature" do
- @class.provider_feature(:system_groups).should_not be_nil
+ expect(@class.provider_feature(:system_groups)).not_to be_nil
end
describe "when validating attributes" do
[:name, :allowdupe].each do |param|
it "should have a #{param} parameter" do
- @class.attrtype(param).should == :param
+ expect(@class.attrtype(param)).to eq(:param)
end
end
[:ensure, :gid].each do |param|
it "should have a #{param} property" do
- @class.attrtype(param).should == :property
+ expect(@class.attrtype(param)).to eq(:property)
end
end
it "should convert gids provided as strings into integers" do
- @class.new(:name => "foo", :gid => "15")[:gid].should == 15
+ expect(@class.new(:name => "foo", :gid => "15")[:gid]).to eq(15)
end
it "should accepts gids provided as integers" do
- @class.new(:name => "foo", :gid => 15)[:gid].should == 15
+ expect(@class.new(:name => "foo", :gid => 15)[:gid]).to eq(15)
end
end
it "should have a boolean method for determining if duplicates are allowed" do
- @class.new(:name => "foo").must respond_to "allowdupe?"
+ expect(@class.new(:name => "foo")).to respond_to "allowdupe?"
end
it "should have a boolean method for determining if system groups are allowed" do
- @class.new(:name => "foo").must respond_to "system?"
+ expect(@class.new(:name => "foo")).to respond_to "system?"
end
it "should call 'create' to create the group" do
group = @class.new(:name => "foo", :ensure => :present)
group.provider.expects(:create)
group.parameter(:ensure).sync
end
it "should call 'delete' to remove the group" do
group = @class.new(:name => "foo", :ensure => :absent)
group.provider.expects(:delete)
group.parameter(:ensure).sync
end
it "delegates the existence check to its provider" do
provider = @class.provide(:testing) {}
provider_instance = provider.new
provider_instance.expects(:exists?).returns true
type = @class.new(:name => "group", :provider => provider_instance)
- type.exists?.should == true
+ expect(type.exists?).to eq(true)
end
describe "should delegate :members implementation to the provider:" do
let (:provider) { @class.provide(:testing) { has_features :manages_members } }
let (:provider_instance) { provider.new }
let (:type) { @class.new(:name => "group", :provider => provider_instance, :members => ['user1']) }
it "insync? calls members_insync?" do
provider_instance.expects(:members_insync?).with(['user1'], ['user1']).returns true
- type.property(:members).insync?(['user1']).should be_true
+ expect(type.property(:members).insync?(['user1'])).to be_truthy
end
it "is_to_s and should_to_s call members_to_s" do
provider_instance.expects(:members_to_s).with(['user2', 'user1']).returns "user2 (), user1 ()"
provider_instance.expects(:members_to_s).with(['user1']).returns "user1 ()"
- type.property(:members).is_to_s('user1').should == 'user1 ()'
- type.property(:members).should_to_s('user2,user1').should == 'user2 (), user1 ()'
+ expect(type.property(:members).is_to_s('user1')).to eq('user1 ()')
+ expect(type.property(:members).should_to_s('user2,user1')).to eq('user2 (), user1 ()')
end
end
end
diff --git a/spec/unit/type/host_spec.rb b/spec/unit/type/host_spec.rb
index 112917b59..8941756b7 100755
--- a/spec/unit/type/host_spec.rb
+++ b/spec/unit/type/host_spec.rb
@@ -1,681 +1,681 @@
#! /usr/bin/env ruby
require 'spec_helper'
host = Puppet::Type.type(:host)
describe host do
FakeHostProvider = Struct.new(:ip, :host_aliases, :comment)
before do
@class = host
@catalog = Puppet::Resource::Catalog.new
@provider = FakeHostProvider.new
@resource = stub 'resource', :resource => nil, :provider => @provider
end
it "should have :name be its namevar" do
- @class.key_attributes.should == [:name]
+ expect(@class.key_attributes).to eq([:name])
end
describe "when validating attributes" do
[:name, :provider ].each do |param|
it "should have a #{param} parameter" do
- @class.attrtype(param).should == :param
+ expect(@class.attrtype(param)).to eq(:param)
end
end
[:ip, :target, :host_aliases, :comment, :ensure].each do |property|
it "should have a #{property} property" do
- @class.attrtype(property).should == :property
+ expect(@class.attrtype(property)).to eq(:property)
end
end
it "should have a list host_aliases" do
- @class.attrclass(:host_aliases).ancestors.should be_include(Puppet::Property::OrderedList)
+ expect(@class.attrclass(:host_aliases).ancestors).to be_include(Puppet::Property::OrderedList)
end
end
describe "when validating values" do
it "should support present as a value for ensure" do
- proc { @class.new(:name => "foo", :ensure => :present) }.should_not raise_error
+ expect { @class.new(:name => "foo", :ensure => :present) }.not_to raise_error
end
it "should support absent as a value for ensure" do
- proc { @class.new(:name => "foo", :ensure => :absent) }.should_not raise_error
+ expect { @class.new(:name => "foo", :ensure => :absent) }.not_to raise_error
end
it "should accept IPv4 addresses" do
- proc { @class.new(:name => "foo", :ip => '10.96.0.1') }.should_not raise_error
+ expect { @class.new(:name => "foo", :ip => '10.96.0.1') }.not_to raise_error
end
it "should accept long IPv6 addresses" do
# Taken from wikipedia article about ipv6
- proc { @class.new(:name => "foo", :ip => '2001:0db8:85a3:08d3:1319:8a2e:0370:7344') }.should_not raise_error
+ expect { @class.new(:name => "foo", :ip => '2001:0db8:85a3:08d3:1319:8a2e:0370:7344') }.not_to raise_error
end
it "should accept one host_alias" do
- proc { @class.new(:name => "foo", :host_aliases => 'alias1') }.should_not raise_error
+ expect { @class.new(:name => "foo", :host_aliases => 'alias1') }.not_to raise_error
end
it "should accept multiple host_aliases" do
- proc { @class.new(:name => "foo", :host_aliases => [ 'alias1', 'alias2' ]) }.should_not raise_error
+ expect { @class.new(:name => "foo", :host_aliases => [ 'alias1', 'alias2' ]) }.not_to raise_error
end
it "should accept shortened IPv6 addresses" do
- proc { @class.new(:name => "foo", :ip => '2001:db8:0:8d3:0:8a2e:70:7344') }.should_not raise_error
- proc { @class.new(:name => "foo", :ip => '::ffff:192.0.2.128') }.should_not raise_error
- proc { @class.new(:name => "foo", :ip => '::1') }.should_not raise_error
+ expect { @class.new(:name => "foo", :ip => '2001:db8:0:8d3:0:8a2e:70:7344') }.not_to raise_error
+ expect { @class.new(:name => "foo", :ip => '::ffff:192.0.2.128') }.not_to raise_error
+ expect { @class.new(:name => "foo", :ip => '::1') }.not_to raise_error
end
it "should not accept malformed IPv4 addresses like 192.168.0.300" do
- proc { @class.new(:name => "foo", :ip => '192.168.0.300') }.should raise_error
+ expect { @class.new(:name => "foo", :ip => '192.168.0.300') }.to raise_error
end
it "should reject over-long IPv4 addresses" do
expect { @class.new(:name => "foo", :ip => '10.10.10.10.10') }.to raise_error
end
it "should not accept malformed IP addresses like 2001:0dg8:85a3:08d3:1319:8a2e:0370:7344" do
- proc { @class.new(:name => "foo", :ip => '2001:0dg8:85a3:08d3:1319:8a2e:0370:7344') }.should raise_error
+ expect { @class.new(:name => "foo", :ip => '2001:0dg8:85a3:08d3:1319:8a2e:0370:7344') }.to raise_error
end
# Assorted, annotated IPv6 passes.
["::1", # loopback, compressed, non-routable
"::", # unspecified, compressed, non-routable
"0:0:0:0:0:0:0:1", # loopback, full
"0:0:0:0:0:0:0:0", # unspecified, full
"2001:DB8:0:0:8:800:200C:417A", # unicast, full
"FF01:0:0:0:0:0:0:101", # multicast, full
"2001:DB8::8:800:200C:417A", # unicast, compressed
"FF01::101", # multicast, compressed
# Some more test cases that should pass.
"2001:0000:1234:0000:0000:C1C0:ABCD:0876",
"3ffe:0b00:0000:0000:0001:0000:0000:000a",
"FF02:0000:0000:0000:0000:0000:0000:0001",
"0000:0000:0000:0000:0000:0000:0000:0001",
"0000:0000:0000:0000:0000:0000:0000:0000",
# Assorted valid, compressed IPv6 addresses.
"2::10",
"ff02::1",
"fe80::",
"2002::",
"2001:db8::",
"2001:0db8:1234::",
"::ffff:0:0",
"::1",
"1:2:3:4:5:6:7:8",
"1:2:3:4:5:6::8",
"1:2:3:4:5::8",
"1:2:3:4::8",
"1:2:3::8",
"1:2::8",
"1::8",
"1::2:3:4:5:6:7",
"1::2:3:4:5:6",
"1::2:3:4:5",
"1::2:3:4",
"1::2:3",
"1::8",
"::2:3:4:5:6:7:8",
"::2:3:4:5:6:7",
"::2:3:4:5:6",
"::2:3:4:5",
"::2:3:4",
"::2:3",
"::8",
"1:2:3:4:5:6::",
"1:2:3:4:5::",
"1:2:3:4::",
"1:2:3::",
"1:2::",
"1::",
"1:2:3:4:5::7:8",
"1:2:3:4::7:8",
"1:2:3::7:8",
"1:2::7:8",
"1::7:8",
# IPv4 addresses as dotted-quads
"1:2:3:4:5:6:1.2.3.4",
"1:2:3:4:5::1.2.3.4",
"1:2:3:4::1.2.3.4",
"1:2:3::1.2.3.4",
"1:2::1.2.3.4",
"1::1.2.3.4",
"1:2:3:4::5:1.2.3.4",
"1:2:3::5:1.2.3.4",
"1:2::5:1.2.3.4",
"1::5:1.2.3.4",
"1::5:11.22.33.44",
"fe80::217:f2ff:254.7.237.98",
"::ffff:192.168.1.26",
"::ffff:192.168.1.1",
"0:0:0:0:0:0:13.1.68.3", # IPv4-compatible IPv6 address, full, deprecated
"0:0:0:0:0:FFFF:129.144.52.38", # IPv4-mapped IPv6 address, full
"::13.1.68.3", # IPv4-compatible IPv6 address, compressed, deprecated
"::FFFF:129.144.52.38", # IPv4-mapped IPv6 address, compressed
"fe80:0:0:0:204:61ff:254.157.241.86",
"fe80::204:61ff:254.157.241.86",
"::ffff:12.34.56.78",
"::ffff:192.0.2.128", # this is OK, since there's a single zero digit in IPv4
"fe80:0000:0000:0000:0204:61ff:fe9d:f156",
"fe80:0:0:0:204:61ff:fe9d:f156",
"fe80::204:61ff:fe9d:f156",
"::1",
"fe80::",
"fe80::1",
"::ffff:c000:280",
# Additional test cases from http://rt.cpan.org/Public/Bug/Display.html?id=50693
"2001:0db8:85a3:0000:0000:8a2e:0370:7334",
"2001:db8:85a3:0:0:8a2e:370:7334",
"2001:db8:85a3::8a2e:370:7334",
"2001:0db8:0000:0000:0000:0000:1428:57ab",
"2001:0db8:0000:0000:0000::1428:57ab",
"2001:0db8:0:0:0:0:1428:57ab",
"2001:0db8:0:0::1428:57ab",
"2001:0db8::1428:57ab",
"2001:db8::1428:57ab",
"0000:0000:0000:0000:0000:0000:0000:0001",
"::1",
"::ffff:0c22:384e",
"2001:0db8:1234:0000:0000:0000:0000:0000",
"2001:0db8:1234:ffff:ffff:ffff:ffff:ffff",
"2001:db8:a::123",
"fe80::",
"1111:2222:3333:4444:5555:6666:7777:8888",
"1111:2222:3333:4444:5555:6666:7777::",
"1111:2222:3333:4444:5555:6666::",
"1111:2222:3333:4444:5555::",
"1111:2222:3333:4444::",
"1111:2222:3333::",
"1111:2222::",
"1111::",
"1111:2222:3333:4444:5555:6666::8888",
"1111:2222:3333:4444:5555::8888",
"1111:2222:3333:4444::8888",
"1111:2222:3333::8888",
"1111:2222::8888",
"1111::8888",
"::8888",
"1111:2222:3333:4444:5555::7777:8888",
"1111:2222:3333:4444::7777:8888",
"1111:2222:3333::7777:8888",
"1111:2222::7777:8888",
"1111::7777:8888",
"::7777:8888",
"1111:2222:3333:4444::6666:7777:8888",
"1111:2222:3333::6666:7777:8888",
"1111:2222::6666:7777:8888",
"1111::6666:7777:8888",
"::6666:7777:8888",
"1111:2222:3333::5555:6666:7777:8888",
"1111:2222::5555:6666:7777:8888",
"1111::5555:6666:7777:8888",
"::5555:6666:7777:8888",
"1111:2222::4444:5555:6666:7777:8888",
"1111::4444:5555:6666:7777:8888",
"::4444:5555:6666:7777:8888",
"1111::3333:4444:5555:6666:7777:8888",
"::3333:4444:5555:6666:7777:8888",
"::2222:3333:4444:5555:6666:7777:8888",
"1111:2222:3333:4444:5555:6666:123.123.123.123",
"1111:2222:3333:4444:5555::123.123.123.123",
"1111:2222:3333:4444::123.123.123.123",
"1111:2222:3333::123.123.123.123",
"1111:2222::123.123.123.123",
"1111::123.123.123.123",
"::123.123.123.123",
"1111:2222:3333:4444::6666:123.123.123.123",
"1111:2222:3333::6666:123.123.123.123",
"1111:2222::6666:123.123.123.123",
"1111::6666:123.123.123.123",
"::6666:123.123.123.123",
"1111:2222:3333::5555:6666:123.123.123.123",
"1111:2222::5555:6666:123.123.123.123",
"1111::5555:6666:123.123.123.123",
"::5555:6666:123.123.123.123",
"1111:2222::4444:5555:6666:123.123.123.123",
"1111::4444:5555:6666:123.123.123.123",
"::4444:5555:6666:123.123.123.123",
"1111::3333:4444:5555:6666:123.123.123.123",
"::2222:3333:4444:5555:6666:123.123.123.123",
# Playing with combinations of "0" and "::"; these are all sytactically
# correct, but are bad form because "0" adjacent to "::" should be
# combined into "::"
"::0:0:0:0:0:0:0",
"::0:0:0:0:0:0",
"::0:0:0:0:0",
"::0:0:0:0",
"::0:0:0",
"::0:0",
"::0",
"0:0:0:0:0:0:0::",
"0:0:0:0:0:0::",
"0:0:0:0:0::",
"0:0:0:0::",
"0:0:0::",
"0:0::",
"0::",
# Additional cases: http://crisp.tweakblogs.net/blog/2031/ipv6-validation-%28and-caveats%29.html
"0:a:b:c:d:e:f::",
"::0:a:b:c:d:e:f", # syntactically correct, but bad form (::0:... could be combined)
"a:b:c:d:e:f:0::",
].each do |ip|
it "should accept #{ip.inspect} as an IPv6 address" do
expect { @class.new(:name => "foo", :ip => ip) }.not_to raise_error
end
end
# ...aaaand, some failure cases.
[":",
"02001:0000:1234:0000:0000:C1C0:ABCD:0876", # extra 0 not allowed!
"2001:0000:1234:0000:00001:C1C0:ABCD:0876", # extra 0 not allowed!
"2001:0000:1234:0000:0000:C1C0:ABCD:0876 0", # junk after valid address
"2001:0000:1234: 0000:0000:C1C0:ABCD:0876", # internal space
"3ffe:0b00:0000:0001:0000:0000:000a", # seven segments
"FF02:0000:0000:0000:0000:0000:0000:0000:0001", # nine segments
"3ffe:b00::1::a", # double "::"
"::1111:2222:3333:4444:5555:6666::", # double "::"
"1:2:3::4:5::7:8", # Double "::"
"12345::6:7:8",
# IPv4 embedded, but bad...
"1::5:400.2.3.4", "1::5:260.2.3.4", "1::5:256.2.3.4", "1::5:1.256.3.4",
"1::5:1.2.256.4", "1::5:1.2.3.256", "1::5:300.2.3.4", "1::5:1.300.3.4",
"1::5:1.2.300.4", "1::5:1.2.3.300", "1::5:900.2.3.4", "1::5:1.900.3.4",
"1::5:1.2.900.4", "1::5:1.2.3.900", "1::5:300.300.300.300", "1::5:3000.30.30.30",
"1::400.2.3.4", "1::260.2.3.4", "1::256.2.3.4", "1::1.256.3.4",
"1::1.2.256.4", "1::1.2.3.256", "1::300.2.3.4", "1::1.300.3.4",
"1::1.2.300.4", "1::1.2.3.300", "1::900.2.3.4", "1::1.900.3.4",
"1::1.2.900.4", "1::1.2.3.900", "1::300.300.300.300", "1::3000.30.30.30",
"::400.2.3.4", "::260.2.3.4", "::256.2.3.4", "::1.256.3.4",
"::1.2.256.4", "::1.2.3.256", "::300.2.3.4", "::1.300.3.4",
"::1.2.300.4", "::1.2.3.300", "::900.2.3.4", "::1.900.3.4",
"::1.2.900.4", "::1.2.3.900", "::300.300.300.300", "::3000.30.30.30",
"2001:1:1:1:1:1:255Z255X255Y255", # garbage instead of "." in IPv4
"::ffff:192x168.1.26", # ditto
"::ffff:2.3.4",
"::ffff:257.1.2.3",
"1.2.3.4:1111:2222:3333:4444::5555",
"1.2.3.4:1111:2222:3333::5555",
"1.2.3.4:1111:2222::5555",
"1.2.3.4:1111::5555",
"1.2.3.4::5555",
"1.2.3.4::",
# Testing IPv4 addresses represented as dotted-quads Leading zero's in
# IPv4 addresses not allowed: some systems treat the leading "0" in
# ".086" as the start of an octal number Update: The BNF in RFC-3986
# explicitly defines the dec-octet (for IPv4 addresses) not to have a
# leading zero
"fe80:0000:0000:0000:0204:61ff:254.157.241.086",
"XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:1.2.3.4",
"1111:2222:3333:4444:5555:6666:00.00.00.00",
"1111:2222:3333:4444:5555:6666:000.000.000.000",
"1111:2222:3333:4444:5555:6666:256.256.256.256",
"1111:2222:3333:4444::5555:",
"1111:2222:3333::5555:",
"1111:2222::5555:",
"1111::5555:",
"::5555:",
":::",
"1111:",
":",
":1111:2222:3333:4444::5555",
":1111:2222:3333::5555",
":1111:2222::5555",
":1111::5555",
":::5555",
":::",
# Additional test cases from http://rt.cpan.org/Public/Bug/Display.html?id=50693
"123",
"ldkfj",
"2001::FFD3::57ab",
"2001:db8:85a3::8a2e:37023:7334",
"2001:db8:85a3::8a2e:370k:7334",
"1:2:3:4:5:6:7:8:9",
"1::2::3",
"1:::3:4:5",
"1:2:3::4:5:6:7:8:9",
# Invalid data
"XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX",
# Too many components
"1111:2222:3333:4444:5555:6666:7777:8888:9999",
"1111:2222:3333:4444:5555:6666:7777:8888::",
"::2222:3333:4444:5555:6666:7777:8888:9999",
# Too few components
"1111:2222:3333:4444:5555:6666:7777",
"1111:2222:3333:4444:5555:6666",
"1111:2222:3333:4444:5555",
"1111:2222:3333:4444",
"1111:2222:3333",
"1111:2222",
"1111",
# Missing :
"11112222:3333:4444:5555:6666:7777:8888",
"1111:22223333:4444:5555:6666:7777:8888",
"1111:2222:33334444:5555:6666:7777:8888",
"1111:2222:3333:44445555:6666:7777:8888",
"1111:2222:3333:4444:55556666:7777:8888",
"1111:2222:3333:4444:5555:66667777:8888",
"1111:2222:3333:4444:5555:6666:77778888",
# Missing : intended for ::
"1111:2222:3333:4444:5555:6666:7777:8888:",
"1111:2222:3333:4444:5555:6666:7777:",
"1111:2222:3333:4444:5555:6666:",
"1111:2222:3333:4444:5555:",
"1111:2222:3333:4444:",
"1111:2222:3333:",
"1111:2222:",
"1111:",
":",
":8888",
":7777:8888",
":6666:7777:8888",
":5555:6666:7777:8888",
":4444:5555:6666:7777:8888",
":3333:4444:5555:6666:7777:8888",
":2222:3333:4444:5555:6666:7777:8888",
":1111:2222:3333:4444:5555:6666:7777:8888",
# :::
":::2222:3333:4444:5555:6666:7777:8888",
"1111:::3333:4444:5555:6666:7777:8888",
"1111:2222:::4444:5555:6666:7777:8888",
"1111:2222:3333:::5555:6666:7777:8888",
"1111:2222:3333:4444:::6666:7777:8888",
"1111:2222:3333:4444:5555:::7777:8888",
"1111:2222:3333:4444:5555:6666:::8888",
"1111:2222:3333:4444:5555:6666:7777:::",
# Double ::",
"::2222::4444:5555:6666:7777:8888",
"::2222:3333::5555:6666:7777:8888",
"::2222:3333:4444::6666:7777:8888",
"::2222:3333:4444:5555::7777:8888",
"::2222:3333:4444:5555:7777::8888",
"::2222:3333:4444:5555:7777:8888::",
"1111::3333::5555:6666:7777:8888",
"1111::3333:4444::6666:7777:8888",
"1111::3333:4444:5555::7777:8888",
"1111::3333:4444:5555:6666::8888",
"1111::3333:4444:5555:6666:7777::",
"1111:2222::4444::6666:7777:8888",
"1111:2222::4444:5555::7777:8888",
"1111:2222::4444:5555:6666::8888",
"1111:2222::4444:5555:6666:7777::",
"1111:2222:3333::5555::7777:8888",
"1111:2222:3333::5555:6666::8888",
"1111:2222:3333::5555:6666:7777::",
"1111:2222:3333:4444::6666::8888",
"1111:2222:3333:4444::6666:7777::",
"1111:2222:3333:4444:5555::7777::",
# Too many components"
"1111:2222:3333:4444:5555:6666:7777:8888:1.2.3.4",
"1111:2222:3333:4444:5555:6666:7777:1.2.3.4",
"1111:2222:3333:4444:5555:6666::1.2.3.4",
"::2222:3333:4444:5555:6666:7777:1.2.3.4",
"1111:2222:3333:4444:5555:6666:1.2.3.4.5",
# Too few components
"1111:2222:3333:4444:5555:1.2.3.4",
"1111:2222:3333:4444:1.2.3.4",
"1111:2222:3333:1.2.3.4",
"1111:2222:1.2.3.4",
"1111:1.2.3.4",
# Missing :
"11112222:3333:4444:5555:6666:1.2.3.4",
"1111:22223333:4444:5555:6666:1.2.3.4",
"1111:2222:33334444:5555:6666:1.2.3.4",
"1111:2222:3333:44445555:6666:1.2.3.4",
"1111:2222:3333:4444:55556666:1.2.3.4",
"1111:2222:3333:4444:5555:66661.2.3.4",
# Missing .
"1111:2222:3333:4444:5555:6666:255255.255.255",
"1111:2222:3333:4444:5555:6666:255.255255.255",
"1111:2222:3333:4444:5555:6666:255.255.255255",
# Missing : intended for ::
":1.2.3.4",
":6666:1.2.3.4",
":5555:6666:1.2.3.4",
":4444:5555:6666:1.2.3.4",
":3333:4444:5555:6666:1.2.3.4",
":2222:3333:4444:5555:6666:1.2.3.4",
":1111:2222:3333:4444:5555:6666:1.2.3.4",
# :::
":::2222:3333:4444:5555:6666:1.2.3.4",
"1111:::3333:4444:5555:6666:1.2.3.4",
"1111:2222:::4444:5555:6666:1.2.3.4",
"1111:2222:3333:::5555:6666:1.2.3.4",
"1111:2222:3333:4444:::6666:1.2.3.4",
"1111:2222:3333:4444:5555:::1.2.3.4",
# Double ::
"::2222::4444:5555:6666:1.2.3.4",
"::2222:3333::5555:6666:1.2.3.4",
"::2222:3333:4444::6666:1.2.3.4",
"::2222:3333:4444:5555::1.2.3.4",
"1111::3333::5555:6666:1.2.3.4",
"1111::3333:4444::6666:1.2.3.4",
"1111::3333:4444:5555::1.2.3.4",
"1111:2222::4444::6666:1.2.3.4",
"1111:2222::4444:5555::1.2.3.4",
"1111:2222:3333::5555::1.2.3.4",
# Missing parts
"::.",
"::..",
"::...",
"::1...",
"::1.2..",
"::1.2.3.",
"::.2..",
"::.2.3.",
"::.2.3.4",
"::..3.",
"::..3.4",
"::...4",
# Extra : in front
":1111:2222:3333:4444:5555:6666:7777::",
":1111:2222:3333:4444:5555:6666::",
":1111:2222:3333:4444:5555::",
":1111:2222:3333:4444::",
":1111:2222:3333::",
":1111:2222::",
":1111::",
":::",
":1111:2222:3333:4444:5555:6666::8888",
":1111:2222:3333:4444:5555::8888",
":1111:2222:3333:4444::8888",
":1111:2222:3333::8888",
":1111:2222::8888",
":1111::8888",
":::8888",
":1111:2222:3333:4444:5555::7777:8888",
":1111:2222:3333:4444::7777:8888",
":1111:2222:3333::7777:8888",
":1111:2222::7777:8888",
":1111::7777:8888",
":::7777:8888",
":1111:2222:3333:4444::6666:7777:8888",
":1111:2222:3333::6666:7777:8888",
":1111:2222::6666:7777:8888",
":1111::6666:7777:8888",
":::6666:7777:8888",
":1111:2222:3333::5555:6666:7777:8888",
":1111:2222::5555:6666:7777:8888",
":1111::5555:6666:7777:8888",
":::5555:6666:7777:8888",
":1111:2222::4444:5555:6666:7777:8888",
":1111::4444:5555:6666:7777:8888",
":::4444:5555:6666:7777:8888",
":1111::3333:4444:5555:6666:7777:8888",
":::3333:4444:5555:6666:7777:8888",
":::2222:3333:4444:5555:6666:7777:8888",
":1111:2222:3333:4444:5555:6666:1.2.3.4",
":1111:2222:3333:4444:5555::1.2.3.4",
":1111:2222:3333:4444::1.2.3.4",
":1111:2222:3333::1.2.3.4",
":1111:2222::1.2.3.4",
":1111::1.2.3.4",
":::1.2.3.4",
":1111:2222:3333:4444::6666:1.2.3.4",
":1111:2222:3333::6666:1.2.3.4",
":1111:2222::6666:1.2.3.4",
":1111::6666:1.2.3.4",
":::6666:1.2.3.4",
":1111:2222:3333::5555:6666:1.2.3.4",
":1111:2222::5555:6666:1.2.3.4",
":1111::5555:6666:1.2.3.4",
":::5555:6666:1.2.3.4",
":1111:2222::4444:5555:6666:1.2.3.4",
":1111::4444:5555:6666:1.2.3.4",
":::4444:5555:6666:1.2.3.4",
":1111::3333:4444:5555:6666:1.2.3.4",
":::2222:3333:4444:5555:6666:1.2.3.4",
# Extra : at end
"1111:2222:3333:4444:5555:6666:7777:::",
"1111:2222:3333:4444:5555:6666:::",
"1111:2222:3333:4444:5555:::",
"1111:2222:3333:4444:::",
"1111:2222:3333:::",
"1111:2222:::",
"1111:::",
":::",
"1111:2222:3333:4444:5555:6666::8888:",
"1111:2222:3333:4444:5555::8888:",
"1111:2222:3333:4444::8888:",
"1111:2222:3333::8888:",
"1111:2222::8888:",
"1111::8888:",
"::8888:",
"1111:2222:3333:4444:5555::7777:8888:",
"1111:2222:3333:4444::7777:8888:",
"1111:2222:3333::7777:8888:",
"1111:2222::7777:8888:",
"1111::7777:8888:",
"::7777:8888:",
"1111:2222:3333:4444::6666:7777:8888:",
"1111:2222:3333::6666:7777:8888:",
"1111:2222::6666:7777:8888:",
"1111::6666:7777:8888:",
"::6666:7777:8888:",
"1111:2222:3333::5555:6666:7777:8888:",
"1111:2222::5555:6666:7777:8888:",
"1111::5555:6666:7777:8888:",
"::5555:6666:7777:8888:",
"1111:2222::4444:5555:6666:7777:8888:",
"1111::4444:5555:6666:7777:8888:",
"::4444:5555:6666:7777:8888:",
"1111::3333:4444:5555:6666:7777:8888:",
"::3333:4444:5555:6666:7777:8888:",
"::2222:3333:4444:5555:6666:7777:8888:",
].each do |ip|
it "should reject #{ip.inspect} as an IPv6 address" do
expect { @class.new(:name => "foo", :ip => ip) }.to raise_error
end
end
it "should not accept newlines in resourcename" do
expect { @class.new(:name => "fo\no", :ip => '127.0.0.1' ) }.to raise_error(Puppet::ResourceError, /Hostname cannot include newline/)
end
it "should not accept newlines in ipaddress" do
expect { @class.new(:name => "foo", :ip => "127.0.0.1\n") }.to raise_error(Puppet::ResourceError, /Invalid IP address/)
end
it "should not accept newlines in host_aliases" do
expect { @class.new(:name => "foo", :ip => '127.0.0.1', :host_aliases => [ 'well_formed', "thisalias\nhavenewline" ] ) }.to raise_error(Puppet::ResourceError, /Host aliases cannot include whitespace/)
end
it "should not accept newlines in comment" do
expect { @class.new(:name => "foo", :ip => '127.0.0.1', :comment => "Test of comment blah blah \n test 123" ) }.to raise_error(Puppet::ResourceError, /Comment cannot include newline/)
end
it "should not accept spaces in resourcename" do
expect { @class.new(:name => "foo bar") }.to raise_error(Puppet::ResourceError, /Invalid host name/)
end
it "should not accept host_aliases with spaces" do
expect { @class.new(:name => "foo", :host_aliases => [ 'well_formed', 'not wellformed' ]) }.to raise_error(Puppet::ResourceError, /Host aliases cannot include whitespace/)
end
it "should not accept empty host_aliases" do
expect { @class.new(:name => "foo", :host_aliases => ['alias1','']) }.to raise_error(Puppet::ResourceError, /Host aliases cannot be an empty string/)
end
end
describe "when syncing" do
it "should send the first value to the provider for ip property" do
@ip = @class.attrclass(:ip).new(:resource => @resource, :should => %w{192.168.0.1 192.168.0.2})
@ip.sync
- @provider.ip.should == '192.168.0.1'
+ expect(@provider.ip).to eq('192.168.0.1')
end
it "should send the first value to the provider for comment property" do
@comment = @class.attrclass(:comment).new(:resource => @resource, :should => %w{Bazinga Notme})
@comment.sync
- @provider.comment.should == 'Bazinga'
+ expect(@provider.comment).to eq('Bazinga')
end
it "should send the joined array to the provider for host_alias" do
@host_aliases = @class.attrclass(:host_aliases).new(:resource => @resource, :should => %w{foo bar})
@host_aliases.sync
- @provider.host_aliases.should == 'foo bar'
+ expect(@provider.host_aliases).to eq('foo bar')
end
it "should also use the specified delimiter for joining" do
@host_aliases = @class.attrclass(:host_aliases).new(:resource => @resource, :should => %w{foo bar})
@host_aliases.stubs(:delimiter).returns "\t"
@host_aliases.sync
- @provider.host_aliases.should == "foo\tbar"
+ expect(@provider.host_aliases).to eq("foo\tbar")
end
it "should care about the order of host_aliases" do
@host_aliases = @class.attrclass(:host_aliases).new(:resource => @resource, :should => %w{foo bar})
- @host_aliases.insync?(%w{foo bar}).should == true
- @host_aliases.insync?(%w{bar foo}).should == false
+ expect(@host_aliases.insync?(%w{foo bar})).to eq(true)
+ expect(@host_aliases.insync?(%w{bar foo})).to eq(false)
end
it "should not consider aliases to be in sync if should is a subset of current" do
@host_aliases = @class.attrclass(:host_aliases).new(:resource => @resource, :should => %w{foo bar})
- @host_aliases.insync?(%w{foo bar anotherone}).should == false
+ expect(@host_aliases.insync?(%w{foo bar anotherone})).to eq(false)
end
end
end
diff --git a/spec/unit/type/interface_spec.rb b/spec/unit/type/interface_spec.rb
index 109c30fd8..fd9e3f050 100755
--- a/spec/unit/type/interface_spec.rb
+++ b/spec/unit/type/interface_spec.rb
@@ -1,97 +1,97 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:interface) do
it "should have a 'name' parameter'" do
- Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1")[:name].should == "FastEthernet 0/1"
+ expect(Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1")[:name]).to eq("FastEthernet 0/1")
end
it "should have a 'device_url' parameter'" do
- Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :device_url => :device)[:device_url].should == :device
+ expect(Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :device_url => :device)[:device_url]).to eq(:device)
end
it "should have an ensure property" do
- Puppet::Type.type(:interface).attrtype(:ensure).should == :property
+ expect(Puppet::Type.type(:interface).attrtype(:ensure)).to eq(:property)
end
it "should be applied on device" do
- Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1").must be_appliable_to_device
+ expect(Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1")).to be_appliable_to_device
end
[:description, :speed, :duplex, :native_vlan, :encapsulation, :mode, :allowed_trunk_vlans, :etherchannel, :ipaddress].each do |p|
it "should have a #{p} property" do
- Puppet::Type.type(:interface).attrtype(p).should == :property
+ expect(Puppet::Type.type(:interface).attrtype(p)).to eq(:property)
end
end
describe "when validating attribute values" do
before do
@provider = stub 'provider', :class => Puppet::Type.type(:interface).defaultprovider, :clear => nil
Puppet::Type.type(:interface).defaultprovider.stubs(:new).returns(@provider)
end
it "should support :present as a value to :ensure" do
Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :ensure => :present)
end
it "should support :shutdown as a value to :ensure" do
Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :ensure => :shutdown)
end
it "should support :no_shutdown as a value to :ensure" do
Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :ensure => :no_shutdown)
end
describe "especially speed" do
it "should allow a number" do
Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :speed => "100")
end
it "should allow :auto" do
Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :speed => :auto)
end
end
describe "especially duplex" do
it "should allow :half" do
Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :duplex => :half)
end
it "should allow :full" do
Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :duplex => :full)
end
it "should allow :auto" do
Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :duplex => :auto)
end
end
describe "especially ipaddress" do
it "should allow ipv4 addresses" do
Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :ipaddress => "192.168.0.1/24")
end
it "should allow arrays of ipv4 addresses" do
Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :ipaddress => ["192.168.0.1/24", "192.168.1.0/24"])
end
it "should allow ipv6 addresses" do
Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :ipaddress => "f0e9::/64")
end
it "should allow ipv6 options" do
Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :ipaddress => "f0e9::/64 link-local")
Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :ipaddress => "f0e9::/64 eui-64")
end
it "should allow a mix of ipv4 and ipv6" do
Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :ipaddress => ["192.168.0.1/24", "f0e9::/64 link-local"])
end
it "should munge ip addresses to a computer format" do
- Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :ipaddress => "192.168.0.1/24")[:ipaddress].should == [[24, IPAddr.new('192.168.0.1'), nil]]
+ expect(Puppet::Type.type(:interface).new(:name => "FastEthernet 0/1", :ipaddress => "192.168.0.1/24")[:ipaddress]).to eq([[24, IPAddr.new('192.168.0.1'), nil]])
end
end
end
end
diff --git a/spec/unit/type/k5login_spec.rb b/spec/unit/type/k5login_spec.rb
index 6c0dbb16d..d70e6955e 100755
--- a/spec/unit/type/k5login_spec.rb
+++ b/spec/unit/type/k5login_spec.rb
@@ -1,115 +1,115 @@
#!/usr/bin/env ruby
require 'spec_helper'
require 'fileutils'
require 'puppet/type'
describe Puppet::Type.type(:k5login), :unless => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
context "the type class" do
subject { described_class }
- it { should be_validattr :ensure }
- it { should be_validattr :path }
- it { should be_validattr :principals }
- it { should be_validattr :mode }
+ it { is_expected.to be_validattr :ensure }
+ it { is_expected.to be_validattr :path }
+ it { is_expected.to be_validattr :principals }
+ it { is_expected.to be_validattr :mode }
# We have one, inline provider implemented.
- it { should be_validattr :provider }
+ it { is_expected.to be_validattr :provider }
end
let(:path) { tmpfile('k5login') }
def resource(attrs = {})
attrs = {
:ensure => 'present',
:path => path,
:principals => 'fred@EXAMPLE.COM'
}.merge(attrs)
if content = attrs.delete(:content)
File.open(path, 'w') { |f| f.print(content) }
end
resource = described_class.new(attrs)
resource
end
before :each do
FileUtils.touch(path)
end
context "the provider" do
context "when the file is missing" do
it "should initially be absent" do
File.delete(path)
- resource.retrieve[:ensure].must == :absent
+ expect(resource.retrieve[:ensure]).to eq(:absent)
end
it "should create the file when synced" do
resource(:ensure => 'present').parameter(:ensure).sync
- Puppet::FileSystem.exist?(path).should be_true
+ expect(Puppet::FileSystem.exist?(path)).to be_truthy
end
end
context "when the file is present" do
context "retrieved initial state" do
subject { resource.retrieve }
it "should retrieve its properties correctly with zero principals" do
- subject[:ensure].should == :present
- subject[:principals].should == []
+ expect(subject[:ensure]).to eq(:present)
+ expect(subject[:principals]).to eq([])
# We don't really care what the mode is, just that it got it
- subject[:mode].should_not be_nil
+ expect(subject[:mode]).not_to be_nil
end
context "with one principal" do
subject { resource(:content => "daniel@EXAMPLE.COM\n").retrieve }
it "should retrieve its principals correctly" do
- subject[:principals].should == ["daniel@EXAMPLE.COM"]
+ expect(subject[:principals]).to eq(["daniel@EXAMPLE.COM"])
end
end
context "with two principals" do
subject do
content = ["daniel@EXAMPLE.COM", "george@EXAMPLE.COM"].join("\n")
resource(:content => content).retrieve
end
it "should retrieve its principals correctly" do
- subject[:principals].should == ["daniel@EXAMPLE.COM", "george@EXAMPLE.COM"]
+ expect(subject[:principals]).to eq(["daniel@EXAMPLE.COM", "george@EXAMPLE.COM"])
end
end
end
it "should remove the file ensure is absent" do
resource(:ensure => 'absent').property(:ensure).sync
- Puppet::FileSystem.exist?(path).should be_false
+ expect(Puppet::FileSystem.exist?(path)).to be_falsey
end
it "should write one principal to the file" do
- File.read(path).should == ""
+ expect(File.read(path)).to eq("")
resource(:principals => ["daniel@EXAMPLE.COM"]).property(:principals).sync
- File.read(path).should == "daniel@EXAMPLE.COM\n"
+ expect(File.read(path)).to eq("daniel@EXAMPLE.COM\n")
end
it "should write multiple principals to the file" do
content = ["daniel@EXAMPLE.COM", "george@EXAMPLE.COM"]
- File.read(path).should == ""
+ expect(File.read(path)).to eq("")
resource(:principals => content).property(:principals).sync
- File.read(path).should == content.join("\n") + "\n"
+ expect(File.read(path)).to eq(content.join("\n") + "\n")
end
describe "when setting the mode" do
# The defined input type is "mode, as an octal string"
["400", "600", "700", "644", "664"].each do |mode|
it "should update the mode to #{mode}" do
resource(:mode => mode).property(:mode).sync
- (Puppet::FileSystem.stat(path).mode & 07777).to_s(8).should == mode
+ expect((Puppet::FileSystem.stat(path).mode & 07777).to_s(8)).to eq(mode)
end
end
end
end
end
end
diff --git a/spec/unit/type/macauthorization_spec.rb b/spec/unit/type/macauthorization_spec.rb
index aec778ab2..81dc73f4d 100755
--- a/spec/unit/type/macauthorization_spec.rb
+++ b/spec/unit/type/macauthorization_spec.rb
@@ -1,110 +1,110 @@
#! /usr/bin/env ruby
require 'spec_helper'
macauth_type = Puppet::Type.type(:macauthorization)
describe Puppet::Type.type(:macauthorization), "when checking macauthorization objects" do
before do
authplist = {}
authplist["rules"] = { "foorule" => "foo" }
authplist["rights"] = { "fooright" => "foo" }
provider_class = macauth_type.provider(macauth_type.providers[0])
Plist.stubs(:parse_xml).with("/etc/authorization").returns(authplist)
macauth_type.stubs(:defaultprovider).returns provider_class
@resource = macauth_type.new(:name => 'foo')
end
describe "when validating attributes" do
parameters = [:name,]
properties = [:auth_type, :allow_root, :authenticate_user, :auth_class,
:comment, :group, :k_of_n, :mechanisms, :rule,
:session_owner, :shared, :timeout, :tries]
parameters.each do |parameter|
it "should have a #{parameter} parameter" do
- macauth_type.attrclass(parameter).ancestors.should be_include(Puppet::Parameter)
+ expect(macauth_type.attrclass(parameter).ancestors).to be_include(Puppet::Parameter)
end
it "should have documentation for its #{parameter} parameter" do
- macauth_type.attrclass(parameter).doc.should be_instance_of(String)
+ expect(macauth_type.attrclass(parameter).doc).to be_instance_of(String)
end
end
properties.each do |property|
it "should have a #{property} property" do
- macauth_type.attrclass(property).ancestors.should be_include(Puppet::Property)
+ expect(macauth_type.attrclass(property).ancestors).to be_include(Puppet::Property)
end
it "should have documentation for its #{property} property" do
- macauth_type.attrclass(property).doc.should be_instance_of(String)
+ expect(macauth_type.attrclass(property).doc).to be_instance_of(String)
end
end
end
describe "when validating properties" do
it "should have a default provider inheriting from Puppet::Provider" do
- macauth_type.defaultprovider.ancestors.should be_include(Puppet::Provider)
+ expect(macauth_type.defaultprovider.ancestors).to be_include(Puppet::Provider)
end
it "should be able to create an instance" do
- lambda {
+ expect {
macauth_type.new(:name => 'foo')
- }.should_not raise_error
+ }.not_to raise_error
end
it "should support :present as a value to :ensure" do
- lambda {
+ expect {
macauth_type.new(:name => "foo", :ensure => :present)
- }.should_not raise_error
+ }.not_to raise_error
end
it "should support :absent as a value to :ensure" do
- lambda {
+ expect {
macauth_type.new(:name => "foo", :ensure => :absent)
- }.should_not raise_error
+ }.not_to raise_error
end
end
[:k_of_n, :timeout, :tries].each do |property|
describe "when managing the #{property} property" do
it "should convert number-looking strings into actual numbers" do
prop = macauth_type.attrclass(property).new(:resource => @resource)
prop.should = "300"
- prop.should.must == 300
+ expect(prop.should).to eq(300)
end
it "should support integers as a value" do
prop = macauth_type.attrclass(property).new(:resource => @resource)
prop.should = 300
- prop.should.must == 300
+ expect(prop.should).to eq(300)
end
it "should raise an error for non-integer values" do
prop = macauth_type.attrclass(property).new(:resource => @resource)
- lambda { prop.should = "foo" }.should raise_error(Puppet::Error)
+ expect { prop.should = "foo" }.to raise_error(Puppet::Error)
end
end
end
[:allow_root, :authenticate_user, :session_owner, :shared].each do |property|
describe "when managing the #{property} property" do
it "should convert boolean-looking false strings into actual booleans" do
prop = macauth_type.attrclass(property).new(:resource => @resource)
prop.should = "false"
- prop.should.must == :false
+ expect(prop.should).to eq(:false)
end
it "should convert boolean-looking true strings into actual booleans" do
prop = macauth_type.attrclass(property).new(:resource => @resource)
prop.should = "true"
- prop.should.must == :true
+ expect(prop.should).to eq(:true)
end
it "should raise an error for non-boolean values" do
prop = macauth_type.attrclass(property).new(:resource => @resource)
- lambda { prop.should = "foo" }.should raise_error(Puppet::Error)
+ expect { prop.should = "foo" }.to raise_error(Puppet::Error)
end
end
end
end
diff --git a/spec/unit/type/mailalias_spec.rb b/spec/unit/type/mailalias_spec.rb
index 45040d626..eb701c669 100755
--- a/spec/unit/type/mailalias_spec.rb
+++ b/spec/unit/type/mailalias_spec.rb
@@ -1,49 +1,49 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:mailalias) do
include PuppetSpec::Files
let :tmpfile_path do tmpfile('afile') end
let :target do tmpfile('mailalias') end
let :recipient_resource do
described_class.new(:name => "luke", :recipient => "yay", :target => target)
end
let :file_resource do
described_class.new(:name => "lukefile", :file => tmpfile_path, :target => target)
end
it "should be initially absent as a recipient" do
- recipient_resource.retrieve_resource[:recipient].should == :absent
+ expect(recipient_resource.retrieve_resource[:recipient]).to eq(:absent)
end
it "should be initially absent as an included file" do
- file_resource.retrieve_resource[:file].should == :absent
+ expect(file_resource.retrieve_resource[:file]).to eq(:absent)
end
it "should try and set the recipient when it does the sync" do
- recipient_resource.retrieve_resource[:recipient].should == :absent
+ expect(recipient_resource.retrieve_resource[:recipient]).to eq(:absent)
recipient_resource.property(:recipient).expects(:set).with(["yay"])
recipient_resource.property(:recipient).sync
end
it "should try and set the included file when it does the sync" do
- file_resource.retrieve_resource[:file].should == :absent
+ expect(file_resource.retrieve_resource[:file]).to eq(:absent)
file_resource.property(:file).expects(:set).with(tmpfile_path)
file_resource.property(:file).sync
end
it "should fail when file is not an absolute path" do
expect {
Puppet::Type.type(:mailalias).new(:name => 'x', :file => 'afile')
}.to raise_error Puppet::Error, /File paths must be fully qualified/
end
it "should fail when both file and recipient are specified" do
expect {
Puppet::Type.type(:mailalias).new(:name => 'x', :file => tmpfile_path,
:recipient => 'foo@example.com')
}.to raise_error Puppet::Error, /cannot specify both a recipient and a file/
end
end
diff --git a/spec/unit/type/maillist_spec.rb b/spec/unit/type/maillist_spec.rb
index e8d14b8f9..ba6fe0a8c 100755
--- a/spec/unit/type/maillist_spec.rb
+++ b/spec/unit/type/maillist_spec.rb
@@ -1,41 +1,41 @@
#! /usr/bin/env ruby
require 'spec_helper'
maillist = Puppet::Type.type(:maillist)
describe maillist do
before do
@provider_class = Puppet::Type.type(:maillist).provider(:mailman)
@provider = stub 'provider', :class => @provider_class, :clear => nil
@provider.stubs(:respond_to).with(:aliases).returns(true)
@provider_class.stubs(:new).returns(@provider)
Puppet::Type.type(:maillist).stubs(:defaultprovider).returns(@provider_class)
@maillist = Puppet::Type.type(:maillist).new( :name => 'test' )
@catalog = Puppet::Resource::Catalog.new
@maillist.catalog = @catalog
end
it "should generate aliases unless they already exist" do
# Mail List aliases are careful not to stomp on managed Mail Alias aliases
# test1 is an unmanaged alias from /etc/aliases
Puppet::Type.type(:mailalias).provider(:aliases).stubs(:target_object).returns( StringIO.new("test1: root\n") )
# test2 is a managed alias from the manifest
dupe = Puppet::Type.type(:mailalias).new( :name => 'test2' )
@catalog.add_resource dupe
@provider.stubs(:aliases).returns({"test1" => 'this will get included', "test2" => 'this will dropped', "test3" => 'this will get included'})
generated = @maillist.generate
- generated.map{ |x| x.name }.sort.should == ['test1', 'test3']
- generated.map{ |x| x.class }.should == [Puppet::Type::Mailalias, Puppet::Type::Mailalias]
+ expect(generated.map{ |x| x.name }.sort).to eq(['test1', 'test3'])
+ expect(generated.map{ |x| x.class }).to eq([Puppet::Type::Mailalias, Puppet::Type::Mailalias])
end
end
diff --git a/spec/unit/type/mcx_spec.rb b/spec/unit/type/mcx_spec.rb
index 39f70c692..47d7599e0 100755
--- a/spec/unit/type/mcx_spec.rb
+++ b/spec/unit/type/mcx_spec.rb
@@ -1,79 +1,79 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/type/mcx'
mcx_type = Puppet::Type.type(:mcx)
describe mcx_type, "when validating attributes" do
properties = [:ensure, :content]
parameters = [:name, :ds_type, :ds_name]
parameters.each do |p|
it "should have a #{p} parameter" do
- mcx_type.attrclass(p).ancestors.should be_include(Puppet::Parameter)
+ expect(mcx_type.attrclass(p).ancestors).to be_include(Puppet::Parameter)
end
it "should have documentation for its #{p} parameter" do
- mcx_type.attrclass(p).doc.should be_instance_of(String)
+ expect(mcx_type.attrclass(p).doc).to be_instance_of(String)
end
end
properties.each do |p|
it "should have a #{p} property" do
- mcx_type.attrclass(p).ancestors.should be_include(Puppet::Property)
+ expect(mcx_type.attrclass(p).ancestors).to be_include(Puppet::Property)
end
it "should have documentation for its #{p} property" do
- mcx_type.attrclass(p).doc.should be_instance_of(String)
+ expect(mcx_type.attrclass(p).doc).to be_instance_of(String)
end
end
end
describe mcx_type, "default values" do
before :each do
provider_class = mcx_type.provider(mcx_type.providers[0])
mcx_type.stubs(:defaultprovider).returns provider_class
end
it "should be nil for :ds_type" do
- mcx_type.new(:name => '/Foo/bar')[:ds_type].should be_nil
+ expect(mcx_type.new(:name => '/Foo/bar')[:ds_type]).to be_nil
end
it "should be nil for :ds_name" do
- mcx_type.new(:name => '/Foo/bar')[:ds_name].should be_nil
+ expect(mcx_type.new(:name => '/Foo/bar')[:ds_name]).to be_nil
end
it "should be nil for :content" do
- mcx_type.new(:name => '/Foo/bar')[:content].should be_nil
+ expect(mcx_type.new(:name => '/Foo/bar')[:content]).to be_nil
end
end
describe mcx_type, "when validating properties" do
before :each do
provider_class = mcx_type.provider(mcx_type.providers[0])
mcx_type.stubs(:defaultprovider).returns provider_class
end
it "should be able to create an instance" do
- lambda {
+ expect {
mcx_type.new(:name => '/Foo/bar')
- }.should_not raise_error
+ }.not_to raise_error
end
it "should support :present as a value to :ensure" do
- lambda {
+ expect {
mcx_type.new(:name => "/Foo/bar", :ensure => :present)
- }.should_not raise_error
+ }.not_to raise_error
end
it "should support :absent as a value to :ensure" do
- lambda {
+ expect {
mcx_type.new(:name => "/Foo/bar", :ensure => :absent)
- }.should_not raise_error
+ }.not_to raise_error
end
end
diff --git a/spec/unit/type/mount_spec.rb b/spec/unit/type/mount_spec.rb
index e860303d6..226e00e2c 100755
--- a/spec/unit/type/mount_spec.rb
+++ b/spec/unit/type/mount_spec.rb
@@ -1,592 +1,592 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:mount), :unless => Puppet.features.microsoft_windows? do
before :each do
Puppet::Type.type(:mount).stubs(:defaultprovider).returns providerclass
end
let :providerclass do
described_class.provide(:fake_mount_provider) do
attr_accessor :property_hash
def create; end
def destroy; end
def exists?
get(:ensure) != :absent
end
def mount; end
def umount; end
def mounted?
[:mounted, :ghost].include?(get(:ensure))
end
mk_resource_methods
end
end
let :provider do
providerclass.new(:name => 'yay')
end
let :resource do
described_class.new(:name => "yay", :audit => :ensure, :provider => provider)
end
let :ensureprop do
resource.property(:ensure)
end
it "should have a :refreshable feature that requires the :remount method" do
- described_class.provider_feature(:refreshable).methods.should == [:remount]
+ expect(described_class.provider_feature(:refreshable).methods).to eq([:remount])
end
it "should have no default value for :ensure" do
mount = described_class.new(:name => "yay")
- mount.should(:ensure).should be_nil
+ expect(mount.should(:ensure)).to be_nil
end
it "should have :name as the only keyattribut" do
- described_class.key_attributes.should == [:name]
+ expect(described_class.key_attributes).to eq([:name])
end
describe "when validating attributes" do
[:name, :remounts, :provider].each do |param|
it "should have a #{param} parameter" do
- described_class.attrtype(param).should == :param
+ expect(described_class.attrtype(param)).to eq(:param)
end
end
[:ensure, :device, :blockdevice, :fstype, :options, :pass, :dump, :atboot, :target].each do |param|
it "should have a #{param} property" do
- described_class.attrtype(param).should == :property
+ expect(described_class.attrtype(param)).to eq(:property)
end
end
end
describe "when validating values" do
describe "for name" do
it "should allow full qualified paths" do
- described_class.new(:name => "/mnt/foo")[:name].should == '/mnt/foo'
+ expect(described_class.new(:name => "/mnt/foo")[:name]).to eq('/mnt/foo')
end
it "should remove trailing slashes" do
- described_class.new(:name => '/')[:name].should == '/'
- described_class.new(:name => '//')[:name].should == '/'
- described_class.new(:name => '/foo/')[:name].should == '/foo'
- described_class.new(:name => '/foo/bar/')[:name].should == '/foo/bar'
- described_class.new(:name => '/foo/bar/baz//')[:name].should == '/foo/bar/baz'
+ expect(described_class.new(:name => '/')[:name]).to eq('/')
+ expect(described_class.new(:name => '//')[:name]).to eq('/')
+ expect(described_class.new(:name => '/foo/')[:name]).to eq('/foo')
+ expect(described_class.new(:name => '/foo/bar/')[:name]).to eq('/foo/bar')
+ expect(described_class.new(:name => '/foo/bar/baz//')[:name]).to eq('/foo/bar/baz')
end
it "should not allow spaces" do
expect { described_class.new(:name => "/mnt/foo bar") }.to raise_error Puppet::Error, /name.*whitespace/
end
it "should allow pseudo mountpoints (e.g. swap)" do
- described_class.new(:name => 'none')[:name].should == 'none'
+ expect(described_class.new(:name => 'none')[:name]).to eq('none')
end
end
describe "for ensure" do
it "should alias :present to :defined as a value to :ensure" do
mount = described_class.new(:name => "yay", :ensure => :present)
- mount.should(:ensure).should == :defined
+ expect(mount.should(:ensure)).to eq(:defined)
end
it "should support :present as a value to :ensure" do
expect { described_class.new(:name => "yay", :ensure => :present) }.to_not raise_error
end
it "should support :defined as a value to :ensure" do
expect { described_class.new(:name => "yay", :ensure => :defined) }.to_not raise_error
end
it "should support :unmounted as a value to :ensure" do
expect { described_class.new(:name => "yay", :ensure => :unmounted) }.to_not raise_error
end
it "should support :absent as a value to :ensure" do
expect { described_class.new(:name => "yay", :ensure => :absent) }.to_not raise_error
end
it "should support :mounted as a value to :ensure" do
expect { described_class.new(:name => "yay", :ensure => :mounted) }.to_not raise_error
end
it "should not support other values for :ensure" do
expect { described_class.new(:name => "yay", :ensure => :mount) }.to raise_error Puppet::Error, /Invalid value/
end
end
describe "for device" do
it "should support normal /dev paths for device" do
expect { described_class.new(:name => "/foo", :ensure => :present, :device => '/dev/hda1') }.to_not raise_error
expect { described_class.new(:name => "/foo", :ensure => :present, :device => '/dev/dsk/c0d0s0') }.to_not raise_error
end
it "should support labels for device" do
expect { described_class.new(:name => "/foo", :ensure => :present, :device => 'LABEL=/boot') }.to_not raise_error
expect { described_class.new(:name => "/foo", :ensure => :present, :device => 'LABEL=SWAP-hda6') }.to_not raise_error
end
it "should support pseudo devices for device" do
expect { described_class.new(:name => "/foo", :ensure => :present, :device => 'ctfs') }.to_not raise_error
expect { described_class.new(:name => "/foo", :ensure => :present, :device => 'swap') }.to_not raise_error
expect { described_class.new(:name => "/foo", :ensure => :present, :device => 'sysfs') }.to_not raise_error
expect { described_class.new(:name => "/foo", :ensure => :present, :device => 'proc') }.to_not raise_error
end
it 'should not support whitespace in device' do
expect { described_class.new(:name => "/foo", :ensure => :present, :device => '/dev/my dev/foo') }.to raise_error Puppet::Error, /device.*whitespace/
expect { described_class.new(:name => "/foo", :ensure => :present, :device => "/dev/my\tdev/foo") }.to raise_error Puppet::Error, /device.*whitespace/
end
end
describe "for blockdevice" do
before :each do
# blockdevice is only used on Solaris
Facter.stubs(:value).with(:operatingsystem).returns 'Solaris'
Facter.stubs(:value).with(:osfamily).returns 'Solaris'
end
it "should support normal /dev/rdsk paths for blockdevice" do
expect { described_class.new(:name => "/foo", :ensure => :present, :blockdevice => '/dev/rdsk/c0d0s0') }.to_not raise_error
end
it "should support a dash for blockdevice" do
expect { described_class.new(:name => "/foo", :ensure => :present, :blockdevice => '-') }.to_not raise_error
end
it "should not support whitespace in blockdevice" do
expect { described_class.new(:name => "/foo", :ensure => :present, :blockdevice => '/dev/my dev/foo') }.to raise_error Puppet::Error, /blockdevice.*whitespace/
expect { described_class.new(:name => "/foo", :ensure => :present, :blockdevice => "/dev/my\tdev/foo") }.to raise_error Puppet::Error, /blockdevice.*whitespace/
end
it "should default to /dev/rdsk/DEVICE if device is /dev/dsk/DEVICE" do
obj = described_class.new(:name => "/foo", :device => '/dev/dsk/c0d0s0')
- obj[:blockdevice].should == '/dev/rdsk/c0d0s0'
+ expect(obj[:blockdevice]).to eq('/dev/rdsk/c0d0s0')
end
it "should default to - if it is an nfs-share" do
obj = described_class.new(:name => "/foo", :device => "server://share", :fstype => 'nfs')
- obj[:blockdevice].should == '-'
+ expect(obj[:blockdevice]).to eq('-')
end
it "should have no default otherwise" do
- described_class.new(:name => "/foo")[:blockdevice].should == nil
- described_class.new(:name => "/foo", :device => "/foo")[:blockdevice].should == nil
+ expect(described_class.new(:name => "/foo")[:blockdevice]).to eq(nil)
+ expect(described_class.new(:name => "/foo", :device => "/foo")[:blockdevice]).to eq(nil)
end
it "should overwrite any default if blockdevice is explicitly set" do
- described_class.new(:name => "/foo", :device => '/dev/dsk/c0d0s0', :blockdevice => '/foo')[:blockdevice].should == '/foo'
- described_class.new(:name => "/foo", :device => "server://share", :fstype => 'nfs', :blockdevice => '/foo')[:blockdevice].should == '/foo'
+ expect(described_class.new(:name => "/foo", :device => '/dev/dsk/c0d0s0', :blockdevice => '/foo')[:blockdevice]).to eq('/foo')
+ expect(described_class.new(:name => "/foo", :device => "server://share", :fstype => 'nfs', :blockdevice => '/foo')[:blockdevice]).to eq('/foo')
end
end
describe "for fstype" do
it "should support valid fstypes" do
expect { described_class.new(:name => "/foo", :ensure => :present, :fstype => 'ext3') }.to_not raise_error
expect { described_class.new(:name => "/foo", :ensure => :present, :fstype => 'proc') }.to_not raise_error
expect { described_class.new(:name => "/foo", :ensure => :present, :fstype => 'sysfs') }.to_not raise_error
end
it "should support auto as a special fstype" do
expect { described_class.new(:name => "/foo", :ensure => :present, :fstype => 'auto') }.to_not raise_error
end
it "should not support whitespace in fstype" do
expect { described_class.new(:name => "/foo", :ensure => :present, :fstype => 'ext 3') }.to raise_error Puppet::Error, /fstype.*whitespace/
end
end
describe "for options" do
it "should support a single option" do
expect { described_class.new(:name => "/foo", :ensure => :present, :options => 'ro') }.to_not raise_error
end
it "should support multiple options as a comma separated list" do
expect { described_class.new(:name => "/foo", :ensure => :present, :options => 'ro,rsize=4096') }.to_not raise_error
end
it "should not support whitespace in options" do
expect { described_class.new(:name => "/foo", :ensure => :present, :options => ['ro','foo bar','intr']) }.to raise_error Puppet::Error, /option.*whitespace/
end
end
describe "for pass" do
it "should support numeric values" do
expect { described_class.new(:name => "/foo", :ensure => :present, :pass => '0') }.to_not raise_error
expect { described_class.new(:name => "/foo", :ensure => :present, :pass => '1') }.to_not raise_error
expect { described_class.new(:name => "/foo", :ensure => :present, :pass => '2') }.to_not raise_error
end
it "should support - on Solaris" do
Facter.stubs(:value).with(:operatingsystem).returns 'Solaris'
Facter.stubs(:value).with(:osfamily).returns 'Solaris'
expect { described_class.new(:name => "/foo", :ensure => :present, :pass => '-') }.to_not raise_error
end
it "should default to 0 on non Solaris" do
Facter.stubs(:value).with(:osfamily).returns nil
Facter.stubs(:value).with(:operatingsystem).returns 'HP-UX'
- described_class.new(:name => "/foo", :ensure => :present)[:pass].should == 0
+ expect(described_class.new(:name => "/foo", :ensure => :present)[:pass]).to eq(0)
end
it "should default to - on Solaris" do
Facter.stubs(:value).with(:operatingsystem).returns 'Solaris'
Facter.stubs(:value).with(:osfamily).returns 'Solaris'
- described_class.new(:name => "/foo", :ensure => :present)[:pass].should == '-'
+ expect(described_class.new(:name => "/foo", :ensure => :present)[:pass]).to eq('-')
end
end
describe "for dump" do
it "should support 0 as a value for dump" do
expect { described_class.new(:name => "/foo", :ensure => :present, :dump => '0') }.to_not raise_error
end
it "should support 1 as a value for dump" do
expect { described_class.new(:name => "/foo", :ensure => :present, :dump => '1') }.to_not raise_error
end
# Unfortunately the operatingsystem is evaluatet at load time so I am unable to stub operatingsystem
it "should support 2 as a value for dump on FreeBSD", :if => Facter.value(:operatingsystem) == 'FreeBSD' do
expect { described_class.new(:name => "/foo", :ensure => :present, :dump => '2') }.to_not raise_error
end
it "should not support 2 as a value for dump when not on FreeBSD", :if => Facter.value(:operatingsystem) != 'FreeBSD' do
expect { described_class.new(:name => "/foo", :ensure => :present, :dump => '2') }.to raise_error Puppet::Error, /Invalid value/
end
it "should default to 0" do
- described_class.new(:name => "/foo", :ensure => :present)[:dump].should == 0
+ expect(described_class.new(:name => "/foo", :ensure => :present)[:dump]).to eq(0)
end
end
describe "for atboot" do
it "does not allow non-boolean values" do
expect { described_class.new(:name => "/foo", :ensure => :present, :atboot => 'unknown') }.to raise_error Puppet::Error, /expected a boolean value/
end
it "interprets yes as yes" do
resource = described_class.new(:name => "/foo", :ensure => :present, :atboot => :yes)
expect(resource[:atboot]).to eq(:yes)
end
it "interprets true as yes" do
resource = described_class.new(:name => "/foo", :ensure => :present, :atboot => :true)
expect(resource[:atboot]).to eq(:yes)
end
it "interprets no as no" do
resource = described_class.new(:name => "/foo", :ensure => :present, :atboot => :no)
expect(resource[:atboot]).to eq(:no)
end
it "interprets false as no" do
resource = described_class.new(:name => "/foo", :ensure => :present, :atboot => false)
expect(resource[:atboot]).to eq(:no)
end
end
end
describe "when changing the host" do
def test_ensure_change(options)
provider.set(:ensure => options[:from])
provider.expects(:create).times(options[:create] || 0)
provider.expects(:destroy).times(options[:destroy] || 0)
provider.expects(:mount).never
provider.expects(:unmount).times(options[:unmount] || 0)
ensureprop.stubs(:syncothers)
ensureprop.should = options[:to]
ensureprop.sync
- (!!provider.property_hash[:needs_mount]).should == (!!options[:mount])
+ expect(!!provider.property_hash[:needs_mount]).to eq(!!options[:mount])
end
it "should create itself when changing from :ghost to :present" do
test_ensure_change(:from => :ghost, :to => :present, :create => 1)
end
it "should create itself when changing from :absent to :present" do
test_ensure_change(:from => :absent, :to => :present, :create => 1)
end
it "should create itself and unmount when changing from :ghost to :unmounted" do
test_ensure_change(:from => :ghost, :to => :unmounted, :create => 1, :unmount => 1)
end
it "should unmount resource when changing from :mounted to :unmounted" do
test_ensure_change(:from => :mounted, :to => :unmounted, :unmount => 1)
end
it "should create itself when changing from :absent to :unmounted" do
test_ensure_change(:from => :absent, :to => :unmounted, :create => 1)
end
it "should unmount resource when changing from :ghost to :absent" do
test_ensure_change(:from => :ghost, :to => :absent, :unmount => 1)
end
it "should unmount and destroy itself when changing from :mounted to :absent" do
test_ensure_change(:from => :mounted, :to => :absent, :destroy => 1, :unmount => 1)
end
it "should destroy itself when changing from :unmounted to :absent" do
test_ensure_change(:from => :unmounted, :to => :absent, :destroy => 1)
end
it "should create itself when changing from :ghost to :mounted" do
test_ensure_change(:from => :ghost, :to => :mounted, :create => 1)
end
it "should create itself and mount when changing from :absent to :mounted" do
test_ensure_change(:from => :absent, :to => :mounted, :create => 1, :mount => 1)
end
it "should mount resource when changing from :unmounted to :mounted" do
test_ensure_change(:from => :unmounted, :to => :mounted, :mount => 1)
end
it "should be in sync if it is :absent and should be :absent" do
ensureprop.should = :absent
- ensureprop.safe_insync?(:absent).should == true
+ expect(ensureprop.safe_insync?(:absent)).to eq(true)
end
it "should be out of sync if it is :absent and should be :defined" do
ensureprop.should = :defined
- ensureprop.safe_insync?(:absent).should == false
+ expect(ensureprop.safe_insync?(:absent)).to eq(false)
end
it "should be out of sync if it is :absent and should be :mounted" do
ensureprop.should = :mounted
- ensureprop.safe_insync?(:absent).should == false
+ expect(ensureprop.safe_insync?(:absent)).to eq(false)
end
it "should be out of sync if it is :absent and should be :unmounted" do
ensureprop.should = :unmounted
- ensureprop.safe_insync?(:absent).should == false
+ expect(ensureprop.safe_insync?(:absent)).to eq(false)
end
it "should be out of sync if it is :mounted and should be :absent" do
ensureprop.should = :absent
- ensureprop.safe_insync?(:mounted).should == false
+ expect(ensureprop.safe_insync?(:mounted)).to eq(false)
end
it "should be in sync if it is :mounted and should be :defined" do
ensureprop.should = :defined
- ensureprop.safe_insync?(:mounted).should == true
+ expect(ensureprop.safe_insync?(:mounted)).to eq(true)
end
it "should be in sync if it is :mounted and should be :mounted" do
ensureprop.should = :mounted
- ensureprop.safe_insync?(:mounted).should == true
+ expect(ensureprop.safe_insync?(:mounted)).to eq(true)
end
it "should be out in sync if it is :mounted and should be :unmounted" do
ensureprop.should = :unmounted
- ensureprop.safe_insync?(:mounted).should == false
+ expect(ensureprop.safe_insync?(:mounted)).to eq(false)
end
it "should be out of sync if it is :unmounted and should be :absent" do
ensureprop.should = :absent
- ensureprop.safe_insync?(:unmounted).should == false
+ expect(ensureprop.safe_insync?(:unmounted)).to eq(false)
end
it "should be in sync if it is :unmounted and should be :defined" do
ensureprop.should = :defined
- ensureprop.safe_insync?(:unmounted).should == true
+ expect(ensureprop.safe_insync?(:unmounted)).to eq(true)
end
it "should be out of sync if it is :unmounted and should be :mounted" do
ensureprop.should = :mounted
- ensureprop.safe_insync?(:unmounted).should == false
+ expect(ensureprop.safe_insync?(:unmounted)).to eq(false)
end
it "should be in sync if it is :unmounted and should be :unmounted" do
ensureprop.should = :unmounted
- ensureprop.safe_insync?(:unmounted).should == true
+ expect(ensureprop.safe_insync?(:unmounted)).to eq(true)
end
it "should be out of sync if it is :ghost and should be :absent" do
ensureprop.should = :absent
- ensureprop.safe_insync?(:ghost).should == false
+ expect(ensureprop.safe_insync?(:ghost)).to eq(false)
end
it "should be out of sync if it is :ghost and should be :defined" do
ensureprop.should = :defined
- ensureprop.safe_insync?(:ghost).should == false
+ expect(ensureprop.safe_insync?(:ghost)).to eq(false)
end
it "should be out of sync if it is :ghost and should be :mounted" do
ensureprop.should = :mounted
- ensureprop.safe_insync?(:ghost).should == false
+ expect(ensureprop.safe_insync?(:ghost)).to eq(false)
end
it "should be out of sync if it is :ghost and should be :unmounted" do
ensureprop.should = :unmounted
- ensureprop.safe_insync?(:ghost).should == false
+ expect(ensureprop.safe_insync?(:ghost)).to eq(false)
end
end
describe "when responding to refresh" do
pending "2.6.x specifies slightly different behavior and the desired behavior needs to be clarified and revisited. See ticket #4904" do
it "should remount if it is supposed to be mounted" do
resource[:ensure] = "mounted"
provider.expects(:remount)
resource.refresh
end
it "should not remount if it is supposed to be present" do
resource[:ensure] = "present"
provider.expects(:remount).never
resource.refresh
end
it "should not remount if it is supposed to be absent" do
resource[:ensure] = "absent"
provider.expects(:remount).never
resource.refresh
end
it "should not remount if it is supposed to be defined" do
resource[:ensure] = "defined"
provider.expects(:remount).never
resource.refresh
end
it "should not remount if it is supposed to be unmounted" do
resource[:ensure] = "unmounted"
provider.expects(:remount).never
resource.refresh
end
it "should not remount swap filesystems" do
resource[:ensure] = "mounted"
resource[:fstype] = "swap"
provider.expects(:remount).never
resource.refresh
end
end
end
describe "when modifying an existing mount entry" do
let :initial_values do
{
:ensure => :mounted,
:name => '/mnt/foo',
:device => "/foo/bar",
:blockdevice => "/other/bar",
:target => "/what/ever",
:options => "soft",
:pass => 0,
:dump => 0,
:atboot => :no,
}
end
let :resource do
described_class.new(initial_values.merge(:provider => provider))
end
let :provider do
providerclass.new(initial_values)
end
def run_in_catalog(*resources)
Puppet::Util::Storage.stubs(:store)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource *resources
catalog.apply
end
it "should use the provider to change the dump value" do
provider.expects(:dump=).with(1)
resource[:dump] = 1
run_in_catalog(resource)
end
it "should umount before flushing changes to disk" do
syncorder = sequence('syncorder')
provider.expects(:unmount).in_sequence(syncorder)
provider.expects(:options=).in_sequence(syncorder).with 'hard'
resource.expects(:flush).in_sequence(syncorder) # Call inside syncothers
resource.expects(:flush).in_sequence(syncorder) # I guess transaction or anything calls flush again
resource[:ensure] = :unmounted
resource[:options] = 'hard'
run_in_catalog(resource)
end
end
describe "establishing autorequires" do
def create_resource(path)
described_class.new(
:name => path,
:provider => providerclass.new(path)
)
end
def create_catalog(*resources)
catalog = Puppet::Resource::Catalog.new
resources.each do |resource|
catalog.add_resource resource
end
catalog
end
let(:root_mount) { create_resource("/") }
let(:var_mount) { create_resource("/var") }
let(:log_mount) { create_resource("/var/log") }
before do
create_catalog(root_mount, var_mount, log_mount)
end
it "adds no autorequires for the root mount" do
expect(root_mount.autorequire).to be_empty
end
it "adds the parent autorequire for a mount with one parent" do
parent_relationship = var_mount.autorequire[0]
expect(var_mount.autorequire).to have_exactly(1).item
expect(parent_relationship.source).to eq root_mount
expect(parent_relationship.target).to eq var_mount
end
it "adds both parent autorequires for a mount with two parents" do
grandparent_relationship = log_mount.autorequire[0]
parent_relationship = log_mount.autorequire[1]
expect(log_mount.autorequire).to have_exactly(2).items
expect(grandparent_relationship.source).to eq root_mount
expect(grandparent_relationship.target).to eq log_mount
expect(parent_relationship.source).to eq var_mount
expect(parent_relationship.target).to eq log_mount
end
end
end
diff --git a/spec/unit/type/nagios_spec.rb b/spec/unit/type/nagios_spec.rb
index 4bd1271c2..ce653e913 100755
--- a/spec/unit/type/nagios_spec.rb
+++ b/spec/unit/type/nagios_spec.rb
@@ -1,293 +1,293 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/external/nagios'
describe "Nagios parser" do
NONESCAPED_SEMICOLON_COMMENT = <<-'EOL'
define host{
use linux-server ; Name of host template to use
host_name localhost
alias localhost
address 127.0.0.1
}
define command{
command_name notify-host-by-email
command_line /usr/bin/printf "%b" "***** Nagios *****\n\nNotification Type: $NOTIFICATIONTYPE$\nHost: $HOSTNAME$\nState: $HOSTSTATE$\nAddress: $HOSTADDRESS$\nInfo: $HOSTOUTPUT$\n\nDate/Time: $LONGDATETIME$\n" | /usr/bin/mail -s "** $NOTIFICATIONTYPE$ Host Alert: $HOSTNAME$ is $HOSTSTATE$ **" $CONTACTEMAIL$
}
EOL
LINE_COMMENT_SNIPPET = <<-'EOL'
# This is a comment starting at the beginning of a line
define command{
# This is a comment starting at the beginning of a line
command_name command_name
# This is a comment starting at the beginning of a line
## --PUPPET_NAME-- (called '_naginator_name' in the manifest) command_name
command_line command_line
# This is a comment starting at the beginning of a line
}
# This is a comment starting at the beginning of a line
EOL
LINE_COMMENT_SNIPPET2 = <<-'EOL'
define host{
use linux-server ; Name of host template to use
host_name localhost
alias localhost
address 127.0.0.1
}
define command{
command_name command_name2
command_line command_line2
}
EOL
UNKNOWN_NAGIOS_OBJECT_DEFINITION = <<-'EOL'
define command2{
command_name notify-host-by-email
command_line /usr/bin/printf "%b" "***** Nagios *****\n\nNotification Type: $NOTIFICATIONTYPE$\nHost: $HOSTNAME$\nState: $HOSTSTATE$\nAddress: $HOSTADDRESS$\nInfo: $HOSTOUTPUT$\n\nDate/Time: $LONGDATETIME$\n" | /usr/bin/mail -s "** $NOTIFICATIONTYPE$ Host Alert: $HOSTNAME$ is $HOSTSTATE$ **" $CONTACTEMAIL$
}
EOL
MISSING_CLOSING_CURLY_BRACKET = <<-'EOL'
define command{
command_name notify-host-by-email
command_line /usr/bin/printf "%b" "***** Nagios *****\n\nNotification Type: $NOTIFICATIONTYPE$\nHost: $HOSTNAME$\nState: $HOSTSTATE$\nAddress: $HOSTADDRESS$\nInfo: $HOSTOUTPUT$\n\nDate/Time: $LONGDATETIME$\n" | /usr/bin/mail -s "** $NOTIFICATIONTYPE$ Host Alert: $HOSTNAME$ is $HOSTSTATE$ **" $CONTACTEMAIL$
EOL
ESCAPED_SEMICOLON = <<-'EOL'
define command {
command_name nagios_table_size
command_line $USER3$/check_mysql_health --hostname localhost --username nagioschecks --password nagiosCheckPWD --mode sql --name "SELECT ROUND(Data_length/1024) as Data_kBytes from INFORMATION_SCHEMA.TABLES where TABLE_NAME=\"$ARG1$\"\;" --name2 "table size" --units kBytes -w $ARG2$ -c $ARG3$
}
EOL
POUND_SIGN_HASH_SYMBOL_NOT_IN_FIRST_COLUMN = <<-'EOL'
define command {
command_name notify-by-irc
command_line /usr/local/bin/riseup-nagios-client.pl "$HOSTNAME$ ($SERVICEDESC$) $NOTIFICATIONTYPE$ #$SERVICEATTEMPT$ $SERVICESTATETYPE$ $SERVICEEXECUTIONTIME$s $SERVICELATENCY$s $SERVICEOUTPUT$ $SERVICEPERFDATA$"
}
EOL
ANOTHER_ESCAPED_SEMICOLON = <<-EOL
define command {
\tcommand_line LC_ALL=en_US.UTF-8 /usr/lib/nagios/plugins/check_haproxy -u 'http://blah:blah@$HOSTADDRESS$:8080/haproxy?stats\\;csv'
\tcommand_name check_haproxy
}
EOL
it "should parse without error" do
parser = Nagios::Parser.new
expect {
results = parser.parse(NONESCAPED_SEMICOLON_COMMENT)
}.to_not raise_error
end
describe "when parsing a statement" do
parser = Nagios::Parser.new
results = parser.parse(NONESCAPED_SEMICOLON_COMMENT)
results.each do |obj|
it "should have the proper base type" do
- obj.should be_a_kind_of(Nagios::Base)
+ expect(obj).to be_a_kind_of(Nagios::Base)
end
end
end
it "should raise an error when an incorrect object definition is present" do
parser = Nagios::Parser.new
expect {
results = parser.parse(UNKNOWN_NAGIOS_OBJECT_DEFINITION)
}.to raise_error Nagios::Base::UnknownNagiosType
end
it "should raise an error when syntax is not correct" do
parser = Nagios::Parser.new
expect {
results = parser.parse(MISSING_CLOSING_CURLY_BRACKET)
}.to raise_error Nagios::Parser::SyntaxError
end
describe "when encoutering ';'" do
it "should not throw an exception" do
parser = Nagios::Parser.new
expect {
results = parser.parse(ESCAPED_SEMICOLON)
}.to_not raise_error
end
it "should ignore it if it is a comment" do
parser = Nagios::Parser.new
results = parser.parse(NONESCAPED_SEMICOLON_COMMENT)
- results[0].use.should eql("linux-server")
+ expect(results[0].use).to eql("linux-server")
end
it "should parse correctly if it is escaped" do
parser = Nagios::Parser.new
results = parser.parse(ESCAPED_SEMICOLON)
- results[0].command_line.should eql("$USER3$/check_mysql_health --hostname localhost --username nagioschecks --password nagiosCheckPWD --mode sql --name \"SELECT ROUND(Data_length/1024) as Data_kBytes from INFORMATION_SCHEMA.TABLES where TABLE_NAME=\\\"$ARG1$\\\";\" --name2 \"table size\" --units kBytes -w $ARG2$ -c $ARG3$")
+ expect(results[0].command_line).to eql("$USER3$/check_mysql_health --hostname localhost --username nagioschecks --password nagiosCheckPWD --mode sql --name \"SELECT ROUND(Data_length/1024) as Data_kBytes from INFORMATION_SCHEMA.TABLES where TABLE_NAME=\\\"$ARG1$\\\";\" --name2 \"table size\" --units kBytes -w $ARG2$ -c $ARG3$")
end
end
describe "when encountering '#'" do
it "should not throw an exception" do
parser = Nagios::Parser.new
expect {
results = parser.parse(POUND_SIGN_HASH_SYMBOL_NOT_IN_FIRST_COLUMN)
}.to_not raise_error
end
it "should ignore it at the beginning of a line" do
parser = Nagios::Parser.new
results = parser.parse(LINE_COMMENT_SNIPPET)
- results[0].command_line.should eql("command_line")
+ expect(results[0].command_line).to eql("command_line")
end
it "should let it go anywhere else" do
parser = Nagios::Parser.new
results = parser.parse(POUND_SIGN_HASH_SYMBOL_NOT_IN_FIRST_COLUMN)
- results[0].command_line.should eql("/usr/local/bin/riseup-nagios-client.pl \"$HOSTNAME$ ($SERVICEDESC$) $NOTIFICATIONTYPE$ \#$SERVICEATTEMPT$ $SERVICESTATETYPE$ $SERVICEEXECUTIONTIME$s $SERVICELATENCY$s $SERVICEOUTPUT$ $SERVICEPERFDATA$\"")
+ expect(results[0].command_line).to eql("/usr/local/bin/riseup-nagios-client.pl \"$HOSTNAME$ ($SERVICEDESC$) $NOTIFICATIONTYPE$ \#$SERVICEATTEMPT$ $SERVICESTATETYPE$ $SERVICEEXECUTIONTIME$s $SERVICELATENCY$s $SERVICEOUTPUT$ $SERVICEPERFDATA$\"")
end
end
describe "when encountering ';' again" do
it "should not throw an exception" do
parser = Nagios::Parser.new
expect {
results = parser.parse(ANOTHER_ESCAPED_SEMICOLON)
}.to_not raise_error
end
it "should parse correctly" do
parser = Nagios::Parser.new
results = parser.parse(ANOTHER_ESCAPED_SEMICOLON)
- results[0].command_line.should eql("LC_ALL=en_US.UTF-8 /usr/lib/nagios/plugins/check_haproxy -u 'http://blah:blah@$HOSTADDRESS$:8080/haproxy?stats;csv'")
+ expect(results[0].command_line).to eql("LC_ALL=en_US.UTF-8 /usr/lib/nagios/plugins/check_haproxy -u 'http://blah:blah@$HOSTADDRESS$:8080/haproxy?stats;csv'")
end
end
it "should be idempotent" do
parser = Nagios::Parser.new
src = ANOTHER_ESCAPED_SEMICOLON.dup
results = parser.parse(src)
nagios_type = Nagios::Base.create(:command)
nagios_type.command_name = results[0].command_name
nagios_type.command_line = results[0].command_line
- nagios_type.to_s.should eql(ANOTHER_ESCAPED_SEMICOLON)
+ expect(nagios_type.to_s).to eql(ANOTHER_ESCAPED_SEMICOLON)
end
end
describe "Nagios generator" do
it "should escape ';'" do
param = '$USER3$/check_mysql_health --hostname localhost --username nagioschecks --password nagiosCheckPWD --mode sql --name "SELECT ROUND(Data_length/1024) as Data_kBytes from INFORMATION_SCHEMA.TABLES where TABLE_NAME=\"$ARG1$\";" --name2 "table size" --units kBytes -w $ARG2$ -c $ARG3$'
nagios_type = Nagios::Base.create(:command)
nagios_type.command_line = param
- nagios_type.to_s.should eql("define command {\n\tcommand_line $USER3$/check_mysql_health --hostname localhost --username nagioschecks --password nagiosCheckPWD --mode sql --name \"SELECT ROUND(Data_length/1024) as Data_kBytes from INFORMATION_SCHEMA.TABLES where TABLE_NAME=\\\"$ARG1$\\\"\\;\" --name2 \"table size\" --units kBytes -w $ARG2$ -c $ARG3$\n}\n")
+ expect(nagios_type.to_s).to eql("define command {\n\tcommand_line $USER3$/check_mysql_health --hostname localhost --username nagioschecks --password nagiosCheckPWD --mode sql --name \"SELECT ROUND(Data_length/1024) as Data_kBytes from INFORMATION_SCHEMA.TABLES where TABLE_NAME=\\\"$ARG1$\\\"\\;\" --name2 \"table size\" --units kBytes -w $ARG2$ -c $ARG3$\n}\n")
end
it "should escape ';' if it is not already the case" do
param = "LC_ALL=en_US.UTF-8 /usr/lib/nagios/plugins/check_haproxy -u 'http://blah:blah@$HOSTADDRESS$:8080/haproxy?stats;csv'"
nagios_type = Nagios::Base.create(:command)
nagios_type.command_line = param
- nagios_type.to_s.should eql("define command {\n\tcommand_line LC_ALL=en_US.UTF-8 /usr/lib/nagios/plugins/check_haproxy -u 'http://blah:blah@$HOSTADDRESS$:8080/haproxy?stats\\;csv'\n}\n")
+ expect(nagios_type.to_s).to eql("define command {\n\tcommand_line LC_ALL=en_US.UTF-8 /usr/lib/nagios/plugins/check_haproxy -u 'http://blah:blah@$HOSTADDRESS$:8080/haproxy?stats\\;csv'\n}\n")
end
it "should be idempotent" do
param = '$USER3$/check_mysql_health --hostname localhost --username nagioschecks --password nagiosCheckPWD --mode sql --name "SELECT ROUND(Data_length/1024) as Data_kBytes from INFORMATION_SCHEMA.TABLES where TABLE_NAME=\"$ARG1$\";" --name2 "table size" --units kBytes -w $ARG2$ -c $ARG3$'
nagios_type = Nagios::Base.create(:command)
nagios_type.command_line = param
parser = Nagios::Parser.new
results = parser.parse(nagios_type.to_s)
- results[0].command_line.should eql(param)
+ expect(results[0].command_line).to eql(param)
end
it "should accept FixNum params and convert to string" do
param = 1
nagios_type = Nagios::Base.create(:serviceescalation)
nagios_type.first_notification = param
parser = Nagios::Parser.new
results = parser.parse(nagios_type.to_s)
- results[0].first_notification.should eql(param.to_s)
+ expect(results[0].first_notification).to eql(param.to_s)
end
end
describe "Nagios resource types" do
Nagios::Base.eachtype do |name, nagios_type|
puppet_type = Puppet::Type.type("nagios_#{name}")
it "should have a valid type for #{name}" do
- puppet_type.should_not be_nil
+ expect(puppet_type).not_to be_nil
end
next unless puppet_type
describe puppet_type do
it "should be defined as a Puppet resource type" do
- puppet_type.should_not be_nil
+ expect(puppet_type).not_to be_nil
end
it "should have documentation" do
- puppet_type.instance_variable_get("@doc").should_not == ""
+ expect(puppet_type.instance_variable_get("@doc")).not_to eq("")
end
it "should have #{nagios_type.namevar} as its key attribute" do
- puppet_type.key_attributes.should == [nagios_type.namevar]
+ expect(puppet_type.key_attributes).to eq([nagios_type.namevar])
end
it "should have documentation for its #{nagios_type.namevar} parameter" do
- puppet_type.attrclass(nagios_type.namevar).instance_variable_get("@doc").should_not be_nil
+ expect(puppet_type.attrclass(nagios_type.namevar).instance_variable_get("@doc")).not_to be_nil
end
it "should have an ensure property" do
- puppet_type.should be_validproperty(:ensure)
+ expect(puppet_type).to be_validproperty(:ensure)
end
it "should have a target property" do
- puppet_type.should be_validproperty(:target)
+ expect(puppet_type).to be_validproperty(:target)
end
it "should have documentation for its target property" do
- puppet_type.attrclass(:target).instance_variable_get("@doc").should_not be_nil
+ expect(puppet_type.attrclass(:target).instance_variable_get("@doc")).not_to be_nil
end
[ :owner, :group, :mode ].each do |fileprop|
it "should have a #{fileprop} parameter" do
- puppet_type.parameters.should be_include(fileprop)
+ expect(puppet_type.parameters).to be_include(fileprop)
end
end
nagios_type.parameters.reject { |param| param == nagios_type.namevar or param.to_s =~ /^[0-9]/ }.each do |param|
it "should have a #{param} property" do
- puppet_type.should be_validproperty(param)
+ expect(puppet_type).to be_validproperty(param)
end
it "should have documentation for its #{param} property" do
- puppet_type.attrclass(param).instance_variable_get("@doc").should_not be_nil
+ expect(puppet_type.attrclass(param).instance_variable_get("@doc")).not_to be_nil
end
end
nagios_type.parameters.find_all { |param| param.to_s =~ /^[0-9]/ }.each do |param|
it "should have not have a #{param} property" do
- puppet_type.should_not be_validproperty(:param)
+ expect(puppet_type).not_to be_validproperty(:param)
end
end
end
end
end
diff --git a/spec/unit/type/noop_metaparam_spec.rb b/spec/unit/type/noop_metaparam_spec.rb
index 895924b0e..8a188a817 100755
--- a/spec/unit/type/noop_metaparam_spec.rb
+++ b/spec/unit/type/noop_metaparam_spec.rb
@@ -1,38 +1,38 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/type'
describe Puppet::Type.type(:file).attrclass(:noop) do
include PuppetSpec::Files
before do
Puppet.settings.stubs(:use)
@file = Puppet::Type.newfile :path => make_absolute("/what/ever")
end
it "should accept true as a value" do
- lambda { @file[:noop] = true }.should_not raise_error
+ expect { @file[:noop] = true }.not_to raise_error
end
it "should accept false as a value" do
- lambda { @file[:noop] = false }.should_not raise_error
+ expect { @file[:noop] = false }.not_to raise_error
end
describe "when set on a resource" do
it "should default to the :noop setting" do
Puppet[:noop] = true
- @file.noop.should == true
+ expect(@file.noop).to eq(true)
end
it "should prefer true values from the attribute" do
@file[:noop] = true
- @file.noop.should be_true
+ expect(@file.noop).to be_truthy
end
it "should prefer false values from the attribute" do
@file[:noop] = false
- @file.noop.should be_false
+ expect(@file.noop).to be_falsey
end
end
end
diff --git a/spec/unit/type/package/package_settings_spec.rb b/spec/unit/type/package/package_settings_spec.rb
index 18e7a4b7e..a029690c2 100755
--- a/spec/unit/type/package/package_settings_spec.rb
+++ b/spec/unit/type/package/package_settings_spec.rb
@@ -1,135 +1,135 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:package) do
before do
Puppet::Util::Storage.stubs(:store)
end
it "should have a :package_settings feature that requires :package_settings_insync?, :package_settings and :package_settings=" do
- described_class.provider_feature(:package_settings).methods.should == [:package_settings_insync?, :package_settings, :package_settings=]
+ expect(described_class.provider_feature(:package_settings).methods).to eq([:package_settings_insync?, :package_settings, :package_settings=])
end
context "when validating attributes" do
it "should have a package_settings property" do
- described_class.attrtype(:package_settings).should == :property
+ expect(described_class.attrtype(:package_settings)).to eq(:property)
end
end
context "when validating attribute values" do
let(:provider) do
stub( 'provider',
:class => described_class.defaultprovider,
:clear => nil,
:validate_source => false )
end
before do
provider.class.stubs(:supports_parameter?).returns(true)
described_class.defaultprovider.stubs(:new).returns(provider)
end
describe 'package_settings' do
context "with a minimalistic provider supporting package_settings" do
context "and {:package_settings => :settings}" do
let(:resource) do
described_class.new :name => 'foo', :package_settings => :settings
end
it { expect { resource }.to_not raise_error }
it "should set package_settings to :settings" do
- resource.value(:package_settings).should be :settings
+ expect(resource.value(:package_settings)).to be :settings
end
end
end
context "with a provider that supports validation of the package_settings" do
context "and {:package_settings => :valid_value}" do
before do
provider.expects(:package_settings_validate).once.with(:valid_value).returns(true)
end
let(:resource) do
described_class.new :name => 'foo', :package_settings => :valid_value
end
it { expect { resource }.to_not raise_error }
it "should set package_settings to :valid_value" do
- resource.value(:package_settings).should == :valid_value
+ expect(resource.value(:package_settings)).to eq(:valid_value)
end
end
context "and {:package_settings => :invalid_value}" do
before do
msg = "package_settings must be a Hash, not Symbol"
provider.expects(:package_settings_validate).once.
with(:invalid_value).raises(ArgumentError, msg)
end
let(:resource) do
described_class.new :name => 'foo', :package_settings => :invalid_value
end
it do
expect { resource }.to raise_error Puppet::Error,
/package_settings must be a Hash, not Symbol/
end
end
end
context "with a provider that supports munging of the package_settings" do
context "and {:package_settings => 'A'}" do
before do
provider.expects(:package_settings_munge).once.with('A').returns(:a)
end
let(:resource) do
described_class.new :name => 'foo', :package_settings => 'A'
end
it do
expect { resource }.to_not raise_error
end
it "should set package_settings to :a" do
- resource.value(:package_settings).should be :a
+ expect(resource.value(:package_settings)).to be :a
end
end
end
end
end
describe "package_settings property" do
let(:provider) do
stub( 'provider',
:class => described_class.defaultprovider,
:clear => nil,
:validate_source => false )
end
before do
provider.class.stubs(:supports_parameter?).returns(true)
described_class.defaultprovider.stubs(:new).returns(provider)
end
context "with {package_settings => :should}" do
let(:resource) do
described_class.new :name => 'foo', :package_settings => :should
end
describe "#insync?(:is)" do
it "returns the result of provider.package_settings_insync?(:should,:is)" do
resource.provider.expects(:package_settings_insync?).once.with(:should,:is).returns :ok1
- resource.property(:package_settings).insync?(:is).should be :ok1
+ expect(resource.property(:package_settings).insync?(:is)).to be :ok1
end
end
describe "#should_to_s(:newvalue)" do
it "returns the result of provider.package_settings_should_to_s(:should,:newvalue)" do
resource.provider.expects(:package_settings_should_to_s).once.with(:should,:newvalue).returns :ok2
- resource.property(:package_settings).should_to_s(:newvalue).should be :ok2
+ expect(resource.property(:package_settings).should_to_s(:newvalue)).to be :ok2
end
end
describe "#is_to_s(:currentvalue)" do
it "returns the result of provider.package_settings_is_to_s(:should,:currentvalue)" do
resource.provider.expects(:package_settings_is_to_s).once.with(:should,:currentvalue).returns :ok3
- resource.property(:package_settings).is_to_s(:currentvalue).should be :ok3
+ expect(resource.property(:package_settings).is_to_s(:currentvalue)).to be :ok3
end
end
end
context "with any non-nil package_settings" do
describe "#change_to_s(:currentvalue,:newvalue)" do
let(:resource) do
described_class.new :name => 'foo', :package_settings => {}
end
it "returns the result of provider.package_settings_change_to_s(:currentvalue,:newvalue)" do
resource.provider.expects(:package_settings_change_to_s).once.with(:currentvalue,:newvalue).returns :ok4
- resource.property(:package_settings).change_to_s(:currentvalue,:newvalue).should be :ok4
+ expect(resource.property(:package_settings).change_to_s(:currentvalue,:newvalue)).to be :ok4
end
end
end
end
end
diff --git a/spec/unit/type/package_spec.rb b/spec/unit/type/package_spec.rb
index 7f5e15847..438d19b0c 100755
--- a/spec/unit/type/package_spec.rb
+++ b/spec/unit/type/package_spec.rb
@@ -1,374 +1,374 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:package) do
before do
Puppet::Util::Storage.stubs(:store)
end
it "should have a :reinstallable feature that requires the :reinstall method" do
- Puppet::Type.type(:package).provider_feature(:reinstallable).methods.should == [:reinstall]
+ expect(Puppet::Type.type(:package).provider_feature(:reinstallable).methods).to eq([:reinstall])
end
it "should have an :installable feature that requires the :install method" do
- Puppet::Type.type(:package).provider_feature(:installable).methods.should == [:install]
+ expect(Puppet::Type.type(:package).provider_feature(:installable).methods).to eq([:install])
end
it "should have an :uninstallable feature that requires the :uninstall method" do
- Puppet::Type.type(:package).provider_feature(:uninstallable).methods.should == [:uninstall]
+ expect(Puppet::Type.type(:package).provider_feature(:uninstallable).methods).to eq([:uninstall])
end
it "should have an :upgradeable feature that requires :update and :latest methods" do
- Puppet::Type.type(:package).provider_feature(:upgradeable).methods.should == [:update, :latest]
+ expect(Puppet::Type.type(:package).provider_feature(:upgradeable).methods).to eq([:update, :latest])
end
it "should have a :purgeable feature that requires the :purge latest method" do
- Puppet::Type.type(:package).provider_feature(:purgeable).methods.should == [:purge]
+ expect(Puppet::Type.type(:package).provider_feature(:purgeable).methods).to eq([:purge])
end
it "should have a :versionable feature" do
- Puppet::Type.type(:package).provider_feature(:versionable).should_not be_nil
+ expect(Puppet::Type.type(:package).provider_feature(:versionable)).not_to be_nil
end
it "should have a :package_settings feature that requires :package_settings_insync?, :package_settings and :package_settings=" do
- Puppet::Type.type(:package).provider_feature(:package_settings).methods.should == [:package_settings_insync?, :package_settings, :package_settings=]
+ expect(Puppet::Type.type(:package).provider_feature(:package_settings).methods).to eq([:package_settings_insync?, :package_settings, :package_settings=])
end
it "should default to being installed" do
pkg = Puppet::Type.type(:package).new(:name => "yay", :provider => :apt)
- pkg.should(:ensure).should == :present
+ expect(pkg.should(:ensure)).to eq(:present)
end
describe "when validating attributes" do
[:name, :source, :instance, :status, :adminfile, :responsefile, :configfiles, :category, :platform, :root, :vendor, :description, :allowcdrom, :allow_virtual, :reinstall_on_refresh].each do |param|
it "should have a #{param} parameter" do
- Puppet::Type.type(:package).attrtype(param).should == :param
+ expect(Puppet::Type.type(:package).attrtype(param)).to eq(:param)
end
end
it "should have an ensure property" do
- Puppet::Type.type(:package).attrtype(:ensure).should == :property
+ expect(Puppet::Type.type(:package).attrtype(:ensure)).to eq(:property)
end
it "should have a package_settings property" do
- Puppet::Type.type(:package).attrtype(:package_settings).should == :property
+ expect(Puppet::Type.type(:package).attrtype(:package_settings)).to eq(:property)
end
end
describe "when validating attribute values" do
before :each do
@provider = stub(
'provider',
:class => Puppet::Type.type(:package).defaultprovider,
:clear => nil,
:validate_source => nil
)
Puppet::Type.type(:package).defaultprovider.stubs(:new).returns(@provider)
end
after :each do
Puppet::Type.type(:package).defaultprovider = nil
end
it "should support :present as a value to :ensure" do
Puppet::Type.type(:package).new(:name => "yay", :ensure => :present)
end
it "should alias :installed to :present as a value to :ensure" do
pkg = Puppet::Type.type(:package).new(:name => "yay", :ensure => :installed)
- pkg.should(:ensure).should == :present
+ expect(pkg.should(:ensure)).to eq(:present)
end
it "should support :absent as a value to :ensure" do
Puppet::Type.type(:package).new(:name => "yay", :ensure => :absent)
end
it "should support :purged as a value to :ensure if the provider has the :purgeable feature" do
@provider.expects(:satisfies?).with([:purgeable]).returns(true)
Puppet::Type.type(:package).new(:name => "yay", :ensure => :purged)
end
it "should not support :purged as a value to :ensure if the provider does not have the :purgeable feature" do
@provider.expects(:satisfies?).with([:purgeable]).returns(false)
expect { Puppet::Type.type(:package).new(:name => "yay", :ensure => :purged) }.to raise_error(Puppet::Error)
end
it "should support :latest as a value to :ensure if the provider has the :upgradeable feature" do
@provider.expects(:satisfies?).with([:upgradeable]).returns(true)
Puppet::Type.type(:package).new(:name => "yay", :ensure => :latest)
end
it "should not support :latest as a value to :ensure if the provider does not have the :upgradeable feature" do
@provider.expects(:satisfies?).with([:upgradeable]).returns(false)
expect { Puppet::Type.type(:package).new(:name => "yay", :ensure => :latest) }.to raise_error(Puppet::Error)
end
it "should support version numbers as a value to :ensure if the provider has the :versionable feature" do
@provider.expects(:satisfies?).with([:versionable]).returns(true)
Puppet::Type.type(:package).new(:name => "yay", :ensure => "1.0")
end
it "should not support version numbers as a value to :ensure if the provider does not have the :versionable feature" do
@provider.expects(:satisfies?).with([:versionable]).returns(false)
expect { Puppet::Type.type(:package).new(:name => "yay", :ensure => "1.0") }.to raise_error(Puppet::Error)
end
it "should accept any string as an argument to :source" do
expect { Puppet::Type.type(:package).new(:name => "yay", :source => "stuff") }.to_not raise_error
end
it "should not accept a non-string name" do
expect do
Puppet::Type.type(:package).new(:name => ["error"])
end.to raise_error(Puppet::ResourceError, /Name must be a String/)
end
end
module PackageEvaluationTesting
def setprops(properties)
@provider.stubs(:properties).returns(properties)
end
end
describe Puppet::Type.type(:package) do
before :each do
@provider = stub(
'provider',
:class => Puppet::Type.type(:package).defaultprovider,
:clear => nil,
:satisfies? => true,
:name => :mock,
:validate_source => nil
)
Puppet::Type.type(:package).defaultprovider.stubs(:new).returns(@provider)
Puppet::Type.type(:package).defaultprovider.stubs(:instances).returns([])
@package = Puppet::Type.type(:package).new(:name => "yay")
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource(@package)
end
describe Puppet::Type.type(:package), "when it should be purged" do
include PackageEvaluationTesting
before { @package[:ensure] = :purged }
it "should do nothing if it is :purged" do
@provider.expects(:properties).returns(:ensure => :purged).at_least_once
@catalog.apply
end
[:absent, :installed, :present, :latest].each do |state|
it "should purge if it is #{state.to_s}" do
@provider.stubs(:properties).returns(:ensure => state)
@provider.expects(:purge)
@catalog.apply
end
end
end
describe Puppet::Type.type(:package), "when it should be absent" do
include PackageEvaluationTesting
before { @package[:ensure] = :absent }
[:purged, :absent].each do |state|
it "should do nothing if it is #{state.to_s}" do
@provider.expects(:properties).returns(:ensure => state).at_least_once
@catalog.apply
end
end
[:installed, :present, :latest].each do |state|
it "should uninstall if it is #{state.to_s}" do
@provider.stubs(:properties).returns(:ensure => state)
@provider.expects(:uninstall)
@catalog.apply
end
end
end
describe Puppet::Type.type(:package), "when it should be present" do
include PackageEvaluationTesting
before { @package[:ensure] = :present }
[:present, :latest, "1.0"].each do |state|
it "should do nothing if it is #{state.to_s}" do
@provider.expects(:properties).returns(:ensure => state).at_least_once
@catalog.apply
end
end
[:purged, :absent].each do |state|
it "should install if it is #{state.to_s}" do
@provider.stubs(:properties).returns(:ensure => state)
@provider.expects(:install)
@catalog.apply
end
end
end
describe Puppet::Type.type(:package), "when it should be latest" do
include PackageEvaluationTesting
before { @package[:ensure] = :latest }
[:purged, :absent].each do |state|
it "should upgrade if it is #{state.to_s}" do
@provider.stubs(:properties).returns(:ensure => state)
@provider.expects(:update)
@catalog.apply
end
end
it "should upgrade if the current version is not equal to the latest version" do
@provider.stubs(:properties).returns(:ensure => "1.0")
@provider.stubs(:latest).returns("2.0")
@provider.expects(:update)
@catalog.apply
end
it "should do nothing if it is equal to the latest version" do
@provider.stubs(:properties).returns(:ensure => "1.0")
@provider.stubs(:latest).returns("1.0")
@provider.expects(:update).never
@catalog.apply
end
it "should do nothing if the provider returns :present as the latest version" do
@provider.stubs(:properties).returns(:ensure => :present)
@provider.stubs(:latest).returns("1.0")
@provider.expects(:update).never
@catalog.apply
end
end
describe Puppet::Type.type(:package), "when it should be a specific version" do
include PackageEvaluationTesting
before { @package[:ensure] = "1.0" }
[:purged, :absent].each do |state|
it "should install if it is #{state.to_s}" do
@provider.stubs(:properties).returns(:ensure => state)
- @package.property(:ensure).insync?(state).should be_false
+ expect(@package.property(:ensure).insync?(state)).to be_falsey
@provider.expects(:install)
@catalog.apply
end
end
it "should do nothing if the current version is equal to the desired version" do
@provider.stubs(:properties).returns(:ensure => "1.0")
- @package.property(:ensure).insync?('1.0').should be_true
+ expect(@package.property(:ensure).insync?('1.0')).to be_truthy
@provider.expects(:install).never
@catalog.apply
end
it "should install if the current version is not equal to the specified version" do
@provider.stubs(:properties).returns(:ensure => "2.0")
- @package.property(:ensure).insync?('2.0').should be_false
+ expect(@package.property(:ensure).insync?('2.0')).to be_falsey
@provider.expects(:install)
@catalog.apply
end
describe "when current value is an array" do
let(:installed_versions) { ["1.0", "2.0", "3.0"] }
before (:each) do
@provider.stubs(:properties).returns(:ensure => installed_versions)
end
it "should install if value not in the array" do
@package[:ensure] = "1.5"
- @package.property(:ensure).insync?(installed_versions).should be_false
+ expect(@package.property(:ensure).insync?(installed_versions)).to be_falsey
@provider.expects(:install)
@catalog.apply
end
it "should not install if value is in the array" do
@package[:ensure] = "2.0"
- @package.property(:ensure).insync?(installed_versions).should be_true
+ expect(@package.property(:ensure).insync?(installed_versions)).to be_truthy
@provider.expects(:install).never
@catalog.apply
end
describe "when ensure is set to 'latest'" do
it "should not install if the value is in the array" do
@provider.expects(:latest).returns("3.0")
@package[:ensure] = "latest"
- @package.property(:ensure).insync?(installed_versions).should be_true
+ expect(@package.property(:ensure).insync?(installed_versions)).to be_truthy
@provider.expects(:install).never
@catalog.apply
end
end
end
end
describe Puppet::Type.type(:package), "when responding to refresh" do
include PackageEvaluationTesting
it "should support :true as a value to :reinstall_on_refresh" do
srv = Puppet::Type.type(:package).new(:name => "yay", :reinstall_on_refresh => :true)
- srv[:reinstall_on_refresh].should == :true
+ expect(srv[:reinstall_on_refresh]).to eq(:true)
end
it "should support :false as a value to :reinstall_on_refresh" do
srv = Puppet::Type.type(:package).new(:name => "yay", :reinstall_on_refresh => :false)
- srv[:reinstall_on_refresh].should == :false
+ expect(srv[:reinstall_on_refresh]).to eq(:false)
end
it "should specify :false as the default value of :reinstall_on_refresh" do
srv = Puppet::Type.type(:package).new(:name => "yay")
- srv[:reinstall_on_refresh].should == :false
+ expect(srv[:reinstall_on_refresh]).to eq(:false)
end
[:latest, :present, :installed].each do |state|
it "should reinstall if it should be #{state.to_s} and reinstall_on_refresh is true" do
@package[:ensure] = state
@package[:reinstall_on_refresh] = :true
@provider.stubs(:reinstallable?).returns(true)
@provider.expects(:reinstall).once
@package.refresh
end
it "should reinstall if it should be #{state.to_s} and reinstall_on_refresh is false" do
@package[:ensure] = state
@package[:reinstall_on_refresh] = :false
@provider.stubs(:reinstallable?).returns(true)
@provider.expects(:reinstall).never
@package.refresh
end
end
[:purged, :absent, :held].each do |state|
it "should not reinstall if it should be #{state.to_s} and reinstall_on_refresh is true" do
@package[:ensure] = state
@provider.stubs(:reinstallable?).returns(true)
@provider.expects(:reinstall).never
@package.refresh
end
it "should not reinstall if it should be #{state.to_s} and reinstall_on_refresh is false" do
@package[:ensure] = state
@provider.stubs(:reinstallable?).returns(true)
@provider.expects(:reinstall).never
@package.refresh
end
end
end
end
describe "allow_virtual" do
it "defaults to true on platforms that support virtual packages" do
pkg = Puppet::Type.type(:package).new(:name => 'yay', :provider => :yum)
expect(pkg[:allow_virtual]).to eq true
end
it "defaults to false on platforms that do not support virtual packages" do
pkg = Puppet::Type.type(:package).new(:name => 'yay', :provider => :apple)
expect(pkg[:allow_virtual]).to be_nil
end
end
end
diff --git a/spec/unit/type/resources_spec.rb b/spec/unit/type/resources_spec.rb
index e985b9752..5850abd63 100755
--- a/spec/unit/type/resources_spec.rb
+++ b/spec/unit/type/resources_spec.rb
@@ -1,318 +1,318 @@
#! /usr/bin/env ruby
require 'spec_helper'
resources = Puppet::Type.type(:resources)
# There are still plenty of tests to port over from test/.
describe resources do
before :each do
described_class.reset_system_users_max_uid!
end
- describe "when initializing" do
+ context "when initializing" do
it "should fail if the specified resource type does not exist" do
Puppet::Type.stubs(:type).with { |x| x.to_s.downcase == "resources"}.returns resources
Puppet::Type.expects(:type).with("nosuchtype").returns nil
- lambda { resources.new :name => "nosuchtype" }.should raise_error(Puppet::Error)
+ expect { resources.new :name => "nosuchtype" }.to raise_error(Puppet::Error)
end
it "should not fail when the specified resource type exists" do
- lambda { resources.new :name => "file" }.should_not raise_error
+ expect { resources.new :name => "file" }.not_to raise_error
end
it "should set its :resource_type attribute" do
- resources.new(:name => "file").resource_type.should == Puppet::Type.type(:file)
+ expect(resources.new(:name => "file").resource_type).to eq(Puppet::Type.type(:file))
end
end
- describe :purge do
+ context "purge" do
let (:instance) { described_class.new(:name => 'file') }
it "defaults to false" do
- instance[:purge].should be_false
+ expect(instance[:purge]).to be_falsey
end
it "can be set to false" do
instance[:purge] = 'false'
end
it "cannot be set to true for a resource type that does not accept ensure" do
instance.resource_type.stubs(:respond_to?).returns true
instance.resource_type.stubs(:validproperty?).returns false
expect { instance[:purge] = 'yes' }.to raise_error Puppet::Error
end
it "cannot be set to true for a resource type that does not have instances" do
instance.resource_type.stubs(:respond_to?).returns false
instance.resource_type.stubs(:validproperty?).returns true
expect { instance[:purge] = 'yes' }.to raise_error Puppet::Error
end
it "can be set to true for a resource type that has instances and can accept ensure" do
instance.resource_type.stubs(:respond_to?).returns true
instance.resource_type.stubs(:validproperty?).returns true
expect { instance[:purge] = 'yes' }.to_not raise_error
end
end
- describe "#check_user purge behaviour" do
- describe "with unless_system_user => true" do
+ context "#check_user purge behaviour" do
+ context "with unless_system_user => true" do
before do
@res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_system_user => true
@res.catalog = Puppet::Resource::Catalog.new
Puppet::FileSystem.stubs(:exist?).with('/etc/login.defs').returns false
end
it "should never purge hardcoded system users" do
%w{root nobody bin noaccess daemon sys}.each do |sys_user|
- @res.user_check(Puppet::Type.type(:user).new(:name => sys_user)).should be_false
+ expect(@res.user_check(Puppet::Type.type(:user).new(:name => sys_user))).to be_falsey
end
end
it "should not purge system users if unless_system_user => true" do
user_hash = {:name => 'system_user', :uid => 125, :system => true}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_false
+ expect(@res.user_check(user)).to be_falsey
end
it "should purge non-system users if unless_system_user => true" do
user_hash = {:name => 'system_user', :uid => described_class.system_users_max_uid + 1, :system => true}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_true
+ expect(@res.user_check(user)).to be_truthy
end
it "should not purge system users under 600 if unless_system_user => 600" do
res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_system_user => 600
res.catalog = Puppet::Resource::Catalog.new
user_hash = {:name => 'system_user', :uid => 500, :system => true}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- res.user_check(user).should be_false
+ expect(res.user_check(user)).to be_falsey
end
end
%w(FreeBSD OpenBSD).each do |os|
- describe "on #{os}" do
+ context "on #{os}" do
before :each do
Facter.stubs(:value).with(:kernel).returns(os)
Facter.stubs(:value).with(:operatingsystem).returns(os)
Facter.stubs(:value).with(:osfamily).returns(os)
Puppet::FileSystem.stubs(:exist?).with('/etc/login.defs').returns false
@res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_system_user => true
@res.catalog = Puppet::Resource::Catalog.new
end
it "should not purge system users under 1000" do
user_hash = {:name => 'system_user', :uid => 999}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_false
+ expect(@res.user_check(user)).to be_falsey
end
it "should purge users over 999" do
user_hash = {:name => 'system_user', :uid => 1000}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_true
+ expect(@res.user_check(user)).to be_truthy
end
end
end
- describe 'with login.defs present' do
+ context 'with login.defs present' do
before :each do
Puppet::FileSystem.expects(:exist?).with('/etc/login.defs').returns true
Puppet::FileSystem.expects(:each_line).with('/etc/login.defs').yields(' UID_MIN 1234 # UID_MIN comment ')
@res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_system_user => true
@res.catalog = Puppet::Resource::Catalog.new
end
it 'should not purge a system user' do
user_hash = {:name => 'system_user', :uid => 1233}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_false
+ expect(@res.user_check(user)).to be_falsey
end
it 'should purge a non-system user' do
user_hash = {:name => 'system_user', :uid => 1234}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_true
+ expect(@res.user_check(user)).to be_truthy
end
end
- describe "with unless_uid" do
- describe "with a uid array" do
+ context "with unless_uid" do
+ context "with a uid array" do
before do
@res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_uid => [15_000, 15_001, 15_002]
@res.catalog = Puppet::Resource::Catalog.new
end
it "should purge uids that are not in a specified array" do
user_hash = {:name => 'special_user', :uid => 25_000}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_true
+ expect(@res.user_check(user)).to be_truthy
end
it "should not purge uids that are in a specified array" do
user_hash = {:name => 'special_user', :uid => 15000}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_false
+ expect(@res.user_check(user)).to be_falsey
end
end
- describe "with a single integer uid" do
+ context "with a single integer uid" do
before do
@res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_uid => 15_000
@res.catalog = Puppet::Resource::Catalog.new
end
it "should purge uids that are not specified" do
user_hash = {:name => 'special_user', :uid => 25_000}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_true
+ expect(@res.user_check(user)).to be_truthy
end
it "should not purge uids that are specified" do
user_hash = {:name => 'special_user', :uid => 15_000}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_false
+ expect(@res.user_check(user)).to be_falsey
end
end
- describe "with a single string uid" do
+ context "with a single string uid" do
before do
@res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_uid => '15000'
@res.catalog = Puppet::Resource::Catalog.new
end
it "should purge uids that are not specified" do
user_hash = {:name => 'special_user', :uid => 25_000}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_true
+ expect(@res.user_check(user)).to be_truthy
end
it "should not purge uids that are specified" do
user_hash = {:name => 'special_user', :uid => 15_000}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_false
+ expect(@res.user_check(user)).to be_falsey
end
end
- describe "with a mixed uid array" do
+ context "with a mixed uid array" do
before do
@res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_uid => ['15000', 16_666]
@res.catalog = Puppet::Resource::Catalog.new
end
it "should not purge ids in the range" do
user_hash = {:name => 'special_user', :uid => 15_000}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_false
+ expect(@res.user_check(user)).to be_falsey
end
it "should not purge specified ids" do
user_hash = {:name => 'special_user', :uid => 16_666}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_false
+ expect(@res.user_check(user)).to be_falsey
end
it "should purge unspecified ids" do
user_hash = {:name => 'special_user', :uid => 17_000}
user = Puppet::Type.type(:user).new(user_hash)
user.stubs(:retrieve_resource).returns Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)
- @res.user_check(user).should be_true
+ expect(@res.user_check(user)).to be_truthy
end
end
end
end
- describe "#generate" do
+ context "#generate" do
before do
@host1 = Puppet::Type.type(:host).new(:name => 'localhost', :ip => '127.0.0.1')
@catalog = Puppet::Resource::Catalog.new
end
- describe "when dealing with non-purging resources" do
+ context "when dealing with non-purging resources" do
before do
@resources = Puppet::Type.type(:resources).new(:name => 'host')
end
it "should not generate any resource" do
- @resources.generate.should be_empty
+ expect(@resources.generate).to be_empty
end
end
- describe "when the catalog contains a purging resource" do
+ context "when the catalog contains a purging resource" do
before do
@resources = Puppet::Type.type(:resources).new(:name => 'host', :purge => true)
@purgeable_resource = Puppet::Type.type(:host).new(:name => 'localhost', :ip => '127.0.0.1')
@catalog.add_resource @resources
end
it "should not generate a duplicate of that resource" do
Puppet::Type.type(:host).stubs(:instances).returns [@host1]
@catalog.add_resource @host1
- @resources.generate.collect { |r| r.ref }.should_not include(@host1.ref)
+ expect(@resources.generate.collect { |r| r.ref }).not_to include(@host1.ref)
end
it "should not include the skipped system users" do
res = Puppet::Type.type(:resources).new :name => :user, :purge => true
res.catalog = Puppet::Resource::Catalog.new
root = Puppet::Type.type(:user).new(:name => "root")
Puppet::Type.type(:user).expects(:instances).returns [ root ]
list = res.generate
names = list.collect { |r| r[:name] }
- names.should_not be_include("root")
+ expect(names).not_to be_include("root")
end
- describe "when generating a purgeable resource" do
+ context "when generating a purgeable resource" do
it "should be included in the generated resources" do
Puppet::Type.type(:host).stubs(:instances).returns [@purgeable_resource]
- @resources.generate.collect { |r| r.ref }.should include(@purgeable_resource.ref)
+ expect(@resources.generate.collect { |r| r.ref }).to include(@purgeable_resource.ref)
end
end
- describe "when the instance's do not have an ensure property" do
+ context "when the instance's do not have an ensure property" do
it "should not be included in the generated resources" do
@no_ensure_resource = Puppet::Type.type(:exec).new(:name => "#{File.expand_path('/usr/bin/env')} echo")
Puppet::Type.type(:host).stubs(:instances).returns [@no_ensure_resource]
- @resources.generate.collect { |r| r.ref }.should_not include(@no_ensure_resource.ref)
+ expect(@resources.generate.collect { |r| r.ref }).not_to include(@no_ensure_resource.ref)
end
end
- describe "when the instance's ensure property does not accept absent" do
+ context "when the instance's ensure property does not accept absent" do
it "should not be included in the generated resources" do
@no_absent_resource = Puppet::Type.type(:service).new(:name => 'foobar')
Puppet::Type.type(:host).stubs(:instances).returns [@no_absent_resource]
- @resources.generate.collect { |r| r.ref }.should_not include(@no_absent_resource.ref)
+ expect(@resources.generate.collect { |r| r.ref }).not_to include(@no_absent_resource.ref)
end
end
- describe "when checking the instance fails" do
+ context "when checking the instance fails" do
it "should not be included in the generated resources" do
@purgeable_resource = Puppet::Type.type(:host).new(:name => 'foobar')
Puppet::Type.type(:host).stubs(:instances).returns [@purgeable_resource]
@resources.expects(:check).with(@purgeable_resource).returns(false)
- @resources.generate.collect { |r| r.ref }.should_not include(@purgeable_resource.ref)
+ expect(@resources.generate.collect { |r| r.ref }).not_to include(@purgeable_resource.ref)
end
end
end
end
end
diff --git a/spec/unit/type/schedule_spec.rb b/spec/unit/type/schedule_spec.rb
index 0610bd175..a6f1dfa7f 100755
--- a/spec/unit/type/schedule_spec.rb
+++ b/spec/unit/type/schedule_spec.rb
@@ -1,607 +1,607 @@
#! /usr/bin/env ruby
require 'spec_helper'
module ScheduleTesting
def diff(unit, incr, method, count)
diff = Time.now.to_i.send(method, incr * count)
Time.at(diff)
end
def day(method, count)
diff(:hour, 3600 * 24, method, count)
end
def hour(method, count)
diff(:hour, 3600, method, count)
end
def min(method, count)
diff(:min, 60, method, count)
end
end
describe Puppet::Type.type(:schedule) do
include ScheduleTesting
before :each do
Puppet[:ignoreschedules] = false
@schedule = Puppet::Type.type(:schedule).new(:name => "testing")
end
describe Puppet::Type.type(:schedule) do
it "should apply to device" do
- @schedule.must be_appliable_to_device
+ expect(@schedule).to be_appliable_to_device
end
it "should apply to host" do
- @schedule.must be_appliable_to_host
+ expect(@schedule).to be_appliable_to_host
end
it "should default to :distance for period-matching" do
- @schedule[:periodmatch].must == :distance
+ expect(@schedule[:periodmatch]).to eq(:distance)
end
it "should default to a :repeat of 1" do
- @schedule[:repeat].must == 1
+ expect(@schedule[:repeat]).to eq(1)
end
it "should never match when the period is :never" do
@schedule[:period] = :never
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
end
describe Puppet::Type.type(:schedule), "when producing default schedules" do
%w{hourly daily weekly monthly never}.each do |period|
period = period.to_sym
it "should produce a #{period} schedule with the period set appropriately" do
schedules = Puppet::Type.type(:schedule).mkdefaultschedules
- schedules.find { |s| s[:name] == period.to_s and s[:period] == period }.must be_instance_of(Puppet::Type.type(:schedule))
+ expect(schedules.find { |s| s[:name] == period.to_s and s[:period] == period }).to be_instance_of(Puppet::Type.type(:schedule))
end
end
it "should not produce default schedules when default_schedules is false" do
Puppet[:default_schedules] = false
schedules = Puppet::Type.type(:schedule).mkdefaultschedules
- schedules.must have_exactly(0).items
+ expect(schedules).to have_exactly(0).items
end
it "should produce a schedule named puppet with a period of hourly and a repeat of 2" do
schedules = Puppet::Type.type(:schedule).mkdefaultschedules
- schedules.find { |s|
+ expect(schedules.find { |s|
s[:name] == "puppet" and s[:period] == :hourly and s[:repeat] == 2
- }.must be_instance_of(Puppet::Type.type(:schedule))
+ }).to be_instance_of(Puppet::Type.type(:schedule))
end
end
describe Puppet::Type.type(:schedule), "when matching ranges" do
before do
Time.stubs(:now).returns(Time.local(2011, "may", 23, 11, 0, 0))
end
it "should match when the start time is before the current time and the end time is after the current time" do
@schedule[:range] = "10:59:50 - 11:00:10"
- @schedule.must be_match
+ expect(@schedule).to be_match
end
it "should not match when the start time is after the current time" do
@schedule[:range] = "11:00:05 - 11:00:10"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
it "should not match when the end time is previous to the current time" do
@schedule[:range] = "10:59:50 - 10:59:55"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
it "should not match the current time fails between an array of ranges" do
@schedule[:range] = ["4-6", "20-23"]
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
it "should match the lower array of ranges" do
@schedule[:range] = ["9-11", "14-16"]
- @schedule.must be_match
+ expect(@schedule).to be_match
end
it "should match the upper array of ranges" do
@schedule[:range] = ["4-6", "11-12"]
- @schedule.must be_match
+ expect(@schedule).to be_match
end
end
describe Puppet::Type.type(:schedule), "when matching ranges with abbreviated time specifications" do
before do
Time.stubs(:now).returns(Time.local(2011, "may", 23, 11, 45, 59))
end
it "should match when just an hour is specified" do
@schedule[:range] = "11-12"
- @schedule.must be_match
+ expect(@schedule).to be_match
end
it "should not match when the ending hour is the current hour" do
@schedule[:range] = "10-11"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
it "should not match when the ending minute is the current minute" do
@schedule[:range] = "10:00 - 11:45"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
end
describe Puppet::Type.type(:schedule), "when matching ranges with abbreviated time specifications, edge cases part 1" do
before do
Time.stubs(:now).returns(Time.local(2011, "may", 23, 11, 00, 00))
end
it "should match when the current time is the start of the range using hours" do
@schedule[:range] = "11 - 12"
- @schedule.must be_match
+ expect(@schedule).to be_match
end
it "should match when the current time is the end of the range using hours" do
@schedule[:range] = "10 - 11"
- @schedule.must be_match
+ expect(@schedule).to be_match
end
it "should match when the current time is the start of the range using hours and minutes" do
@schedule[:range] = "11:00 - 12:00"
- @schedule.must be_match
+ expect(@schedule).to be_match
end
it "should match when the current time is the end of the range using hours and minutes" do
@schedule[:range] = "10:00 - 11:00"
- @schedule.must be_match
+ expect(@schedule).to be_match
end
end
describe Puppet::Type.type(:schedule), "when matching ranges with abbreviated time specifications, edge cases part 2" do
before do
Time.stubs(:now).returns(Time.local(2011, "may", 23, 11, 00, 01))
end
it "should match when the current time is just past the start of the range using hours" do
@schedule[:range] = "11 - 12"
- @schedule.must be_match
+ expect(@schedule).to be_match
end
it "should not match when the current time is just past the end of the range using hours" do
@schedule[:range] = "10 - 11"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
it "should match when the current time is just past the start of the range using hours and minutes" do
@schedule[:range] = "11:00 - 12:00"
- @schedule.must be_match
+ expect(@schedule).to be_match
end
it "should not match when the current time is just past the end of the range using hours and minutes" do
@schedule[:range] = "10:00 - 11:00"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
end
describe Puppet::Type.type(:schedule), "when matching ranges with abbreviated time specifications, edge cases part 3" do
before do
Time.stubs(:now).returns(Time.local(2011, "may", 23, 10, 59, 59))
end
it "should not match when the current time is just before the start of the range using hours" do
@schedule[:range] = "11 - 12"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
it "should match when the current time is just before the end of the range using hours" do
@schedule[:range] = "10 - 11"
- @schedule.must be_match
+ expect(@schedule).to be_match
end
it "should not match when the current time is just before the start of the range using hours and minutes" do
@schedule[:range] = "11:00 - 12:00"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
it "should match when the current time is just before the end of the range using hours and minutes" do
@schedule[:range] = "10:00 - 11:00"
- @schedule.must be_match
+ expect(@schedule).to be_match
end
end
describe Puppet::Type.type(:schedule), "when matching ranges spanning days, day 1" do
before do
# Test with the current time at a month's end boundary to ensure we are
# advancing the day properly when we push the ending limit out a day.
# For example, adding 1 to 31 would throw an error instead of advancing
# the date.
Time.stubs(:now).returns(Time.local(2011, "mar", 31, 22, 30, 0))
end
it "should match when the start time is before current time and the end time is the following day" do
@schedule[:range] = "22:00:00 - 02:00:00"
- @schedule.must be_match
+ expect(@schedule).to be_match
end
it "should not match when the current time is outside the range" do
@schedule[:range] = "23:30:00 - 21:00:00"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
end
describe Puppet::Type.type(:schedule), "when matching ranges spanning days, day 2" do
before do
# Test with the current time at a month's end boundary to ensure we are
# advancing the day properly when we push the ending limit out a day.
# For example, adding 1 to 31 would throw an error instead of advancing
# the date.
Time.stubs(:now).returns(Time.local(2011, "mar", 31, 1, 30, 0))
end
it "should match when the start time is the day before the current time and the end time is after the current time" do
@schedule[:range] = "22:00:00 - 02:00:00"
- @schedule.must be_match
+ expect(@schedule).to be_match
end
it "should not match when the start time is after the current time" do
@schedule[:range] = "02:00:00 - 00:30:00"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
it "should not match when the end time is before the current time" do
@schedule[:range] = "22:00:00 - 01:00:00"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
end
describe Puppet::Type.type(:schedule), "when matching hourly by distance" do
before do
@schedule[:period] = :hourly
@schedule[:periodmatch] = :distance
Time.stubs(:now).returns(Time.local(2011, "may", 23, 11, 0, 0))
end
it "should match when the previous time was an hour ago" do
- @schedule.must be_match(hour("-", 1))
+ expect(@schedule).to be_match(hour("-", 1))
end
it "should not match when the previous time was now" do
- @schedule.must_not be_match(Time.now)
+ expect(@schedule).to_not be_match(Time.now)
end
it "should not match when the previous time was 59 minutes ago" do
- @schedule.must_not be_match(min("-", 59))
+ expect(@schedule).to_not be_match(min("-", 59))
end
end
describe Puppet::Type.type(:schedule), "when matching daily by distance" do
before do
@schedule[:period] = :daily
@schedule[:periodmatch] = :distance
Time.stubs(:now).returns(Time.local(2011, "may", 23, 11, 0, 0))
end
it "should match when the previous time was one day ago" do
- @schedule.must be_match(day("-", 1))
+ expect(@schedule).to be_match(day("-", 1))
end
it "should not match when the previous time is now" do
- @schedule.must_not be_match(Time.now)
+ expect(@schedule).to_not be_match(Time.now)
end
it "should not match when the previous time was 23 hours ago" do
- @schedule.must_not be_match(hour("-", 23))
+ expect(@schedule).to_not be_match(hour("-", 23))
end
end
describe Puppet::Type.type(:schedule), "when matching weekly by distance" do
before do
@schedule[:period] = :weekly
@schedule[:periodmatch] = :distance
Time.stubs(:now).returns(Time.local(2011, "may", 23, 11, 0, 0))
end
it "should match when the previous time was seven days ago" do
- @schedule.must be_match(day("-", 7))
+ expect(@schedule).to be_match(day("-", 7))
end
it "should not match when the previous time was now" do
- @schedule.must_not be_match(Time.now)
+ expect(@schedule).to_not be_match(Time.now)
end
it "should not match when the previous time was six days ago" do
- @schedule.must_not be_match(day("-", 6))
+ expect(@schedule).to_not be_match(day("-", 6))
end
end
describe Puppet::Type.type(:schedule), "when matching monthly by distance" do
before do
@schedule[:period] = :monthly
@schedule[:periodmatch] = :distance
Time.stubs(:now).returns(Time.local(2011, "may", 23, 11, 0, 0))
end
it "should match when the previous time was 32 days ago" do
- @schedule.must be_match(day("-", 32))
+ expect(@schedule).to be_match(day("-", 32))
end
it "should not match when the previous time was now" do
- @schedule.must_not be_match(Time.now)
+ expect(@schedule).to_not be_match(Time.now)
end
it "should not match when the previous time was 27 days ago" do
- @schedule.must_not be_match(day("-", 27))
+ expect(@schedule).to_not be_match(day("-", 27))
end
end
describe Puppet::Type.type(:schedule), "when matching hourly by number" do
before do
@schedule[:period] = :hourly
@schedule[:periodmatch] = :number
end
it "should match if the times are one minute apart and the current minute is 0" do
current = Time.utc(2008, 1, 1, 0, 0, 0)
previous = Time.utc(2007, 12, 31, 23, 59, 0)
Time.stubs(:now).returns(current)
- @schedule.must be_match(previous)
+ expect(@schedule).to be_match(previous)
end
it "should not match if the times are 59 minutes apart and the current minute is 59" do
current = Time.utc(2009, 2, 1, 12, 59, 0)
previous = Time.utc(2009, 2, 1, 12, 0, 0)
Time.stubs(:now).returns(current)
- @schedule.must_not be_match(previous)
+ expect(@schedule).to_not be_match(previous)
end
end
describe Puppet::Type.type(:schedule), "when matching daily by number" do
before do
@schedule[:period] = :daily
@schedule[:periodmatch] = :number
end
it "should match if the times are one minute apart and the current minute and hour are 0" do
current = Time.utc(2010, "nov", 7, 0, 0, 0)
# Now set the previous time to one minute before that
previous = current - 60
Time.stubs(:now).returns(current)
- @schedule.must be_match(previous)
+ expect(@schedule).to be_match(previous)
end
it "should not match if the times are 23 hours and 58 minutes apart and the current hour is 23 and the current minute is 59" do
# Reset the previous time to 00:00:00
previous = Time.utc(2010, "nov", 7, 0, 0, 0)
# Set the current time to 23:59
now = previous + (23 * 3600) + (59 * 60)
Time.stubs(:now).returns(now)
- @schedule.must_not be_match(previous)
+ expect(@schedule).to_not be_match(previous)
end
end
describe Puppet::Type.type(:schedule), "when matching weekly by number" do
before do
@schedule[:period] = :weekly
@schedule[:periodmatch] = :number
end
it "should match if the previous time is prior to the most recent Sunday" do
now = Time.utc(2010, "nov", 11, 0, 0, 0) # Thursday
Time.stubs(:now).returns(now)
previous = Time.utc(2010, "nov", 6, 23, 59, 59) # Sat
- @schedule.must be_match(previous)
+ expect(@schedule).to be_match(previous)
end
it "should not match if the previous time is after the most recent Saturday" do
now = Time.utc(2010, "nov", 11, 0, 0, 0) # Thursday
Time.stubs(:now).returns(now)
previous = Time.utc(2010, "nov", 7, 0, 0, 0) # Sunday
- @schedule.must_not be_match(previous)
+ expect(@schedule).to_not be_match(previous)
end
end
describe Puppet::Type.type(:schedule), "when matching monthly by number" do
before do
@schedule[:period] = :monthly
@schedule[:periodmatch] = :number
end
it "should match when the previous time is prior to the first day of this month" do
now = Time.utc(2010, "nov", 8, 00, 59, 59)
Time.stubs(:now).returns(now)
previous = Time.utc(2010, "oct", 31, 23, 59, 59)
- @schedule.must be_match(previous)
+ expect(@schedule).to be_match(previous)
end
it "should not match when the previous time is after the last day of last month" do
now = Time.utc(2010, "nov", 8, 00, 59, 59)
Time.stubs(:now).returns(now)
previous = Time.utc(2010, "nov", 1, 0, 0, 0)
- @schedule.must_not be_match(previous)
+ expect(@schedule).to_not be_match(previous)
end
end
describe Puppet::Type.type(:schedule), "when matching with a repeat greater than one" do
before do
@schedule[:period] = :daily
@schedule[:repeat] = 2
Time.stubs(:now).returns(Time.local(2011, "may", 23, 11, 0, 0))
end
it "should fail if the periodmatch is 'number'" do
@schedule[:periodmatch] = :number
- proc { @schedule[:repeat] = 2 }.must raise_error(Puppet::Error)
+ expect(proc { @schedule[:repeat] = 2 }).to raise_error(Puppet::Error)
end
it "should match if the previous run was further away than the distance divided by the repeat" do
previous = Time.now - (3600 * 13)
- @schedule.must be_match(previous)
+ expect(@schedule).to be_match(previous)
end
it "should not match if the previous run was closer than the distance divided by the repeat" do
previous = Time.now - (3600 * 11)
- @schedule.must_not be_match(previous)
+ expect(@schedule).to_not be_match(previous)
end
end
describe Puppet::Type.type(:schedule), "when matching days of the week" do
before do
# 2011-05-23 is a Monday
Time.stubs(:now).returns(Time.local(2011, "may", 23, 11, 0, 0))
end
it "should raise an error if the weekday is 'Someday'" do
- proc { @schedule[:weekday] = "Someday" }.should raise_error(Puppet::Error)
+ expect { @schedule[:weekday] = "Someday" }.to raise_error(Puppet::Error)
end
it "should raise an error if the weekday is '7'" do
- proc { @schedule[:weekday] = "7" }.should raise_error(Puppet::Error)
+ expect { @schedule[:weekday] = "7" }.to raise_error(Puppet::Error)
end
it "should accept all full weekday names as valid values" do
- proc { @schedule[:weekday] = ['Sunday', 'Monday', 'Tuesday', 'Wednesday',
- 'Thursday', 'Friday', 'Saturday'] }.should_not raise_error
+ expect { @schedule[:weekday] = ['Sunday', 'Monday', 'Tuesday', 'Wednesday',
+ 'Thursday', 'Friday', 'Saturday'] }.not_to raise_error
end
it "should accept all short weekday names as valid values" do
- proc { @schedule[:weekday] = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu',
- 'Fri', 'Sat'] }.should_not raise_error
+ expect { @schedule[:weekday] = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu',
+ 'Fri', 'Sat'] }.not_to raise_error
end
it "should match if the weekday is 'Monday'" do
@schedule[:weekday] = "Monday"
- @schedule.match?.should be_true
+ expect(@schedule.match?).to be_truthy
end
it "should match if the weekday is 'Mon'" do
@schedule[:weekday] = "Mon"
- @schedule.match?.should be_true
+ expect(@schedule.match?).to be_truthy
end
it "should match if the weekday is '1'" do
@schedule[:weekday] = "1"
- @schedule.match?.should be_true
+ expect(@schedule.match?).to be_truthy
end
it "should not match if the weekday is Tuesday" do
@schedule[:weekday] = "Tuesday"
- @schedule.should_not be_match
+ expect(@schedule).not_to be_match
end
it "should match if weekday is ['Sun', 'Mon']" do
@schedule[:weekday] = ["Sun", "Mon"]
- @schedule.match?.should be_true
+ expect(@schedule.match?).to be_truthy
end
it "should not match if weekday is ['Sun', 'Tue']" do
@schedule[:weekday] = ["Sun", "Tue"]
- @schedule.should_not be_match
+ expect(@schedule).not_to be_match
end
it "should match if the weekday is 'Monday'" do
@schedule[:weekday] = "Monday"
- @schedule.match?.should be_true
+ expect(@schedule.match?).to be_truthy
end
it "should match if the weekday is 'Mon'" do
@schedule[:weekday] = "Mon"
- @schedule.match?.should be_true
+ expect(@schedule.match?).to be_truthy
end
it "should match if the weekday is '1'" do
@schedule[:weekday] = "1"
- @schedule.match?.should be_true
+ expect(@schedule.match?).to be_truthy
end
it "should not match if the weekday is Tuesday" do
@schedule[:weekday] = "Tuesday"
- @schedule.should_not be_match
+ expect(@schedule).not_to be_match
end
it "should match if weekday is ['Sun', 'Mon']" do
@schedule[:weekday] = ["Sun", "Mon"]
- @schedule.match?.should be_true
+ expect(@schedule.match?).to be_truthy
end
end
describe Puppet::Type.type(:schedule), "when matching days of week and ranges spanning days, day 1" do
before do
# Test with ranges and days-of-week both set. 2011-03-31 was a Thursday.
Time.stubs(:now).returns(Time.local(2011, "mar", 31, 22, 30, 0))
end
it "should match when the range and day of week matches" do
@schedule[:range] = "22:00:00 - 02:00:00"
@schedule[:weekday] = "Thursday"
- @schedule.must be_match
+ expect(@schedule).to be_match
end
it "should not match when the range doesn't match even if the day-of-week matches" do
@schedule[:range] = "23:30:00 - 21:00:00"
@schedule[:weekday] = "Thursday"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
it "should not match when day-of-week doesn't match even if the range matches (1 day later)" do
@schedule[:range] = "22:00:00 - 01:00:00"
@schedule[:weekday] = "Friday"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
it "should not match when day-of-week doesn't match even if the range matches (1 day earlier)" do
@schedule[:range] = "22:00:00 - 01:00:00"
@schedule[:weekday] = "Wednesday"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
end
describe Puppet::Type.type(:schedule), "when matching days of week and ranges spanning days, day 2" do
before do
# 2011-03-31 was a Thursday. As the end-time of a day spanning match, that means
# we need to match on Wednesday.
Time.stubs(:now).returns(Time.local(2011, "mar", 31, 1, 30, 0))
end
it "should match when the range matches and the day of week should match" do
@schedule[:range] = "22:00:00 - 02:00:00"
@schedule[:weekday] = "Wednesday"
- @schedule.must be_match
+ expect(@schedule).to be_match
end
it "should not match when the range does not match and the day of week should match" do
@schedule[:range] = "22:00:00 - 01:00:00"
@schedule[:weekday] = "Thursday"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
it "should not match when the range matches but the day-of-week does not (1 day later)" do
@schedule[:range] = "22:00:00 - 02:00:00"
@schedule[:weekday] = "Thursday"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
it "should not match when the range matches but the day-of-week does not (1 day later)" do
@schedule[:range] = "22:00:00 - 02:00:00"
@schedule[:weekday] = "Tuesday"
- @schedule.must_not be_match
+ expect(@schedule).to_not be_match
end
end
end
diff --git a/spec/unit/type/scheduled_task_spec.rb b/spec/unit/type/scheduled_task_spec.rb
index 71322f737..cc4e6fc0b 100644
--- a/spec/unit/type/scheduled_task_spec.rb
+++ b/spec/unit/type/scheduled_task_spec.rb
@@ -1,103 +1,103 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:scheduled_task), :if => Puppet.features.microsoft_windows? do
it 'should use name as the namevar' do
- described_class.new(
+ expect(described_class.new(
:title => 'Foo',
:command => 'C:\Windows\System32\notepad.exe'
- ).name.must == 'Foo'
+ ).name).to eq('Foo')
end
describe 'when setting the command' do
it 'should accept an absolute path to the command' do
- described_class.new(:name => 'Test Task', :command => 'C:\Windows\System32\notepad.exe')[:command].should == 'C:\Windows\System32\notepad.exe'
+ expect(described_class.new(:name => 'Test Task', :command => 'C:\Windows\System32\notepad.exe')[:command]).to eq('C:\Windows\System32\notepad.exe')
end
it 'should convert forward slashes to backslashes' do
- described_class.new(
+ expect(described_class.new(
:name => 'Test Task',
:command => 'C:/Windows/System32/notepad.exe'
- )[:command].should == 'C:\Windows\System32\notepad.exe'
+ )[:command]).to eq('C:\Windows\System32\notepad.exe')
end
it 'should normalize backslashes' do
- described_class.new(
+ expect(described_class.new(
:name => 'Test Task',
:command => 'C:\Windows\\System32\\\\notepad.exe'
- )[:command].should == 'C:\Windows\System32\notepad.exe'
+ )[:command]).to eq('C:\Windows\System32\notepad.exe')
end
it 'should fail if the path to the command is not absolute' do
expect {
described_class.new(:name => 'Test Task', :command => 'notepad.exe')
}.to raise_error(
Puppet::Error,
/Parameter command failed on Scheduled_task\[Test Task\]: Must be specified using an absolute path\./
)
end
end
describe 'when setting the command arguments' do
it 'should accept a string' do
- described_class.new(
+ expect(described_class.new(
:name => 'Test Task',
:command => 'C:\Windows\System32\notepad.exe',
:arguments => '/a /b /c'
- )[:arguments].should == '/a /b /c'
+ )[:arguments]).to eq('/a /b /c')
end
it 'should allow not specifying any command arguments' do
- described_class.new(
+ expect(described_class.new(
:name => 'Test Task',
:command => 'C:\Windows\System32\notepad.exe'
- )[:arguments].should_not be
+ )[:arguments]).not_to be
end
end
describe 'when setting whether the task is enabled or not' do
end
describe 'when setting the working directory' do
it 'should accept an absolute path to the working directory' do
- described_class.new(
+ expect(described_class.new(
:name => 'Test Task',
:command => 'C:\Windows\System32\notepad.exe',
:working_dir => 'C:\Windows\System32'
- )[:working_dir].should == 'C:\Windows\System32'
+ )[:working_dir]).to eq('C:\Windows\System32')
end
it 'should fail if the path to the working directory is not absolute' do
expect {
described_class.new(
:name => 'Test Task',
:command => 'C:\Windows\System32\notepad.exe',
:working_dir => 'Windows\System32'
)
}.to raise_error(
Puppet::Error,
/Parameter working_dir failed on Scheduled_task\[Test Task\]: Must be specified using an absolute path/
)
end
it 'should allow not specifying any working directory' do
- described_class.new(
+ expect(described_class.new(
:name => 'Test Task',
:command => 'C:\Windows\System32\notepad.exe'
- )[:working_dir].should_not be
+ )[:working_dir]).not_to be
end
end
describe 'when setting the trigger' do
it 'should delegate to the provider to validate the trigger' do
described_class.defaultprovider.any_instance.expects(:validate_trigger).returns(true)
described_class.new(
:name => 'Test Task',
:command => 'C:\Windows\System32\notepad.exe',
:trigger => {'schedule' => 'once', 'start_date' => '2011-09-16', 'start_time' => '13:20'}
)
end
end
end
diff --git a/spec/unit/type/selboolean_spec.rb b/spec/unit/type/selboolean_spec.rb
index 9f48a436b..e607b4bd8 100755
--- a/spec/unit/type/selboolean_spec.rb
+++ b/spec/unit/type/selboolean_spec.rb
@@ -1,44 +1,44 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:selboolean), "when validating attributes" do
[:name, :persistent].each do |param|
it "should have a #{param} parameter" do
- Puppet::Type.type(:selboolean).attrtype(param).should == :param
+ expect(Puppet::Type.type(:selboolean).attrtype(param)).to eq(:param)
end
end
it "should have a value property" do
- Puppet::Type.type(:selboolean).attrtype(:value).should == :property
+ expect(Puppet::Type.type(:selboolean).attrtype(:value)).to eq(:property)
end
end
describe Puppet::Type.type(:selboolean), "when validating values" do
before do
@class = Puppet::Type.type(:selboolean)
@provider_class = stub 'provider_class', :name => "fake", :suitable? => true, :supports_parameter? => true
@class.stubs(:defaultprovider).returns(@provider_class)
@class.stubs(:provider).returns(@provider_class)
@provider = stub 'provider', :class => @provider_class, :clear => nil
@provider_class.stubs(:new).returns(@provider)
end
it "should support :on as a value to :value" do
Puppet::Type.type(:selboolean).new(:name => "yay", :value => :on)
end
it "should support :off as a value to :value" do
Puppet::Type.type(:selboolean).new(:name => "yay", :value => :off)
end
it "should support :true as a value to :persistent" do
Puppet::Type.type(:selboolean).new(:name => "yay", :value => :on, :persistent => :true)
end
it "should support :false as a value to :persistent" do
Puppet::Type.type(:selboolean).new(:name => "yay", :value => :on, :persistent => :false)
end
end
diff --git a/spec/unit/type/selmodule_spec.rb b/spec/unit/type/selmodule_spec.rb
index af732b175..feaacbd69 100755
--- a/spec/unit/type/selmodule_spec.rb
+++ b/spec/unit/type/selmodule_spec.rb
@@ -1,17 +1,17 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:selmodule), "when validating attributes" do
[:name, :selmoduledir, :selmodulepath].each do |param|
it "should have a #{param} parameter" do
- Puppet::Type.type(:selmodule).attrtype(param).should == :param
+ expect(Puppet::Type.type(:selmodule).attrtype(param)).to eq(:param)
end
end
[:ensure, :syncversion].each do |param|
it "should have a #{param} property" do
- Puppet::Type.type(:selmodule).attrtype(param).should == :property
+ expect(Puppet::Type.type(:selmodule).attrtype(param)).to eq(:property)
end
end
end
diff --git a/spec/unit/type/service_spec.rb b/spec/unit/type/service_spec.rb
index cfb701d0c..765085ada 100755
--- a/spec/unit/type/service_spec.rb
+++ b/spec/unit/type/service_spec.rb
@@ -1,261 +1,261 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:service) do
it "should have an :enableable feature that requires the :enable, :disable, and :enabled? methods" do
- Puppet::Type.type(:service).provider_feature(:enableable).methods.should == [:disable, :enable, :enabled?]
+ expect(Puppet::Type.type(:service).provider_feature(:enableable).methods).to eq([:disable, :enable, :enabled?])
end
it "should have a :refreshable feature that requires the :restart method" do
- Puppet::Type.type(:service).provider_feature(:refreshable).methods.should == [:restart]
+ expect(Puppet::Type.type(:service).provider_feature(:refreshable).methods).to eq([:restart])
end
end
describe Puppet::Type.type(:service), "when validating attributes" do
[:name, :binary, :hasstatus, :path, :pattern, :start, :restart, :stop, :status, :hasrestart, :control].each do |param|
it "should have a #{param} parameter" do
- Puppet::Type.type(:service).attrtype(param).should == :param
+ expect(Puppet::Type.type(:service).attrtype(param)).to eq(:param)
end
end
[:ensure, :enable].each do |param|
it "should have an #{param} property" do
- Puppet::Type.type(:service).attrtype(param).should == :property
+ expect(Puppet::Type.type(:service).attrtype(param)).to eq(:property)
end
end
end
describe Puppet::Type.type(:service), "when validating attribute values" do
before do
@provider = stub 'provider', :class => Puppet::Type.type(:service).defaultprovider, :clear => nil, :controllable? => false
Puppet::Type.type(:service).defaultprovider.stubs(:new).returns(@provider)
end
it "should support :running as a value to :ensure" do
Puppet::Type.type(:service).new(:name => "yay", :ensure => :running)
end
it "should support :stopped as a value to :ensure" do
Puppet::Type.type(:service).new(:name => "yay", :ensure => :stopped)
end
it "should alias the value :true to :running in :ensure" do
svc = Puppet::Type.type(:service).new(:name => "yay", :ensure => true)
- svc.should(:ensure).should == :running
+ expect(svc.should(:ensure)).to eq(:running)
end
it "should alias the value :false to :stopped in :ensure" do
svc = Puppet::Type.type(:service).new(:name => "yay", :ensure => false)
- svc.should(:ensure).should == :stopped
+ expect(svc.should(:ensure)).to eq(:stopped)
end
describe "the enable property" do
before :each do
@provider.class.stubs(:supports_parameter?).returns true
end
it "should support :true as a value" do
srv = Puppet::Type.type(:service).new(:name => "yay", :enable => :true)
- srv.should(:enable).should == :true
+ expect(srv.should(:enable)).to eq(:true)
end
it "should support :false as a value" do
srv = Puppet::Type.type(:service).new(:name => "yay", :enable => :false)
- srv.should(:enable).should == :false
+ expect(srv.should(:enable)).to eq(:false)
end
it "should support :manual as a value on Windows" do
Puppet.features.stubs(:microsoft_windows?).returns true
srv = Puppet::Type.type(:service).new(:name => "yay", :enable => :manual)
- srv.should(:enable).should == :manual
+ expect(srv.should(:enable)).to eq(:manual)
end
it "should not support :manual as a value when not on Windows" do
Puppet.features.stubs(:microsoft_windows?).returns false
expect { Puppet::Type.type(:service).new(:name => "yay", :enable => :manual) }.to raise_error(
Puppet::Error,
/Setting enable to manual is only supported on Microsoft Windows\./
)
end
end
it "should support :true as a value to :hasstatus" do
srv = Puppet::Type.type(:service).new(:name => "yay", :hasstatus => :true)
- srv[:hasstatus].should == :true
+ expect(srv[:hasstatus]).to eq(:true)
end
it "should support :false as a value to :hasstatus" do
srv = Puppet::Type.type(:service).new(:name => "yay", :hasstatus => :false)
- srv[:hasstatus].should == :false
+ expect(srv[:hasstatus]).to eq(:false)
end
it "should specify :true as the default value of hasstatus" do
srv = Puppet::Type.type(:service).new(:name => "yay")
- srv[:hasstatus].should == :true
+ expect(srv[:hasstatus]).to eq(:true)
end
it "should support :true as a value to :hasrestart" do
srv = Puppet::Type.type(:service).new(:name => "yay", :hasrestart => :true)
- srv[:hasrestart].should == :true
+ expect(srv[:hasrestart]).to eq(:true)
end
it "should support :false as a value to :hasrestart" do
srv = Puppet::Type.type(:service).new(:name => "yay", :hasrestart => :false)
- srv[:hasrestart].should == :false
+ expect(srv[:hasrestart]).to eq(:false)
end
it "should allow setting the :enable parameter if the provider has the :enableable feature" do
Puppet::Type.type(:service).defaultprovider.stubs(:supports_parameter?).returns(true)
Puppet::Type.type(:service).defaultprovider.expects(:supports_parameter?).with(Puppet::Type.type(:service).attrclass(:enable)).returns(true)
svc = Puppet::Type.type(:service).new(:name => "yay", :enable => true)
- svc.should(:enable).should == :true
+ expect(svc.should(:enable)).to eq(:true)
end
it "should not allow setting the :enable parameter if the provider is missing the :enableable feature" do
Puppet::Type.type(:service).defaultprovider.stubs(:supports_parameter?).returns(true)
Puppet::Type.type(:service).defaultprovider.expects(:supports_parameter?).with(Puppet::Type.type(:service).attrclass(:enable)).returns(false)
svc = Puppet::Type.type(:service).new(:name => "yay", :enable => true)
- svc.should(:enable).should be_nil
+ expect(svc.should(:enable)).to be_nil
end
it "should split paths on '#{File::PATH_SEPARATOR}'" do
Puppet::FileSystem.stubs(:exist?).returns(true)
FileTest.stubs(:directory?).returns(true)
svc = Puppet::Type.type(:service).new(:name => "yay", :path => "/one/two#{File::PATH_SEPARATOR}/three/four")
- svc[:path].should == %w{/one/two /three/four}
+ expect(svc[:path]).to eq(%w{/one/two /three/four})
end
it "should accept arrays of paths joined by '#{File::PATH_SEPARATOR}'" do
Puppet::FileSystem.stubs(:exist?).returns(true)
FileTest.stubs(:directory?).returns(true)
svc = Puppet::Type.type(:service).new(:name => "yay", :path => ["/one#{File::PATH_SEPARATOR}/two", "/three#{File::PATH_SEPARATOR}/four"])
- svc[:path].should == %w{/one /two /three /four}
+ expect(svc[:path]).to eq(%w{/one /two /three /four})
end
end
describe Puppet::Type.type(:service), "when setting default attribute values" do
it "should default to the provider's default path if one is available" do
FileTest.stubs(:directory?).returns(true)
Puppet::FileSystem.stubs(:exist?).returns(true)
Puppet::Type.type(:service).defaultprovider.stubs(:respond_to?).returns(true)
Puppet::Type.type(:service).defaultprovider.stubs(:defpath).returns("testing")
svc = Puppet::Type.type(:service).new(:name => "other")
- svc[:path].should == ["testing"]
+ expect(svc[:path]).to eq(["testing"])
end
it "should default 'pattern' to the binary if one is provided" do
svc = Puppet::Type.type(:service).new(:name => "other", :binary => "/some/binary")
- svc[:pattern].should == "/some/binary"
+ expect(svc[:pattern]).to eq("/some/binary")
end
it "should default 'pattern' to the name if no pattern is provided" do
svc = Puppet::Type.type(:service).new(:name => "other")
- svc[:pattern].should == "other"
+ expect(svc[:pattern]).to eq("other")
end
it "should default 'control' to the upcased service name with periods replaced by underscores if the provider supports the 'controllable' feature" do
provider = stub 'provider', :controllable? => true, :class => Puppet::Type.type(:service).defaultprovider, :clear => nil
Puppet::Type.type(:service).defaultprovider.stubs(:new).returns(provider)
svc = Puppet::Type.type(:service).new(:name => "nfs.client")
- svc[:control].should == "NFS_CLIENT_START"
+ expect(svc[:control]).to eq("NFS_CLIENT_START")
end
end
describe Puppet::Type.type(:service), "when retrieving the host's current state" do
before do
@service = Puppet::Type.type(:service).new(:name => "yay")
end
it "should use the provider's status to determine whether the service is running" do
@service.provider.expects(:status).returns(:yepper)
@service[:ensure] = :running
- @service.property(:ensure).retrieve.should == :yepper
+ expect(@service.property(:ensure).retrieve).to eq(:yepper)
end
it "should ask the provider whether it is enabled" do
@service.provider.class.stubs(:supports_parameter?).returns(true)
@service.provider.expects(:enabled?).returns(:yepper)
@service[:enable] = true
- @service.property(:enable).retrieve.should == :yepper
+ expect(@service.property(:enable).retrieve).to eq(:yepper)
end
end
describe Puppet::Type.type(:service), "when changing the host" do
before do
@service = Puppet::Type.type(:service).new(:name => "yay")
end
it "should start the service if it is supposed to be running" do
@service[:ensure] = :running
@service.provider.expects(:start)
@service.property(:ensure).sync
end
it "should stop the service if it is supposed to be stopped" do
@service[:ensure] = :stopped
@service.provider.expects(:stop)
@service.property(:ensure).sync
end
it "should enable the service if it is supposed to be enabled" do
@service.provider.class.stubs(:supports_parameter?).returns(true)
@service[:enable] = true
@service.provider.expects(:enable)
@service.property(:enable).sync
end
it "should disable the service if it is supposed to be disabled" do
@service.provider.class.stubs(:supports_parameter?).returns(true)
@service[:enable] = false
@service.provider.expects(:disable)
@service.property(:enable).sync
end
it "should sync the service's enable state when changing the state of :ensure if :enable is being managed" do
@service.provider.class.stubs(:supports_parameter?).returns(true)
@service[:enable] = false
@service[:ensure] = :stopped
@service.property(:enable).expects(:retrieve).returns("whatever")
@service.property(:enable).expects(:insync?).returns(false)
@service.property(:enable).expects(:sync)
@service.provider.stubs(:stop)
@service.property(:ensure).sync
end
end
describe Puppet::Type.type(:service), "when refreshing the service" do
before do
@service = Puppet::Type.type(:service).new(:name => "yay")
end
it "should restart the service if it is running" do
@service[:ensure] = :running
@service.provider.expects(:status).returns(:running)
@service.provider.expects(:restart)
@service.refresh
end
it "should restart the service if it is running, even if it is supposed to stopped" do
@service[:ensure] = :stopped
@service.provider.expects(:status).returns(:running)
@service.provider.expects(:restart)
@service.refresh
end
it "should not restart the service if it is not running" do
@service[:ensure] = :running
@service.provider.expects(:status).returns(:stopped)
@service.refresh
end
it "should add :ensure as a property if it is not being managed" do
@service.provider.expects(:status).returns(:running)
@service.provider.expects(:restart)
@service.refresh
end
end
diff --git a/spec/unit/type/ssh_authorized_key_spec.rb b/spec/unit/type/ssh_authorized_key_spec.rb
index 3e819540f..4eebbf521 100755
--- a/spec/unit/type/ssh_authorized_key_spec.rb
+++ b/spec/unit/type/ssh_authorized_key_spec.rb
@@ -1,258 +1,258 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:ssh_authorized_key), :unless => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
before do
provider_class = stub 'provider_class', :name => "fake", :suitable? => true, :supports_parameter? => true
described_class.stubs(:defaultprovider).returns(provider_class)
described_class.stubs(:provider).returns(provider_class)
provider = stub 'provider', :class => provider_class, :file_path => make_absolute("/tmp/whatever"), :clear => nil
provider_class.stubs(:new).returns(provider)
end
it "has :name as its namevar" do
expect(described_class.key_attributes).to eq [:name]
end
describe "when validating attributes" do
[:name, :provider].each do |param|
it "has a #{param} parameter" do
expect(described_class.attrtype(param)).to eq :param
end
end
[:type, :key, :user, :target, :options, :ensure].each do |property|
it "has a #{property} property" do
expect(described_class.attrtype(property)).to eq :property
end
end
end
describe "when validating values" do
describe "for name" do
it "supports valid names" do
described_class.new(:name => "username", :ensure => :present, :user => "nobody")
described_class.new(:name => "username@hostname", :ensure => :present, :user => "nobody")
end
it "supports whitespace" do
described_class.new(:name => "my test", :ensure => :present, :user => "nobody")
end
end
describe "for ensure" do
it "supports :present" do
described_class.new(:name => "whev", :ensure => :present, :user => "nobody")
end
it "supports :absent" do
described_class.new(:name => "whev", :ensure => :absent, :user => "nobody")
end
it "nots support other values" do
expect { described_class.new(:name => "whev", :ensure => :foo, :user => "nobody") }.to raise_error(Puppet::Error, /Invalid value/)
end
end
describe "for type" do
[
:'ssh-dss', :dsa,
:'ssh-rsa', :rsa,
:'ecdsa-sha2-nistp256',
:'ecdsa-sha2-nistp384',
:'ecdsa-sha2-nistp521',
:ed25519, :'ssh-ed25519',
].each do |keytype|
it "supports #{keytype}" do
described_class.new(:name => "whev", :type => keytype, :user => "nobody")
end
end
it "aliases :rsa to :ssh-rsa" do
key = described_class.new(:name => "whev", :type => :rsa, :user => "nobody")
expect(key.should(:type)).to eq :'ssh-rsa'
end
it "aliases :dsa to :ssh-dss" do
key = described_class.new(:name => "whev", :type => :dsa, :user => "nobody")
expect(key.should(:type)).to eq :'ssh-dss'
end
it "doesn't support values other than ssh-dss, ssh-rsa, dsa, rsa" do
expect { described_class.new(:name => "whev", :type => :something) }.to raise_error(Puppet::Error,/Invalid value/)
end
end
describe "for key" do
it "supports a valid key like a 1024 bit rsa key" do
expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :key => 'AAAAB3NzaC1yc2EAAAADAQABAAAAgQDCPfzW2ry7XvMc6E5Kj2e5fF/YofhKEvsNMUogR3PGL/HCIcBlsEjKisrY0aYgD8Ikp7ZidpXLbz5dBsmPy8hJiBWs5px9ZQrB/EOQAwXljvj69EyhEoGawmxQMtYw+OAIKHLJYRuk1QiHAMHLp5piqem8ZCV2mLb9AsJ6f7zUVw==')}.to_not raise_error
end
it "supports a valid key like a 4096 bit rsa key" do
expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :key => 'AAAAB3NzaC1yc2EAAAADAQABAAACAQDEY4pZFyzSfRc9wVWI3DfkgT/EL033UZm/7x1M+d+lBD00qcpkZ6CPT7lD3Z+vylQlJ5S8Wcw6C5Smt6okZWY2WXA9RCjNJMIHQbJAzwuQwgnwU/1VMy9YPp0tNVslg0sUUgpXb13WW4mYhwxyGmIVLJnUrjrQmIFhtfHsJAH8ZVqCWaxKgzUoC/YIu1u1ScH93lEdoBPLlwm6J0aiM7KWXRb7Oq1nEDZtug1zpX5lhgkQWrs0BwceqpUbY+n9sqeHU5e7DCyX/yEIzoPRW2fe2Gx1Iq6JKM/5NNlFfaW8rGxh3Z3S1NpzPHTRjw8js3IeGiV+OPFoaTtM1LsWgPDSBlzIdyTbSQR7gKh0qWYCNV/7qILEfa0yIFB5wIo4667iSPZw2pNgESVtenm8uXyoJdk8iWQ4mecdoposV/znknNb2GPgH+n/2vme4btZ0Sl1A6rev22GQjVgbWOn8zaDglJ2vgCN1UAwmq41RXprPxENGeLnWQppTnibhsngu0VFllZR5kvSIMlekLRSOFLFt92vfd+tk9hZIiKm9exxcbVCGGQPsf6dZ27rTOmg0xM2Sm4J6RRKuz79HQgA4Eg18+bqRP7j/itb89DmtXEtoZFAsEJw8IgIfeGGDtHTkfAlAC92mtK8byeaxGq57XCTKbO/r5gcOMElZHy1AcB8kw==')}.to_not raise_error
end
it "supports a valid key like a 1024 bit dsa key" do
expect { described_class.new(:name => "whev", :type => :dsa, :user => "nobody", :key => 'AAAAB3NzaC1kc3MAAACBAI80iR78QCgpO4WabVqHHdEDigOjUEHwIjYHIubR/7u7DYrXY+e+TUmZ0CVGkiwB/0yLHK5dix3Y/bpj8ZiWCIhFeunnXccOdE4rq5sT2V3l1p6WP33RpyVYbLmeuHHl5VQ1CecMlca24nHhKpfh6TO/FIwkMjghHBfJIhXK+0w/AAAAFQDYzLupuMY5uz+GVrcP+Kgd8YqMmwAAAIB3SVN71whLWjFPNTqGyyIlMy50624UfNOaH4REwO+Of3wm/cE6eP8n75vzTwQGBpJX3BPaBGW1S1Zp/DpTOxhCSAwZzAwyf4WgW7YyAOdxN3EwTDJZeyiyjWMAOjW9/AOWt9gtKg0kqaylbMHD4kfiIhBzo31ZY81twUzAfN7angAAAIBfva8sTSDUGKsWWIXkdbVdvM4X14K4gFdy0ZJVzaVOtZ6alysW6UQypnsl6jfnbKvsZ0tFgvcX/CPyqNY/gMR9lyh/TCZ4XQcbqeqYPuceGehz+jL5vArfqsW2fJYFzgCcklmr/VxtP5h6J/T0c9YcDgc/xIfWdZAlznOnphI/FA==')}.to_not raise_error
end
it "doesn't support whitespaces" do
expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :key => 'AAA FA==')}.to raise_error(Puppet::Error,/Key must not contain whitespace/)
end
end
describe "for options" do
it "supports flags as options" do
expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => 'cert-authority')}.to_not raise_error
expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => 'no-port-forwarding')}.to_not raise_error
end
it "supports key-value pairs as options" do
expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => 'command="command"')}.to_not raise_error
end
it "supports key-value pairs where value consist of multiple items" do
expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => 'from="*.domain1,host1.domain2"')}.to_not raise_error
end
it "supports environments as options" do
expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => 'environment="NAME=value"')}.to_not raise_error
end
it "supports multiple options as an array" do
expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => ['cert-authority','environment="NAME=value"'])}.to_not raise_error
end
it "doesn't support a comma separated list" do
expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => 'cert-authority,no-port-forwarding')}.to raise_error(Puppet::Error, /must be provided as an array/)
end
it "uses :absent as a default value" do
expect(described_class.new(:name => "whev", :type => :rsa, :user => "nobody").should(:options)).to eq [:absent]
end
it "property should return well formed string of arrays from is_to_s" do
resource = described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => ["a","b","c"])
expect(resource.property(:options).is_to_s(["a","b","c"])).to eq "a,b,c"
end
it "property should return well formed string of arrays from should_to_s" do
resource = described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => ["a","b","c"])
expect(resource.property(:options).should_to_s(["a","b","c"])).to eq "a,b,c"
end
end
describe "for user" do
it "supports present users" do
described_class.new(:name => "whev", :type => :rsa, :user => "root")
end
it "supports absent users" do
described_class.new(:name => "whev", :type => :rsa, :user => "ihopeimabsent")
end
end
describe "for target" do
it "supports absolute paths" do
described_class.new(:name => "whev", :type => :rsa, :target => "/tmp/here")
end
it "uses the user's path if not explicitly specified" do
expect(described_class.new(:name => "whev", :user => 'root').should(:target)).to eq File.expand_path("~root/.ssh/authorized_keys")
end
it "doesn't consider the user's path if explicitly specified" do
expect(described_class.new(:name => "whev", :user => 'root', :target => '/tmp/here').should(:target)).to eq '/tmp/here'
end
it "informs about an absent user" do
Puppet::Log.level = :debug
described_class.new(:name => "whev", :user => 'idontexist').should(:target)
- @logs.map(&:message).should include("The required user is not yet present on the system")
+ expect(@logs.map(&:message)).to include("The required user is not yet present on the system")
end
end
end
describe "when neither user nor target is specified" do
it "raises an error" do
expect do
described_class.new(
:name => "Test",
:key => "AAA",
:type => "ssh-rsa",
:ensure => :present)
end.to raise_error(Puppet::Error,/user.*or.*target.*mandatory/)
end
end
describe "when both target and user are specified" do
it "uses target" do
resource = described_class.new(
:name => "Test",
:user => "root",
:target => "/tmp/blah"
)
expect(resource.should(:target)).to eq "/tmp/blah"
end
end
describe "when user is specified" do
it "determines target" do
resource = described_class.new(
:name => "Test",
:user => "root"
)
target = File.expand_path("~root/.ssh/authorized_keys")
expect(resource.should(:target)).to eq target
end
# Bug #2124 - ssh_authorized_key always changes target if target is not defined
it "doesn't raise spurious change events" do
resource = described_class.new(:name => "Test", :user => "root")
target = File.expand_path("~root/.ssh/authorized_keys")
expect(resource.property(:target).safe_insync?(target)).to eq true
end
end
describe "when calling validate" do
it "doesn't crash on a non-existent user" do
resource = described_class.new(
:name => "Test",
:user => "ihopesuchuserdoesnotexist"
)
resource.validate
end
end
end
diff --git a/spec/unit/type/stage_spec.rb b/spec/unit/type/stage_spec.rb
index c23bc4c09..c9f6242ee 100755
--- a/spec/unit/type/stage_spec.rb
+++ b/spec/unit/type/stage_spec.rb
@@ -1,8 +1,8 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:stage) do
it "should have a 'name' parameter'" do
- Puppet::Type.type(:stage).new(:name => :foo)[:name].should == :foo
+ expect(Puppet::Type.type(:stage).new(:name => :foo)[:name]).to eq(:foo)
end
end
diff --git a/spec/unit/type/tidy_spec.rb b/spec/unit/type/tidy_spec.rb
index b0f40c280..8e5110314 100755
--- a/spec/unit/type/tidy_spec.rb
+++ b/spec/unit/type/tidy_spec.rb
@@ -1,445 +1,445 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_bucket/dipper'
tidy = Puppet::Type.type(:tidy)
describe tidy do
include PuppetSpec::Files
before do
@basepath = make_absolute("/what/ever")
Puppet.settings.stubs(:use)
end
it "should use :lstat when stating a file" do
path = '/foo/bar'
stat = mock 'stat'
Puppet::FileSystem.expects(:lstat).with(path).returns stat
resource = tidy.new :path => path, :age => "1d"
- resource.stat(path).should == stat
+ expect(resource.stat(path)).to eq(stat)
end
[:age, :size, :path, :matches, :type, :recurse, :rmdirs].each do |param|
it "should have a #{param} parameter" do
- Puppet::Type.type(:tidy).attrclass(param).ancestors.should be_include(Puppet::Parameter)
+ expect(Puppet::Type.type(:tidy).attrclass(param).ancestors).to be_include(Puppet::Parameter)
end
it "should have documentation for its #{param} param" do
- Puppet::Type.type(:tidy).attrclass(param).doc.should be_instance_of(String)
+ expect(Puppet::Type.type(:tidy).attrclass(param).doc).to be_instance_of(String)
end
end
describe "when validating parameter values" do
describe "for 'recurse'" do
before do
@tidy = Puppet::Type.type(:tidy).new :path => "/tmp", :age => "100d"
end
it "should allow 'true'" do
- lambda { @tidy[:recurse] = true }.should_not raise_error
+ expect { @tidy[:recurse] = true }.not_to raise_error
end
it "should allow 'false'" do
- lambda { @tidy[:recurse] = false }.should_not raise_error
+ expect { @tidy[:recurse] = false }.not_to raise_error
end
it "should allow integers" do
- lambda { @tidy[:recurse] = 10 }.should_not raise_error
+ expect { @tidy[:recurse] = 10 }.not_to raise_error
end
it "should allow string representations of integers" do
- lambda { @tidy[:recurse] = "10" }.should_not raise_error
+ expect { @tidy[:recurse] = "10" }.not_to raise_error
end
it "should allow 'inf'" do
- lambda { @tidy[:recurse] = "inf" }.should_not raise_error
+ expect { @tidy[:recurse] = "inf" }.not_to raise_error
end
it "should not allow arbitrary values" do
- lambda { @tidy[:recurse] = "whatever" }.should raise_error
+ expect { @tidy[:recurse] = "whatever" }.to raise_error
end
end
describe "for 'matches'" do
before do
@tidy = Puppet::Type.type(:tidy).new :path => "/tmp", :age => "100d"
end
it "should object if matches is given with recurse is not specified" do
- lambda { @tidy[:matches] = '*.doh' }.should raise_error
+ expect { @tidy[:matches] = '*.doh' }.to raise_error
end
it "should object if matches is given and recurse is 0" do
- lambda { @tidy[:recurse] = 0; @tidy[:matches] = '*.doh' }.should raise_error
+ expect { @tidy[:recurse] = 0; @tidy[:matches] = '*.doh' }.to raise_error
end
it "should object if matches is given and recurse is false" do
- lambda { @tidy[:recurse] = false; @tidy[:matches] = '*.doh' }.should raise_error
+ expect { @tidy[:recurse] = false; @tidy[:matches] = '*.doh' }.to raise_error
end
it "should not object if matches is given and recurse is > 0" do
- lambda { @tidy[:recurse] = 1; @tidy[:matches] = '*.doh' }.should_not raise_error
+ expect { @tidy[:recurse] = 1; @tidy[:matches] = '*.doh' }.not_to raise_error
end
it "should not object if matches is given and recurse is true" do
- lambda { @tidy[:recurse] = true; @tidy[:matches] = '*.doh' }.should_not raise_error
+ expect { @tidy[:recurse] = true; @tidy[:matches] = '*.doh' }.not_to raise_error
end
end
end
describe "when matching files by age" do
convertors = {
:second => 1,
:minute => 60
}
convertors[:hour] = convertors[:minute] * 60
convertors[:day] = convertors[:hour] * 24
convertors[:week] = convertors[:day] * 7
convertors.each do |unit, multiple|
it "should consider a #{unit} to be #{multiple} seconds" do
@tidy = Puppet::Type.type(:tidy).new :path => @basepath, :age => "5#{unit.to_s[0..0]}"
- @tidy[:age].should == 5 * multiple
+ expect(@tidy[:age]).to eq(5 * multiple)
end
end
end
describe "when matching files by size" do
convertors = {
:b => 0,
:kb => 1,
:mb => 2,
:gb => 3,
:tb => 4
}
convertors.each do |unit, multiple|
it "should consider a #{unit} to be 1024^#{multiple} bytes" do
@tidy = Puppet::Type.type(:tidy).new :path => @basepath, :size => "5#{unit}"
total = 5
multiple.times { total *= 1024 }
- @tidy[:size].should == total
+ expect(@tidy[:size]).to eq(total)
end
end
end
describe "when tidying" do
before do
@tidy = Puppet::Type.type(:tidy).new :path => @basepath
@stat = stub 'stat', :ftype => "directory"
lstat_is(@basepath, @stat)
end
describe "and generating files" do
it "should set the backup on the file if backup is set on the tidy instance" do
@tidy[:backup] = "whatever"
Puppet::Type.type(:file).expects(:new).with { |args| args[:backup] == "whatever" }
@tidy.mkfile(@basepath)
end
it "should set the file's path to the tidy's path" do
Puppet::Type.type(:file).expects(:new).with { |args| args[:path] == @basepath }
@tidy.mkfile(@basepath)
end
it "should configure the file for deletion" do
Puppet::Type.type(:file).expects(:new).with { |args| args[:ensure] == :absent }
@tidy.mkfile(@basepath)
end
it "should force deletion on the file" do
Puppet::Type.type(:file).expects(:new).with { |args| args[:force] == true }
@tidy.mkfile(@basepath)
end
it "should do nothing if the targeted file does not exist" do
lstat_raises(@basepath, Errno::ENOENT)
- @tidy.generate.should == []
+ expect(@tidy.generate).to eq([])
end
end
describe "and recursion is not used" do
it "should generate a file resource if the file should be tidied" do
@tidy.expects(:tidy?).with(@basepath).returns true
file = Puppet::Type.type(:file).new(:path => @basepath+"/eh")
@tidy.expects(:mkfile).with(@basepath).returns file
- @tidy.generate.should == [file]
+ expect(@tidy.generate).to eq([file])
end
it "should do nothing if the file should not be tidied" do
@tidy.expects(:tidy?).with(@basepath).returns false
@tidy.expects(:mkfile).never
- @tidy.generate.should == []
+ expect(@tidy.generate).to eq([])
end
end
describe "and recursion is used" do
before do
@tidy[:recurse] = true
Puppet::FileServing::Fileset.any_instance.stubs(:stat).returns mock("stat")
@fileset = Puppet::FileServing::Fileset.new(@basepath)
Puppet::FileServing::Fileset.stubs(:new).returns @fileset
end
it "should use a Fileset for infinite recursion" do
Puppet::FileServing::Fileset.expects(:new).with(@basepath, :recurse => true).returns @fileset
@fileset.expects(:files).returns %w{. one two}
@tidy.stubs(:tidy?).returns false
@tidy.generate
end
it "should use a Fileset for limited recursion" do
@tidy[:recurse] = 42
Puppet::FileServing::Fileset.expects(:new).with(@basepath, :recurse => true, :recurselimit => 42).returns @fileset
@fileset.expects(:files).returns %w{. one two}
@tidy.stubs(:tidy?).returns false
@tidy.generate
end
it "should generate a file resource for every file that should be tidied but not for files that should not be tidied" do
@fileset.expects(:files).returns %w{. one two}
@tidy.expects(:tidy?).with(@basepath).returns true
@tidy.expects(:tidy?).with(@basepath+"/one").returns true
@tidy.expects(:tidy?).with(@basepath+"/two").returns false
file = Puppet::Type.type(:file).new(:path => @basepath+"/eh")
@tidy.expects(:mkfile).with(@basepath).returns file
@tidy.expects(:mkfile).with(@basepath+"/one").returns file
@tidy.generate
end
end
describe "and determining whether a file matches provided glob patterns" do
before do
@tidy = Puppet::Type.type(:tidy).new :path => @basepath, :recurse => 1
@tidy[:matches] = %w{*foo* *bar*}
@stat = mock 'stat'
@matcher = @tidy.parameter(:matches)
end
it "should always convert the globs to an array" do
@matcher.value = "*foo*"
- @matcher.value.should == %w{*foo*}
+ expect(@matcher.value).to eq(%w{*foo*})
end
it "should return true if any pattern matches the last part of the file" do
@matcher.value = %w{*foo* *bar*}
- @matcher.must be_tidy("/file/yaybarness", @stat)
+ expect(@matcher).to be_tidy("/file/yaybarness", @stat)
end
it "should return false if no pattern matches the last part of the file" do
@matcher.value = %w{*foo* *bar*}
- @matcher.should_not be_tidy("/file/yayness", @stat)
+ expect(@matcher).not_to be_tidy("/file/yayness", @stat)
end
end
describe "and determining whether a file is too old" do
before do
@tidy = Puppet::Type.type(:tidy).new :path => @basepath
@stat = stub 'stat'
@tidy[:age] = "1s"
@tidy[:type] = "mtime"
@ager = @tidy.parameter(:age)
end
it "should use the age type specified" do
@tidy[:type] = :ctime
@stat.expects(:ctime).returns(Time.now)
@ager.tidy?(@basepath, @stat)
end
it "should return false if the file is more recent than the specified age" do
@stat.expects(:mtime).returns(Time.now)
- @ager.should_not be_tidy(@basepath, @stat)
+ expect(@ager).not_to be_tidy(@basepath, @stat)
end
it "should return true if the file is older than the specified age" do
@stat.expects(:mtime).returns(Time.now - 10)
- @ager.must be_tidy(@basepath, @stat)
+ expect(@ager).to be_tidy(@basepath, @stat)
end
end
describe "and determining whether a file is too large" do
before do
@tidy = Puppet::Type.type(:tidy).new :path => @basepath
@stat = stub 'stat', :ftype => "file"
@tidy[:size] = "1kb"
@sizer = @tidy.parameter(:size)
end
it "should return false if the file is smaller than the specified size" do
@stat.expects(:size).returns(4) # smaller than a kilobyte
- @sizer.should_not be_tidy(@basepath, @stat)
+ expect(@sizer).not_to be_tidy(@basepath, @stat)
end
it "should return true if the file is larger than the specified size" do
@stat.expects(:size).returns(1500) # larger than a kilobyte
- @sizer.must be_tidy(@basepath, @stat)
+ expect(@sizer).to be_tidy(@basepath, @stat)
end
it "should return true if the file is equal to the specified size" do
@stat.expects(:size).returns(1024)
- @sizer.must be_tidy(@basepath, @stat)
+ expect(@sizer).to be_tidy(@basepath, @stat)
end
end
describe "and determining whether a file should be tidied" do
before do
@tidy = Puppet::Type.type(:tidy).new :path => @basepath
@stat = stub 'stat', :ftype => "file"
lstat_is(@basepath, @stat)
end
it "should not try to recurse if the file does not exist" do
@tidy[:recurse] = true
lstat_is(@basepath, nil)
- @tidy.generate.should == []
+ expect(@tidy.generate).to eq([])
end
it "should not be tidied if the file does not exist" do
lstat_raises(@basepath, Errno::ENOENT)
- @tidy.should_not be_tidy(@basepath)
+ expect(@tidy).not_to be_tidy(@basepath)
end
it "should not be tidied if the user has no access to the file" do
lstat_raises(@basepath, Errno::EACCES)
- @tidy.should_not be_tidy(@basepath)
+ expect(@tidy).not_to be_tidy(@basepath)
end
it "should not be tidied if it is a directory and rmdirs is set to false" do
stat = mock 'stat', :ftype => "directory"
lstat_is(@basepath, stat)
- @tidy.should_not be_tidy(@basepath)
+ expect(@tidy).not_to be_tidy(@basepath)
end
it "should return false if it does not match any provided globs" do
@tidy[:recurse] = 1
@tidy[:matches] = "globs"
matches = @tidy.parameter(:matches)
matches.expects(:tidy?).with(@basepath, @stat).returns false
- @tidy.should_not be_tidy(@basepath)
+ expect(@tidy).not_to be_tidy(@basepath)
end
it "should return false if it does not match aging requirements" do
@tidy[:age] = "1d"
ager = @tidy.parameter(:age)
ager.expects(:tidy?).with(@basepath, @stat).returns false
- @tidy.should_not be_tidy(@basepath)
+ expect(@tidy).not_to be_tidy(@basepath)
end
it "should return false if it does not match size requirements" do
@tidy[:size] = "1b"
sizer = @tidy.parameter(:size)
sizer.expects(:tidy?).with(@basepath, @stat).returns false
- @tidy.should_not be_tidy(@basepath)
+ expect(@tidy).not_to be_tidy(@basepath)
end
it "should tidy a file if age and size are set but only size matches" do
@tidy[:size] = "1b"
@tidy[:age] = "1d"
@tidy.parameter(:size).stubs(:tidy?).returns true
@tidy.parameter(:age).stubs(:tidy?).returns false
- @tidy.must be_tidy(@basepath)
+ expect(@tidy).to be_tidy(@basepath)
end
it "should tidy a file if age and size are set but only age matches" do
@tidy[:size] = "1b"
@tidy[:age] = "1d"
@tidy.parameter(:size).stubs(:tidy?).returns false
@tidy.parameter(:age).stubs(:tidy?).returns true
- @tidy.must be_tidy(@basepath)
+ expect(@tidy).to be_tidy(@basepath)
end
it "should tidy all files if neither age nor size is set" do
- @tidy.must be_tidy(@basepath)
+ expect(@tidy).to be_tidy(@basepath)
end
it "should sort the results inversely by path length, so files are added to the catalog before their directories" do
@tidy[:recurse] = true
@tidy[:rmdirs] = true
fileset = Puppet::FileServing::Fileset.new(@basepath)
Puppet::FileServing::Fileset.expects(:new).returns fileset
fileset.expects(:files).returns %w{. one one/two}
@tidy.stubs(:tidy?).returns true
- @tidy.generate.collect { |r| r[:path] }.should == [@basepath+"/one/two", @basepath+"/one", @basepath]
+ expect(@tidy.generate.collect { |r| r[:path] }).to eq([@basepath+"/one/two", @basepath+"/one", @basepath])
end
end
it "should configure directories to require their contained files if rmdirs is enabled, so the files will be deleted first" do
@tidy[:recurse] = true
@tidy[:rmdirs] = true
fileset = mock 'fileset'
Puppet::FileServing::Fileset.expects(:new).with(@basepath, :recurse => true).returns fileset
fileset.expects(:files).returns %w{. one two one/subone two/subtwo one/subone/ssone}
@tidy.stubs(:tidy?).returns true
result = @tidy.generate.inject({}) { |hash, res| hash[res[:path]] = res; hash }
{
@basepath => [ @basepath+"/one", @basepath+"/two" ],
@basepath+"/one" => [@basepath+"/one/subone"],
@basepath+"/two" => [@basepath+"/two/subtwo"],
@basepath+"/one/subone" => [@basepath+"/one/subone/ssone"]
}.each do |parent, children|
children.each do |child|
ref = Puppet::Resource.new(:file, child)
- result[parent][:require].find { |req| req.to_s == ref.to_s }.should_not be_nil
+ expect(result[parent][:require].find { |req| req.to_s == ref.to_s }).not_to be_nil
end
end
end
it "should configure directories to require their contained files in sorted order" do
@tidy[:recurse] = true
@tidy[:rmdirs] = true
fileset = mock 'fileset'
Puppet::FileServing::Fileset.expects(:new).with(@basepath, :recurse => true).returns fileset
fileset.expects(:files).returns %w{. a a/2 a/1 a/3}
@tidy.stubs(:tidy?).returns true
result = @tidy.generate.inject({}) { |hash, res| hash[res[:path]] = res; hash }
- result[@basepath + '/a'][:require].collect{|a| a.name[('File//a/' + @basepath).length..-1]}.join().should == '321'
+ expect(result[@basepath + '/a'][:require].collect{|a| a.name[('File//a/' + @basepath).length..-1]}.join()).to eq('321')
end
end
def lstat_is(path, stat)
Puppet::FileSystem.stubs(:lstat).with(path).returns(stat)
end
def lstat_raises(path, error_class)
Puppet::FileSystem.expects(:lstat).with(path).raises Errno::ENOENT
end
end
diff --git a/spec/unit/type/user_spec.rb b/spec/unit/type/user_spec.rb
index 974054309..028638fa9 100755
--- a/spec/unit/type/user_spec.rb
+++ b/spec/unit/type/user_spec.rb
@@ -1,519 +1,519 @@
#! /usr/bin/env ruby
# encoding: UTF-8
require 'spec_helper'
describe Puppet::Type.type(:user) do
before :each do
@provider_class = described_class.provide(:simple) do
has_features :manages_expiry, :manages_password_age, :manages_passwords, :manages_solaris_rbac, :manages_shell
mk_resource_methods
def create; end
def delete; end
def exists?; get(:ensure) != :absent; end
def flush; end
def self.instances; []; end
end
described_class.stubs(:defaultprovider).returns @provider_class
end
it "should be able to create an instance" do
- described_class.new(:name => "foo").should_not be_nil
+ expect(described_class.new(:name => "foo")).not_to be_nil
end
it "should have an allows_duplicates feature" do
- described_class.provider_feature(:allows_duplicates).should_not be_nil
+ expect(described_class.provider_feature(:allows_duplicates)).not_to be_nil
end
it "should have a manages_homedir feature" do
- described_class.provider_feature(:manages_homedir).should_not be_nil
+ expect(described_class.provider_feature(:manages_homedir)).not_to be_nil
end
it "should have a manages_passwords feature" do
- described_class.provider_feature(:manages_passwords).should_not be_nil
+ expect(described_class.provider_feature(:manages_passwords)).not_to be_nil
end
it "should have a manages_solaris_rbac feature" do
- described_class.provider_feature(:manages_solaris_rbac).should_not be_nil
+ expect(described_class.provider_feature(:manages_solaris_rbac)).not_to be_nil
end
it "should have a manages_expiry feature" do
- described_class.provider_feature(:manages_expiry).should_not be_nil
+ expect(described_class.provider_feature(:manages_expiry)).not_to be_nil
end
it "should have a manages_password_age feature" do
- described_class.provider_feature(:manages_password_age).should_not be_nil
+ expect(described_class.provider_feature(:manages_password_age)).not_to be_nil
end
it "should have a system_users feature" do
- described_class.provider_feature(:system_users).should_not be_nil
+ expect(described_class.provider_feature(:system_users)).not_to be_nil
end
it "should have a manages_shell feature" do
- described_class.provider_feature(:manages_shell).should_not be_nil
+ expect(described_class.provider_feature(:manages_shell)).not_to be_nil
end
- describe :managehome do
+ context "managehome" do
let (:provider) { @provider_class.new(:name => 'foo', :ensure => :absent) }
let (:instance) { described_class.new(:name => 'foo', :provider => provider) }
it "defaults to false" do
- instance[:managehome].should be_false
+ expect(instance[:managehome]).to be_falsey
end
it "can be set to false" do
instance[:managehome] = 'false'
end
it "cannot be set to true for a provider that does not manage homedirs" do
provider.class.stubs(:manages_homedir?).returns false
expect { instance[:managehome] = 'yes' }.to raise_error(Puppet::Error, /can not manage home directories/)
end
it "can be set to true for a provider that does manage homedirs" do
provider.class.stubs(:manages_homedir?).returns true
instance[:managehome] = 'yes'
end
end
describe "instances" do
it "should delegate existence questions to its provider" do
@provider = @provider_class.new(:name => 'foo', :ensure => :absent)
instance = described_class.new(:name => "foo", :provider => @provider)
- instance.exists?.should == false
+ expect(instance.exists?).to eq(false)
@provider.set(:ensure => :present)
- instance.exists?.should == true
+ expect(instance.exists?).to eq(true)
end
end
properties = [:ensure, :uid, :gid, :home, :comment, :shell, :password, :password_min_age, :password_max_age, :groups, :roles, :auths, :profiles, :project, :keys, :expiry]
properties.each do |property|
it "should have a #{property} property" do
- described_class.attrclass(property).ancestors.should be_include(Puppet::Property)
+ expect(described_class.attrclass(property).ancestors).to be_include(Puppet::Property)
end
it "should have documentation for its #{property} property" do
- described_class.attrclass(property).doc.should be_instance_of(String)
+ expect(described_class.attrclass(property).doc).to be_instance_of(String)
end
end
list_properties = [:groups, :roles, :auths]
list_properties.each do |property|
it "should have a list '#{property}'" do
- described_class.attrclass(property).ancestors.should be_include(Puppet::Property::List)
+ expect(described_class.attrclass(property).ancestors).to be_include(Puppet::Property::List)
end
end
it "should have an ordered list 'profiles'" do
- described_class.attrclass(:profiles).ancestors.should be_include(Puppet::Property::OrderedList)
+ expect(described_class.attrclass(:profiles).ancestors).to be_include(Puppet::Property::OrderedList)
end
it "should have key values 'keys'" do
- described_class.attrclass(:keys).ancestors.should be_include(Puppet::Property::KeyValue)
+ expect(described_class.attrclass(:keys).ancestors).to be_include(Puppet::Property::KeyValue)
end
describe "when retrieving all current values" do
before do
@provider = @provider_class.new(:name => 'foo', :ensure => :present, :uid => 15, :gid => 15)
@user = described_class.new(:name => "foo", :uid => 10, :provider => @provider)
end
it "should return a hash containing values for all set properties" do
@user[:gid] = 10
values = @user.retrieve
- [@user.property(:uid), @user.property(:gid)].each { |property| values.should be_include(property) }
+ [@user.property(:uid), @user.property(:gid)].each { |property| expect(values).to be_include(property) }
end
it "should set all values to :absent if the user is absent" do
@user.property(:ensure).expects(:retrieve).returns :absent
@user.property(:uid).expects(:retrieve).never
- @user.retrieve[@user.property(:uid)].should == :absent
+ expect(@user.retrieve[@user.property(:uid)]).to eq(:absent)
end
it "should include the result of retrieving each property's current value if the user is present" do
- @user.retrieve[@user.property(:uid)].should == 15
+ expect(@user.retrieve[@user.property(:uid)]).to eq(15)
end
end
describe "when managing the ensure property" do
it "should support a :present value" do
expect { described_class.new(:name => 'foo', :ensure => :present) }.to_not raise_error
end
it "should support an :absent value" do
expect { described_class.new(:name => 'foo', :ensure => :absent) }.to_not raise_error
end
it "should call :create on the provider when asked to sync to the :present state" do
@provider = @provider_class.new(:name => 'foo', :ensure => :absent)
@provider.expects(:create)
described_class.new(:name => 'foo', :ensure => :present, :provider => @provider).parameter(:ensure).sync
end
it "should call :delete on the provider when asked to sync to the :absent state" do
@provider = @provider_class.new(:name => 'foo', :ensure => :present)
@provider.expects(:delete)
described_class.new(:name => 'foo', :ensure => :absent, :provider => @provider).parameter(:ensure).sync
end
describe "and determining the current state" do
it "should return :present when the provider indicates the user exists" do
@provider = @provider_class.new(:name => 'foo', :ensure => :present)
- described_class.new(:name => 'foo', :ensure => :absent, :provider => @provider).parameter(:ensure).retrieve.should == :present
+ expect(described_class.new(:name => 'foo', :ensure => :absent, :provider => @provider).parameter(:ensure).retrieve).to eq(:present)
end
it "should return :absent when the provider indicates the user does not exist" do
@provider = @provider_class.new(:name => 'foo', :ensure => :absent)
- described_class.new(:name => 'foo', :ensure => :present, :provider => @provider).parameter(:ensure).retrieve.should == :absent
+ expect(described_class.new(:name => 'foo', :ensure => :present, :provider => @provider).parameter(:ensure).retrieve).to eq(:absent)
end
end
end
describe "when managing the uid property" do
it "should convert number-looking strings into actual numbers" do
- described_class.new(:name => 'foo', :uid => '50')[:uid].should == 50
+ expect(described_class.new(:name => 'foo', :uid => '50')[:uid]).to eq(50)
end
it "should support UIDs as numbers" do
- described_class.new(:name => 'foo', :uid => 50)[:uid].should == 50
+ expect(described_class.new(:name => 'foo', :uid => 50)[:uid]).to eq(50)
end
it "should support :absent as a value" do
- described_class.new(:name => 'foo', :uid => :absent)[:uid].should == :absent
+ expect(described_class.new(:name => 'foo', :uid => :absent)[:uid]).to eq(:absent)
end
end
describe "when managing the gid" do
it "should support :absent as a value" do
- described_class.new(:name => 'foo', :gid => :absent)[:gid].should == :absent
+ expect(described_class.new(:name => 'foo', :gid => :absent)[:gid]).to eq(:absent)
end
it "should convert number-looking strings into actual numbers" do
- described_class.new(:name => 'foo', :gid => '50')[:gid].should == 50
+ expect(described_class.new(:name => 'foo', :gid => '50')[:gid]).to eq(50)
end
it "should support GIDs specified as integers" do
- described_class.new(:name => 'foo', :gid => 50)[:gid].should == 50
+ expect(described_class.new(:name => 'foo', :gid => 50)[:gid]).to eq(50)
end
it "should support groups specified by name" do
- described_class.new(:name => 'foo', :gid => 'foo')[:gid].should == 'foo'
+ expect(described_class.new(:name => 'foo', :gid => 'foo')[:gid]).to eq('foo')
end
describe "when testing whether in sync" do
it "should return true if no 'should' values are set" do
# this is currently not the case because gid has no default value, so we would never even
# call insync? on that property
if param = described_class.new(:name => 'foo').parameter(:gid)
- param.must be_safe_insync(500)
+ expect(param).to be_safe_insync(500)
end
end
it "should return true if any of the specified groups are equal to the current integer" do
Puppet::Util.expects(:gid).with("foo").returns 300
Puppet::Util.expects(:gid).with("bar").returns 500
- described_class.new(:name => 'baz', :gid => [ 'foo', 'bar' ]).parameter(:gid).must be_safe_insync(500)
+ expect(described_class.new(:name => 'baz', :gid => [ 'foo', 'bar' ]).parameter(:gid)).to be_safe_insync(500)
end
it "should return false if none of the specified groups are equal to the current integer" do
Puppet::Util.expects(:gid).with("foo").returns 300
Puppet::Util.expects(:gid).with("bar").returns 500
- described_class.new(:name => 'baz', :gid => [ 'foo', 'bar' ]).parameter(:gid).must_not be_safe_insync(700)
+ expect(described_class.new(:name => 'baz', :gid => [ 'foo', 'bar' ]).parameter(:gid)).to_not be_safe_insync(700)
end
end
describe "when syncing" do
it "should use the first found, specified group as the desired value and send it to the provider" do
Puppet::Util.expects(:gid).with("foo").returns nil
Puppet::Util.expects(:gid).with("bar").returns 500
@provider = @provider_class.new(:name => 'foo')
resource = described_class.new(:name => 'foo', :provider => @provider, :gid => [ 'foo', 'bar' ])
@provider.expects(:gid=).with 500
resource.parameter(:gid).sync
end
end
end
describe "when managing groups" do
it "should support a singe group" do
expect { described_class.new(:name => 'foo', :groups => 'bar') }.to_not raise_error
end
it "should support multiple groups as an array" do
expect { described_class.new(:name => 'foo', :groups => [ 'bar' ]) }.to_not raise_error
expect { described_class.new(:name => 'foo', :groups => [ 'bar', 'baz' ]) }.to_not raise_error
end
it "should not support a comma separated list" do
expect { described_class.new(:name => 'foo', :groups => 'bar,baz') }.to raise_error(Puppet::Error, /Group names must be provided as an array/)
end
it "should not support an empty string" do
expect { described_class.new(:name => 'foo', :groups => '') }.to raise_error(Puppet::Error, /Group names must not be empty/)
end
describe "when testing is in sync" do
before :each do
# the useradd provider uses a single string to represent groups and so does Puppet::Property::List when converting to should values
@provider = @provider_class.new(:name => 'foo', :groups => 'a,b,e,f')
end
it "should not care about order" do
@property = described_class.new(:name => 'foo', :groups => [ 'a', 'c', 'b' ]).property(:groups)
- @property.must be_safe_insync([ 'a', 'b', 'c' ])
- @property.must be_safe_insync([ 'a', 'c', 'b' ])
- @property.must be_safe_insync([ 'b', 'a', 'c' ])
- @property.must be_safe_insync([ 'b', 'c', 'a' ])
- @property.must be_safe_insync([ 'c', 'a', 'b' ])
- @property.must be_safe_insync([ 'c', 'b', 'a' ])
+ expect(@property).to be_safe_insync([ 'a', 'b', 'c' ])
+ expect(@property).to be_safe_insync([ 'a', 'c', 'b' ])
+ expect(@property).to be_safe_insync([ 'b', 'a', 'c' ])
+ expect(@property).to be_safe_insync([ 'b', 'c', 'a' ])
+ expect(@property).to be_safe_insync([ 'c', 'a', 'b' ])
+ expect(@property).to be_safe_insync([ 'c', 'b', 'a' ])
end
it "should merge current value and desired value if membership minimal" do
@instance = described_class.new(:name => 'foo', :groups => [ 'a', 'c', 'b' ], :provider => @provider)
@instance[:membership] = :minimum
- @instance[:groups].should == 'a,b,c,e,f'
+ expect(@instance[:groups]).to eq('a,b,c,e,f')
end
it "should not treat a subset of groups insync if membership inclusive" do
@instance = described_class.new(:name => 'foo', :groups => [ 'a', 'c', 'b' ], :provider => @provider)
@instance[:membership] = :inclusive
- @instance[:groups].should == 'a,b,c'
+ expect(@instance[:groups]).to eq('a,b,c')
end
end
end
describe "when managing expiry" do
it "should fail if given an invalid date" do
expect { described_class.new(:name => 'foo', :expiry => "200-20-20") }.to raise_error(Puppet::Error, /Expiry dates must be YYYY-MM-DD/)
end
end
describe "when managing minimum password age" do
it "should accept a negative minimum age" do
expect { described_class.new(:name => 'foo', :password_min_age => '-1') }.to_not raise_error
end
it "should fail with an empty minimum age" do
expect { described_class.new(:name => 'foo', :password_min_age => '') }.to raise_error(Puppet::Error, /minimum age must be provided as a number/)
end
end
describe "when managing maximum password age" do
it "should accept a negative maximum age" do
expect { described_class.new(:name => 'foo', :password_max_age => '-1') }.to_not raise_error
end
it "should fail with an empty maximum age" do
expect { described_class.new(:name => 'foo', :password_max_age => '') }.to raise_error(Puppet::Error, /maximum age must be provided as a number/)
end
end
describe "when managing passwords" do
before do
@password = described_class.new(:name => 'foo', :password => 'mypass').parameter(:password)
end
it "should not include the password in the change log when adding the password" do
- @password.change_to_s(:absent, "mypass").should_not be_include("mypass")
+ expect(@password.change_to_s(:absent, "mypass")).not_to be_include("mypass")
end
it "should not include the password in the change log when changing the password" do
- @password.change_to_s("other", "mypass").should_not be_include("mypass")
+ expect(@password.change_to_s("other", "mypass")).not_to be_include("mypass")
end
it "should redact the password when displaying the old value" do
- @password.is_to_s("currentpassword").should =~ /^\[old password hash redacted\]$/
+ expect(@password.is_to_s("currentpassword")).to match(/^\[old password hash redacted\]$/)
end
it "should redact the password when displaying the new value" do
- @password.should_to_s("newpassword").should =~ /^\[new password hash redacted\]$/
+ expect(@password.should_to_s("newpassword")).to match(/^\[new password hash redacted\]$/)
end
it "should fail if a ':' is included in the password" do
expect { described_class.new(:name => 'foo', :password => "some:thing") }.to raise_error(Puppet::Error, /Passwords cannot include ':'/)
end
it "should allow the value to be set to :absent" do
expect { described_class.new(:name => 'foo', :password => :absent) }.to_not raise_error
end
end
describe "when managing comment on Ruby 1.9", :if => String.method_defined?(:encode) do
it "should force value encoding to ASCII-8BIT" do
value = 'abcd™'
- value.encoding.should == Encoding::UTF_8
+ expect(value.encoding).to eq(Encoding::UTF_8)
user = described_class.new(:name => 'foo', :comment => value)
- user[:comment].encoding.should == Encoding::ASCII_8BIT
- user[:comment].should == value.force_encoding(Encoding::ASCII_8BIT)
+ expect(user[:comment].encoding).to eq(Encoding::ASCII_8BIT)
+ expect(user[:comment]).to eq(value.force_encoding(Encoding::ASCII_8BIT))
end
end
describe "when manages_solaris_rbac is enabled" do
it "should support a :role value for ensure" do
expect { described_class.new(:name => 'foo', :ensure => :role) }.to_not raise_error
end
end
describe "when user has roles" do
it "should autorequire roles" do
testuser = described_class.new(:name => "testuser", :roles => ['testrole'] )
testrole = described_class.new(:name => "testrole")
config = Puppet::Resource::Catalog.new :testing do |conf|
[testuser, testrole].each { |resource| conf.add_resource resource }
end
Puppet::Type::User::ProviderDirectoryservice.stubs(:get_macosx_version_major).returns "10.5"
rel = testuser.autorequire[0]
- rel.source.ref.should == testrole.ref
- rel.target.ref.should == testuser.ref
+ expect(rel.source.ref).to eq(testrole.ref)
+ expect(rel.target.ref).to eq(testuser.ref)
end
end
describe "when setting shell" do
before :each do
@shell_provider_class = described_class.provide(:shell_manager) do
has_features :manages_shell
mk_resource_methods
def create; check_valid_shell;end
def shell=(value); check_valid_shell; end
def delete; end
def exists?; get(:ensure) != :absent; end
def flush; end
def self.instances; []; end
def check_valid_shell; end
end
described_class.stubs(:defaultprovider).returns @shell_provider_class
end
it "should call :check_valid_shell on the provider when changing shell value" do
@provider = @shell_provider_class.new(:name => 'foo', :shell => '/bin/bash', :ensure => :present)
@provider.expects(:check_valid_shell)
resource = described_class.new(:name => 'foo', :shell => '/bin/zsh', :provider => @provider)
Puppet::Util::Storage.stubs(:load)
Puppet::Util::Storage.stubs(:store)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource resource
catalog.apply
end
it "should call :check_valid_shell on the provider when changing ensure from present to absent" do
@provider = @shell_provider_class.new(:name => 'foo', :shell => '/bin/bash', :ensure => :absent)
@provider.expects(:check_valid_shell)
resource = described_class.new(:name => 'foo', :shell => '/bin/zsh', :provider => @provider)
Puppet::Util::Storage.stubs(:load)
Puppet::Util::Storage.stubs(:store)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource resource
catalog.apply
end
end
describe "when purging ssh keys" do
it "should not accept a keyfile with a relative path" do
expect {
described_class.new(:name => "a", :purge_ssh_keys => "keys")
}.to raise_error(Puppet::Error, /Paths to keyfiles must be absolute, not keys/)
end
context "with a home directory specified" do
it "should accept true" do
described_class.new(:name => "a", :home => "/tmp", :purge_ssh_keys => true)
end
it "should accept the ~ wildcard" do
described_class.new(:name => "a", :home => "/tmp", :purge_ssh_keys => "~/keys")
end
it "should accept the %h wildcard" do
described_class.new(:name => "a", :home => "/tmp", :purge_ssh_keys => "%h/keys")
end
it "raises when given a relative path" do
expect {
described_class.new(:name => "a", :home => "/tmp", :purge_ssh_keys => "keys")
}.to raise_error(Puppet::Error, /Paths to keyfiles must be absolute/)
end
end
context "with no home directory specified" do
it "should not accept true" do
expect {
described_class.new(:name => "a", :purge_ssh_keys => true)
}.to raise_error(Puppet::Error, /purge_ssh_keys can only be true for users with a defined home directory/)
end
it "should not accept the ~ wildcard" do
expect {
described_class.new(:name => "a", :purge_ssh_keys => "~/keys")
}.to raise_error(Puppet::Error, /meta character ~ or %h only allowed for users with a defined home directory/)
end
it "should not accept the %h wildcard" do
expect {
described_class.new(:name => "a", :purge_ssh_keys => "%h/keys")
}.to raise_error(Puppet::Error, /meta character ~ or %h only allowed for users with a defined home directory/)
end
end
context "with a valid parameter" do
let(:paths) do
[ "/dev/null", "/tmp/keyfile" ].map { |path| File.expand_path(path) }
end
subject do
res = described_class.new(:name => "test", :purge_ssh_keys => paths)
res.catalog = Puppet::Resource::Catalog.new
res
end
it "should not just return from generate" do
subject.expects :find_unmanaged_keys
subject.generate
end
it "should check each keyfile for readability" do
paths.each do |path|
File.expects(:readable?).with(path)
end
subject.generate
end
end
describe "generated keys" do
subject do
res = described_class.new(:name => "test_user_name", :purge_ssh_keys => purge_param)
res.catalog = Puppet::Resource::Catalog.new
res
end
context "when purging is disabled" do
let(:purge_param) { false }
its(:generate) { should be_empty }
end
context "when purging is enabled" do
let(:purge_param) { my_fixture('authorized_keys') }
let(:resources) { subject.generate }
it "should contain a resource for each key" do
names = resources.collect { |res| res.name }
- names.should include("key1 name")
- names.should include("keyname2")
+ expect(names).to include("key1 name")
+ expect(names).to include("keyname2")
end
it "should not include keys in comment lines" do
names = resources.collect { |res| res.name }
- names.should_not include("keyname3")
+ expect(names).not_to include("keyname3")
end
it "should generate names for unnamed keys" do
names = resources.collect { |res| res.name }
fixture_path = File.join(my_fixture_dir, 'authorized_keys')
- names.should include("#{fixture_path}:unnamed-1")
+ expect(names).to include("#{fixture_path}:unnamed-1")
end
it "should each have a value for the user property" do
- resources.map { |res|
+ expect(resources.map { |res|
res[:user]
}.reject { |user_name|
user_name == "test_user_name"
- }.should be_empty
+ }).to be_empty
end
end
end
end
end
diff --git a/spec/unit/type/vlan_spec.rb b/spec/unit/type/vlan_spec.rb
index bf9027199..b60247846 100755
--- a/spec/unit/type/vlan_spec.rb
+++ b/spec/unit/type/vlan_spec.rb
@@ -1,44 +1,44 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:vlan) do
it "should have a 'name' parameter'" do
- Puppet::Type.type(:vlan).new(:name => "200")[:name].should == "200"
+ expect(Puppet::Type.type(:vlan).new(:name => "200")[:name]).to eq("200")
end
it "should have a 'device_url' parameter'" do
- Puppet::Type.type(:vlan).new(:name => "200", :device_url => :device)[:device_url].should == :device
+ expect(Puppet::Type.type(:vlan).new(:name => "200", :device_url => :device)[:device_url]).to eq(:device)
end
it "should be applied on device" do
- Puppet::Type.type(:vlan).new(:name => "200").must be_appliable_to_device
+ expect(Puppet::Type.type(:vlan).new(:name => "200")).to be_appliable_to_device
end
it "should have an ensure property" do
- Puppet::Type.type(:vlan).attrtype(:ensure).should == :property
+ expect(Puppet::Type.type(:vlan).attrtype(:ensure)).to eq(:property)
end
it "should have a description property" do
- Puppet::Type.type(:vlan).attrtype(:description).should == :property
+ expect(Puppet::Type.type(:vlan).attrtype(:description)).to eq(:property)
end
describe "when validating attribute values" do
before do
@provider = stub 'provider', :class => Puppet::Type.type(:vlan).defaultprovider, :clear => nil
Puppet::Type.type(:vlan).defaultprovider.stubs(:new).returns(@provider)
end
it "should support :present as a value to :ensure" do
Puppet::Type.type(:vlan).new(:name => "200", :ensure => :present)
end
it "should support :absent as a value to :ensure" do
Puppet::Type.type(:vlan).new(:name => "200", :ensure => :absent)
end
it "should fail if vlan name is not a number" do
- lambda { Puppet::Type.type(:vlan).new(:name => "notanumber", :ensure => :present) }.should raise_error
+ expect { Puppet::Type.type(:vlan).new(:name => "notanumber", :ensure => :present) }.to raise_error
end
end
end
diff --git a/spec/unit/type/whit_spec.rb b/spec/unit/type/whit_spec.rb
index 73498e55d..7455484d8 100755
--- a/spec/unit/type/whit_spec.rb
+++ b/spec/unit/type/whit_spec.rb
@@ -1,10 +1,10 @@
#! /usr/bin/env ruby
require 'spec_helper'
whit = Puppet::Type.type(:whit)
describe whit do
it "should stringify in a way that users will regognise" do
- whit.new(:name => "Foo::Bar").to_s.should == "Foo::Bar"
+ expect(whit.new(:name => "Foo::Bar").to_s).to eq("Foo::Bar")
end
end
diff --git a/spec/unit/type/zfs_spec.rb b/spec/unit/type/zfs_spec.rb
index d019cafea..4f0c5d07e 100755
--- a/spec/unit/type/zfs_spec.rb
+++ b/spec/unit/type/zfs_spec.rb
@@ -1,46 +1,46 @@
#! /usr/bin/env ruby
require 'spec_helper'
zfs = Puppet::Type.type(:zfs)
describe zfs do
properties = [:ensure, :mountpoint, :compression, :copies, :quota, :reservation, :sharenfs, :snapdir]
properties.each do |property|
it "should have a #{property} property" do
- zfs.attrclass(property).ancestors.should be_include(Puppet::Property)
+ expect(zfs.attrclass(property).ancestors).to be_include(Puppet::Property)
end
end
parameters = [:name]
parameters.each do |parameter|
it "should have a #{parameter} parameter" do
- zfs.attrclass(parameter).ancestors.should be_include(Puppet::Parameter)
+ expect(zfs.attrclass(parameter).ancestors).to be_include(Puppet::Parameter)
end
end
it "should autorequire the containing zfs and the zpool" do
zfs_provider = mock "provider"
zfs_provider.stubs(:name).returns(:zfs)
zfs.stubs(:defaultprovider).returns(zfs_provider)
zpool_provider = mock "provider"
zpool_provider.stubs(:name).returns(:zpool)
Puppet::Type.type(:zpool).stubs(:defaultprovider).returns(zpool_provider)
foo_pool = Puppet::Type.type(:zpool).new(:name => "foo")
foo_bar_zfs = Puppet::Type.type(:zfs).new(:name => "foo/bar")
foo_bar_baz_zfs = Puppet::Type.type(:zfs).new(:name => "foo/bar/baz")
foo_bar_baz_buz_zfs = Puppet::Type.type(:zfs).new(:name => "foo/bar/baz/buz")
config = Puppet::Resource::Catalog.new :testing do |conf|
[foo_pool, foo_bar_zfs, foo_bar_baz_zfs, foo_bar_baz_buz_zfs].each { |resource| conf.add_resource resource }
end
req = foo_bar_baz_buz_zfs.autorequire.collect { |edge| edge.source.ref }
- [foo_pool.ref, foo_bar_zfs.ref, foo_bar_baz_zfs.ref].each { |ref| req.include?(ref).should == true }
+ [foo_pool.ref, foo_bar_zfs.ref, foo_bar_baz_zfs.ref].each { |ref| expect(req.include?(ref)).to eq(true) }
end
end
diff --git a/spec/unit/type/zone_spec.rb b/spec/unit/type/zone_spec.rb
index 3497ae3a7..d4595f5f8 100755
--- a/spec/unit/type/zone_spec.rb
+++ b/spec/unit/type/zone_spec.rb
@@ -1,172 +1,172 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Type.type(:zone) do
let(:zone) { described_class.new(:name => 'dummy', :path => '/dummy', :provider => :solaris, :ip=>'if:1.2.3.4:2.3.4.5', :inherit=>'/', :dataset=>'tank') }
let(:provider) { zone.provider }
let(:ip) { zone.property(:ip) }
let(:inherit) { zone.property(:inherit) }
let(:dataset) { zone.property(:dataset) }
parameters = [:create_args, :install_args, :sysidcfg, :realhostname]
parameters.each do |parameter|
it "should have a #{parameter} parameter" do
- described_class.attrclass(parameter).ancestors.should be_include(Puppet::Parameter)
+ expect(described_class.attrclass(parameter).ancestors).to be_include(Puppet::Parameter)
end
end
properties = [:ip, :iptype, :autoboot, :pool, :shares, :inherit, :path]
properties.each do |property|
it "should have a #{property} property" do
- described_class.attrclass(property).ancestors.should be_include(Puppet::Property)
+ expect(described_class.attrclass(property).ancestors).to be_include(Puppet::Property)
end
end
describe "when trying to set a property that is empty" do
it "should verify that property.insync? of nil or :absent is true" do
[inherit, ip, dataset].each do |prop|
prop.stubs(:should).returns []
end
[inherit, ip, dataset].each do |prop|
- prop.insync?(nil).should be_true
+ expect(prop.insync?(nil)).to be_truthy
end
[inherit, ip, dataset].each do |prop|
- prop.insync?(:absent).should be_true
+ expect(prop.insync?(:absent)).to be_truthy
end
end
end
describe "when trying to set a property that is non empty" do
it "should verify that property.insync? of nil or :absent is false" do
[inherit, ip, dataset].each do |prop|
prop.stubs(:should).returns ['a','b']
end
[inherit, ip, dataset].each do |prop|
- prop.insync?(nil).should be_false
+ expect(prop.insync?(nil)).to be_falsey
end
[inherit, ip, dataset].each do |prop|
- prop.insync?(:absent).should be_false
+ expect(prop.insync?(:absent)).to be_falsey
end
end
end
describe "when trying to set a property that is non empty" do
it "insync? should return true or false depending on the current value, and new value" do
[inherit, ip, dataset].each do |prop|
prop.stubs(:should).returns ['a','b']
end
[inherit, ip, dataset].each do |prop|
- prop.insync?(['b', 'a']).should be_true
+ expect(prop.insync?(['b', 'a'])).to be_truthy
end
[inherit, ip, dataset].each do |prop|
- prop.insync?(['a']).should be_false
+ expect(prop.insync?(['a'])).to be_falsey
end
end
end
it "should be valid when only :path is given" do
described_class.new(:name => "dummy", :path => '/dummy', :provider => :solaris)
end
it "should be invalid when :ip is missing a \":\" and iptype is :shared" do
expect {
described_class.new(:name => "dummy", :ip => "if", :path => "/dummy", :provider => :solaris)
}.to raise_error(Puppet::Error, /ip must contain interface name and ip address separated by a ":"/)
end
it "should be invalid when :ip has a \":\" and iptype is :exclusive" do
expect {
described_class.new(:name => "dummy", :ip => "if:1.2.3.4", :iptype => :exclusive, :provider => :solaris)
}.to raise_error(Puppet::Error, /only interface may be specified when using exclusive IP stack/)
end
it "should be invalid when :ip has two \":\" and iptype is :exclusive" do
expect {
described_class.new(:name => "dummy", :ip => "if:1.2.3.4:2.3.4.5", :iptype => :exclusive, :provider => :solaris)
}.to raise_error(Puppet::Error, /only interface may be specified when using exclusive IP stack/)
end
it "should be valid when :iptype is :shared and using interface and ip" do
described_class.new(:name => "dummy", :path => "/dummy", :ip => "if:1.2.3.4", :provider => :solaris)
end
it "should be valid when :iptype is :shared and using interface, ip and default route" do
described_class.new(:name => "dummy", :path => "/dummy", :ip => "if:1.2.3.4:2.3.4.5", :provider => :solaris)
end
it "should be valid when :iptype is :exclusive and using interface" do
described_class.new(:name => "dummy", :path => "/dummy", :ip => "if", :iptype => :exclusive, :provider => :solaris)
end
it "should auto-require :dataset entries" do
fs = 'random-pool/some-zfs'
catalog = Puppet::Resource::Catalog.new
relationship_graph = Puppet::Graph::RelationshipGraph.new(Puppet::Graph::RandomPrioritizer.new)
zfs = Puppet::Type.type(:zfs).new(:name => fs)
catalog.add_resource zfs
zone = described_class.new(:name => "dummy",
:path => "/foo",
:ip => 'en1:1.0.0.0',
:dataset => fs,
:provider => :solaris)
catalog.add_resource zone
relationship_graph.populate_from(catalog)
- relationship_graph.dependencies(zone).should == [zfs]
+ expect(relationship_graph.dependencies(zone)).to eq([zfs])
end
describe Puppet::Zone::StateMachine do
let (:sm) { Puppet::Zone::StateMachine.new }
before :each do
sm.insert_state :absent, :down => :destroy
sm.insert_state :configured, :up => :configure, :down => :uninstall
sm.insert_state :installed, :up => :install, :down => :stop
sm.insert_state :running, :up => :start
end
context ":insert_state" do
it "should insert state in correct order" do
sm.insert_state :dummy, :left => :right
- sm.index(:dummy).should == 4
+ expect(sm.index(:dummy)).to eq(4)
end
end
context ":alias_state" do
it "should alias state" do
sm.alias_state :dummy, :running
- sm.name(:dummy).should == :running
+ expect(sm.name(:dummy)).to eq(:running)
end
end
context ":name" do
it "should get an aliased state correctly" do
sm.alias_state :dummy, :running
- sm.name(:dummy).should == :running
+ expect(sm.name(:dummy)).to eq(:running)
end
it "should get an un aliased state correctly" do
- sm.name(:dummy).should == :dummy
+ expect(sm.name(:dummy)).to eq(:dummy)
end
end
context ":index" do
it "should return the state index correctly" do
sm.insert_state :dummy, :left => :right
- sm.index(:dummy).should == 4
+ expect(sm.index(:dummy)).to eq(4)
end
end
context ":sequence" do
it "should correctly return the actions to reach state specified" do
- sm.sequence(:absent, :running).map{|p|p[:up]}.should == [:configure,:install,:start]
+ expect(sm.sequence(:absent, :running).map{|p|p[:up]}).to eq([:configure,:install,:start])
end
it "should correctly return the actions to reach state specified(2)" do
- sm.sequence(:running, :absent).map{|p|p[:down]}.should == [:stop, :uninstall, :destroy]
+ expect(sm.sequence(:running, :absent).map{|p|p[:down]}).to eq([:stop, :uninstall, :destroy])
end
end
context ":cmp" do
it "should correctly compare state sequence values" do
- sm.cmp?(:absent, :running).should == true
- sm.cmp?(:running, :running).should == false
- sm.cmp?(:running, :absent).should == false
+ expect(sm.cmp?(:absent, :running)).to eq(true)
+ expect(sm.cmp?(:running, :running)).to eq(false)
+ expect(sm.cmp?(:running, :absent)).to eq(false)
end
end
end
end
diff --git a/spec/unit/type/zpool_spec.rb b/spec/unit/type/zpool_spec.rb
index e6d551cff..3320cb8a8 100755
--- a/spec/unit/type/zpool_spec.rb
+++ b/spec/unit/type/zpool_spec.rb
@@ -1,109 +1,109 @@
#! /usr/bin/env ruby
require 'spec_helper'
zpool = Puppet::Type.type(:zpool)
describe zpool do
before do
@provider = stub 'provider'
@resource = stub 'resource', :resource => nil, :provider => @provider, :line => nil, :file => nil
end
properties = [:ensure, :disk, :mirror, :raidz, :spare, :log]
properties.each do |property|
it "should have a #{property} property" do
- zpool.attrclass(property).ancestors.should be_include(Puppet::Property)
+ expect(zpool.attrclass(property).ancestors).to be_include(Puppet::Property)
end
end
parameters = [:pool, :raid_parity]
parameters.each do |parameter|
it "should have a #{parameter} parameter" do
- zpool.attrclass(parameter).ancestors.should be_include(Puppet::Parameter)
+ expect(zpool.attrclass(parameter).ancestors).to be_include(Puppet::Parameter)
end
end
end
vdev_property = Puppet::Property::VDev
describe vdev_property do
before do
vdev_property.initvars
@resource = stub 'resource', :[]= => nil, :property => nil
@property = vdev_property.new(:resource => @resource)
end
it "should be insync if the devices are the same" do
@property.should = ["dev1 dev2"]
- @property.safe_insync?(["dev2 dev1"]).must be_true
+ expect(@property.safe_insync?(["dev2 dev1"])).to be_truthy
end
it "should be out of sync if the devices are not the same" do
@property.should = ["dev1 dev3"]
- @property.safe_insync?(["dev2 dev1"]).must be_false
+ expect(@property.safe_insync?(["dev2 dev1"])).to be_falsey
end
it "should be insync if the devices are the same and the should values are comma separated" do
@property.should = ["dev1", "dev2"]
- @property.safe_insync?(["dev2 dev1"]).must be_true
+ expect(@property.safe_insync?(["dev2 dev1"])).to be_truthy
end
it "should be out of sync if the device is absent and should has a value" do
@property.should = ["dev1", "dev2"]
- @property.safe_insync?(:absent).must be_false
+ expect(@property.safe_insync?(:absent)).to be_falsey
end
it "should be insync if the device is absent and should is absent" do
@property.should = [:absent]
- @property.safe_insync?(:absent).must be_true
+ expect(@property.safe_insync?(:absent)).to be_truthy
end
end
multi_vdev_property = Puppet::Property::MultiVDev
describe multi_vdev_property do
before do
multi_vdev_property.initvars
@resource = stub 'resource', :[]= => nil, :property => nil
@property = multi_vdev_property.new(:resource => @resource)
end
it "should be insync if the devices are the same" do
@property.should = ["dev1 dev2"]
- @property.safe_insync?(["dev2 dev1"]).must be_true
+ expect(@property.safe_insync?(["dev2 dev1"])).to be_truthy
end
it "should be out of sync if the devices are not the same" do
@property.should = ["dev1 dev3"]
- @property.safe_insync?(["dev2 dev1"]).must be_false
+ expect(@property.safe_insync?(["dev2 dev1"])).to be_falsey
end
it "should be out of sync if the device is absent and should has a value" do
@property.should = ["dev1", "dev2"]
- @property.safe_insync?(:absent).must be_false
+ expect(@property.safe_insync?(:absent)).to be_falsey
end
it "should be insync if the device is absent and should is absent" do
@property.should = [:absent]
- @property.safe_insync?(:absent).must be_true
+ expect(@property.safe_insync?(:absent)).to be_truthy
end
describe "when there are multiple lists of devices" do
it "should be in sync if each group has the same devices" do
@property.should = ["dev1 dev2", "dev3 dev4"]
- @property.safe_insync?(["dev2 dev1", "dev3 dev4"]).must be_true
+ expect(@property.safe_insync?(["dev2 dev1", "dev3 dev4"])).to be_truthy
end
it "should be out of sync if any group has the different devices" do
@property.should = ["dev1 devX", "dev3 dev4"]
- @property.safe_insync?(["dev2 dev1", "dev3 dev4"]).must be_false
+ expect(@property.safe_insync?(["dev2 dev1", "dev3 dev4"])).to be_falsey
end
it "should be out of sync if devices are in the wrong group" do
@property.should = ["dev1 dev2", "dev3 dev4"]
- @property.safe_insync?(["dev2 dev3", "dev1 dev4"]).must be_false
+ expect(@property.safe_insync?(["dev2 dev3", "dev1 dev4"])).to be_falsey
end
end
end
diff --git a/spec/unit/type_spec.rb b/spec/unit/type_spec.rb
index 9b9b73172..03d6653a8 100755
--- a/spec/unit/type_spec.rb
+++ b/spec/unit/type_spec.rb
@@ -1,1185 +1,1187 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/compiler'
describe Puppet::Type, :unless => Puppet.features.microsoft_windows? do
include PuppetSpec::Files
include PuppetSpec::Compiler
it "should be Comparable" do
a = Puppet::Type.type(:notify).new(:name => "a")
b = Puppet::Type.type(:notify).new(:name => "b")
c = Puppet::Type.type(:notify).new(:name => "c")
[[a, b, c], [a, c, b], [b, a, c], [b, c, a], [c, a, b], [c, b, a]].each do |this|
- this.sort.should == [a, b, c]
+ expect(this.sort).to eq([a, b, c])
end
- a.must be < b
- a.must be < c
- b.must be > a
- b.must be < c
- c.must be > a
- c.must be > b
+ expect(a).to be < b
+ expect(a).to be < c
+ expect(b).to be > a
+ expect(b).to be < c
+ expect(c).to be > a
+ expect(c).to be > b
- [a, b, c].each {|x| a.must be <= x }
- [a, b, c].each {|x| c.must be >= x }
+ [a, b, c].each {|x| expect(a).to be <= x }
+ [a, b, c].each {|x| expect(c).to be >= x }
- b.must be_between(a, c)
+ expect(b).to be_between(a, c)
end
it "should consider a parameter to be valid if it is a valid parameter" do
- Puppet::Type.type(:mount).should be_valid_parameter(:name)
+ expect(Puppet::Type.type(:mount)).to be_valid_parameter(:name)
end
it "should consider a parameter to be valid if it is a valid property" do
- Puppet::Type.type(:mount).should be_valid_parameter(:fstype)
+ expect(Puppet::Type.type(:mount)).to be_valid_parameter(:fstype)
end
it "should consider a parameter to be valid if it is a valid metaparam" do
- Puppet::Type.type(:mount).should be_valid_parameter(:noop)
+ expect(Puppet::Type.type(:mount)).to be_valid_parameter(:noop)
end
it "should be able to retrieve a property by name" do
resource = Puppet::Type.type(:mount).new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present)
- resource.property(:fstype).must be_instance_of(Puppet::Type.type(:mount).attrclass(:fstype))
+ expect(resource.property(:fstype)).to be_instance_of(Puppet::Type.type(:mount).attrclass(:fstype))
end
it "should be able to retrieve a parameter by name" do
resource = Puppet::Type.type(:mount).new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present)
- resource.parameter(:name).must be_instance_of(Puppet::Type.type(:mount).attrclass(:name))
+ expect(resource.parameter(:name)).to be_instance_of(Puppet::Type.type(:mount).attrclass(:name))
end
it "should be able to retrieve a property by name using the :parameter method" do
resource = Puppet::Type.type(:mount).new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present)
- resource.parameter(:fstype).must be_instance_of(Puppet::Type.type(:mount).attrclass(:fstype))
+ expect(resource.parameter(:fstype)).to be_instance_of(Puppet::Type.type(:mount).attrclass(:fstype))
end
it "should be able to retrieve all set properties" do
resource = Puppet::Type.type(:mount).new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present)
props = resource.properties
- props.should_not be_include(nil)
+ expect(props).not_to be_include(nil)
[:fstype, :ensure, :pass].each do |name|
- props.should be_include(resource.parameter(name))
+ expect(props).to be_include(resource.parameter(name))
end
end
it "can retrieve all set parameters" do
resource = Puppet::Type.type(:mount).new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present, :tag => 'foo')
params = resource.parameters_with_value
[:name, :provider, :ensure, :fstype, :pass, :dump, :target, :loglevel, :tag].each do |name|
- params.should be_include(resource.parameter(name))
+ expect(params).to be_include(resource.parameter(name))
end
end
it "can not return any `nil` values when retrieving all set parameters" do
resource = Puppet::Type.type(:mount).new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present, :tag => 'foo')
params = resource.parameters_with_value
- params.should_not be_include(nil)
+ expect(params).not_to be_include(nil)
end
it "can return an iterator for all set parameters" do
resource = Puppet::Type.type(:notify).new(:name=>'foo',:message=>'bar',:tag=>'baz',:require=> "File['foo']")
params = [:name, :message, :withpath, :loglevel, :tag, :require]
resource.eachparameter { |param|
- params.should be_include(param.to_s.to_sym)
+ expect(params).to be_include(param.to_s.to_sym)
}
end
it "should have a method for setting default values for resources" do
- Puppet::Type.type(:mount).new(:name => "foo").must respond_to(:set_default)
+ expect(Puppet::Type.type(:mount).new(:name => "foo")).to respond_to(:set_default)
end
it "should do nothing for attributes that have no defaults and no specified value" do
- Puppet::Type.type(:mount).new(:name => "foo").parameter(:noop).should be_nil
+ expect(Puppet::Type.type(:mount).new(:name => "foo").parameter(:noop)).to be_nil
end
it "should have a method for adding tags" do
- Puppet::Type.type(:mount).new(:name => "foo").must respond_to(:tags)
+ expect(Puppet::Type.type(:mount).new(:name => "foo")).to respond_to(:tags)
end
it "should use the tagging module" do
- Puppet::Type.type(:mount).ancestors.should be_include(Puppet::Util::Tagging)
+ expect(Puppet::Type.type(:mount).ancestors).to be_include(Puppet::Util::Tagging)
end
it "should delegate to the tagging module when tags are added" do
resource = Puppet::Type.type(:mount).new(:name => "foo")
resource.stubs(:tag).with(:mount)
resource.expects(:tag).with(:tag1, :tag2)
resource.tags = [:tag1,:tag2]
end
it "should add the current type as tag" do
resource = Puppet::Type.type(:mount).new(:name => "foo")
resource.stubs(:tag)
resource.expects(:tag).with(:mount)
resource.tags = [:tag1,:tag2]
end
it "should have a method to know if the resource is exported" do
- Puppet::Type.type(:mount).new(:name => "foo").must respond_to(:exported?)
+ expect(Puppet::Type.type(:mount).new(:name => "foo")).to respond_to(:exported?)
end
it "should have a method to know if the resource is virtual" do
- Puppet::Type.type(:mount).new(:name => "foo").must respond_to(:virtual?)
+ expect(Puppet::Type.type(:mount).new(:name => "foo")).to respond_to(:virtual?)
end
it "should consider its version to be zero if it has no catalog" do
- Puppet::Type.type(:mount).new(:name => "foo").version.should == 0
+ expect(Puppet::Type.type(:mount).new(:name => "foo").version).to eq(0)
end
it "reports the correct path even after path is used during setup of the type" do
Puppet::Type.newtype(:testing) do
newparam(:name) do
isnamevar
validate do |value|
path # forces the computation of the path
end
end
end
ral = compile_to_ral(<<-MANIFEST)
class something {
testing { something: }
}
include something
MANIFEST
- ral.resource("Testing[something]").path.should == "/Stage[main]/Something/Testing[something]"
+ expect(ral.resource("Testing[something]").path).to eq("/Stage[main]/Something/Testing[something]")
end
context "alias metaparam" do
it "creates a new name that can be used for resource references" do
ral = compile_to_ral(<<-MANIFEST)
notify { a: alias => c }
MANIFEST
expect(ral.resource("Notify[a]")).to eq(ral.resource("Notify[c]"))
end
end
context "resource attributes" do
let(:resource) {
resource = Puppet::Type.type(:mount).new(:name => "foo")
catalog = Puppet::Resource::Catalog.new
catalog.version = 50
catalog.add_resource resource
resource
}
it "should consider its version to be its catalog version" do
- resource.version.should == 50
+ expect(resource.version).to eq(50)
end
it "should have tags" do
expect(resource).to be_tagged("mount")
expect(resource).to be_tagged("foo")
end
it "should have a path" do
- resource.path.should == "/Mount[foo]"
+ expect(resource.path).to eq("/Mount[foo]")
end
end
it "should consider its type to be the name of its class" do
- Puppet::Type.type(:mount).new(:name => "foo").type.should == :mount
+ expect(Puppet::Type.type(:mount).new(:name => "foo").type).to eq(:mount)
end
it "should use any provided noop value" do
- Puppet::Type.type(:mount).new(:name => "foo", :noop => true).must be_noop
+ expect(Puppet::Type.type(:mount).new(:name => "foo", :noop => true)).to be_noop
end
it "should use the global noop value if none is provided" do
Puppet[:noop] = true
- Puppet::Type.type(:mount).new(:name => "foo").must be_noop
+ expect(Puppet::Type.type(:mount).new(:name => "foo")).to be_noop
end
it "should not be noop if in a non-host_config catalog" do
resource = Puppet::Type.type(:mount).new(:name => "foo")
catalog = Puppet::Resource::Catalog.new
catalog.add_resource resource
- resource.should_not be_noop
+ expect(resource).not_to be_noop
end
describe "when creating an event" do
before do
@resource = Puppet::Type.type(:mount).new :name => "foo"
end
it "should have the resource's reference as the resource" do
- @resource.event.resource.should == "Mount[foo]"
+ expect(@resource.event.resource).to eq("Mount[foo]")
end
it "should have the resource's log level as the default log level" do
@resource[:loglevel] = :warning
- @resource.event.default_log_level.should == :warning
+ expect(@resource.event.default_log_level).to eq(:warning)
end
{:file => "/my/file", :line => 50}.each do |attr, value|
it "should set the #{attr}" do
@resource.stubs(attr).returns value
- @resource.event.send(attr).should == value
+ expect(@resource.event.send(attr)).to eq(value)
end
end
it "should set the tags" do
@resource.tag("abc", "def")
- @resource.event.should be_tagged("abc")
- @resource.event.should be_tagged("def")
+ expect(@resource.event).to be_tagged("abc")
+ expect(@resource.event).to be_tagged("def")
end
it "should allow specification of event attributes" do
- @resource.event(:status => "noop").status.should == "noop"
+ expect(@resource.event(:status => "noop").status).to eq("noop")
end
end
describe "when creating a provider" do
before :each do
@type = Puppet::Type.newtype(:provider_test_type) do
newparam(:name) { isnamevar }
newparam(:foo)
newproperty(:bar)
end
end
after :each do
@type.provider_hash.clear
end
describe "when determining if instances of the type are managed" do
it "should not consider audit only resources to be managed" do
- @type.new(:name => "foo", :audit => 'all').managed?.should be_false
+ expect(@type.new(:name => "foo", :audit => 'all').managed?).to be_falsey
end
it "should not consider resources with only parameters to be managed" do
- @type.new(:name => "foo", :foo => 'did someone say food?').managed?.should be_false
+ expect(@type.new(:name => "foo", :foo => 'did someone say food?').managed?).to be_falsey
end
it "should consider resources with any properties set to be managed" do
- @type.new(:name => "foo", :bar => 'Let us all go there').managed?.should be_true
+ expect(@type.new(:name => "foo", :bar => 'Let us all go there').managed?).to be_truthy
end
end
it "should have documentation for the 'provider' parameter if there are providers" do
@type.provide(:test_provider)
- @type.paramdoc(:provider).should =~ /`provider_test_type`[\s\r]+resource/
+ expect(@type.paramdoc(:provider)).to match(/`provider_test_type`[\s\r]+resource/)
end
it "should not have documentation for the 'provider' parameter if there are no providers" do
expect { @type.paramdoc(:provider) }.to raise_error(NoMethodError)
end
it "should create a subclass of Puppet::Provider for the provider" do
provider = @type.provide(:test_provider)
- provider.ancestors.should include(Puppet::Provider)
+ expect(provider.ancestors).to include(Puppet::Provider)
end
it "should use a parent class if specified" do
parent_provider = @type.provide(:parent_provider)
child_provider = @type.provide(:child_provider, :parent => parent_provider)
- child_provider.ancestors.should include(parent_provider)
+ expect(child_provider.ancestors).to include(parent_provider)
end
it "should use a parent class if specified by name" do
parent_provider = @type.provide(:parent_provider)
child_provider = @type.provide(:child_provider, :parent => :parent_provider)
- child_provider.ancestors.should include(parent_provider)
+ expect(child_provider.ancestors).to include(parent_provider)
end
it "should raise an error when the parent class can't be found" do
expect {
@type.provide(:child_provider, :parent => :parent_provider)
}.to raise_error(Puppet::DevError, /Could not find parent provider.+parent_provider/)
end
it "should ensure its type has a 'provider' parameter" do
@type.provide(:test_provider)
- @type.parameters.should include(:provider)
+ expect(@type.parameters).to include(:provider)
end
it "should remove a previously registered provider with the same name" do
old_provider = @type.provide(:test_provider)
new_provider = @type.provide(:test_provider)
- old_provider.should_not equal(new_provider)
+ expect(old_provider).not_to equal(new_provider)
end
it "should register itself as a provider for the type" do
provider = @type.provide(:test_provider)
- provider.should == @type.provider(:test_provider)
+ expect(provider).to eq(@type.provider(:test_provider))
end
it "should create a provider when a provider with the same name previously failed" do
@type.provide(:test_provider) do
raise "failed to create this provider"
end rescue nil
provider = @type.provide(:test_provider)
- provider.ancestors.should include(Puppet::Provider)
- provider.should == @type.provider(:test_provider)
+ expect(provider.ancestors).to include(Puppet::Provider)
+ expect(provider).to eq(@type.provider(:test_provider))
end
describe "with a parent class from another type" do
before :each do
@parent_type = Puppet::Type.newtype(:provider_parent_type) do
newparam(:name) { isnamevar }
end
@parent_provider = @parent_type.provide(:parent_provider)
end
it "should be created successfully" do
child_provider = @type.provide(:child_provider, :parent => @parent_provider)
- child_provider.ancestors.should include(@parent_provider)
+ expect(child_provider.ancestors).to include(@parent_provider)
end
it "should be registered as a provider of the child type" do
child_provider = @type.provide(:child_provider, :parent => @parent_provider)
- @type.providers.should include(:child_provider)
- @parent_type.providers.should_not include(:child_provider)
+ expect(@type.providers).to include(:child_provider)
+ expect(@parent_type.providers).not_to include(:child_provider)
end
end
end
describe "when choosing a default provider" do
it "should choose the provider with the highest specificity" do
# Make a fake type
type = Puppet::Type.newtype(:defaultprovidertest) do
newparam(:name) do end
end
basic = type.provide(:basic) {}
greater = type.provide(:greater) {}
basic.stubs(:specificity).returns 1
greater.stubs(:specificity).returns 2
- type.defaultprovider.should equal(greater)
+ expect(type.defaultprovider).to equal(greater)
end
end
context "autorelations" do
before :each do
type = Puppet::Type.newtype(:autorelation_one) do
newparam(:name) { isnamevar }
end
end
describe "when building autorelations" do
it "should be able to autorequire resources" do
type = Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autorequire(:autorelation_one) { ['foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
- relationship_graph.edge?(src,dst).should be_true
- relationship_graph.edges_between(src,dst).first.event.should == :NONE
+ expect(relationship_graph.edge?(src,dst)).to be_truthy
+ expect(relationship_graph.edges_between(src,dst).first.event).to eq(:NONE)
end
it "should be able to autosubscribe resources" do
type = Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autosubscribe(:autorelation_one) { ['foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
- relationship_graph.edge?(src,dst).should be_true
- relationship_graph.edges_between(src,dst).first.event.should == :ALL_EVENTS
+ expect(relationship_graph.edge?(src,dst)).to be_truthy
+ expect(relationship_graph.edges_between(src,dst).first.event).to eq(:ALL_EVENTS)
end
it "should be able to autobefore resources" do
type = Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autobefore(:autorelation_one) { ['foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
- relationship_graph.edge?(src,dst).should be_true
- relationship_graph.edges_between(src,dst).first.event.should == :NONE
+ expect(relationship_graph.edge?(src,dst)).to be_truthy
+ expect(relationship_graph.edges_between(src,dst).first.event).to eq(:NONE)
end
it "should be able to autonotify resources" do
type = Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autonotify(:autorelation_one) { ['foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
- relationship_graph.edge?(src,dst).should be_true
- relationship_graph.edges_between(src,dst).first.event.should == :ALL_EVENTS
+ expect(relationship_graph.edge?(src,dst)).to be_truthy
+ expect(relationship_graph.edges_between(src,dst).first.event).to eq(:ALL_EVENTS)
end
end
end
describe "when initializing" do
describe "and passed a Puppet::Resource instance" do
it "should set its title to the title of the resource if the resource type is equal to the current type" do
resource = Puppet::Resource.new(:mount, "/foo", :parameters => {:name => "/other"})
- Puppet::Type.type(:mount).new(resource).title.should == "/foo"
+ expect(Puppet::Type.type(:mount).new(resource).title).to eq("/foo")
end
it "should set its title to the resource reference if the resource type is not equal to the current type" do
resource = Puppet::Resource.new(:user, "foo")
- Puppet::Type.type(:mount).new(resource).title.should == "User[foo]"
+ expect(Puppet::Type.type(:mount).new(resource).title).to eq("User[foo]")
end
[:line, :file, :catalog, :exported, :virtual].each do |param|
it "should copy '#{param}' from the resource if present" do
resource = Puppet::Resource.new(:mount, "/foo")
resource.send(param.to_s + "=", "foo")
resource.send(param.to_s + "=", "foo")
- Puppet::Type.type(:mount).new(resource).send(param).should == "foo"
+ expect(Puppet::Type.type(:mount).new(resource).send(param)).to eq("foo")
end
end
it "should copy any tags from the resource" do
resource = Puppet::Resource.new(:mount, "/foo")
resource.tag "one", "two"
tags = Puppet::Type.type(:mount).new(resource).tags
- tags.should be_include("one")
- tags.should be_include("two")
+ expect(tags).to be_include("one")
+ expect(tags).to be_include("two")
end
it "should copy the resource's parameters as its own" do
resource = Puppet::Resource.new(:mount, "/foo", :parameters => {:atboot => :yes, :fstype => "boo"})
params = Puppet::Type.type(:mount).new(resource).to_hash
- params[:fstype].should == "boo"
- params[:atboot].should == :yes
+ expect(params[:fstype]).to eq("boo")
+ expect(params[:atboot]).to eq(:yes)
end
end
describe "and passed a Hash" do
it "should extract the title from the hash" do
- Puppet::Type.type(:mount).new(:title => "/yay").title.should == "/yay"
+ expect(Puppet::Type.type(:mount).new(:title => "/yay").title).to eq("/yay")
end
it "should work when hash keys are provided as strings" do
- Puppet::Type.type(:mount).new("title" => "/yay").title.should == "/yay"
+ expect(Puppet::Type.type(:mount).new("title" => "/yay").title).to eq("/yay")
end
it "should work when hash keys are provided as symbols" do
- Puppet::Type.type(:mount).new(:title => "/yay").title.should == "/yay"
+ expect(Puppet::Type.type(:mount).new(:title => "/yay").title).to eq("/yay")
end
it "should use the name from the hash as the title if no explicit title is provided" do
- Puppet::Type.type(:mount).new(:name => "/yay").title.should == "/yay"
+ expect(Puppet::Type.type(:mount).new(:name => "/yay").title).to eq("/yay")
end
it "should use the Resource Type's namevar to determine how to find the name in the hash" do
yay = make_absolute('/yay')
- Puppet::Type.type(:file).new(:path => yay).title.should == yay
+ expect(Puppet::Type.type(:file).new(:path => yay).title).to eq(yay)
end
[:catalog].each do |param|
it "should extract '#{param}' from the hash if present" do
- Puppet::Type.type(:mount).new(:name => "/yay", param => "foo").send(param).should == "foo"
+ expect(Puppet::Type.type(:mount).new(:name => "/yay", param => "foo").send(param)).to eq("foo")
end
end
it "should use any remaining hash keys as its parameters" do
resource = Puppet::Type.type(:mount).new(:title => "/foo", :catalog => "foo", :atboot => :yes, :fstype => "boo")
- resource[:fstype].must == "boo"
- resource[:atboot].must == :yes
+ expect(resource[:fstype]).to eq("boo")
+ expect(resource[:atboot]).to eq(:yes)
end
end
it "should fail if any invalid attributes have been provided" do
expect { Puppet::Type.type(:mount).new(:title => "/foo", :nosuchattr => "whatever") }.to raise_error(Puppet::Error, /Invalid parameter/)
end
context "when an attribute fails validation" do
it "should fail with Puppet::ResourceError when PuppetError raised" do
expect { Puppet::Type.type(:file).new(:title => "/foo", :source => "unknown:///") }.to raise_error(Puppet::ResourceError, /Parameter source failed on File\[.*foo\]/)
end
it "should fail with Puppet::ResourceError when ArgumentError raised" do
expect { Puppet::Type.type(:file).new(:title => "/foo", :mode => "abcdef") }.to raise_error(Puppet::ResourceError, /Parameter mode failed on File\[.*foo\]/)
end
it "should include the file/line in the error" do
Puppet::Type.type(:file).any_instance.stubs(:file).returns("example.pp")
Puppet::Type.type(:file).any_instance.stubs(:line).returns(42)
expect { Puppet::Type.type(:file).new(:title => "/foo", :source => "unknown:///") }.to raise_error(Puppet::ResourceError, /example.pp:42/)
end
end
it "should set its name to the resource's title if the resource does not have a :name or namevar parameter set" do
resource = Puppet::Resource.new(:mount, "/foo")
- Puppet::Type.type(:mount).new(resource).name.should == "/foo"
+ expect(Puppet::Type.type(:mount).new(resource).name).to eq("/foo")
end
it "should fail if no title, name, or namevar are provided" do
expect { Puppet::Type.type(:mount).new(:atboot => :yes) }.to raise_error(Puppet::Error)
end
it "should set the attributes in the order returned by the class's :allattrs method" do
Puppet::Type.type(:mount).stubs(:allattrs).returns([:name, :atboot, :noop])
resource = Puppet::Resource.new(:mount, "/foo", :parameters => {:name => "myname", :atboot => :yes, :noop => "whatever"})
set = []
Puppet::Type.type(:mount).any_instance.stubs(:newattr).with do |param, hash|
set << param
true
end.returns(stub_everything("a property"))
Puppet::Type.type(:mount).new(resource)
- set[-1].should == :noop
- set[-2].should == :atboot
+ expect(set[-1]).to eq(:noop)
+ expect(set[-2]).to eq(:atboot)
end
it "should always set the name and then default provider before anything else" do
Puppet::Type.type(:mount).stubs(:allattrs).returns([:provider, :name, :atboot])
resource = Puppet::Resource.new(:mount, "/foo", :parameters => {:name => "myname", :atboot => :yes})
set = []
Puppet::Type.type(:mount).any_instance.stubs(:newattr).with do |param, hash|
set << param
true
end.returns(stub_everything("a property"))
Puppet::Type.type(:mount).new(resource)
- set[0].should == :name
- set[1].should == :provider
+ expect(set[0]).to eq(:name)
+ expect(set[1]).to eq(:provider)
end
# This one is really hard to test :/
it "should set each default immediately if no value is provided" do
defaults = []
Puppet::Type.type(:service).any_instance.stubs(:set_default).with { |value| defaults << value; true }
Puppet::Type.type(:service).new :name => "whatever"
- defaults[0].should == :provider
+ expect(defaults[0]).to eq(:provider)
end
it "should retain a copy of the originally provided parameters" do
- Puppet::Type.type(:mount).new(:name => "foo", :atboot => :yes, :noop => false).original_parameters.should == {:atboot => :yes, :noop => false}
+ expect(Puppet::Type.type(:mount).new(:name => "foo", :atboot => :yes, :noop => false).original_parameters).to eq({:atboot => :yes, :noop => false})
end
it "should delete the name via the namevar from the originally provided parameters" do
- Puppet::Type.type(:file).new(:name => make_absolute('/foo')).original_parameters[:path].should be_nil
+ expect(Puppet::Type.type(:file).new(:name => make_absolute('/foo')).original_parameters[:path]).to be_nil
end
context "when validating the resource" do
it "should call the type's validate method if present" do
Puppet::Type.type(:file).any_instance.expects(:validate)
Puppet::Type.type(:file).new(:name => make_absolute('/foo'))
end
it "should raise Puppet::ResourceError with resource name when Puppet::Error raised" do
expect do
Puppet::Type.type(:file).new(
:name => make_absolute('/foo'),
:source => "puppet:///",
:content => "foo"
)
end.to raise_error(Puppet::ResourceError, /Validation of File\[.*foo.*\]/)
end
it "should raise Puppet::ResourceError with manifest file and line on failure" do
Puppet::Type.type(:file).any_instance.stubs(:file).returns("example.pp")
Puppet::Type.type(:file).any_instance.stubs(:line).returns(42)
expect do
Puppet::Type.type(:file).new(
:name => make_absolute('/foo'),
:source => "puppet:///",
:content => "foo"
)
end.to raise_error(Puppet::ResourceError, /Validation.*example.pp:42/)
end
end
end
describe "when #finish is called on a type" do
let(:post_hook_type) do
Puppet::Type.newtype(:finish_test) do
newparam(:name) { isnamevar }
newparam(:post) do
def post_compile
raise "post_compile hook ran"
end
end
end
end
let(:post_hook_resource) do
post_hook_type.new(:name => 'foo',:post => 'fake_value')
end
it "should call #post_compile on parameters that implement it" do
expect { post_hook_resource.finish }.to raise_error(RuntimeError, "post_compile hook ran")
end
end
it "should have a class method for converting a hash into a Puppet::Resource instance" do
- Puppet::Type.type(:mount).must respond_to(:hash2resource)
+ expect(Puppet::Type.type(:mount)).to respond_to(:hash2resource)
end
describe "when converting a hash to a Puppet::Resource instance" do
before do
@type = Puppet::Type.type(:mount)
end
it "should treat a :title key as the title of the resource" do
- @type.hash2resource(:name => "/foo", :title => "foo").title.should == "foo"
+ expect(@type.hash2resource(:name => "/foo", :title => "foo").title).to eq("foo")
end
it "should use the name from the hash as the title if no explicit title is provided" do
- @type.hash2resource(:name => "foo").title.should == "foo"
+ expect(@type.hash2resource(:name => "foo").title).to eq("foo")
end
it "should use the Resource Type's namevar to determine how to find the name in the hash" do
@type.stubs(:key_attributes).returns([ :myname ])
- @type.hash2resource(:myname => "foo").title.should == "foo"
+ expect(@type.hash2resource(:myname => "foo").title).to eq("foo")
end
[:catalog].each do |attr|
it "should use any provided #{attr}" do
- @type.hash2resource(:name => "foo", attr => "eh").send(attr).should == "eh"
+ expect(@type.hash2resource(:name => "foo", attr => "eh").send(attr)).to eq("eh")
end
end
it "should set all provided parameters on the resource" do
- @type.hash2resource(:name => "foo", :fstype => "boo", :boot => "fee").to_hash.should == {:name => "foo", :fstype => "boo", :boot => "fee"}
+ expect(@type.hash2resource(:name => "foo", :fstype => "boo", :boot => "fee").to_hash).to eq({:name => "foo", :fstype => "boo", :boot => "fee"})
end
it "should not set the title as a parameter on the resource" do
- @type.hash2resource(:name => "foo", :title => "eh")[:title].should be_nil
+ expect(@type.hash2resource(:name => "foo", :title => "eh")[:title]).to be_nil
end
it "should not set the catalog as a parameter on the resource" do
- @type.hash2resource(:name => "foo", :catalog => "eh")[:catalog].should be_nil
+ expect(@type.hash2resource(:name => "foo", :catalog => "eh")[:catalog]).to be_nil
end
it "should treat hash keys equivalently whether provided as strings or symbols" do
resource = @type.hash2resource("name" => "foo", "title" => "eh", "fstype" => "boo")
- resource.title.should == "eh"
- resource[:name].should == "foo"
- resource[:fstype].should == "boo"
+ expect(resource.title).to eq("eh")
+ expect(resource[:name]).to eq("foo")
+ expect(resource[:fstype]).to eq("boo")
end
end
describe "when retrieving current property values" do
before do
@resource = Puppet::Type.type(:mount).new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present)
@resource.property(:ensure).stubs(:retrieve).returns :absent
end
it "should fail if its provider is unsuitable" do
@resource = Puppet::Type.type(:mount).new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present)
@resource.provider.class.expects(:suitable?).returns false
expect { @resource.retrieve_resource }.to raise_error(Puppet::Error)
end
it "should return a Puppet::Resource instance with its type and title set appropriately" do
result = @resource.retrieve_resource
- result.should be_instance_of(Puppet::Resource)
- result.type.should == "Mount"
- result.title.should == "foo"
+ expect(result).to be_instance_of(Puppet::Resource)
+ expect(result.type).to eq("Mount")
+ expect(result.title).to eq("foo")
end
it "should set the name of the returned resource if its own name and title differ" do
@resource[:name] = "myname"
@resource.title = "other name"
- @resource.retrieve_resource[:name].should == "myname"
+ expect(@resource.retrieve_resource[:name]).to eq("myname")
end
it "should provide a value for all set properties" do
values = @resource.retrieve_resource
- [:ensure, :fstype, :pass].each { |property| values[property].should_not be_nil }
+ [:ensure, :fstype, :pass].each { |property| expect(values[property]).not_to be_nil }
end
it "should provide a value for 'ensure' even if no desired value is provided" do
@resource = Puppet::Type.type(:file).new(:path => make_absolute("/my/file/that/can't/exist"))
end
it "should not call retrieve on non-ensure properties if the resource is absent and should consider the property absent" do
@resource.property(:ensure).expects(:retrieve).returns :absent
@resource.property(:fstype).expects(:retrieve).never
- @resource.retrieve_resource[:fstype].should == :absent
+ expect(@resource.retrieve_resource[:fstype]).to eq(:absent)
end
it "should include the result of retrieving each property's current value if the resource is present" do
@resource.property(:ensure).expects(:retrieve).returns :present
@resource.property(:fstype).expects(:retrieve).returns 15
@resource.retrieve_resource[:fstype] == 15
end
end
describe "#to_resource" do
it "should return a Puppet::Resource that includes properties, parameters and tags" do
type_resource = Puppet::Type.type(:mount).new(
:ensure => :present,
:name => "foo",
:fstype => "bar",
:remounts => true
)
type_resource.tags = %w{bar baz}
# If it's not a property it's a parameter
- type_resource.parameters[:remounts].should_not be_a(Puppet::Property)
- type_resource.parameters[:fstype].is_a?(Puppet::Property).should be_true
+ expect(type_resource.parameters[:remounts]).not_to be_a(Puppet::Property)
+ expect(type_resource.parameters[:fstype].is_a?(Puppet::Property)).to be_truthy
type_resource.property(:ensure).expects(:retrieve).returns :present
type_resource.property(:fstype).expects(:retrieve).returns 15
resource = type_resource.to_resource
- resource.should be_a Puppet::Resource
- resource[:fstype].should == 15
- resource[:remounts].should == :true
- resource.tags.should == Puppet::Util::TagSet.new(%w{foo bar baz mount})
+ expect(resource).to be_a Puppet::Resource
+ expect(resource[:fstype]).to eq(15)
+ expect(resource[:remounts]).to eq(:true)
+ expect(resource.tags).to eq(Puppet::Util::TagSet.new(%w{foo bar baz mount}))
end
end
describe ".title_patterns" do
describe "when there's one namevar" do
before do
@type_class = Puppet::Type.type(:notify)
@type_class.stubs(:key_attributes).returns([:one])
end
it "should have a default pattern for when there's one namevar" do
patterns = @type_class.title_patterns
- patterns.length.should == 1
- patterns[0].length.should == 2
+ expect(patterns.length).to eq(1)
+ expect(patterns[0].length).to eq(2)
end
it "should have a regexp that captures the entire string" do
patterns = @type_class.title_patterns
string = "abc\n\tdef"
patterns[0][0] =~ string
- $1.should == "abc\n\tdef"
+ expect($1).to eq("abc\n\tdef")
end
end
end
describe "when in a catalog" do
before do
@catalog = Puppet::Resource::Catalog.new
@container = Puppet::Type.type(:component).new(:name => "container")
@one = Puppet::Type.type(:file).new(:path => make_absolute("/file/one"))
@two = Puppet::Type.type(:file).new(:path => make_absolute("/file/two"))
@catalog.add_resource @container
@catalog.add_resource @one
@catalog.add_resource @two
@catalog.add_edge @container, @one
@catalog.add_edge @container, @two
end
it "should have no parent if there is no in edge" do
- @container.parent.should be_nil
+ expect(@container.parent).to be_nil
end
it "should set its parent to its in edge" do
- @one.parent.ref.should == @container.ref
+ expect(@one.parent.ref).to eq(@container.ref)
end
after do
@catalog.clear(true)
end
end
it "should have a 'stage' metaparam" do
- Puppet::Type.metaparamclass(:stage).should be_instance_of(Class)
+ expect(Puppet::Type.metaparamclass(:stage)).to be_instance_of(Class)
end
describe "#suitable?" do
let(:type) { Puppet::Type.type(:file) }
let(:resource) { type.new :path => tmpfile('suitable') }
let(:provider) { resource.provider }
it "should be suitable if its type doesn't use providers" do
type.stubs(:paramclass).with(:provider).returns nil
- resource.must be_suitable
+ expect(resource).to be_suitable
end
it "should be suitable if it has a provider which is suitable" do
- resource.must be_suitable
+ expect(resource).to be_suitable
end
it "should not be suitable if it has a provider which is not suitable" do
provider.class.stubs(:suitable?).returns false
- resource.should_not be_suitable
+ expect(resource).not_to be_suitable
end
it "should be suitable if it does not have a provider and there is a default provider" do
resource.stubs(:provider).returns nil
- resource.must be_suitable
+ expect(resource).to be_suitable
end
it "should not be suitable if it doesn't have a provider and there is not default provider" do
resource.stubs(:provider).returns nil
type.stubs(:defaultprovider).returns nil
- resource.should_not be_suitable
+ expect(resource).not_to be_suitable
end
end
describe "::instances" do
after :each do Puppet::Type.rmtype(:type_spec_fake_type) end
let :type do
Puppet::Type.newtype(:type_spec_fake_type) do
newparam(:name) do
isnamevar
end
newproperty(:prop1) {}
end
Puppet::Type.type(:type_spec_fake_type)
end
it "should not fail if no suitable providers are found" do
type.provide(:fake1) do
confine :exists => '/no/such/file'
mk_resource_methods
end
- expect { type.instances.should == [] }.to_not raise_error
+ expect { expect(type.instances).to eq([]) }.to_not raise_error
end
context "with a default provider" do
before :each do
type.provide(:default) do
defaultfor :operatingsystem => Facter.value(:operatingsystem)
mk_resource_methods
class << self
attr_accessor :names
end
def self.instance(name)
new(:name => name, :ensure => :present)
end
def self.instances
@instances ||= names.collect { |name| instance(name.to_s) }
end
@names = [:one, :two]
end
end
it "should return only instances of the type" do
- type.instances.should be_all {|x| x.is_a? type }
+ expect(type.instances).to be_all {|x| x.is_a? type }
end
it "should return instances from the default provider" do
- type.instances.map(&:name).should == ["one", "two"]
+ expect(type.instances.map(&:name)).to eq(["one", "two"])
end
it "should return instances from all providers" do
type.provide(:fake1, :parent => :default) { @names = [:three, :four] }
- type.instances.map(&:name).should == ["one", "two", "three", "four"]
+ expect(type.instances.map(&:name)).to eq(["one", "two", "three", "four"])
end
it "should not return instances from unsuitable providers" do
type.provide(:fake1, :parent => :default) do
@names = [:three, :four]
confine :exists => "/no/such/file"
end
- type.instances.map(&:name).should == ["one", "two"]
+ expect(type.instances.map(&:name)).to eq(["one", "two"])
end
end
end
describe "::ensurable?" do
before :each do
class TestEnsurableType < Puppet::Type
def exists?; end
def create; end
def destroy; end
end
end
it "is true if the class has exists?, create, and destroy methods defined" do
- TestEnsurableType.should be_ensurable
+ expect(TestEnsurableType).to be_ensurable
end
it "is false if exists? is not defined" do
TestEnsurableType.class_eval { remove_method(:exists?) }
- TestEnsurableType.should_not be_ensurable
+ expect(TestEnsurableType).not_to be_ensurable
end
it "is false if create is not defined" do
TestEnsurableType.class_eval { remove_method(:create) }
- TestEnsurableType.should_not be_ensurable
+ expect(TestEnsurableType).not_to be_ensurable
end
it "is false if destroy is not defined" do
TestEnsurableType.class_eval { remove_method(:destroy) }
- TestEnsurableType.should_not be_ensurable
+ expect(TestEnsurableType).not_to be_ensurable
end
end
end
describe Puppet::Type::RelationshipMetaparam do
include PuppetSpec::Files
it "should be a subclass of Puppet::Parameter" do
- Puppet::Type::RelationshipMetaparam.superclass.should equal(Puppet::Parameter)
+ expect(Puppet::Type::RelationshipMetaparam.superclass).to equal(Puppet::Parameter)
end
it "should be able to produce a list of subclasses" do
- Puppet::Type::RelationshipMetaparam.should respond_to(:subclasses)
+ expect(Puppet::Type::RelationshipMetaparam).to respond_to(:subclasses)
end
describe "when munging relationships" do
before do
@path = File.expand_path('/foo')
@resource = Puppet::Type.type(:file).new :name => @path
@metaparam = Puppet::Type.metaparamclass(:require).new :resource => @resource
end
it "should accept Puppet::Resource instances" do
ref = Puppet::Resource.new(:file, @path)
- @metaparam.munge(ref)[0].should equal(ref)
+ expect(@metaparam.munge(ref)[0]).to equal(ref)
end
it "should turn any string into a Puppet::Resource" do
- @metaparam.munge("File[/ref]")[0].should be_instance_of(Puppet::Resource)
+ expect(@metaparam.munge("File[/ref]")[0]).to be_instance_of(Puppet::Resource)
end
end
it "should be able to validate relationships" do
- Puppet::Type.metaparamclass(:require).new(:resource => mock("resource")).should respond_to(:validate_relationship)
+ expect(Puppet::Type.metaparamclass(:require).new(:resource => mock("resource"))).to respond_to(:validate_relationship)
end
describe 'if any specified resource is not in the catalog' do
let(:catalog) { mock 'catalog' }
let(:resource) do
stub 'resource',
:catalog => catalog,
:ref => 'resource',
:line= => nil,
- :file= => nil
+ :line => nil,
+ :file= => nil,
+ :file => nil
end
let(:param) { Puppet::Type.metaparamclass(:require).new(:resource => resource, :value => %w{Foo[bar] Class[test]}) }
before do
catalog.expects(:resource).with("Foo[bar]").returns "something"
catalog.expects(:resource).with("Class[Test]").returns nil
end
describe "and the resource doesn't have a file or line number" do
it "raises an error" do
expect { param.validate_relationship }.to raise_error do |error|
- error.should be_a Puppet::ResourceError
- error.message.should match %r[Class\[Test\]]
+ expect(error).to be_a Puppet::ResourceError
+ expect(error.message).to match %r[Class\[Test\]]
end
end
end
describe "and the resource has a file or line number" do
before do
resource.stubs(:line).returns '42'
resource.stubs(:file).returns '/hitchhikers/guide/to/the/galaxy'
end
it "raises an error with context" do
expect { param.validate_relationship }.to raise_error do |error|
- error.should be_a Puppet::ResourceError
- error.message.should match %r[Class\[Test\]]
- error.message.should match %r["in /hitchhikers/guide/to/the/galaxy:42"]
+ expect(error).to be_a Puppet::ResourceError
+ expect(error.message).to match %r[Class\[Test\]]
+ expect(error.message).to match %r[/hitchhikers/guide/to/the/galaxy:42]
end
end
end
end
end
describe Puppet::Type.metaparamclass(:audit) do
include PuppetSpec::Files
before do
@resource = Puppet::Type.type(:file).new :path => make_absolute('/foo')
end
it "should default to being nil" do
- @resource[:audit].should be_nil
+ expect(@resource[:audit]).to be_nil
end
it "should specify all possible properties when asked to audit all properties" do
@resource[:audit] = :all
list = @resource.class.properties.collect { |p| p.name }
- @resource[:audit].should == list
+ expect(@resource[:audit]).to eq(list)
end
it "should accept the string 'all' to specify auditing all possible properties" do
@resource[:audit] = 'all'
list = @resource.class.properties.collect { |p| p.name }
- @resource[:audit].should == list
+ expect(@resource[:audit]).to eq(list)
end
it "should fail if asked to audit an invalid property" do
expect { @resource[:audit] = :foobar }.to raise_error(Puppet::Error)
end
it "should create an attribute instance for each auditable property" do
@resource[:audit] = :mode
- @resource.parameter(:mode).should_not be_nil
+ expect(@resource.parameter(:mode)).not_to be_nil
end
it "should accept properties specified as a string" do
@resource[:audit] = "mode"
- @resource.parameter(:mode).should_not be_nil
+ expect(@resource.parameter(:mode)).not_to be_nil
end
it "should not create attribute instances for parameters, only properties" do
@resource[:audit] = :noop
- @resource.parameter(:noop).should be_nil
+ expect(@resource.parameter(:noop)).to be_nil
end
describe "when generating the uniqueness key" do
it "should include all of the key_attributes in alphabetical order by attribute name" do
Puppet::Type.type(:file).stubs(:key_attributes).returns [:path, :mode, :owner]
Puppet::Type.type(:file).stubs(:title_patterns).returns(
[ [ /(.*)/, [ [:path, lambda{|x| x} ] ] ] ]
)
myfile = make_absolute('/my/file')
res = Puppet::Type.type(:file).new( :title => myfile, :path => myfile, :owner => 'root', :content => 'hello' )
- res.uniqueness_key.should == [ nil, 'root', myfile]
+ expect(res.uniqueness_key).to eq([ nil, 'root', myfile])
end
end
context "type attribute bracket methods" do
after :each do Puppet::Type.rmtype(:attributes) end
let :type do
Puppet::Type.newtype(:attributes) do
newparam(:name) {}
end
end
it "should work with parameters" do
type.newparam(:param) {}
instance = type.new(:name => 'test')
expect { instance[:param] = true }.to_not raise_error
expect { instance["param"] = true }.to_not raise_error
- instance[:param].should == true
- instance["param"].should == true
+ expect(instance[:param]).to eq(true)
+ expect(instance["param"]).to eq(true)
end
it "should work with meta-parameters" do
instance = type.new(:name => 'test')
expect { instance[:noop] = true }.to_not raise_error
expect { instance["noop"] = true }.to_not raise_error
- instance[:noop].should == true
- instance["noop"].should == true
+ expect(instance[:noop]).to eq(true)
+ expect(instance["noop"]).to eq(true)
end
it "should work with properties" do
type.newproperty(:property) {}
instance = type.new(:name => 'test')
expect { instance[:property] = true }.to_not raise_error
expect { instance["property"] = true }.to_not raise_error
- instance.property(:property).must be
- instance.should(:property).must be_true
+ expect(instance.property(:property)).to be
+ expect(instance.should(:property)).to be_truthy
end
it "should handle proprieties correctly" do
# Order of assignment is significant in this test.
props = {}
[:one, :two, :three].each {|prop| type.newproperty(prop) {} }
instance = type.new(:name => "test")
instance[:one] = "boo"
one = instance.property(:one)
- instance.properties.must == [one]
+ expect(instance.properties).to eq [one]
instance[:three] = "rah"
three = instance.property(:three)
- instance.properties.must == [one, three]
+ expect(instance.properties).to eq [one, three]
instance[:two] = "whee"
two = instance.property(:two)
- instance.properties.must == [one, two, three]
+ expect(instance.properties).to eq [one, two, three]
end
it "newattr should handle required features correctly" do
Puppet::Util::Log.level = :debug
type.feature :feature1, "one"
type.feature :feature2, "two"
none = type.newproperty(:none) {}
one = type.newproperty(:one, :required_features => :feature1) {}
two = type.newproperty(:two, :required_features => [:feature1, :feature2]) {}
nope = type.provide(:nope) {}
maybe = type.provide(:maybe) { has_features :feature1 }
yep = type.provide(:yep) { has_features :feature1, :feature2 }
[nope, maybe, yep].each_with_index do |provider, i|
rsrc = type.new(:provider => provider.name, :name => "test#{i}",
:none => "a", :one => "b", :two => "c")
- rsrc.should(:none).must be
+ expect(rsrc.should(:none)).to be
if provider.declared_feature? :feature1
- rsrc.should(:one).must be
+ expect(rsrc.should(:one)).to be
else
- rsrc.should(:one).must_not be
- @logs.find {|l| l.message =~ /not managing attribute one/ }.should be
+ expect(rsrc.should(:one)).to_not be
+ expect(@logs.find {|l| l.message =~ /not managing attribute one/ }).to be
end
if provider.declared_feature? :feature2
- rsrc.should(:two).must be
+ expect(rsrc.should(:two)).to be
else
- rsrc.should(:two).must_not be
- @logs.find {|l| l.message =~ /not managing attribute two/ }.should be
+ expect(rsrc.should(:two)).to_not be
+ expect(@logs.find {|l| l.message =~ /not managing attribute two/ }).to be
end
end
end
end
end
diff --git a/spec/unit/util/autoload_spec.rb b/spec/unit/util/autoload_spec.rb
index ba9c137a8..e630efc73 100755
--- a/spec/unit/util/autoload_spec.rb
+++ b/spec/unit/util/autoload_spec.rb
@@ -1,281 +1,281 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/autoload'
describe Puppet::Util::Autoload do
include PuppetSpec::Files
before do
@autoload = Puppet::Util::Autoload.new("foo", "tmp")
@loaded = {}
@autoload.class.stubs(:loaded).returns(@loaded)
end
describe "when building the search path" do
before :each do
## modulepath/libdir can't be used until after app settings are initialized, so we need to simulate that:
Puppet.settings.expects(:app_defaults_initialized?).returns(true).at_least_once
end
it "should collect all of the lib directories that exist in the current environment's module path" do
dira = dir_containing('dir_a', {
"one" => {},
"two" => { "lib" => {} }
})
dirb = dir_containing('dir_a', {
"one" => {},
"two" => { "lib" => {} }
})
environment = Puppet::Node::Environment.create(:foo, [dira, dirb])
- @autoload.class.module_directories(environment).should == ["#{dira}/two/lib", "#{dirb}/two/lib"]
+ expect(@autoload.class.module_directories(environment)).to eq(["#{dira}/two/lib", "#{dirb}/two/lib"])
end
it "ignores missing module directories" do
environment = Puppet::Node::Environment.create(:foo, [File.expand_path('does/not/exist')])
- @autoload.class.module_directories(environment).should be_empty
+ expect(@autoload.class.module_directories(environment)).to be_empty
end
it "ignores the configured environment when it doesn't exist" do
Puppet[:environment] = 'nonexistent'
Puppet.override({ :environments => Puppet::Environments::Static.new() }) do
- @autoload.class.module_directories(nil).should be_empty
+ expect(@autoload.class.module_directories(nil)).to be_empty
end
end
it "uses the configured environment when no environment is given" do
Puppet[:environment] = 'nonexistent'
Puppet.override({ :environments => Puppet::Environments::Static.new() }) do
- @autoload.class.module_directories(nil).should be_empty
+ expect(@autoload.class.module_directories(nil)).to be_empty
end
end
it "should include the module directories, the Puppet libdir, and all of the Ruby load directories" do
Puppet[:libdir] = '/libdir1'
@autoload.class.expects(:gem_directories).returns %w{/one /two}
@autoload.class.expects(:module_directories).returns %w{/three /four}
- @autoload.class.search_directories(nil).should == %w{/one /two /three /four} + [Puppet[:libdir]] + $LOAD_PATH
+ expect(@autoload.class.search_directories(nil)).to eq(%w{/one /two /three /four} + [Puppet[:libdir]] + $LOAD_PATH)
end
it "does not split the Puppet[:libdir]" do
Puppet[:libdir] = "/libdir1#{File::PATH_SEPARATOR}/libdir2"
- @autoload.class.libdirs.should == [Puppet[:libdir]]
+ expect(@autoload.class.libdirs).to eq([Puppet[:libdir]])
end
end
describe "when loading a file" do
before do
@autoload.class.stubs(:search_directories).returns [make_absolute("/a")]
FileTest.stubs(:directory?).returns true
@time_a = Time.utc(2010, 'jan', 1, 6, 30)
File.stubs(:mtime).returns @time_a
end
[RuntimeError, LoadError, SyntaxError].each do |error|
it "should die with Puppet::Error if a #{error.to_s} exception is thrown" do
Puppet::FileSystem.stubs(:exist?).returns true
Kernel.expects(:load).raises error
- lambda { @autoload.load("foo") }.should raise_error(Puppet::Error)
+ expect { @autoload.load("foo") }.to raise_error(Puppet::Error)
end
end
it "should not raise an error if the file is missing" do
- @autoload.load("foo").should == false
+ expect(@autoload.load("foo")).to eq(false)
end
it "should register loaded files with the autoloader" do
Puppet::FileSystem.stubs(:exist?).returns true
Kernel.stubs(:load)
@autoload.load("myfile")
- @autoload.class.loaded?("tmp/myfile.rb").should be
+ expect(@autoload.class.loaded?("tmp/myfile.rb")).to be
$LOADED_FEATURES.delete("tmp/myfile.rb")
end
it "should be seen by loaded? on the instance using the short name" do
Puppet::FileSystem.stubs(:exist?).returns true
Kernel.stubs(:load)
@autoload.load("myfile")
- @autoload.loaded?("myfile.rb").should be
+ expect(@autoload.loaded?("myfile.rb")).to be
$LOADED_FEATURES.delete("tmp/myfile.rb")
end
it "should register loaded files with the main loaded file list so they are not reloaded by ruby" do
Puppet::FileSystem.stubs(:exist?).returns true
Kernel.stubs(:load)
@autoload.load("myfile")
- $LOADED_FEATURES.should be_include("tmp/myfile.rb")
+ expect($LOADED_FEATURES).to be_include("tmp/myfile.rb")
$LOADED_FEATURES.delete("tmp/myfile.rb")
end
it "should load the first file in the searchpath" do
@autoload.stubs(:search_directories).returns [make_absolute("/a"), make_absolute("/b")]
FileTest.stubs(:directory?).returns true
Puppet::FileSystem.stubs(:exist?).returns true
Kernel.expects(:load).with(make_absolute("/a/tmp/myfile.rb"), optionally(anything))
@autoload.load("myfile")
$LOADED_FEATURES.delete("tmp/myfile.rb")
end
it "should treat equivalent paths to a loaded file as loaded" do
Puppet::FileSystem.stubs(:exist?).returns true
Kernel.stubs(:load)
@autoload.load("myfile")
- @autoload.class.loaded?("tmp/myfile").should be
- @autoload.class.loaded?("tmp/./myfile.rb").should be
- @autoload.class.loaded?("./tmp/myfile.rb").should be
- @autoload.class.loaded?("tmp/../tmp/myfile.rb").should be
+ expect(@autoload.class.loaded?("tmp/myfile")).to be
+ expect(@autoload.class.loaded?("tmp/./myfile.rb")).to be
+ expect(@autoload.class.loaded?("./tmp/myfile.rb")).to be
+ expect(@autoload.class.loaded?("tmp/../tmp/myfile.rb")).to be
$LOADED_FEATURES.delete("tmp/myfile.rb")
end
end
describe "when loading all files" do
before do
@autoload.class.stubs(:search_directories).returns [make_absolute("/a")]
FileTest.stubs(:directory?).returns true
Dir.stubs(:glob).returns [make_absolute("/a/foo/file.rb")]
Puppet::FileSystem.stubs(:exist?).returns true
@time_a = Time.utc(2010, 'jan', 1, 6, 30)
File.stubs(:mtime).returns @time_a
@autoload.class.stubs(:loaded?).returns(false)
end
[RuntimeError, LoadError, SyntaxError].each do |error|
it "should die an if a #{error.to_s} exception is thrown" do
Kernel.expects(:load).raises error
- lambda { @autoload.loadall }.should raise_error(Puppet::Error)
+ expect { @autoload.loadall }.to raise_error(Puppet::Error)
end
end
it "should require the full path to the file" do
Kernel.expects(:load).with(make_absolute("/a/foo/file.rb"), optionally(anything))
@autoload.loadall
end
end
describe "when reloading files" do
before :each do
@file_a = make_absolute("/a/file.rb")
@file_b = make_absolute("/b/file.rb")
@first_time = Time.utc(2010, 'jan', 1, 6, 30)
@second_time = @first_time + 60
end
after :each do
$LOADED_FEATURES.delete("a/file.rb")
$LOADED_FEATURES.delete("b/file.rb")
end
it "#changed? should return true for a file that was not loaded" do
- @autoload.class.changed?(@file_a).should be
+ expect(@autoload.class.changed?(@file_a)).to be
end
it "changes should be seen by changed? on the instance using the short name" do
File.stubs(:mtime).returns(@first_time)
Puppet::FileSystem.stubs(:exist?).returns true
Kernel.stubs(:load)
@autoload.load("myfile")
- @autoload.loaded?("myfile").should be
- @autoload.changed?("myfile").should_not be
+ expect(@autoload.loaded?("myfile")).to be
+ expect(@autoload.changed?("myfile")).not_to be
File.stubs(:mtime).returns(@second_time)
- @autoload.changed?("myfile").should be
+ expect(@autoload.changed?("myfile")).to be
$LOADED_FEATURES.delete("tmp/myfile.rb")
end
describe "in one directory" do
before :each do
@autoload.class.stubs(:search_directories).returns [make_absolute("/a")]
File.expects(:mtime).with(@file_a).returns(@first_time)
@autoload.class.mark_loaded("file", @file_a)
end
it "should reload if mtime changes" do
File.stubs(:mtime).with(@file_a).returns(@first_time + 60)
Puppet::FileSystem.stubs(:exist?).with(@file_a).returns true
Kernel.expects(:load).with(@file_a, optionally(anything))
@autoload.class.reload_changed
end
it "should do nothing if the file is deleted" do
File.stubs(:mtime).with(@file_a).raises(Errno::ENOENT)
Puppet::FileSystem.stubs(:exist?).with(@file_a).returns false
Kernel.expects(:load).never
@autoload.class.reload_changed
end
end
describe "in two directories" do
before :each do
@autoload.class.stubs(:search_directories).returns [make_absolute("/a"), make_absolute("/b")]
end
it "should load b/file when a/file is deleted" do
File.expects(:mtime).with(@file_a).returns(@first_time)
@autoload.class.mark_loaded("file", @file_a)
File.stubs(:mtime).with(@file_a).raises(Errno::ENOENT)
Puppet::FileSystem.stubs(:exist?).with(@file_a).returns false
Puppet::FileSystem.stubs(:exist?).with(@file_b).returns true
File.stubs(:mtime).with(@file_b).returns @first_time
Kernel.expects(:load).with(@file_b, optionally(anything))
@autoload.class.reload_changed
- @autoload.class.send(:loaded)["file"].should == [@file_b, @first_time]
+ expect(@autoload.class.send(:loaded)["file"]).to eq([@file_b, @first_time])
end
it "should load a/file when b/file is loaded and a/file is created" do
File.stubs(:mtime).with(@file_b).returns @first_time
Puppet::FileSystem.stubs(:exist?).with(@file_b).returns true
@autoload.class.mark_loaded("file", @file_b)
File.stubs(:mtime).with(@file_a).returns @first_time
Puppet::FileSystem.stubs(:exist?).with(@file_a).returns true
Kernel.expects(:load).with(@file_a, optionally(anything))
@autoload.class.reload_changed
- @autoload.class.send(:loaded)["file"].should == [@file_a, @first_time]
+ expect(@autoload.class.send(:loaded)["file"]).to eq([@file_a, @first_time])
end
end
end
describe "#cleanpath" do
it "should leave relative paths relative" do
path = "hello/there"
- Puppet::Util::Autoload.cleanpath(path).should == path
+ expect(Puppet::Util::Autoload.cleanpath(path)).to eq(path)
end
describe "on Windows", :if => Puppet.features.microsoft_windows? do
it "should convert c:\ to c:/" do
- Puppet::Util::Autoload.cleanpath('c:\\').should == 'c:/'
+ expect(Puppet::Util::Autoload.cleanpath('c:\\')).to eq('c:/')
end
end
end
describe "#expand" do
it "should expand relative to the autoloader's prefix" do
- @autoload.expand('bar').should == 'tmp/bar'
+ expect(@autoload.expand('bar')).to eq('tmp/bar')
end
end
end
diff --git a/spec/unit/util/backups_spec.rb b/spec/unit/util/backups_spec.rb
index ce7b9b756..140fec0d8 100755
--- a/spec/unit/util/backups_spec.rb
+++ b/spec/unit/util/backups_spec.rb
@@ -1,134 +1,134 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/backups'
describe Puppet::Util::Backups do
include PuppetSpec::Files
let(:bucket) { stub('bucket', :name => "foo") }
let!(:file) do
f = Puppet::Type.type(:file).new(:name => path, :backup => 'foo')
f.stubs(:bucket).returns(bucket)
f
end
describe "when backing up a file" do
let(:path) { make_absolute('/no/such/file') }
it "should noop if the file does not exist" do
file = Puppet::Type.type(:file).new(:name => path)
file.expects(:bucket).never
Puppet::FileSystem.expects(:exist?).with(path).returns false
file.perform_backup
end
it "should succeed silently if self[:backup] is false" do
file = Puppet::Type.type(:file).new(:name => path, :backup => false)
file.expects(:bucket).never
Puppet::FileSystem.expects(:exist?).never
file.perform_backup
end
it "a bucket should be used when provided" do
lstat_path_as(path, 'file')
bucket.expects(:backup).with(path).returns("mysum")
Puppet::FileSystem.expects(:exist?).with(path).returns(true)
file.perform_backup
end
it "should propagate any exceptions encountered when backing up to a filebucket" do
lstat_path_as(path, 'file')
bucket.expects(:backup).raises ArgumentError
Puppet::FileSystem.expects(:exist?).with(path).returns(true)
- lambda { file.perform_backup }.should raise_error(ArgumentError)
+ expect { file.perform_backup }.to raise_error(ArgumentError)
end
describe "and local backup is configured" do
let(:ext) { 'foobkp' }
let(:backup) { path + '.' + ext }
let(:file) { Puppet::Type.type(:file).new(:name => path, :backup => '.'+ext) }
it "should remove any local backup if one exists" do
lstat_path_as(backup, 'file')
Puppet::FileSystem.expects(:unlink).with(backup)
FileUtils.stubs(:cp_r)
Puppet::FileSystem.expects(:exist?).with(path).returns(true)
file.perform_backup
end
it "should fail when the old backup can't be removed" do
lstat_path_as(backup, 'file')
Puppet::FileSystem.expects(:unlink).with(backup).raises ArgumentError
FileUtils.expects(:cp_r).never
Puppet::FileSystem.expects(:exist?).with(path).returns(true)
- lambda { file.perform_backup }.should raise_error(Puppet::Error)
+ expect { file.perform_backup }.to raise_error(Puppet::Error)
end
it "should not try to remove backups that don't exist" do
Puppet::FileSystem.expects(:lstat).with(backup).raises(Errno::ENOENT)
Puppet::FileSystem.expects(:unlink).with(backup).never
FileUtils.stubs(:cp_r)
Puppet::FileSystem.expects(:exist?).with(path).returns(true)
file.perform_backup
end
it "a copy should be created in the local directory" do
FileUtils.expects(:cp_r).with(path, backup, :preserve => true)
Puppet::FileSystem.stubs(:exist?).with(path).returns(true)
- file.perform_backup.should be_true
+ expect(file.perform_backup).to be_truthy
end
it "should propagate exceptions if no backup can be created" do
FileUtils.expects(:cp_r).raises ArgumentError
Puppet::FileSystem.stubs(:exist?).with(path).returns(true)
- lambda { file.perform_backup }.should raise_error(Puppet::Error)
+ expect { file.perform_backup }.to raise_error(Puppet::Error)
end
end
end
describe "when backing up a directory" do
let(:path) { make_absolute('/my/dir') }
let(:filename) { File.join(path, 'file') }
it "a bucket should work when provided" do
File.stubs(:file?).with(filename).returns true
Find.expects(:find).with(path).yields(filename)
bucket.expects(:backup).with(filename).returns true
lstat_path_as(path, 'directory')
Puppet::FileSystem.stubs(:exist?).with(path).returns(true)
Puppet::FileSystem.stubs(:exist?).with(filename).returns(true)
file.perform_backup
end
it "should do nothing when recursing" do
file = Puppet::Type.type(:file).new(:name => path, :backup => 'foo', :recurse => true)
bucket.expects(:backup).never
stub_file = stub('file', :stat => stub('stat', :ftype => 'directory'))
Puppet::FileSystem.stubs(:new).with(path).returns stub_file
Find.expects(:find).never
file.perform_backup
end
end
def lstat_path_as(path, ftype)
Puppet::FileSystem.expects(:lstat).with(path).returns(stub('File::Stat', :ftype => ftype))
end
end
diff --git a/spec/unit/util/checksums_spec.rb b/spec/unit/util/checksums_spec.rb
index e72bb02a8..ace6e7ab0 100755
--- a/spec/unit/util/checksums_spec.rb
+++ b/spec/unit/util/checksums_spec.rb
@@ -1,179 +1,179 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/checksums'
describe Puppet::Util::Checksums do
include PuppetSpec::Files
before do
@summer = Puppet::Util::Checksums
end
content_sums = [:md5, :md5lite, :sha1, :sha1lite, :sha256, :sha256lite]
file_only = [:ctime, :mtime, :none]
content_sums.each do |sumtype|
it "should be able to calculate #{sumtype} sums from strings" do
- @summer.should be_respond_to(sumtype)
+ expect(@summer).to be_respond_to(sumtype)
end
end
content_sums.each do |sumtype|
it "should know the expected length of #{sumtype} sums" do
- @summer.should be_respond_to(sumtype.to_s + "_hex_length")
+ expect(@summer).to be_respond_to(sumtype.to_s + "_hex_length")
end
end
[content_sums, file_only].flatten.each do |sumtype|
it "should be able to calculate #{sumtype} sums from files" do
- @summer.should be_respond_to(sumtype.to_s + "_file")
+ expect(@summer).to be_respond_to(sumtype.to_s + "_file")
end
end
[content_sums, file_only].flatten.each do |sumtype|
it "should be able to calculate #{sumtype} sums from stream" do
- @summer.should be_respond_to(sumtype.to_s + "_stream")
+ expect(@summer).to be_respond_to(sumtype.to_s + "_stream")
end
end
it "should have a method for determining whether a given string is a checksum" do
- @summer.should respond_to(:checksum?)
+ expect(@summer).to respond_to(:checksum?)
end
%w{{md5}asdfasdf {sha1}asdfasdf {ctime}asdasdf {mtime}asdfasdf
{sha256}asdfasdf {sha256lite}asdfasdf}.each do |sum|
it "should consider #{sum} to be a checksum" do
- @summer.should be_checksum(sum)
+ expect(@summer).to be_checksum(sum)
end
end
%w{{nosuchsumthislong}asdfasdf {a}asdfasdf {ctime}}.each do |sum|
it "should not consider #{sum} to be a checksum" do
- @summer.should_not be_checksum(sum)
+ expect(@summer).not_to be_checksum(sum)
end
end
it "should have a method for stripping a sum type from an existing checksum" do
- @summer.sumtype("{md5}asdfasdfa").should == "md5"
+ expect(@summer.sumtype("{md5}asdfasdfa")).to eq("md5")
end
it "should have a method for stripping the data from a checksum" do
- @summer.sumdata("{md5}asdfasdfa").should == "asdfasdfa"
+ expect(@summer.sumdata("{md5}asdfasdfa")).to eq("asdfasdfa")
end
it "should return a nil sumtype if the checksum does not mention a checksum type" do
- @summer.sumtype("asdfasdfa").should be_nil
+ expect(@summer.sumtype("asdfasdfa")).to be_nil
end
{:md5 => Digest::MD5, :sha1 => Digest::SHA1, :sha256 => Digest::SHA256}.each do |sum, klass|
describe("when using #{sum}") do
it "should use #{klass} to calculate string checksums" do
klass.expects(:hexdigest).with("mycontent").returns "whatever"
- @summer.send(sum, "mycontent").should == "whatever"
+ expect(@summer.send(sum, "mycontent")).to eq("whatever")
end
it "should use incremental #{klass} sums to calculate file checksums" do
digest = mock 'digest'
klass.expects(:new).returns digest
file = "/path/to/my/file"
fh = mock 'filehandle'
fh.expects(:read).with(4096).times(3).returns("firstline").then.returns("secondline").then.returns(nil)
#fh.expects(:read).with(512).returns("secondline")
#fh.expects(:read).with(512).returns(nil)
File.expects(:open).with(file, "rb").yields(fh)
digest.expects(:<<).with "firstline"
digest.expects(:<<).with "secondline"
digest.expects(:hexdigest).returns :mydigest
- @summer.send(sum.to_s + "_file", file).should == :mydigest
+ expect(@summer.send(sum.to_s + "_file", file)).to eq(:mydigest)
end
it "should yield #{klass} to the given block to calculate stream checksums" do
digest = mock 'digest'
klass.expects(:new).returns digest
digest.expects(:hexdigest).returns :mydigest
- @summer.send(sum.to_s + "_stream") do |checksum|
- checksum.should == digest
- end.should == :mydigest
+ expect(@summer.send(sum.to_s + "_stream") do |checksum|
+ expect(checksum).to eq(digest)
+ end).to eq(:mydigest)
end
end
end
{:md5lite => Digest::MD5, :sha1lite => Digest::SHA1, :sha256lite => Digest::SHA256}.each do |sum, klass|
describe("when using #{sum}") do
it "should use #{klass} to calculate string checksums from the first 512 characters of the string" do
content = "this is a test" * 100
klass.expects(:hexdigest).with(content[0..511]).returns "whatever"
- @summer.send(sum, content).should == "whatever"
+ expect(@summer.send(sum, content)).to eq("whatever")
end
it "should use #{klass} to calculate a sum from the first 512 characters in the file" do
digest = mock 'digest'
klass.expects(:new).returns digest
file = "/path/to/my/file"
fh = mock 'filehandle'
fh.expects(:read).with(512).returns('my content')
File.expects(:open).with(file, "rb").yields(fh)
digest.expects(:<<).with "my content"
digest.expects(:hexdigest).returns :mydigest
- @summer.send(sum.to_s + "_file", file).should == :mydigest
+ expect(@summer.send(sum.to_s + "_file", file)).to eq(:mydigest)
end
end
end
[:ctime, :mtime].each do |sum|
describe("when using #{sum}") do
it "should use the '#{sum}' on the file to determine the ctime" do
file = "/my/file"
stat = mock 'stat', sum => "mysum"
Puppet::FileSystem.expects(:stat).with(file).returns(stat)
- @summer.send(sum.to_s + "_file", file).should == "mysum"
+ expect(@summer.send(sum.to_s + "_file", file)).to eq("mysum")
end
it "should return nil for streams" do
expectation = stub "expectation"
expectation.expects(:do_something!).at_least_once
- @summer.send(sum.to_s + "_stream"){ |checksum| checksum << "anything" ; expectation.do_something! }.should be_nil
+ expect(@summer.send(sum.to_s + "_stream"){ |checksum| checksum << "anything" ; expectation.do_something! }).to be_nil
end
end
end
describe "when using the none checksum" do
it "should return an empty string" do
- @summer.none_file("/my/file").should == ""
+ expect(@summer.none_file("/my/file")).to eq("")
end
it "should return an empty string for streams" do
expectation = stub "expectation"
expectation.expects(:do_something!).at_least_once
- @summer.none_stream{ |checksum| checksum << "anything" ; expectation.do_something! }.should == ""
+ expect(@summer.none_stream{ |checksum| checksum << "anything" ; expectation.do_something! }).to eq("")
end
end
{:md5 => Digest::MD5, :sha1 => Digest::SHA1}.each do |sum, klass|
describe "when using #{sum}" do
let(:content) { "hello\r\nworld" }
let(:path) do
path = tmpfile("checksum_#{sum}")
File.open(path, 'wb') {|f| f.write(content)}
path
end
it "should preserve nl/cr sequences" do
- @summer.send(sum.to_s + "_file", path).should == klass.hexdigest(content)
+ expect(@summer.send(sum.to_s + "_file", path)).to eq(klass.hexdigest(content))
end
end
end
end
diff --git a/spec/unit/util/colors_spec.rb b/spec/unit/util/colors_spec.rb
index b0f791f82..10231d094 100755
--- a/spec/unit/util/colors_spec.rb
+++ b/spec/unit/util/colors_spec.rb
@@ -1,89 +1,89 @@
#!/usr/bin/env ruby
require 'spec_helper'
describe Puppet::Util::Colors do
include Puppet::Util::Colors
let (:message) { 'a message' }
let (:color) { :black }
let (:subject) { self }
describe ".console_color" do
- it { should respond_to :console_color }
+ it { is_expected.to respond_to :console_color }
it "should generate ANSI escape sequences" do
- subject.console_color(color, message).should == "\e[0;30m#{message}\e[0m"
+ expect(subject.console_color(color, message)).to eq("\e[0;30m#{message}\e[0m")
end
end
describe ".html_color" do
- it { should respond_to :html_color }
+ it { is_expected.to respond_to :html_color }
it "should generate an HTML span element and style attribute" do
- subject.html_color(color, message).should =~ /<span style=\"color: #FFA0A0\">#{message}<\/span>/
+ expect(subject.html_color(color, message)).to match(/<span style=\"color: #FFA0A0\">#{message}<\/span>/)
end
end
describe ".colorize" do
- it { should respond_to :colorize }
+ it { is_expected.to respond_to :colorize }
context "ansicolor supported" do
before :each do
subject.stubs(:console_has_color?).returns(true)
end
it "should colorize console output" do
Puppet[:color] = true
subject.expects(:console_color).with(color, message)
subject.colorize(:black, message)
end
it "should not colorize unknown color schemes" do
Puppet[:color] = :thisisanunknownscheme
- subject.colorize(:black, message).should == message
+ expect(subject.colorize(:black, message)).to eq(message)
end
end
context "ansicolor not supported" do
before :each do
subject.stubs(:console_has_color?).returns(false)
end
it "should not colorize console output" do
Puppet[:color] = true
subject.expects(:console_color).never
- subject.colorize(:black, message).should == message
+ expect(subject.colorize(:black, message)).to eq(message)
end
it "should colorize html output" do
Puppet[:color] = :html
subject.expects(:html_color).with(color, message)
subject.colorize(color, message)
end
end
end
context "on Windows in Ruby 1.x", :if => Puppet.features.microsoft_windows? && RUBY_VERSION =~ /^1./ do
it "should define WideConsole" do
- expect(defined?(Puppet::Util::Colors::WideConsole)).to be_true
+ expect(defined?(Puppet::Util::Colors::WideConsole)).to be_truthy
end
it "should define WideIO" do
- expect(defined?(Puppet::Util::Colors::WideIO)).to be_true
+ expect(defined?(Puppet::Util::Colors::WideIO)).to be_truthy
end
end
context "on Windows in Ruby 2.x", :if => Puppet.features.microsoft_windows? && RUBY_VERSION =~ /^2./ do
it "should not define WideConsole" do
- expect(defined?(Puppet::Util::Colors::WideConsole)).to be_false
+ expect(defined?(Puppet::Util::Colors::WideConsole)).to be_falsey
end
it "should not define WideIO" do
- expect(defined?(Puppet::Util::Colors::WideIO)).to be_false
+ expect(defined?(Puppet::Util::Colors::WideIO)).to be_falsey
end
end
end
diff --git a/spec/unit/util/command_line_spec.rb b/spec/unit/util/command_line_spec.rb
index 37a77b4e6..212babcb2 100755
--- a/spec/unit/util/command_line_spec.rb
+++ b/spec/unit/util/command_line_spec.rb
@@ -1,168 +1,168 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/face'
require 'puppet/util/command_line'
describe Puppet::Util::CommandLine do
include PuppetSpec::Files
context "#initialize" do
it "should pull off the first argument if it looks like a subcommand" do
command_line = Puppet::Util::CommandLine.new("puppet", %w{ client --help whatever.pp })
- command_line.subcommand_name.should == "client"
- command_line.args.should == %w{ --help whatever.pp }
+ expect(command_line.subcommand_name).to eq("client")
+ expect(command_line.args).to eq(%w{ --help whatever.pp })
end
it "should return nil if the first argument looks like a .pp file" do
command_line = Puppet::Util::CommandLine.new("puppet", %w{ whatever.pp })
- command_line.subcommand_name.should == nil
- command_line.args.should == %w{ whatever.pp }
+ expect(command_line.subcommand_name).to eq(nil)
+ expect(command_line.args).to eq(%w{ whatever.pp })
end
it "should return nil if the first argument looks like a flag" do
command_line = Puppet::Util::CommandLine.new("puppet", %w{ --debug })
- command_line.subcommand_name.should == nil
- command_line.args.should == %w{ --debug }
+ expect(command_line.subcommand_name).to eq(nil)
+ expect(command_line.args).to eq(%w{ --debug })
end
it "should return nil if the first argument is -" do
command_line = Puppet::Util::CommandLine.new("puppet", %w{ - })
- command_line.subcommand_name.should == nil
- command_line.args.should == %w{ - }
+ expect(command_line.subcommand_name).to eq(nil)
+ expect(command_line.args).to eq(%w{ - })
end
it "should return nil if the first argument is --help" do
command_line = Puppet::Util::CommandLine.new("puppet", %w{ --help })
- command_line.subcommand_name.should == nil
+ expect(command_line.subcommand_name).to eq(nil)
end
it "should return nil if there are no arguments" do
command_line = Puppet::Util::CommandLine.new("puppet", [])
- command_line.subcommand_name.should == nil
- command_line.args.should == []
+ expect(command_line.subcommand_name).to eq(nil)
+ expect(command_line.args).to eq([])
end
it "should pick up changes to the array of arguments" do
args = %w{subcommand}
command_line = Puppet::Util::CommandLine.new("puppet", args)
args[0] = 'different_subcommand'
- command_line.subcommand_name.should == 'different_subcommand'
+ expect(command_line.subcommand_name).to eq('different_subcommand')
end
end
context "#execute" do
%w{--version -V}.each do |arg|
it "should print the version and exit if #{arg} is given" do
expect do
described_class.new("puppet", [arg]).execute
end.to have_printed(/^#{Regexp.escape(Puppet.version)}$/)
end
end
end
describe "when dealing with puppet commands" do
it "should return the executable name if it is not puppet" do
command_line = Puppet::Util::CommandLine.new("puppetmasterd", [])
- command_line.subcommand_name.should == "puppetmasterd"
+ expect(command_line.subcommand_name).to eq("puppetmasterd")
end
describe "when the subcommand is not implemented" do
it "should find and invoke an executable with a hyphenated name" do
commandline = Puppet::Util::CommandLine.new("puppet", ['whatever', 'argument'])
Puppet::Util.expects(:which).with('puppet-whatever').
returns('/dev/null/puppet-whatever')
Kernel.expects(:exec).with('/dev/null/puppet-whatever', 'argument')
commandline.execute
end
describe "and an external implementation cannot be found" do
before :each do
Puppet::Util::CommandLine::UnknownSubcommand.any_instance.stubs(:console_has_color?).returns false
end
it "should abort and show the usage message" do
Puppet::Util.expects(:which).with('puppet-whatever').returns(nil)
commandline = Puppet::Util::CommandLine.new("puppet", ['whatever', 'argument'])
commandline.expects(:exec).never
expect {
commandline.execute
}.to have_printed(/Unknown Puppet subcommand 'whatever'/).and_exit_with(1)
end
it "should abort and show the help message" do
Puppet::Util.expects(:which).with('puppet-whatever').returns(nil)
commandline = Puppet::Util::CommandLine.new("puppet", ['whatever', 'argument'])
commandline.expects(:exec).never
expect {
commandline.execute
}.to have_printed(/See 'puppet help' for help on available puppet subcommands/).and_exit_with(1)
end
%w{--version -V}.each do |arg|
it "should abort and display #{arg} information" do
Puppet::Util.expects(:which).with('puppet-whatever').returns(nil)
commandline = Puppet::Util::CommandLine.new("puppet", ['whatever', arg])
commandline.expects(:exec).never
expect {
commandline.execute
}.to have_printed(%r[^#{Regexp.escape(Puppet.version)}$]).and_exit_with(1)
end
end
end
end
describe 'when setting process priority' do
let(:command_line) do
Puppet::Util::CommandLine.new("puppet", %w{ agent })
end
before :each do
Puppet::Util::CommandLine::ApplicationSubcommand.any_instance.stubs(:run)
end
it 'should never set priority by default' do
Process.expects(:setpriority).never
command_line.execute
end
it 'should lower the process priority if one has been specified' do
Puppet[:priority] = 10
Process.expects(:setpriority).with(0, Process.pid, 10)
command_line.execute
end
it 'should warn if trying to raise priority, but not privileged user' do
Puppet[:priority] = -10
Process.expects(:setpriority).raises(Errno::EACCES, 'Permission denied')
Puppet.expects(:warning).with("Failed to set process priority to '-10'")
command_line.execute
end
it "should warn if the platform doesn't support `Process.setpriority`" do
Puppet[:priority] = 15
Process.expects(:setpriority).raises(NotImplementedError, 'NotImplementedError: setpriority() function is unimplemented on this machine')
Puppet.expects(:warning).with("Failed to set process priority to '15'")
command_line.execute
end
end
end
end
diff --git a/spec/unit/util/command_line_utils/puppet_option_parser_spec.rb b/spec/unit/util/command_line_utils/puppet_option_parser_spec.rb
index 676da54f3..c83655816 100644
--- a/spec/unit/util/command_line_utils/puppet_option_parser_spec.rb
+++ b/spec/unit/util/command_line_utils/puppet_option_parser_spec.rb
@@ -1,129 +1,129 @@
require 'spec_helper'
require 'puppet/util/command_line/puppet_option_parser'
describe Puppet::Util::CommandLine::PuppetOptionParser do
let(:option_parser) { described_class.new }
describe "an option with a value" do
it "parses a 'long' option with a value" do
parses(
:option => ["--angry", "Angry", :REQUIRED],
:from_arguments => ["--angry", "foo"],
:expects => "foo"
)
end
it "parses a 'short' option with a value" do
parses(
:option => ["--angry", "-a", "Angry", :REQUIRED],
:from_arguments => ["-a", "foo"],
:expects => "foo"
)
end
it "overrides a previous argument with a later one" do
parses(
:option => ["--later", "Later", :REQUIRED],
:from_arguments => ["--later", "tomorrow", "--later", "morgen"],
:expects => "morgen"
)
end
end
describe "an option without a value" do
it "parses a 'long' option" do
parses(
:option => ["--angry", "Angry", :NONE],
:from_arguments => ["--angry"],
:expects => true
)
end
it "parses a 'short' option" do
parses(
:option => ["--angry", "-a", "Angry", :NONE],
:from_arguments => ["-a"],
:expects => true
)
end
it "supports the '--no-blah' syntax" do
parses(
:option => ["--[no-]rage", "Rage", :NONE],
:from_arguments => ["--no-rage"],
:expects => false
)
end
it "overrides a previous argument with a later one" do
parses(
:option => ["--[no-]rage", "Rage", :NONE],
:from_arguments => ["--rage", "--no-rage"],
:expects => false
)
end
end
it "does not accept an unknown option specification" do
expect {
option_parser.on("not", "enough")
}.to raise_error(ArgumentError, /this method only takes 3 or 4 arguments/)
end
it "does not modify the original argument array" do
option_parser.on("--foo", "Foo", :NONE) { |val| }
args = ["--foo"]
option_parser.parse(args)
- args.length.should == 1
+ expect(args.length).to eq(1)
end
# The ruby stdlib OptionParser has an awesome "feature" that you cannot disable, whereby if
# it sees a short option that you haven't specifically registered with it (e.g., "-r"), it
# will automatically attempt to expand it out to whatever long options that you might have
# registered. Since we need to do our option parsing in two passes (one pass against only
# the global/puppet-wide settings definitions, and then a second pass that includes the
# application or face settings--because we can't load the app/face until we've determined
# the libdir), it is entirely possible that we intend to define our "short" option as part
# of the second pass. Therefore, if the option parser attempts to expand it out into a
# long option during the first pass, terrible things will happen.
#
# A long story short: we need to have the ability to control this kind of behavior in our
# option parser, and this test simply affirms that we do.
it "does not try to expand short options that weren't explicitly registered" do
[
["--ridiculous", "This is ridiculous", :REQUIRED],
["--rage-inducing", "This is rage-inducing", :REQUIRED]
].each do |option|
option_parser.on(*option) {}
end
expect { option_parser.parse(["-r"]) }.to raise_error(Puppet::Util::CommandLine::PuppetOptionError)
end
it "respects :ignore_invalid_options" do
option_parser.ignore_invalid_options = true
expect { option_parser.parse(["--unknown-option"]) }.not_to raise_error
end
it "raises if there is an invalid option and :ignore_invalid_options is not set" do
expect { option_parser.parse(["--unknown-option"]) }.to raise_error(Puppet::Util::CommandLine::PuppetOptionError)
end
def parses(option_case)
option = option_case[:option]
expected_value = option_case[:expects]
arguments = option_case[:from_arguments]
seen_value = nil
option_parser.on(*option) do |val|
seen_value = val
end
option_parser.parse(arguments)
- seen_value.should == expected_value
+ expect(seen_value).to eq(expected_value)
end
end
diff --git a/spec/unit/util/constant_inflector_spec.rb b/spec/unit/util/constant_inflector_spec.rb
index b4492a6d9..72387214e 100755
--- a/spec/unit/util/constant_inflector_spec.rb
+++ b/spec/unit/util/constant_inflector_spec.rb
@@ -1,56 +1,56 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/constant_inflector'
describe Puppet::Util::ConstantInflector, "when converting file names to constants" do
it "should capitalize terms" do
- subject.file2constant("file").should == "File"
+ expect(subject.file2constant("file")).to eq("File")
end
it "should switch all '/' characters to double colons" do
- subject.file2constant("file/other").should == "File::Other"
+ expect(subject.file2constant("file/other")).to eq("File::Other")
end
it "should remove underscores and capitalize the proceeding letter" do
- subject.file2constant("file_other").should == "FileOther"
+ expect(subject.file2constant("file_other")).to eq("FileOther")
end
it "should correctly replace as many underscores as exist in the file name" do
- subject.file2constant("two_under_scores/with_some_more_underscores").should == "TwoUnderScores::WithSomeMoreUnderscores"
+ expect(subject.file2constant("two_under_scores/with_some_more_underscores")).to eq("TwoUnderScores::WithSomeMoreUnderscores")
end
it "should collapse multiple underscores" do
- subject.file2constant("many___scores").should == "ManyScores"
+ expect(subject.file2constant("many___scores")).to eq("ManyScores")
end
it "should correctly handle file names deeper than two directories" do
- subject.file2constant("one_two/three_four/five_six").should == "OneTwo::ThreeFour::FiveSix"
+ expect(subject.file2constant("one_two/three_four/five_six")).to eq("OneTwo::ThreeFour::FiveSix")
end
end
describe Puppet::Util::ConstantInflector, "when converting constnats to file names" do
it "should convert them to a string if necessary" do
- subject.constant2file(Puppet::Util::ConstantInflector).should be_instance_of(String)
+ expect(subject.constant2file(Puppet::Util::ConstantInflector)).to be_instance_of(String)
end
it "should accept string inputs" do
- subject.constant2file("Puppet::Util::ConstantInflector").should be_instance_of(String)
+ expect(subject.constant2file("Puppet::Util::ConstantInflector")).to be_instance_of(String)
end
it "should downcase all terms" do
- subject.constant2file("Puppet").should == "puppet"
+ expect(subject.constant2file("Puppet")).to eq("puppet")
end
it "should convert '::' to '/'" do
- subject.constant2file("Puppet::Util::Constant").should == "puppet/util/constant"
+ expect(subject.constant2file("Puppet::Util::Constant")).to eq("puppet/util/constant")
end
it "should convert mid-word capitalization to an underscore" do
- subject.constant2file("OneTwo::ThreeFour").should == "one_two/three_four"
+ expect(subject.constant2file("OneTwo::ThreeFour")).to eq("one_two/three_four")
end
it "should correctly handle constants with more than two parts" do
- subject.constant2file("OneTwoThree::FourFiveSixSeven").should == "one_two_three/four_five_six_seven"
+ expect(subject.constant2file("OneTwoThree::FourFiveSixSeven")).to eq("one_two_three/four_five_six_seven")
end
end
diff --git a/spec/unit/util/diff_spec.rb b/spec/unit/util/diff_spec.rb
index 6bf40948b..80f4c1ccc 100755
--- a/spec/unit/util/diff_spec.rb
+++ b/spec/unit/util/diff_spec.rb
@@ -1,39 +1,39 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/diff'
require 'puppet/util/execution'
describe Puppet::Util::Diff do
describe ".diff" do
it "should execute the diff command with arguments" do
Puppet[:diff] = 'foo'
Puppet[:diff_args] = 'bar'
Puppet::Util::Execution.expects(:execute).with(['foo', 'bar', 'a', 'b'], {:failonfail => false, :combine => false}).returns('baz')
- subject.diff('a', 'b').should == 'baz'
+ expect(subject.diff('a', 'b')).to eq('baz')
end
it "should execute the diff command with multiple arguments" do
Puppet[:diff] = 'foo'
Puppet[:diff_args] = 'bar qux'
Puppet::Util::Execution.expects(:execute).with(['foo', 'bar', 'qux', 'a', 'b'], anything).returns('baz')
- subject.diff('a', 'b').should == 'baz'
+ expect(subject.diff('a', 'b')).to eq('baz')
end
it "should omit diff arguments if none are specified" do
Puppet[:diff] = 'foo'
Puppet[:diff_args] = ''
Puppet::Util::Execution.expects(:execute).with(['foo', 'a', 'b'], {:failonfail => false, :combine => false}).returns('baz')
- subject.diff('a', 'b').should == 'baz'
+ expect(subject.diff('a', 'b')).to eq('baz')
end
it "should return empty string if the diff command is empty" do
Puppet[:diff] = ''
Puppet::Util::Execution.expects(:execute).never
- subject.diff('a', 'b').should == ''
+ expect(subject.diff('a', 'b')).to eq('')
end
end
end
diff --git a/spec/unit/util/errors_spec.rb b/spec/unit/util/errors_spec.rb
index 1e1782275..1f904bc00 100755
--- a/spec/unit/util/errors_spec.rb
+++ b/spec/unit/util/errors_spec.rb
@@ -1,37 +1,37 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/errors'
class ErrorTester
include Puppet::Util::Errors
attr_accessor :line, :file
end
describe Puppet::Util::Errors do
before do
@tester = ErrorTester.new
end
it "should provide a 'fail' method" do
- @tester.should respond_to(:fail)
+ expect(@tester).to respond_to(:fail)
end
it "should provide a 'devfail' method" do
- @tester.should respond_to(:devfail)
+ expect(@tester).to respond_to(:devfail)
end
it "should raise any provided error when failing" do
- lambda { @tester.fail(Puppet::ParseError, "stuff") }.should raise_error(Puppet::ParseError)
+ expect { @tester.fail(Puppet::ParseError, "stuff") }.to raise_error(Puppet::ParseError)
end
it "should default to Puppet::Error when failing" do
- lambda { @tester.fail("stuff") }.should raise_error(Puppet::Error)
+ expect { @tester.fail("stuff") }.to raise_error(Puppet::Error)
end
it "should have a method for converting error context into a string" do
@tester.file = "/my/file"
@tester.line = 50
- @tester.error_context.should == " at /my/file:50"
+ expect(@tester.error_context).to eq(" at /my/file:50")
end
end
diff --git a/spec/unit/util/execution_spec.rb b/spec/unit/util/execution_spec.rb
index 9e3111ac3..de5c4a285 100755
--- a/spec/unit/util/execution_spec.rb
+++ b/spec/unit/util/execution_spec.rb
@@ -1,675 +1,675 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/file_system/uniquefile'
describe Puppet::Util::Execution do
include Puppet::Util::Execution
# utility methods to help us test some private methods without being quite so verbose
def call_exec_posix(command, arguments, stdin, stdout, stderr)
Puppet::Util::Execution.send(:execute_posix, command, arguments, stdin, stdout, stderr)
end
def call_exec_windows(command, arguments, stdin, stdout, stderr)
Puppet::Util::Execution.send(:execute_windows, command, arguments, stdin, stdout, stderr)
end
describe "execution methods" do
let(:pid) { 5501 }
let(:process_handle) { 0xDEADBEEF }
let(:thread_handle) { 0xCAFEBEEF }
let(:proc_info_stub) { stub 'processinfo', :process_handle => process_handle, :thread_handle => thread_handle, :process_id => pid}
let(:null_file) { Puppet.features.microsoft_windows? ? 'NUL' : '/dev/null' }
def stub_process_wait(exitstatus)
if Puppet.features.microsoft_windows?
Puppet::Util::Windows::Process.stubs(:wait_process).with(process_handle).returns(exitstatus)
FFI::WIN32.stubs(:CloseHandle).with(process_handle)
FFI::WIN32.stubs(:CloseHandle).with(thread_handle)
else
Process.stubs(:waitpid2).with(pid).returns([pid, stub('child_status', :exitstatus => exitstatus)])
end
end
describe "#execute_posix (stubs)", :unless => Puppet.features.microsoft_windows? do
before :each do
# Most of the things this method does are bad to do during specs. :/
Kernel.stubs(:fork).returns(pid).yields
Process.stubs(:setsid)
Kernel.stubs(:exec)
Puppet::Util::SUIDManager.stubs(:change_user)
Puppet::Util::SUIDManager.stubs(:change_group)
# ensure that we don't really close anything!
(0..256).each {|n| IO.stubs(:new) }
$stdin.stubs(:reopen)
$stdout.stubs(:reopen)
$stderr.stubs(:reopen)
@stdin = File.open(null_file, 'r')
@stdout = Puppet::FileSystem::Uniquefile.new('stdout')
@stderr = File.open(null_file, 'w')
# there is a danger here that ENV will be modified by exec_posix. Normally it would only affect the ENV
# of a forked process, but here, we're stubbing Kernel.fork, so the method has the ability to override the
# "real" ENV. To guard against this, we'll capture a snapshot of ENV before each test.
@saved_env = ENV.to_hash
# Now, we're going to effectively "mock" the magic ruby 'ENV' variable by creating a local definition of it
# inside of the module we're testing.
Puppet::Util::Execution::ENV = {}
end
after :each do
# And here we remove our "mock" version of 'ENV', which will allow us to validate that the real ENV has been
# left unharmed.
Puppet::Util::Execution.send(:remove_const, :ENV)
# capture the current environment and make sure it's the same as it was before the test
cur_env = ENV.to_hash
# we will get some fairly useless output if we just use the raw == operator on the hashes here, so we'll
# be a bit more explicit and laborious in the name of making the error more useful...
- @saved_env.each_pair { |key,val| cur_env[key].should == val }
- (cur_env.keys - @saved_env.keys).should == []
+ @saved_env.each_pair { |key,val| expect(cur_env[key]).to eq(val) }
+ expect(cur_env.keys - @saved_env.keys).to eq([])
end
it "should fork a child process to execute the command" do
Kernel.expects(:fork).returns(pid).yields
Kernel.expects(:exec).with('test command')
call_exec_posix('test command', {}, @stdin, @stdout, @stderr)
end
it "should start a new session group" do
Process.expects(:setsid)
call_exec_posix('test command', {}, @stdin, @stdout, @stderr)
end
it "should permanently change to the correct user and group if specified" do
Puppet::Util::SUIDManager.expects(:change_group).with(55, true)
Puppet::Util::SUIDManager.expects(:change_user).with(50, true)
call_exec_posix('test command', {:uid => 50, :gid => 55}, @stdin, @stdout, @stderr)
end
it "should exit failure if there is a problem execing the command" do
Kernel.expects(:exec).with('test command').raises("failed to execute!")
Puppet::Util::Execution.stubs(:puts)
Puppet::Util::Execution.expects(:exit!).with(1)
call_exec_posix('test command', {}, @stdin, @stdout, @stderr)
end
it "should properly execute commands specified as arrays" do
Kernel.expects(:exec).with('test command', 'with', 'arguments')
call_exec_posix(['test command', 'with', 'arguments'], {:uid => 50, :gid => 55}, @stdin, @stdout, @stderr)
end
it "should properly execute string commands with embedded newlines" do
Kernel.expects(:exec).with("/bin/echo 'foo' ; \n /bin/echo 'bar' ;")
call_exec_posix("/bin/echo 'foo' ; \n /bin/echo 'bar' ;", {:uid => 50, :gid => 55}, @stdin, @stdout, @stderr)
end
it "should return the pid of the child process" do
- call_exec_posix('test command', {}, @stdin, @stdout, @stderr).should == pid
+ expect(call_exec_posix('test command', {}, @stdin, @stdout, @stderr)).to eq(pid)
end
end
describe "#execute_windows (stubs)", :if => Puppet.features.microsoft_windows? do
before :each do
Process.stubs(:create).returns(proc_info_stub)
stub_process_wait(0)
@stdin = File.open(null_file, 'r')
@stdout = Puppet::FileSystem::Uniquefile.new('stdout')
@stderr = File.open(null_file, 'w')
end
it "should create a new process for the command" do
Process.expects(:create).with(
:command_line => "test command",
:startup_info => {:stdin => @stdin, :stdout => @stdout, :stderr => @stderr},
:close_handles => false
).returns(proc_info_stub)
call_exec_windows('test command', {}, @stdin, @stdout, @stderr)
end
it "should return the process info of the child process" do
- call_exec_windows('test command', {}, @stdin, @stdout, @stderr).should == proc_info_stub
+ expect(call_exec_windows('test command', {}, @stdin, @stdout, @stderr)).to eq(proc_info_stub)
end
it "should quote arguments containing spaces if command is specified as an array" do
Process.expects(:create).with do |args|
args[:command_line] == '"test command" with some "arguments \"with spaces"'
end.returns(proc_info_stub)
call_exec_windows(['test command', 'with', 'some', 'arguments "with spaces'], {}, @stdin, @stdout, @stderr)
end
end
describe "#execute (stubs)" do
before :each do
stub_process_wait(0)
end
describe "when an execution stub is specified" do
before :each do
Puppet::Util::ExecutionStub.set do |command,args,stdin,stdout,stderr|
"execution stub output"
end
end
it "should call the block on the stub" do
- Puppet::Util::Execution.execute("/usr/bin/run_my_execute_stub").should == "execution stub output"
+ expect(Puppet::Util::Execution.execute("/usr/bin/run_my_execute_stub")).to eq("execution stub output")
end
it "should not actually execute anything" do
Puppet::Util::Execution.expects(:execute_posix).never
Puppet::Util::Execution.expects(:execute_windows).never
Puppet::Util::Execution.execute("/usr/bin/run_my_execute_stub")
end
end
describe "when setting up input and output files" do
include PuppetSpec::Files
let(:executor) { Puppet.features.microsoft_windows? ? 'execute_windows' : 'execute_posix' }
let(:rval) { Puppet.features.microsoft_windows? ? proc_info_stub : pid }
before :each do
Puppet::Util::Execution.stubs(:wait_for_output)
end
it "should set stdin to the stdinfile if specified" do
input = tmpfile('stdin')
FileUtils.touch(input)
Puppet::Util::Execution.expects(executor).with do |_,_,stdin,_,_|
stdin.path == input
end.returns(rval)
Puppet::Util::Execution.execute('test command', :stdinfile => input)
end
it "should set stdin to the null file if not specified" do
Puppet::Util::Execution.expects(executor).with do |_,_,stdin,_,_|
stdin.path == null_file
end.returns(rval)
Puppet::Util::Execution.execute('test command')
end
describe "when squelch is set" do
it "should set stdout and stderr to the null file" do
Puppet::Util::Execution.expects(executor).with do |_,_,_,stdout,stderr|
stdout.path == null_file and stderr.path == null_file
end.returns(rval)
Puppet::Util::Execution.execute('test command', :squelch => true)
end
end
describe "when squelch is not set" do
it "should set stdout to a temporary output file" do
outfile = Puppet::FileSystem::Uniquefile.new('stdout')
Puppet::FileSystem::Uniquefile.stubs(:new).returns(outfile)
Puppet::Util::Execution.expects(executor).with do |_,_,_,stdout,_|
stdout.path == outfile.path
end.returns(rval)
Puppet::Util::Execution.execute('test command', :squelch => false)
end
it "should set stderr to the same file as stdout if combine is true" do
outfile = Puppet::FileSystem::Uniquefile.new('stdout')
Puppet::FileSystem::Uniquefile.stubs(:new).returns(outfile)
Puppet::Util::Execution.expects(executor).with do |_,_,_,stdout,stderr|
stdout.path == outfile.path and stderr.path == outfile.path
end.returns(rval)
Puppet::Util::Execution.execute('test command', :squelch => false, :combine => true)
end
it "should set stderr to the null device if combine is false" do
outfile = Puppet::FileSystem::Uniquefile.new('stdout')
Puppet::FileSystem::Uniquefile.stubs(:new).returns(outfile)
Puppet::Util::Execution.expects(executor).with do |_,_,_,stdout,stderr|
stdout.path == outfile.path and stderr.path == null_file
end.returns(rval)
Puppet::Util::Execution.execute('test command', :squelch => false, :combine => false)
end
it "should combine stdout and stderr if combine is true" do
outfile = Puppet::FileSystem::Uniquefile.new('stdout')
Puppet::FileSystem::Uniquefile.stubs(:new).returns(outfile)
Puppet::Util::Execution.expects(executor).with do |_,_,_,stdout,stderr|
stdout.path == outfile.path and stderr.path == outfile.path
end.returns(rval)
Puppet::Util::Execution.execute('test command', :combine => true)
end
it "should default combine to true when no options are specified" do
outfile = Puppet::FileSystem::Uniquefile.new('stdout')
Puppet::FileSystem::Uniquefile.stubs(:new).returns(outfile)
Puppet::Util::Execution.expects(executor).with do |_,_,_,stdout,stderr|
stdout.path == outfile.path and stderr.path == outfile.path
end.returns(rval)
Puppet::Util::Execution.execute('test command')
end
it "should default combine to false when options are specified, but combine is not" do
outfile = Puppet::FileSystem::Uniquefile.new('stdout')
Puppet::FileSystem::Uniquefile.stubs(:new).returns(outfile)
Puppet::Util::Execution.expects(executor).with do |_,_,_,stdout,stderr|
stdout.path == outfile.path and stderr.path == null_file
end.returns(rval)
Puppet::Util::Execution.execute('test command', :failonfail => false)
end
it "should default combine to false when an empty hash of options is specified" do
outfile = Puppet::FileSystem::Uniquefile.new('stdout')
Puppet::FileSystem::Uniquefile.stubs(:new).returns(outfile)
Puppet::Util::Execution.expects(executor).with do |_,_,_,stdout,stderr|
stdout.path == outfile.path and stderr.path == null_file
end.returns(rval)
Puppet::Util::Execution.execute('test command', {})
end
end
end
describe "on Windows", :if => Puppet.features.microsoft_windows? do
it "should always close the process and thread handles" do
Puppet::Util::Execution.stubs(:execute_windows).returns(proc_info_stub)
Puppet::Util::Windows::Process.expects(:wait_process).with(process_handle).raises('whatever')
FFI::WIN32.expects(:CloseHandle).with(thread_handle)
FFI::WIN32.expects(:CloseHandle).with(process_handle)
expect { Puppet::Util::Execution.execute('test command') }.to raise_error(RuntimeError)
end
it "should return the correct exit status even when exit status is greater than 256" do
real_exit_status = 3010
Puppet::Util::Execution.stubs(:execute_windows).returns(proc_info_stub)
stub_process_wait(real_exit_status)
$CHILD_STATUS.stubs(:exitstatus).returns(real_exit_status % 256) # The exitstatus is changed to be mod 256 so that ruby can fit it into 8 bits.
- Puppet::Util::Execution.execute('test command', :failonfail => false).exitstatus.should == real_exit_status
+ expect(Puppet::Util::Execution.execute('test command', :failonfail => false).exitstatus).to eq(real_exit_status)
end
end
end
describe "#execute (posix locale)", :unless => Puppet.features.microsoft_windows? do
before :each do
# there is a danger here that ENV will be modified by exec_posix. Normally it would only affect the ENV
# of a forked process, but, in some of the previous tests in this file we're stubbing Kernel.fork., which could
# allow the method to override the "real" ENV. This shouldn't be a problem for these tests because they are
# not stubbing Kernel.fork, but, better safe than sorry... so, to guard against this, we'll capture a snapshot
# of ENV before each test.
@saved_env = ENV.to_hash
end
after :each do
# capture the current environment and make sure it's the same as it was before the test
cur_env = ENV.to_hash
# we will get some fairly useless output if we just use the raw == operator on the hashes here, so we'll
# be a bit more explicit and laborious in the name of making the error more useful...
- @saved_env.each_pair { |key,val| cur_env[key].should == val }
- (cur_env.keys - @saved_env.keys).should == []
+ @saved_env.each_pair { |key,val| expect(cur_env[key]).to eq(val) }
+ expect(cur_env.keys - @saved_env.keys).to eq([])
end
# build up a printf-style string that contains a command to get the value of an environment variable
# from the operating system. We can substitute into this with the names of the desired environment variables later.
get_env_var_cmd = 'echo $%s'
# a sentinel value that we can use to emulate what locale environment variables might be set to on an international
# system.
lang_sentinel_value = "en_US.UTF-8"
# a temporary hash that contains sentinel values for each of the locale environment variables that we override in
# "execute"
locale_sentinel_env = {}
Puppet::Util::POSIX::LOCALE_ENV_VARS.each { |var| locale_sentinel_env[var] = lang_sentinel_value }
it "should override the locale environment variables when :override_locale is not set (defaults to true)" do
# temporarily override the locale environment vars with a sentinel value, so that we can confirm that
# execute is actually setting them.
Puppet::Util.withenv(locale_sentinel_env) do
Puppet::Util::POSIX::LOCALE_ENV_VARS.each do |var|
# we expect that all of the POSIX vars will have been cleared except for LANG and LC_ALL
expected_value = (['LANG', 'LC_ALL'].include?(var)) ? "C" : ""
- Puppet::Util::Execution.execute(get_env_var_cmd % var).strip.should == expected_value
+ expect(Puppet::Util::Execution.execute(get_env_var_cmd % var).strip).to eq(expected_value)
end
end
end
it "should override the LANG environment variable when :override_locale is set to true" do
# temporarily override the locale environment vars with a sentinel value, so that we can confirm that
# execute is actually setting them.
Puppet::Util.withenv(locale_sentinel_env) do
Puppet::Util::POSIX::LOCALE_ENV_VARS.each do |var|
# we expect that all of the POSIX vars will have been cleared except for LANG and LC_ALL
expected_value = (['LANG', 'LC_ALL'].include?(var)) ? "C" : ""
- Puppet::Util::Execution.execute(get_env_var_cmd % var, {:override_locale => true}).strip.should == expected_value
+ expect(Puppet::Util::Execution.execute(get_env_var_cmd % var, {:override_locale => true}).strip).to eq(expected_value)
end
end
end
it "should *not* override the LANG environment variable when :override_locale is set to false" do
# temporarily override the locale environment vars with a sentinel value, so that we can confirm that
# execute is not setting them.
Puppet::Util.withenv(locale_sentinel_env) do
Puppet::Util::POSIX::LOCALE_ENV_VARS.each do |var|
- Puppet::Util::Execution.execute(get_env_var_cmd % var, {:override_locale => false}).strip.should == lang_sentinel_value
+ expect(Puppet::Util::Execution.execute(get_env_var_cmd % var, {:override_locale => false}).strip).to eq(lang_sentinel_value)
end
end
end
it "should have restored the LANG and locale environment variables after execution" do
# we'll do this once without any sentinel values, to give us a little more test coverage
orig_env_vals = {}
Puppet::Util::POSIX::LOCALE_ENV_VARS.each do |var|
orig_env_vals[var] = ENV[var]
end
# now we can really execute any command--doesn't matter what it is...
Puppet::Util::Execution.execute(get_env_var_cmd % 'anything', {:override_locale => true})
# now we check and make sure the original environment was restored
Puppet::Util::POSIX::LOCALE_ENV_VARS.each do |var|
- ENV[var].should == orig_env_vals[var]
+ expect(ENV[var]).to eq(orig_env_vals[var])
end
# now, once more... but with our sentinel values
Puppet::Util.withenv(locale_sentinel_env) do
# now we can really execute any command--doesn't matter what it is...
Puppet::Util::Execution.execute(get_env_var_cmd % 'anything', {:override_locale => true})
# now we check and make sure the original environment was restored
Puppet::Util::POSIX::LOCALE_ENV_VARS.each do |var|
- ENV[var].should == locale_sentinel_env[var]
+ expect(ENV[var]).to eq(locale_sentinel_env[var])
end
end
end
end
describe "#execute (posix user env vars)", :unless => Puppet.features.microsoft_windows? do
# build up a printf-style string that contains a command to get the value of an environment variable
# from the operating system. We can substitute into this with the names of the desired environment variables later.
get_env_var_cmd = 'echo $%s'
# a sentinel value that we can use to emulate what locale environment variables might be set to on an international
# system.
user_sentinel_value = "Abracadabra"
# a temporary hash that contains sentinel values for each of the locale environment variables that we override in
# "execute"
user_sentinel_env = {}
Puppet::Util::POSIX::USER_ENV_VARS.each { |var| user_sentinel_env[var] = user_sentinel_value }
it "should unset user-related environment vars during execution" do
# first we set up a temporary execution environment with sentinel values for the user-related environment vars
# that we care about.
Puppet::Util.withenv(user_sentinel_env) do
# with this environment, we loop over the vars in question
Puppet::Util::POSIX::USER_ENV_VARS.each do |var|
# ensure that our temporary environment is set up as we expect
- ENV[var].should == user_sentinel_env[var]
+ expect(ENV[var]).to eq(user_sentinel_env[var])
# run an "exec" via the provider and ensure that it unsets the vars
- Puppet::Util::Execution.execute(get_env_var_cmd % var).strip.should == ""
+ expect(Puppet::Util::Execution.execute(get_env_var_cmd % var).strip).to eq("")
# ensure that after the exec, our temporary env is still intact
- ENV[var].should == user_sentinel_env[var]
+ expect(ENV[var]).to eq(user_sentinel_env[var])
end
end
end
it "should have restored the user-related environment variables after execution" do
# we'll do this once without any sentinel values, to give us a little more test coverage
orig_env_vals = {}
Puppet::Util::POSIX::USER_ENV_VARS.each do |var|
orig_env_vals[var] = ENV[var]
end
# now we can really execute any command--doesn't matter what it is...
Puppet::Util::Execution.execute(get_env_var_cmd % 'anything')
# now we check and make sure the original environment was restored
Puppet::Util::POSIX::USER_ENV_VARS.each do |var|
- ENV[var].should == orig_env_vals[var]
+ expect(ENV[var]).to eq(orig_env_vals[var])
end
# now, once more... but with our sentinel values
Puppet::Util.withenv(user_sentinel_env) do
# now we can really execute any command--doesn't matter what it is...
Puppet::Util::Execution.execute(get_env_var_cmd % 'anything')
# now we check and make sure the original environment was restored
Puppet::Util::POSIX::USER_ENV_VARS.each do |var|
- ENV[var].should == user_sentinel_env[var]
+ expect(ENV[var]).to eq(user_sentinel_env[var])
end
end
end
end
describe "#execute (debug logging)" do
before :each do
stub_process_wait(0)
if Puppet.features.microsoft_windows?
Puppet::Util::Execution.stubs(:execute_windows).returns(proc_info_stub)
else
Puppet::Util::Execution.stubs(:execute_posix).returns(pid)
end
end
it "should log if no uid or gid specified" do
Puppet::Util::Execution.expects(:debug).with("Executing: 'echo hello'")
Puppet::Util::Execution.execute('echo hello')
end
it "should log numeric uid if specified" do
Puppet::Util::Execution.expects(:debug).with("Executing with uid=100: 'echo hello'")
Puppet::Util::Execution.execute('echo hello', {:uid => 100})
end
it "should log numeric gid if specified" do
Puppet::Util::Execution.expects(:debug).with("Executing with gid=500: 'echo hello'")
Puppet::Util::Execution.execute('echo hello', {:gid => 500})
end
it "should log numeric uid and gid if specified" do
Puppet::Util::Execution.expects(:debug).with("Executing with uid=100 gid=500: 'echo hello'")
Puppet::Util::Execution.execute('echo hello', {:uid => 100, :gid => 500})
end
it "should log string uid if specified" do
Puppet::Util::Execution.expects(:debug).with("Executing with uid=myuser: 'echo hello'")
Puppet::Util::Execution.execute('echo hello', {:uid => 'myuser'})
end
it "should log string gid if specified" do
Puppet::Util::Execution.expects(:debug).with("Executing with gid=mygroup: 'echo hello'")
Puppet::Util::Execution.execute('echo hello', {:gid => 'mygroup'})
end
it "should log string uid and gid if specified" do
Puppet::Util::Execution.expects(:debug).with("Executing with uid=myuser gid=mygroup: 'echo hello'")
Puppet::Util::Execution.execute('echo hello', {:uid => 'myuser', :gid => 'mygroup'})
end
it "should log numeric uid and string gid if specified" do
Puppet::Util::Execution.expects(:debug).with("Executing with uid=100 gid=mygroup: 'echo hello'")
Puppet::Util::Execution.execute('echo hello', {:uid => 100, :gid => 'mygroup'})
end
end
describe "after execution" do
before :each do
stub_process_wait(0)
if Puppet.features.microsoft_windows?
Puppet::Util::Execution.stubs(:execute_windows).returns(proc_info_stub)
else
Puppet::Util::Execution.stubs(:execute_posix).returns(pid)
end
end
it "should wait for the child process to exit" do
Puppet::Util::Execution.stubs(:wait_for_output)
Puppet::Util::Execution.execute('test command')
end
it "should close the stdin/stdout/stderr files used by the child" do
stdin = mock 'file', :close
stdout = mock 'file', :close
stderr = mock 'file', :close
File.expects(:open).
times(3).
returns(stdin).
then.returns(stdout).
then.returns(stderr)
Puppet::Util::Execution.execute('test command', {:squelch => true, :combine => false})
end
it "should read and return the output if squelch is false" do
stdout = Puppet::FileSystem::Uniquefile.new('test')
Puppet::FileSystem::Uniquefile.stubs(:new).returns(stdout)
stdout.write("My expected command output")
- Puppet::Util::Execution.execute('test command').should == "My expected command output"
+ expect(Puppet::Util::Execution.execute('test command')).to eq("My expected command output")
end
it "should not read the output if squelch is true" do
stdout = Puppet::FileSystem::Uniquefile.new('test')
Puppet::FileSystem::Uniquefile.stubs(:new).returns(stdout)
stdout.write("My expected command output")
- Puppet::Util::Execution.execute('test command', :squelch => true).should == ''
+ expect(Puppet::Util::Execution.execute('test command', :squelch => true)).to eq('')
end
it "should delete the file used for output if squelch is false" do
stdout = Puppet::FileSystem::Uniquefile.new('test')
path = stdout.path
Puppet::FileSystem::Uniquefile.stubs(:new).returns(stdout)
Puppet::Util::Execution.execute('test command')
- Puppet::FileSystem.exist?(path).should be_false
+ expect(Puppet::FileSystem.exist?(path)).to be_falsey
end
it "should not raise an error if the file is open" do
stdout = Puppet::FileSystem::Uniquefile.new('test')
Puppet::FileSystem::Uniquefile.stubs(:new).returns(stdout)
file = File.new(stdout.path, 'r')
Puppet::Util::Execution.execute('test command')
end
it "should raise an error if failonfail is true and the child failed" do
stub_process_wait(1)
expect {
subject.execute('fail command', :failonfail => true)
}.to raise_error(Puppet::ExecutionFailure, /Execution of 'fail command' returned 1/)
end
it "should not raise an error if failonfail is false and the child failed" do
stub_process_wait(1)
subject.execute('fail command', :failonfail => false)
end
it "should not raise an error if failonfail is true and the child succeeded" do
stub_process_wait(0)
subject.execute('fail command', :failonfail => true)
end
it "should not raise an error if failonfail is false and the child succeeded" do
stub_process_wait(0)
subject.execute('fail command', :failonfail => false)
end
it "should default failonfail to true when no options are specified" do
stub_process_wait(1)
expect {
subject.execute('fail command')
}.to raise_error(Puppet::ExecutionFailure, /Execution of 'fail command' returned 1/)
end
it "should default failonfail to false when options are specified, but failonfail is not" do
stub_process_wait(1)
subject.execute('fail command', { :combine => true })
end
it "should default failonfail to false when an empty hash of options is specified" do
stub_process_wait(1)
subject.execute('fail command', {})
end
it "should raise an error if a nil option is specified" do
expect {
Puppet::Util::Execution.execute('fail command', nil)
}.to raise_error(TypeError, /(can\'t convert|no implicit conversion of) nil into Hash/)
end
end
end
describe "#execpipe" do
it "should execute a string as a string" do
Puppet::Util::Execution.expects(:open).with('| echo hello 2>&1').returns('hello')
Puppet::Util::Execution.expects(:exitstatus).returns(0)
- Puppet::Util::Execution.execpipe('echo hello').should == 'hello'
+ expect(Puppet::Util::Execution.execpipe('echo hello')).to eq('hello')
end
it "should print meaningful debug message for string argument" do
Puppet::Util::Execution.expects(:debug).with("Executing 'echo hello'")
Puppet::Util::Execution.expects(:open).with('| echo hello 2>&1').returns('hello')
Puppet::Util::Execution.expects(:exitstatus).returns(0)
Puppet::Util::Execution.execpipe('echo hello')
end
it "should print meaningful debug message for array argument" do
Puppet::Util::Execution.expects(:debug).with("Executing 'echo hello'")
Puppet::Util::Execution.expects(:open).with('| echo hello 2>&1').returns('hello')
Puppet::Util::Execution.expects(:exitstatus).returns(0)
Puppet::Util::Execution.execpipe(['echo','hello'])
end
it "should execute an array by pasting together with spaces" do
Puppet::Util::Execution.expects(:open).with('| echo hello 2>&1').returns('hello')
Puppet::Util::Execution.expects(:exitstatus).returns(0)
- Puppet::Util::Execution.execpipe(['echo', 'hello']).should == 'hello'
+ expect(Puppet::Util::Execution.execpipe(['echo', 'hello'])).to eq('hello')
end
it "should fail if asked to fail, and the child does" do
Puppet::Util::Execution.stubs(:open).with('| echo hello 2>&1').returns('error message')
Puppet::Util::Execution.expects(:exitstatus).returns(1)
expect { Puppet::Util::Execution.execpipe('echo hello') }.
to raise_error Puppet::ExecutionFailure, /error message/
end
it "should not fail if asked not to fail, and the child does" do
Puppet::Util::Execution.stubs(:open).returns('error message')
- Puppet::Util::Execution.execpipe('echo hello', false).should == 'error message'
+ expect(Puppet::Util::Execution.execpipe('echo hello', false)).to eq('error message')
end
end
end
diff --git a/spec/unit/util/execution_stub_spec.rb b/spec/unit/util/execution_stub_spec.rb
index 9d5bc7aef..4aca015db 100755
--- a/spec/unit/util/execution_stub_spec.rb
+++ b/spec/unit/util/execution_stub_spec.rb
@@ -1,39 +1,39 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Util::ExecutionStub do
it "should use the provided stub code when 'set' is called" do
Puppet::Util::ExecutionStub.set do |command, options|
- command.should == ['/bin/foo', 'bar']
+ expect(command).to eq(['/bin/foo', 'bar'])
"stub output"
end
- Puppet::Util::ExecutionStub.current_value.should_not == nil
- Puppet::Util::Execution.execute(['/bin/foo', 'bar']).should == "stub output"
+ expect(Puppet::Util::ExecutionStub.current_value).not_to eq(nil)
+ expect(Puppet::Util::Execution.execute(['/bin/foo', 'bar'])).to eq("stub output")
end
it "should automatically restore normal execution at the conclusion of each spec test" do
# Note: this test relies on the previous test creating a stub.
- Puppet::Util::ExecutionStub.current_value.should == nil
+ expect(Puppet::Util::ExecutionStub.current_value).to eq(nil)
end
it "should restore normal execution after 'reset' is called" do
# Note: "true" exists at different paths in different OSes
if Puppet.features.microsoft_windows?
true_command = [Puppet::Util.which('cmd.exe').tr('/', '\\'), '/c', 'exit 0']
else
true_command = [Puppet::Util.which('true')]
end
stub_call_count = 0
Puppet::Util::ExecutionStub.set do |command, options|
- command.should == true_command
+ expect(command).to eq(true_command)
stub_call_count += 1
'stub called'
end
- Puppet::Util::Execution.execute(true_command).should == 'stub called'
- stub_call_count.should == 1
+ expect(Puppet::Util::Execution.execute(true_command)).to eq('stub called')
+ expect(stub_call_count).to eq(1)
Puppet::Util::ExecutionStub.reset
- Puppet::Util::ExecutionStub.current_value.should == nil
- Puppet::Util::Execution.execute(true_command).should == ''
- stub_call_count.should == 1
+ expect(Puppet::Util::ExecutionStub.current_value).to eq(nil)
+ expect(Puppet::Util::Execution.execute(true_command)).to eq('')
+ expect(stub_call_count).to eq(1)
end
end
diff --git a/spec/unit/util/feature_spec.rb b/spec/unit/util/feature_spec.rb
index e6d844533..6b59a6187 100755
--- a/spec/unit/util/feature_spec.rb
+++ b/spec/unit/util/feature_spec.rb
@@ -1,106 +1,102 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/feature'
describe Puppet::Util::Feature do
before do
@features = Puppet::Util::Feature.new("features")
@features.stubs(:warn)
end
- it "should consider undefined features to be absent" do
- @features.should_not be_defined_feature
- end
-
it "should be able to add new features" do
@features.add(:myfeature) {}
- @features.should respond_to(:myfeature?)
+ expect(@features).to respond_to(:myfeature?)
end
it "should call associated code when loading a feature" do
$loaded_feature = false
@features.add(:myfeature) { $loaded_feature = true}
- $loaded_feature.should be_true
+ expect($loaded_feature).to be_truthy
end
it "should consider a feature absent when the feature load fails" do
@features.add(:failer) { raise "foo" }
- @features.should_not be_failer
+ expect(@features).not_to be_failer
end
it "should consider a feature to be absent when the feature load returns false" do
@features.add(:failer) { false }
- @features.should_not be_failer
+ expect(@features).not_to be_failer
end
it "should consider a feature to be present when the feature load returns true" do
@features.add(:available) { true }
- @features.should be_available
+ expect(@features).to be_available
end
it "should cache the results of a feature load via code block" do
$loaded_feature = 0
@features.add(:myfeature) { $loaded_feature += 1 }
@features.myfeature?
@features.myfeature?
- $loaded_feature.should == 1
+ expect($loaded_feature).to eq(1)
end
it "should invalidate the cache for the feature when loading" do
# block defined features are evaluated at load time
@features.add(:myfeature) { false }
- @features.should_not be_myfeature
+ expect(@features).not_to be_myfeature
# features with no block have deferred evaluation so an existing cached
# value would take precedence
@features.add(:myfeature)
- @features.should be_myfeature
+ expect(@features).to be_myfeature
end
it "should support features with libraries" do
- lambda { @features.add(:puppet, :libs => %w{puppet}) }.should_not raise_error
+ expect { @features.add(:puppet, :libs => %w{puppet}) }.not_to raise_error
end
it "should consider a feature to be present if all of its libraries are present" do
@features.add(:myfeature, :libs => %w{foo bar})
@features.expects(:require).with("foo")
@features.expects(:require).with("bar")
- @features.should be_myfeature
+ expect(@features).to be_myfeature
end
it "should log and consider a feature to be absent if any of its libraries are absent" do
@features.add(:myfeature, :libs => %w{foo bar})
@features.expects(:require).with("foo").raises(LoadError)
@features.stubs(:require).with("bar")
Puppet.expects(:debug)
- @features.should_not be_myfeature
+ expect(@features).not_to be_myfeature
end
it "should change the feature to be present when its libraries become available" do
@features.add(:myfeature, :libs => %w{foo bar})
@features.expects(:require).twice().with("foo").raises(LoadError).then.returns(nil)
@features.stubs(:require).with("bar")
Puppet::Util::RubyGems::Source.stubs(:source).returns(Puppet::Util::RubyGems::OldGemsSource)
Puppet::Util::RubyGems::OldGemsSource.any_instance.expects(:clear_paths).times(3)
Puppet.expects(:debug)
- @features.should_not be_myfeature
- @features.should be_myfeature
+ expect(@features).not_to be_myfeature
+ expect(@features).to be_myfeature
end
it "should cache load failures when configured to do so" do
Puppet[:always_cache_features] = true
@features.add(:myfeature, :libs => %w{foo bar})
@features.expects(:require).with("foo").raises(LoadError)
- @features.should_not be_myfeature
+ expect(@features).not_to be_myfeature
# second call would cause an expectation exception if 'require' was
# called a second time
- @features.should_not be_myfeature
+ expect(@features).not_to be_myfeature
end
end
diff --git a/spec/unit/util/filetype_spec.rb b/spec/unit/util/filetype_spec.rb
index 304b49352..9d69502a6 100755
--- a/spec/unit/util/filetype_spec.rb
+++ b/spec/unit/util/filetype_spec.rb
@@ -1,211 +1,211 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/filetype'
# XXX Import all of the tests into this file.
describe Puppet::Util::FileType do
describe "the flat filetype" do
let(:path) { '/my/file' }
let(:type) { Puppet::Util::FileType.filetype(:flat) }
let(:file) { type.new(path) }
it "should exist" do
- type.should_not be_nil
+ expect(type).not_to be_nil
end
describe "when the file already exists" do
it "should return the file's contents when asked to read it" do
Puppet::FileSystem.expects(:exist?).with(path).returns true
File.expects(:read).with(path).returns "my text"
- file.read.should == "my text"
+ expect(file.read).to eq("my text")
end
it "should unlink the file when asked to remove it" do
Puppet::FileSystem.expects(:exist?).with(path).returns true
Puppet::FileSystem.expects(:unlink).with(path)
file.remove
end
end
describe "when the file does not exist" do
it "should return an empty string when asked to read the file" do
Puppet::FileSystem.expects(:exist?).with(path).returns false
- file.read.should == ""
+ expect(file.read).to eq("")
end
end
describe "when writing the file" do
let(:tempfile) { stub 'tempfile', :print => nil, :close => nil, :flush => nil, :path => "/other/file" }
before do
FileUtils.stubs(:cp)
Tempfile.stubs(:new).returns tempfile
end
it "should first create a temp file and copy its contents over to the file location" do
Tempfile.expects(:new).with("puppet").returns tempfile
tempfile.expects(:print).with("my text")
tempfile.expects(:flush)
tempfile.expects(:close)
FileUtils.expects(:cp).with(tempfile.path, path)
file.write "my text"
end
it "should set the selinux default context on the file" do
file.expects(:set_selinux_default_context).with(path)
file.write "eh"
end
end
describe "when backing up a file" do
it "should do nothing if the file does not exist" do
Puppet::FileSystem.expects(:exist?).with(path).returns false
file.expects(:bucket).never
file.backup
end
it "should use its filebucket to backup the file if it exists" do
Puppet::FileSystem.expects(:exist?).with(path).returns true
bucket = mock 'bucket'
bucket.expects(:backup).with(path)
file.expects(:bucket).returns bucket
file.backup
end
it "should use the default filebucket" do
bucket = mock 'bucket'
bucket.expects(:bucket).returns "mybucket"
Puppet::Type.type(:filebucket).expects(:mkdefaultbucket).returns bucket
- file.bucket.should == "mybucket"
+ expect(file.bucket).to eq("mybucket")
end
end
end
shared_examples_for "crontab provider" do
let(:cron) { type.new('no_such_user') }
let(:crontab) { File.read(my_fixture(crontab_output)) }
let(:options) { { :failonfail => true, :combine => true } }
let(:uid) { 'no_such_user' }
let(:user_options) { options.merge({:uid => uid}) }
it "should exist" do
- type.should_not be_nil
+ expect(type).not_to be_nil
end
# make Puppet::Util::SUIDManager return something deterministic, not the
# uid of the user running the tests, except where overridden below.
before :each do
Puppet::Util::SUIDManager.stubs(:uid).returns 1234
end
describe "#read" do
it "should run crontab -l as the target user" do
Puppet::Util::Execution.expects(:execute).with(['crontab', '-l'], user_options).returns crontab
- cron.read.should == crontab
+ expect(cron.read).to eq(crontab)
end
it "should not switch user if current user is the target user" do
Puppet::Util.expects(:uid).with(uid).returns 9000
Puppet::Util::SUIDManager.expects(:uid).returns 9000
Puppet::Util::Execution.expects(:execute).with(['crontab', '-l'], options).returns crontab
- cron.read.should == crontab
+ expect(cron.read).to eq(crontab)
end
it "should treat an absent crontab as empty" do
Puppet::Util::Execution.expects(:execute).with(['crontab', '-l'], user_options).raises(Puppet::ExecutionFailure, absent_crontab)
- cron.read.should == ''
+ expect(cron.read).to eq('')
end
it "should raise an error if the user is not authorized to use cron" do
Puppet::Util::Execution.expects(:execute).with(['crontab', '-l'], user_options).raises(Puppet::ExecutionFailure, unauthorized_crontab)
expect {
cron.read
}.to raise_error Puppet::Error, /User #{uid} not authorized to use cron/
end
end
describe "#remove" do
it "should run crontab -r as the target user" do
Puppet::Util::Execution.expects(:execute).with(['crontab', '-r'], user_options)
cron.remove
end
it "should not switch user if current user is the target user" do
Puppet::Util.expects(:uid).with(uid).returns 9000
Puppet::Util::SUIDManager.expects(:uid).returns 9000
Puppet::Util::Execution.expects(:execute).with(['crontab','-r'], options)
cron.remove
end
end
describe "#write" do
before :each do
@tmp_cron = Tempfile.new("puppet_crontab_spec")
@tmp_cron_path = @tmp_cron.path
Puppet::Util.stubs(:uid).with(uid).returns 9000
Tempfile.expects(:new).with("puppet_#{name}").returns @tmp_cron
end
after :each do
- Puppet::FileSystem.exist?(@tmp_cron_path).should be_false
+ expect(Puppet::FileSystem.exist?(@tmp_cron_path)).to be_falsey
end
it "should run crontab as the target user on a temporary file" do
File.expects(:chown).with(9000, nil, @tmp_cron_path)
Puppet::Util::Execution.expects(:execute).with(["crontab", @tmp_cron_path], user_options)
@tmp_cron.expects(:print).with("foo\n")
cron.write "foo\n"
end
it "should not switch user if current user is the target user" do
Puppet::Util::SUIDManager.expects(:uid).returns 9000
File.expects(:chown).with(9000, nil, @tmp_cron_path)
Puppet::Util::Execution.expects(:execute).with(["crontab", @tmp_cron_path], options)
@tmp_cron.expects(:print).with("foo\n")
cron.write "foo\n"
end
end
end
describe "the suntab filetype", :unless => Puppet.features.microsoft_windows? do
let(:type) { Puppet::Util::FileType.filetype(:suntab) }
let(:name) { type.name }
let(:crontab_output) { 'suntab_output' }
# possible crontab output was taken from here:
# http://docs.oracle.com/cd/E19082-01/819-2380/sysrescron-60/index.html
let(:absent_crontab) do
'crontab: can\'t open your crontab file'
end
let(:unauthorized_crontab) do
'crontab: you are not authorized to use cron. Sorry.'
end
it_should_behave_like "crontab provider"
end
describe "the aixtab filetype", :unless => Puppet.features.microsoft_windows? do
let(:type) { Puppet::Util::FileType.filetype(:aixtab) }
let(:name) { type.name }
let(:crontab_output) { 'aixtab_output' }
let(:absent_crontab) do
'0481-103 Cannot open a file in the /var/spool/cron/crontabs directory.'
end
let(:unauthorized_crontab) do
'0481-109 You are not authorized to use the cron command.'
end
it_should_behave_like "crontab provider"
end
end
diff --git a/spec/unit/util/http_proxy_spec.rb b/spec/unit/util/http_proxy_spec.rb
index 59f39c511..6a7e10df0 100644
--- a/spec/unit/util/http_proxy_spec.rb
+++ b/spec/unit/util/http_proxy_spec.rb
@@ -1,125 +1,125 @@
require 'uri'
require 'spec_helper'
require 'puppet/util/http_proxy'
describe Puppet::Util::HttpProxy do
host, port, user, password = 'some.host', 1234, 'user1', 'pAssw0rd'
describe ".http_proxy_env" do
it "should return nil if no environment variables" do
- subject.http_proxy_env.should == nil
+ expect(subject.http_proxy_env).to eq(nil)
end
it "should return a URI::HTTP object if http_proxy env variable is set" do
Puppet::Util.withenv('HTTP_PROXY' => host) do
- subject.http_proxy_env.should == URI.parse(host)
+ expect(subject.http_proxy_env).to eq(URI.parse(host))
end
end
it "should return a URI::HTTP object if HTTP_PROXY env variable is set" do
Puppet::Util.withenv('HTTP_PROXY' => host) do
- subject.http_proxy_env.should == URI.parse(host)
+ expect(subject.http_proxy_env).to eq(URI.parse(host))
end
end
it "should return a URI::HTTP object with .host and .port if URI is given" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do
- subject.http_proxy_env.should == URI.parse("http://#{host}:#{port}")
+ expect(subject.http_proxy_env).to eq(URI.parse("http://#{host}:#{port}"))
end
end
it "should return nil if proxy variable is malformed" do
Puppet::Util.withenv('HTTP_PROXY' => 'this is not a valid URI') do
- subject.http_proxy_env.should == nil
+ expect(subject.http_proxy_env).to eq(nil)
end
end
end
describe ".http_proxy_host" do
it "should return nil if no proxy host in config or env" do
- subject.http_proxy_host.should == nil
+ expect(subject.http_proxy_host).to eq(nil)
end
it "should return a proxy host if set in config" do
Puppet.settings[:http_proxy_host] = host
- subject.http_proxy_host.should == host
+ expect(subject.http_proxy_host).to eq(host)
end
it "should return nil if set to `none` in config" do
Puppet.settings[:http_proxy_host] = 'none'
- subject.http_proxy_host.should == nil
+ expect(subject.http_proxy_host).to eq(nil)
end
it "uses environment variable before puppet settings" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do
Puppet.settings[:http_proxy_host] = 'not.correct'
- subject.http_proxy_host.should == host
+ expect(subject.http_proxy_host).to eq(host)
end
end
end
describe ".http_proxy_port" do
it "should return a proxy port if set in environment" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do
- subject.http_proxy_port.should == port
+ expect(subject.http_proxy_port).to eq(port)
end
end
it "should return a proxy port if set in config" do
Puppet.settings[:http_proxy_port] = port
- subject.http_proxy_port.should == port
+ expect(subject.http_proxy_port).to eq(port)
end
it "uses environment variable before puppet settings" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do
Puppet.settings[:http_proxy_port] = 7456
- subject.http_proxy_port.should == port
+ expect(subject.http_proxy_port).to eq(port)
end
end
end
describe ".http_proxy_user" do
it "should return a proxy user if set in environment" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{user}:#{password}@#{host}:#{port}") do
- subject.http_proxy_user.should == user
+ expect(subject.http_proxy_user).to eq(user)
end
end
it "should return a proxy user if set in config" do
Puppet.settings[:http_proxy_user] = user
- subject.http_proxy_user.should == user
+ expect(subject.http_proxy_user).to eq(user)
end
it "should use environment variable before puppet settings" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{user}:#{password}@#{host}:#{port}") do
Puppet.settings[:http_proxy_user] = 'clownpants'
- subject.http_proxy_user.should == user
+ expect(subject.http_proxy_user).to eq(user)
end
end
end
describe ".http_proxy_password" do
it "should return a proxy password if set in environment" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{user}:#{password}@#{host}:#{port}") do
- subject.http_proxy_password.should == password
+ expect(subject.http_proxy_password).to eq(password)
end
end
it "should return a proxy password if set in config" do
Puppet.settings[:http_proxy_user] = user
Puppet.settings[:http_proxy_password] = password
- subject.http_proxy_password.should == password
+ expect(subject.http_proxy_password).to eq(password)
end
it "should use environment variable before puppet settings" do
Puppet::Util.withenv('HTTP_PROXY' => "http://#{user}:#{password}@#{host}:#{port}") do
Puppet.settings[:http_proxy_password] = 'clownpants'
- subject.http_proxy_password.should == password
+ expect(subject.http_proxy_password).to eq(password)
end
end
end
end
diff --git a/spec/unit/util/inifile_spec.rb b/spec/unit/util/inifile_spec.rb
index f81647ad7..05e0db434 100644
--- a/spec/unit/util/inifile_spec.rb
+++ b/spec/unit/util/inifile_spec.rb
@@ -1,492 +1,492 @@
require 'spec_helper'
require 'puppet/util/inifile'
describe Puppet::Util::IniConfig::Section do
subject { described_class.new('testsection', '/some/imaginary/file') }
describe "determining if the section is dirty" do
it "is not dirty on creation" do
expect(subject).to_not be_dirty
end
it "is dirty if a key is changed" do
subject['hello'] = 'world'
expect(subject).to be_dirty
end
it "is dirty if the section has been explicitly marked as dirty" do
subject.mark_dirty
expect(subject).to be_dirty
end
it "is dirty if the section is marked for deletion" do
subject.destroy = true
expect(subject).to be_dirty
end
it "is clean if the section has been explicitly marked as clean" do
subject['hello'] = 'world'
subject.mark_clean
expect(subject).to_not be_dirty
end
end
describe "reading an entry" do
it "returns nil if the key is not present" do
expect(subject['hello']).to be_nil
end
it "returns the value if the key is specified" do
subject.entries << ['hello', 'world']
expect(subject['hello']).to eq 'world'
end
it "ignores comments when looking for a match" do
subject.entries << '#this = comment'
expect(subject['#this']).to be_nil
end
end
describe "formatting the section" do
it "prefixes the output with the section header" do
expect(subject.format).to eq "[testsection]\n"
end
it "restores comments and blank lines" do
subject.entries << "#comment\n"
subject.entries << " "
expect(subject.format).to eq(
"[testsection]\n" +
"#comment\n" +
" "
)
end
it "adds all keys that have values" do
subject.entries << ['somekey', 'somevalue']
expect(subject.format).to eq("[testsection]\nsomekey=somevalue\n")
end
it "excludes keys that have a value of nil" do
subject.entries << ['empty', nil]
expect(subject.format).to eq("[testsection]\n")
end
it "preserves the order of the section" do
subject.entries << ['firstkey', 'firstval']
subject.entries << "# I am a comment, hear me roar\n"
subject.entries << ['secondkey', 'secondval']
expect(subject.format).to eq(
"[testsection]\n" +
"firstkey=firstval\n" +
"# I am a comment, hear me roar\n" +
"secondkey=secondval\n"
)
end
it "is empty if the section is marked for deletion" do
subject.entries << ['firstkey', 'firstval']
subject.destroy = true
expect(subject.format).to eq('')
end
end
end
describe Puppet::Util::IniConfig::PhysicalFile do
subject { described_class.new('/some/nonexistent/file') }
let(:first_sect) do
sect = Puppet::Util::IniConfig::Section.new('firstsection', '/some/imaginary/file')
sect.entries << "# comment\n" << ['onefish', 'redfish'] << "\n"
sect
end
let(:second_sect) do
sect = Puppet::Util::IniConfig::Section.new('secondsection', '/some/imaginary/file')
sect.entries << ['twofish', 'bluefish']
sect
end
describe "when reading a file" do
it "raises an error if the file does not exist" do
subject.filetype.stubs(:read)
expect {
subject.read
}.to raise_error(%r[Cannot read nonexistent file .*/some/nonexistent/file])
end
it "passes the contents of the file to #parse" do
subject.filetype.stubs(:read).returns "[section]"
subject.expects(:parse).with("[section]")
subject.read
end
end
describe "when parsing a file" do
describe "parsing sections" do
it "creates new sections the first time that the section is found" do
text = "[mysect]\n"
subject.parse(text)
expect(subject.contents).to have(1).items
sect = subject.contents[0]
expect(sect.name).to eq "mysect"
end
it "raises an error if a section is redefined in the file" do
text = "[mysect]\n[mysect]\n"
expect {
subject.parse(text)
}.to raise_error(Puppet::Util::IniConfig::IniParseError,
/Section "mysect" is already defined, cannot redefine/)
end
it "raises an error if a section is redefined in the file collection" do
subject.file_collection = stub('file collection', :get_section => true)
text = "[mysect]\n[mysect]\n"
expect {
subject.parse(text)
}.to raise_error(Puppet::Util::IniConfig::IniParseError,
/Section "mysect" is already defined, cannot redefine/)
end
end
describe "parsing properties" do
it "raises an error if the property is not within a section" do
text = "key=val\n"
expect {
subject.parse(text)
}.to raise_error(Puppet::Util::IniConfig::IniParseError,
/Property with key "key" outside of a section/)
end
it "adds the property to the current section" do
text = "[main]\nkey=val\n"
subject.parse(text)
expect(subject.contents).to have(1).items
sect = subject.contents[0]
expect(sect['key']).to eq "val"
end
end
describe "parsing line continuations" do
it "adds the continued line to the last parsed property" do
text = "[main]\nkey=val\n moreval"
subject.parse(text)
expect(subject.contents).to have(1).items
sect = subject.contents[0]
expect(sect['key']).to eq "val\n moreval"
end
end
describe "parsing comments and whitespace" do
it "treats # as a comment leader" do
text = "# octothorpe comment"
subject.parse(text)
expect(subject.contents).to eq ["# octothorpe comment"]
end
it "treats ; as a comment leader" do
text = "; semicolon comment"
subject.parse(text)
expect(subject.contents).to eq ["; semicolon comment"]
end
it "treates 'rem' as a comment leader" do
text = "rem rapid eye movement comment"
subject.parse(text)
expect(subject.contents).to eq ["rem rapid eye movement comment"]
end
it "stores comments and whitespace in a section in the correct section" do
text = "[main]\n; main section comment"
subject.parse(text)
sect = subject.get_section("main")
expect(sect.entries).to eq ["; main section comment"]
end
end
end
it "can return all sections" do
text = "[first]\n" +
"; comment\n" +
"[second]\n" +
"key=value"
subject.parse(text)
sections = subject.sections
expect(sections).to have(2).items
expect(sections[0].name).to eq "first"
expect(sections[1].name).to eq "second"
end
it "can retrieve a specific section" do
text = "[first]\n" +
"; comment\n" +
"[second]\n" +
"key=value"
subject.parse(text)
section = subject.get_section("second")
expect(section.name).to eq "second"
expect(section["key"]).to eq "value"
end
describe "formatting" do
it "concatenates each formatted section in order" do
subject.contents << first_sect << second_sect
expected = "[firstsection]\n" +
"# comment\n" +
"onefish=redfish\n" +
"\n" +
"[secondsection]\n" +
"twofish=bluefish\n"
expect(subject.format).to eq expected
end
it "includes comments that are not within a section" do
subject.contents << "# This comment is not in a section\n" << first_sect << second_sect
expected = "# This comment is not in a section\n" +
"[firstsection]\n" +
"# comment\n" +
"onefish=redfish\n" +
"\n" +
"[secondsection]\n" +
"twofish=bluefish\n"
expect(subject.format).to eq expected
end
it "excludes sections that are marked to be destroyed" do
subject.contents << first_sect << second_sect
first_sect.destroy = true
expected = "[secondsection]\n" + "twofish=bluefish\n"
expect(subject.format).to eq expected
end
end
describe "storing the file" do
describe "with empty contents" do
describe "and destroy_empty is true" do
before { subject.destroy_empty = true }
it "removes the file if there are no sections" do
File.expects(:unlink)
subject.store
end
it "removes the file if all sections are marked to be destroyed" do
subject.contents << first_sect << second_sect
first_sect.destroy = true
second_sect.destroy = true
File.expects(:unlink)
subject.store
end
it "doesn't remove the file if not all sections are marked to be destroyed" do
subject.contents << first_sect << second_sect
first_sect.destroy = true
second_sect.destroy = false
File.expects(:unlink).never
subject.filetype.stubs(:write)
subject.store
end
end
it "rewrites the file if destroy_empty is false" do
subject.contents << first_sect << second_sect
first_sect.destroy = true
second_sect.destroy = true
File.expects(:unlink).never
subject.stubs(:format).returns "formatted"
subject.filetype.expects(:write).with("formatted")
subject.store
end
end
it "rewrites the file if any section is dirty" do
subject.contents << first_sect << second_sect
first_sect.mark_dirty
second_sect.mark_clean
subject.stubs(:format).returns "formatted"
subject.filetype.expects(:write).with("formatted")
subject.store
end
it "doesn't modify the file if all sections are clean" do
subject.contents << first_sect << second_sect
first_sect.mark_clean
second_sect.mark_clean
subject.stubs(:format).returns "formatted"
subject.filetype.expects(:write).never
subject.store
end
end
end
describe Puppet::Util::IniConfig::FileCollection do
let(:path_a) { '/some/nonexistent/file/a' }
let(:path_b) { '/some/nonexistent/file/b' }
let(:file_a) { Puppet::Util::IniConfig::PhysicalFile.new(path_a) }
let(:file_b) { Puppet::Util::IniConfig::PhysicalFile.new(path_b) }
let(:sect_a1) { Puppet::Util::IniConfig::Section.new('sect_a1', path_a) }
let(:sect_a2) { Puppet::Util::IniConfig::Section.new('sect_a2', path_a) }
let(:sect_b1) { Puppet::Util::IniConfig::Section.new('sect_b1', path_b) }
let(:sect_b2) { Puppet::Util::IniConfig::Section.new('sect_b2', path_b) }
before do
file_a.contents << sect_a1 << sect_a2
file_b.contents << sect_b1 << sect_b2
end
describe "reading a file" do
let(:stub_file) { stub('Physical file') }
it "creates a new PhysicalFile and uses that to read the file" do
stub_file.expects(:read)
stub_file.expects(:file_collection=)
Puppet::Util::IniConfig::PhysicalFile.expects(:new).with(path_a).returns stub_file
subject.read(path_a)
end
it "stores the PhysicalFile and the path to the file" do
stub_file.stubs(:read)
stub_file.stubs(:file_collection=)
Puppet::Util::IniConfig::PhysicalFile.stubs(:new).with(path_a).returns stub_file
subject.read(path_a)
path, physical_file = subject.files.first
expect(path).to eq(path_a)
expect(physical_file).to eq stub_file
end
end
describe "storing all files" do
before do
subject.files[path_a] = file_a
subject.files[path_b] = file_b
end
it "stores all files in the collection" do
file_a.expects(:store).once
file_b.expects(:store).once
subject.store
end
end
describe "iterating over sections" do
before do
subject.files[path_a] = file_a
subject.files[path_b] = file_b
end
it "yields every section from every file" do
[sect_a1, sect_a2, sect_b1, sect_b2].each do |sect|
sect.expects(:touch).once
end
subject.each_section do |sect|
sect.touch
end
end
end
describe "iterating over files" do
before do
subject.files[path_a] = file_a
subject.files[path_b] = file_b
end
it "yields the path to every file in the collection" do
seen = []
subject.each_file do |file|
seen << file
end
expect(seen).to include(path_a)
expect(seen).to include(path_b)
end
end
describe "retrieving a specific section" do
before do
subject.files[path_a] = file_a
subject.files[path_b] = file_b
end
it "retrieves the first section defined" do
expect(subject.get_section('sect_b1')).to eq sect_b1
end
it "returns nil if there was no section with the given name" do
expect(subject.get_section('nope')).to be_nil
end
it "allows #[] to be used as an alias to #get_section" do
expect(subject['b2']).to eq subject.get_section('b2')
end
end
describe "checking if a section has been defined" do
before do
subject.files[path_a] = file_a
subject.files[path_b] = file_b
end
it "is true if a section with the given name is defined" do
- expect(subject.include?('sect_a1')).to be_true
+ expect(subject.include?('sect_a1')).to be_truthy
end
it "is false if a section with the given name can't be found" do
- expect(subject.include?('nonexistent')).to be_false
+ expect(subject.include?('nonexistent')).to be_falsey
end
end
describe "adding a new section" do
before do
subject.files[path_a] = file_a
subject.files[path_b] = file_b
end
it "adds the section to the appropriate file" do
file_a.expects(:add_section).with('newsect')
subject.add_section('newsect', path_a)
end
end
end
diff --git a/spec/unit/util/json_lockfile_spec.rb b/spec/unit/util/json_lockfile_spec.rb
index a547508a5..aa927c39d 100644
--- a/spec/unit/util/json_lockfile_spec.rb
+++ b/spec/unit/util/json_lockfile_spec.rb
@@ -1,50 +1,50 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/json_lockfile'
describe Puppet::Util::JsonLockfile do
require 'puppet_spec/files'
include PuppetSpec::Files
before(:each) do
@lockfile = tmpfile("lock")
@lock = Puppet::Util::JsonLockfile.new(@lockfile)
end
describe "#lock" do
it "should create a lock file containing a json hash" do
data = { "foo" => "foofoo", "bar" => "barbar" }
@lock.lock(data)
- PSON.parse(File.read(@lockfile)).should == data
+ expect(PSON.parse(File.read(@lockfile))).to eq(data)
end
end
describe "reading lock data" do
it "returns deserialized JSON from the lockfile" do
data = { "foo" => "foofoo", "bar" => "barbar" }
@lock.lock(data)
expect(@lock.lock_data).to eq data
end
it "returns nil if the file read returned nil" do
@lock.lock
File.stubs(:read).returns nil
expect(@lock.lock_data).to be_nil
end
it "returns nil if the file was empty" do
@lock.lock
File.stubs(:read).returns ''
expect(@lock.lock_data).to be_nil
end
it "returns nil if the file was not in PSON" do
@lock.lock
File.stubs(:read).returns ']['
expect(@lock.lock_data).to be_nil
end
end
end
diff --git a/spec/unit/util/ldap/connection_spec.rb b/spec/unit/util/ldap/connection_spec.rb
index 97a0765d8..6cd965ffa 100755
--- a/spec/unit/util/ldap/connection_spec.rb
+++ b/spec/unit/util/ldap/connection_spec.rb
@@ -1,161 +1,161 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/ldap/connection'
# So our mocks and such all work, even when ldap isn't available.
unless Puppet.features.ldap?
class LDAP
class Conn
def initialize(*args)
end
end
class SSLConn < Conn; end
LDAP_OPT_PROTOCOL_VERSION = 1
LDAP_OPT_REFERRALS = 2
LDAP_OPT_ON = 3
end
end
describe Puppet::Util::Ldap::Connection do
before do
Puppet.features.stubs(:ldap?).returns true
@ldapconn = mock 'ldap'
LDAP::Conn.stubs(:new).returns(@ldapconn)
LDAP::SSLConn.stubs(:new).returns(@ldapconn)
@ldapconn.stub_everything
@connection = Puppet::Util::Ldap::Connection.new("host", "port")
end
describe "when creating connections" do
it "should require the host and port" do
- lambda { Puppet::Util::Ldap::Connection.new("myhost") }.should raise_error(ArgumentError)
+ expect { Puppet::Util::Ldap::Connection.new("myhost") }.to raise_error(ArgumentError)
end
it "should allow specification of a user and password" do
- lambda { Puppet::Util::Ldap::Connection.new("myhost", "myport", :user => "blah", :password => "boo") }.should_not raise_error
+ expect { Puppet::Util::Ldap::Connection.new("myhost", "myport", :user => "blah", :password => "boo") }.not_to raise_error
end
it "should allow specification of ssl" do
- lambda { Puppet::Util::Ldap::Connection.new("myhost", "myport", :ssl => :tsl) }.should_not raise_error
+ expect { Puppet::Util::Ldap::Connection.new("myhost", "myport", :ssl => :tsl) }.not_to raise_error
end
it "should support requiring a new connection" do
- lambda { Puppet::Util::Ldap::Connection.new("myhost", "myport", :reset => true) }.should_not raise_error
+ expect { Puppet::Util::Ldap::Connection.new("myhost", "myport", :reset => true) }.not_to raise_error
end
it "should fail if ldap is unavailable" do
Puppet.features.expects(:ldap?).returns(false)
- lambda { Puppet::Util::Ldap::Connection.new("host", "port") }.should raise_error(Puppet::Error)
+ expect { Puppet::Util::Ldap::Connection.new("host", "port") }.to raise_error(Puppet::Error)
end
it "should use neither ssl nor tls by default" do
LDAP::Conn.expects(:new).with("host", "port").returns(@ldapconn)
@connection.start
end
it "should use LDAP::SSLConn if ssl is requested" do
LDAP::SSLConn.expects(:new).with("host", "port").returns(@ldapconn)
@connection.ssl = true
@connection.start
end
it "should use LDAP::SSLConn and tls if tls is requested" do
LDAP::SSLConn.expects(:new).with("host", "port", true).returns(@ldapconn)
@connection.ssl = :tls
@connection.start
end
it "should set the protocol version to 3 and enable referrals" do
@ldapconn.expects(:set_option).with(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3)
@ldapconn.expects(:set_option).with(LDAP::LDAP_OPT_REFERRALS, LDAP::LDAP_OPT_ON)
@connection.start
end
it "should bind with the provided user and password" do
@connection.user = "myuser"
@connection.password = "mypassword"
@ldapconn.expects(:simple_bind).with("myuser", "mypassword")
@connection.start
end
it "should bind with no user and password if none has been provided" do
@ldapconn.expects(:simple_bind).with(nil, nil)
@connection.start
end
end
describe "when closing connections" do
it "should not close connections that are not open" do
@connection.stubs(:connection).returns(@ldapconn)
@ldapconn.expects(:bound?).returns false
@ldapconn.expects(:unbind).never
@connection.close
end
end
it "should have a class-level method for creating a default connection" do
- Puppet::Util::Ldap::Connection.should respond_to(:instance)
+ expect(Puppet::Util::Ldap::Connection).to respond_to(:instance)
end
describe "when creating a default connection" do
it "should use the :ldapserver setting to determine the host" do
Puppet[:ldapserver] = "myserv"
Puppet::Util::Ldap::Connection.expects(:new).with { |host, port, options| host == "myserv" }
Puppet::Util::Ldap::Connection.instance
end
it "should use the :ldapport setting to determine the port" do
Puppet[:ldapport] = "456"
Puppet::Util::Ldap::Connection.expects(:new).with { |host, port, options| port == "456" }
Puppet::Util::Ldap::Connection.instance
end
it "should set ssl to :tls if tls is enabled" do
Puppet[:ldaptls] = true
Puppet::Util::Ldap::Connection.expects(:new).with { |host, port, options| options[:ssl] == :tls }
Puppet::Util::Ldap::Connection.instance
end
it "should set ssl to 'true' if ssl is enabled and tls is not" do
Puppet[:ldaptls] = false
Puppet[:ldapssl] = true
Puppet::Util::Ldap::Connection.expects(:new).with { |host, port, options| options[:ssl] == true }
Puppet::Util::Ldap::Connection.instance
end
it "should set ssl to false if neither ssl nor tls are enabled" do
Puppet[:ldaptls] = false
Puppet[:ldapssl] = false
Puppet::Util::Ldap::Connection.expects(:new).with { |host, port, options| options[:ssl] == false }
Puppet::Util::Ldap::Connection.instance
end
it "should set the ldapuser if one is set" do
Puppet[:ldapuser] = "foo"
Puppet::Util::Ldap::Connection.expects(:new).with { |host, port, options| options[:user] == "foo" }
Puppet::Util::Ldap::Connection.instance
end
it "should set the ldapuser and ldappassword if both is set" do
Puppet[:ldapuser] = "foo"
Puppet[:ldappassword] = "bar"
Puppet::Util::Ldap::Connection.expects(:new).with { |host, port, options| options[:user] == "foo" and options[:password] == "bar" }
Puppet::Util::Ldap::Connection.instance
end
end
end
diff --git a/spec/unit/util/ldap/generator_spec.rb b/spec/unit/util/ldap/generator_spec.rb
index 1e2fc128c..1cfd9a280 100755
--- a/spec/unit/util/ldap/generator_spec.rb
+++ b/spec/unit/util/ldap/generator_spec.rb
@@ -1,50 +1,50 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/ldap/generator'
describe Puppet::Util::Ldap::Generator do
before do
@generator = Puppet::Util::Ldap::Generator.new(:uno)
end
it "should require a parameter name at initialization" do
- lambda { Puppet::Util::Ldap::Generator.new }.should raise_error
+ expect { Puppet::Util::Ldap::Generator.new }.to raise_error
end
it "should always return its name as a string" do
g = Puppet::Util::Ldap::Generator.new(:myname)
- g.name.should == "myname"
+ expect(g.name).to eq("myname")
end
it "should provide a method for declaring the source parameter" do
@generator.from(:dos)
end
it "should always return a set source as a string" do
@generator.from(:dos)
- @generator.source.should == "dos"
+ expect(@generator.source).to eq("dos")
end
it "should return the source as nil if there is no source" do
- @generator.source.should be_nil
+ expect(@generator.source).to be_nil
end
it "should return itself when declaring the source" do
- @generator.from(:dos).should equal(@generator)
+ expect(@generator.from(:dos)).to equal(@generator)
end
it "should run the provided block when asked to generate the value" do
@generator.with { "yayness" }
- @generator.generate.should == "yayness"
+ expect(@generator.generate).to eq("yayness")
end
it "should pass in any provided value to the block" do
@generator.with { |value| value.upcase }
- @generator.generate("myval").should == "MYVAL"
+ expect(@generator.generate("myval")).to eq("MYVAL")
end
it "should return itself when declaring the code used for generating" do
- @generator.with { |value| value.upcase }.should equal(@generator)
+ expect(@generator.with { |value| value.upcase }).to equal(@generator)
end
end
diff --git a/spec/unit/util/ldap/manager_spec.rb b/spec/unit/util/ldap/manager_spec.rb
index db4d39dd9..adc8c12f5 100755
--- a/spec/unit/util/ldap/manager_spec.rb
+++ b/spec/unit/util/ldap/manager_spec.rb
@@ -1,641 +1,641 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/ldap/manager'
# If the ldap classes aren't available, go ahead and
# create some, so our tests will pass.
unless defined?(LDAP::Mod)
class LDAP
LDAP_MOD_ADD = :adding
LDAP_MOD_REPLACE = :replacing
LDAP_MOD_DELETE = :deleting
class ResultError < RuntimeError; end
class Mod
def initialize(*args)
end
end
end
end
describe Puppet::Util::Ldap::Manager do
before do
@manager = Puppet::Util::Ldap::Manager.new
end
it "should return self when specifying objectclasses" do
- @manager.manages(:one, :two).should equal(@manager)
+ expect(@manager.manages(:one, :two)).to equal(@manager)
end
it "should allow specification of what objectclasses are managed" do
- @manager.manages(:one, :two).objectclasses.should == [:one, :two]
+ expect(@manager.manages(:one, :two).objectclasses).to eq([:one, :two])
end
it "should return self when specifying the relative base" do
- @manager.at("yay").should equal(@manager)
+ expect(@manager.at("yay")).to equal(@manager)
end
it "should allow specification of the relative base" do
- @manager.at("yay").location.should == "yay"
+ expect(@manager.at("yay").location).to eq("yay")
end
it "should return self when specifying the attribute map" do
- @manager.maps(:one => :two).should equal(@manager)
+ expect(@manager.maps(:one => :two)).to equal(@manager)
end
it "should allow specification of the rdn attribute" do
- @manager.named_by(:uid).rdn.should == :uid
+ expect(@manager.named_by(:uid).rdn).to eq(:uid)
end
it "should allow specification of the attribute map" do
- @manager.maps(:one => :two).puppet2ldap.should == {:one => :two}
+ expect(@manager.maps(:one => :two).puppet2ldap).to eq({:one => :two})
end
it "should have a no-op 'and' method that just returns self" do
- @manager.and.should equal(@manager)
+ expect(@manager.and).to equal(@manager)
end
it "should allow specification of generated attributes" do
- @manager.generates(:thing).should be_instance_of(Puppet::Util::Ldap::Generator)
+ expect(@manager.generates(:thing)).to be_instance_of(Puppet::Util::Ldap::Generator)
end
describe "when generating attributes" do
before do
@generator = stub 'generator', :source => "one", :name => "myparam"
Puppet::Util::Ldap::Generator.stubs(:new).with(:myparam).returns @generator
end
it "should create a generator to do the parameter generation" do
Puppet::Util::Ldap::Generator.expects(:new).with(:myparam).returns @generator
@manager.generates(:myparam)
end
it "should return the generator from the :generates method" do
- @manager.generates(:myparam).should equal(@generator)
+ expect(@manager.generates(:myparam)).to equal(@generator)
end
it "should not replace already present values" do
@manager.generates(:myparam)
attrs = {"myparam" => "testing"}
@generator.expects(:generate).never
@manager.generate attrs
- attrs["myparam"].should == "testing"
+ expect(attrs["myparam"]).to eq("testing")
end
it "should look for the parameter as a string, not a symbol" do
@manager.generates(:myparam)
@generator.expects(:generate).with("yay").returns %w{double yay}
attrs = {"one" => "yay"}
@manager.generate attrs
- attrs["myparam"].should == %w{double yay}
+ expect(attrs["myparam"]).to eq(%w{double yay})
end
it "should fail if a source is specified and no source value is not defined" do
@manager.generates(:myparam)
- lambda { @manager.generate "two" => "yay" }.should raise_error(ArgumentError)
+ expect { @manager.generate "two" => "yay" }.to raise_error(ArgumentError)
end
it "should use the source value to generate the new value if a source attribute is specified" do
@manager.generates(:myparam)
@generator.expects(:generate).with("yay").returns %w{double yay}
@manager.generate "one" => "yay"
end
it "should not pass in any value if no source attribute is specified" do
@generator.stubs(:source).returns nil
@manager.generates(:myparam)
@generator.expects(:generate).with.returns %w{double yay}
@manager.generate "one" => "yay"
end
it "should convert any results to arrays of strings if necessary" do
@generator.expects(:generate).returns :test
@manager.generates(:myparam)
attrs = {"one" => "two"}
@manager.generate(attrs)
- attrs["myparam"].should == ["test"]
+ expect(attrs["myparam"]).to eq(["test"])
end
it "should add the result to the passed-in attribute hash" do
@generator.expects(:generate).returns %w{test}
@manager.generates(:myparam)
attrs = {"one" => "two"}
@manager.generate(attrs)
- attrs["myparam"].should == %w{test}
+ expect(attrs["myparam"]).to eq(%w{test})
end
end
it "should be considered invalid if it is missing a location" do
@manager.manages :me
@manager.maps :me => :you
- @manager.should_not be_valid
+ expect(@manager).not_to be_valid
end
it "should be considered invalid if it is missing an objectclass list" do
@manager.maps :me => :you
@manager.at "ou=yayness"
- @manager.should_not be_valid
+ expect(@manager).not_to be_valid
end
it "should be considered invalid if it is missing an attribute map" do
@manager.manages :me
@manager.at "ou=yayness"
- @manager.should_not be_valid
+ expect(@manager).not_to be_valid
end
it "should be considered valid if it has an attribute map, location, and objectclass list" do
@manager.maps :me => :you
@manager.manages :me
@manager.at "ou=yayness"
- @manager.should be_valid
+ expect(@manager).to be_valid
end
it "should calculate an instance's dn using the :ldapbase setting and the relative base" do
Puppet[:ldapbase] = "dc=testing"
@manager.at "ou=mybase"
- @manager.dn("me").should == "cn=me,ou=mybase,dc=testing"
+ expect(@manager.dn("me")).to eq("cn=me,ou=mybase,dc=testing")
end
it "should use the specified rdn when calculating an instance's dn" do
Puppet[:ldapbase] = "dc=testing"
@manager.named_by :uid
@manager.at "ou=mybase"
- @manager.dn("me").should =~ /^uid=me/
+ expect(@manager.dn("me")).to match(/^uid=me/)
end
it "should calculate its base using the :ldapbase setting and the relative base" do
Puppet[:ldapbase] = "dc=testing"
@manager.at "ou=mybase"
- @manager.base.should == "ou=mybase,dc=testing"
+ expect(@manager.base).to eq("ou=mybase,dc=testing")
end
describe "when generating its search filter" do
it "should using a single 'objectclass=<name>' filter if a single objectclass is specified" do
@manager.manages("testing")
- @manager.filter.should == "objectclass=testing"
+ expect(@manager.filter).to eq("objectclass=testing")
end
it "should create an LDAP AND filter if multiple objectclasses are specified" do
@manager.manages "testing", "okay", "done"
- @manager.filter.should == "(&(objectclass=testing)(objectclass=okay)(objectclass=done))"
+ expect(@manager.filter).to eq("(&(objectclass=testing)(objectclass=okay)(objectclass=done))")
end
end
it "should have a method for converting a Puppet attribute name to an LDAP attribute name as a string" do
@manager.maps :puppet_attr => :ldap_attr
- @manager.ldap_name(:puppet_attr).should == "ldap_attr"
+ expect(@manager.ldap_name(:puppet_attr)).to eq("ldap_attr")
end
it "should have a method for converting an LDAP attribute name to a Puppet attribute name" do
@manager.maps :puppet_attr => :ldap_attr
- @manager.puppet_name(:ldap_attr).should == :puppet_attr
+ expect(@manager.puppet_name(:ldap_attr)).to eq(:puppet_attr)
end
it "should have a :create method for creating ldap entries" do
- @manager.should respond_to(:create)
+ expect(@manager).to respond_to(:create)
end
it "should have a :delete method for deleting ldap entries" do
- @manager.should respond_to(:delete)
+ expect(@manager).to respond_to(:delete)
end
it "should have a :modify method for modifying ldap entries" do
- @manager.should respond_to(:modify)
+ expect(@manager).to respond_to(:modify)
end
it "should have a method for finding an entry by name in ldap" do
- @manager.should respond_to(:find)
+ expect(@manager).to respond_to(:find)
end
describe "when converting ldap entries to hashes for providers" do
before do
@manager.maps :uno => :one, :dos => :two
@result = @manager.entry2provider("dn" => ["cn=one,ou=people,dc=madstop"], "one" => ["two"], "three" => %w{four}, "objectclass" => %w{yay ness})
end
it "should set the name to the short portion of the dn" do
- @result[:name].should == "one"
+ expect(@result[:name]).to eq("one")
end
it "should remove the objectclasses" do
- @result["objectclass"].should be_nil
+ expect(@result["objectclass"]).to be_nil
end
it "should remove any attributes that are not mentioned in the map" do
- @result["three"].should be_nil
+ expect(@result["three"]).to be_nil
end
it "should rename convert to symbols all attributes to their puppet names" do
- @result[:uno].should == %w{two}
+ expect(@result[:uno]).to eq(%w{two})
end
it "should set the value of all unset puppet attributes as :absent" do
- @result[:dos].should == :absent
+ expect(@result[:dos]).to eq(:absent)
end
end
describe "when using an ldap connection" do
before do
@ldapconn = mock 'ldapconn'
@conn = stub 'connection', :connection => @ldapconn, :start => nil, :close => nil
Puppet::Util::Ldap::Connection.stubs(:new).returns(@conn)
end
it "should fail unless a block is given" do
expect { @manager.connect }.to raise_error(ArgumentError, /must pass a block/)
end
it "should open the connection with its server set to :ldapserver" do
Puppet[:ldapserver] = "myserver"
Puppet::Util::Ldap::Connection.expects(:new).with { |*args| args[0] == "myserver" }.returns @conn
@manager.connect { |c| }
end
it "should open the connection with its port set to the :ldapport" do
Puppet[:ldapport] = "28"
Puppet::Util::Ldap::Connection.expects(:new).with { |*args| args[1] == "28" }.returns @conn
@manager.connect { |c| }
end
it "should open the connection with no user if :ldapuser is not set" do
Puppet[:ldapuser] = ""
Puppet::Util::Ldap::Connection.expects(:new).with { |*args| args[2][:user].nil? }.returns @conn
@manager.connect { |c| }
end
it "should open the connection with its user set to the :ldapuser if it is set" do
Puppet[:ldapuser] = "mypass"
Puppet::Util::Ldap::Connection.expects(:new).with { |*args| args[2][:user] == "mypass" }.returns @conn
@manager.connect { |c| }
end
it "should open the connection with no password if :ldappassword is not set" do
Puppet[:ldappassword] = ""
Puppet::Util::Ldap::Connection.expects(:new).with { |*args| args[2][:password].nil? }.returns @conn
@manager.connect { |c| }
end
it "should open the connection with its password set to the :ldappassword if it is set" do
Puppet[:ldappassword] = "mypass"
Puppet::Util::Ldap::Connection.expects(:new).with { |*args| args[2][:password] == "mypass" }.returns @conn
@manager.connect { |c| }
end
it "should set ssl to :tls if ldaptls is enabled" do
Puppet[:ldaptls] = true
Puppet::Util::Ldap::Connection.expects(:new).with { |*args| args[2][:ssl] == :tls }.returns @conn
@manager.connect { |c| }
end
it "should set ssl to true if ldapssl is enabled" do
Puppet[:ldapssl] = true
Puppet::Util::Ldap::Connection.expects(:new).with { |*args| args[2][:ssl] == true }.returns @conn
@manager.connect { |c| }
end
it "should set ssl to false if neither ldaptls nor ldapssl is enabled" do
Puppet[:ldapssl] = false
Puppet::Util::Ldap::Connection.expects(:new).with { |*args| args[2][:ssl] == false }.returns @conn
@manager.connect { |c| }
end
it "should open, yield, and then close the connection" do
@conn.expects(:start)
@conn.expects(:close)
Puppet::Util::Ldap::Connection.expects(:new).returns(@conn)
@ldapconn.expects(:test)
@manager.connect { |c| c.test }
end
it "should close the connection even if there's an exception in the passed block" do
@conn.expects(:close)
- lambda { @manager.connect { |c| raise ArgumentError } }.should raise_error(ArgumentError)
+ expect { @manager.connect { |c| raise ArgumentError } }.to raise_error(ArgumentError)
end
end
describe "when using ldap" do
before do
@conn = mock 'connection'
@manager.stubs(:connect).yields @conn
@manager.stubs(:objectclasses).returns [:oc1, :oc2]
@manager.maps :one => :uno, :two => :dos, :three => :tres, :four => :quatro
end
describe "to create entries" do
it "should convert the first argument to its :create method to a full dn and pass the resulting argument list to its connection" do
@manager.expects(:dn).with("myname").returns "mydn"
@conn.expects(:add).with { |name, attrs| name == "mydn" }
@manager.create("myname", {"attr" => "myattrs"})
end
it "should add the objectclasses to the attributes" do
@manager.expects(:dn).with("myname").returns "mydn"
@conn.expects(:add).with { |name, attrs| attrs["objectClass"].include?("oc1") and attrs["objectClass"].include?("oc2") }
@manager.create("myname", {:one => :testing})
end
it "should add the rdn to the attributes" do
@manager.expects(:dn).with("myname").returns "mydn"
@conn.expects(:add).with { |name, attrs| attrs["cn"] == %w{myname} }
@manager.create("myname", {:one => :testing})
end
it "should add 'top' to the objectclasses if it is not listed" do
@manager.expects(:dn).with("myname").returns "mydn"
@conn.expects(:add).with { |name, attrs| attrs["objectClass"].include?("top") }
@manager.create("myname", {:one => :testing})
end
it "should add any generated values that are defined" do
generator = stub 'generator', :source => :one, :name => "myparam"
Puppet::Util::Ldap::Generator.expects(:new).with(:myparam).returns generator
@manager.generates(:myparam)
@manager.stubs(:dn).with("myname").returns "mydn"
generator.expects(:generate).with(:testing).returns ["generated value"]
@conn.expects(:add).with { |name, attrs| attrs["myparam"] == ["generated value"] }
@manager.create("myname", {:one => :testing})
end
it "should convert any generated values to arrays of strings if necessary" do
generator = stub 'generator', :source => :one, :name => "myparam"
Puppet::Util::Ldap::Generator.expects(:new).with(:myparam).returns generator
@manager.generates(:myparam)
@manager.stubs(:dn).returns "mydn"
generator.expects(:generate).returns :generated
@conn.expects(:add).with { |name, attrs| attrs["myparam"] == ["generated"] }
@manager.create("myname", {:one => :testing})
end
end
describe "do delete entries" do
it "should convert the first argument to its :delete method to a full dn and pass the resulting argument list to its connection" do
@manager.expects(:dn).with("myname").returns "mydn"
@conn.expects(:delete).with("mydn")
@manager.delete("myname")
end
end
describe "to modify entries" do
it "should convert the first argument to its :modify method to a full dn and pass the resulting argument list to its connection" do
@manager.expects(:dn).with("myname").returns "mydn"
@conn.expects(:modify).with("mydn", :mymods)
@manager.modify("myname", :mymods)
end
end
describe "to find a single entry" do
it "should use the dn of the provided name as the search base, a scope of 0, and 'objectclass=*' as the filter for a search2 call" do
@manager.expects(:dn).with("myname").returns "mydn"
@conn.expects(:search2).with("mydn", 0, "objectclass=*")
@manager.find("myname")
end
it "should return nil if an exception is thrown because no result is found" do
@manager.expects(:dn).with("myname").returns "mydn"
@conn.expects(:search2).raises LDAP::ResultError
- @manager.find("myname").should be_nil
+ expect(@manager.find("myname")).to be_nil
end
it "should return a converted provider hash if the result is found" do
@manager.expects(:dn).with("myname").returns "mydn"
result = {"one" => "two"}
@conn.expects(:search2).yields result
@manager.expects(:entry2provider).with(result).returns "myprovider"
- @manager.find("myname").should == "myprovider"
+ expect(@manager.find("myname")).to eq("myprovider")
end
end
describe "to search for multiple entries" do
before do
@manager.stubs(:filter).returns "myfilter"
end
it "should use the manager's search base as the dn of the provided name as the search base" do
@manager.expects(:base).returns "mybase"
@conn.expects(:search2).with { |base, scope, filter| base == "mybase" }
@manager.search
end
it "should use a scope of 1" do
@conn.expects(:search2).with { |base, scope, filter| scope == 1 }
@manager.search
end
it "should use any specified search filter" do
@manager.expects(:filter).never
@conn.expects(:search2).with { |base, scope, filter| filter == "boo" }
@manager.search("boo")
end
it "should turn its objectclass list into its search filter if one is not specified" do
@manager.expects(:filter).returns "yay"
@conn.expects(:search2).with { |base, scope, filter| filter == "yay" }
@manager.search
end
it "should return nil if no result is found" do
@conn.expects(:search2)
- @manager.search.should be_nil
+ expect(@manager.search).to be_nil
end
it "should return an array of the found results converted to provider hashes" do
# LAK: AFAICT, it's impossible to yield multiple times in an expectation.
one = {"dn" => "cn=one,dc=madstop,dc=com", "one" => "two"}
@conn.expects(:search2).yields(one)
@manager.expects(:entry2provider).with(one).returns "myprov"
- @manager.search.should == ["myprov"]
+ expect(@manager.search).to eq(["myprov"])
end
end
end
describe "when an instance" do
before do
@name = "myname"
@manager.maps :one => :uno, :two => :dos, :three => :tres, :four => :quatro
end
describe "is being updated" do
it "should get created if the current attribute list is empty and the desired attribute list has :ensure == :present" do
@manager.expects(:create)
@manager.update(@name, {}, {:ensure => :present})
end
it "should get created if the current attribute list has :ensure == :absent and the desired attribute list has :ensure == :present" do
@manager.expects(:create)
@manager.update(@name, {:ensure => :absent}, {:ensure => :present})
end
it "should get deleted if the current attribute list has :ensure == :present and the desired attribute list has :ensure == :absent" do
@manager.expects(:delete)
@manager.update(@name, {:ensure => :present}, {:ensure => :absent})
end
it "should get modified if both attribute lists have :ensure == :present" do
@manager.expects(:modify)
@manager.update(@name, {:ensure => :present, :one => :two}, {:ensure => :present, :one => :three})
end
end
describe "is being deleted" do
it "should call the :delete method with its name and manager" do
@manager.expects(:delete).with(@name)
@manager.update(@name, {}, {:ensure => :absent})
end
end
describe "is being created" do
before do
@is = {}
@should = {:ensure => :present, :one => :yay, :two => :absent}
end
it "should call the :create method with its name" do
@manager.expects(:create).with { |name, attrs| name == @name }
@manager.update(@name, @is, @should)
end
it "should call the :create method with its property hash converted to ldap attribute names" do
@manager.expects(:create).with { |name, attrs| attrs["uno"] == ["yay"] }
@manager.update(@name, @is, @should)
end
it "should convert the property names to strings" do
@manager.expects(:create).with { |name, attrs| attrs["uno"] == ["yay"] }
@manager.update(@name, @is, @should)
end
it "should convert the property values to arrays if necessary" do
@manager.expects(:create).with { |name, attrs| attrs["uno"] == ["yay"] }
@manager.update(@name, @is, @should)
end
it "should convert the property values to strings if necessary" do
@manager.expects(:create).with { |name, attrs| attrs["uno"] == ["yay"] }
@manager.update(@name, @is, @should)
end
it "should not include :ensure in the properties sent" do
@manager.expects(:create).with { |*args| args[1][:ensure].nil? }
@manager.update(@name, @is, @should)
end
it "should not include attributes set to :absent in the properties sent" do
@manager.expects(:create).with { |*args| args[1][:dos].nil? }
@manager.update(@name, @is, @should)
end
end
describe "is being modified" do
it "should call the :modify method with its name and an array of LDAP::Mod instances" do
LDAP::Mod.stubs(:new).returns "whatever"
@is = {:one => :yay}
@should = {:one => :yay, :two => :foo}
@manager.expects(:modify).with { |name, mods| name == @name }
@manager.update(@name, @is, @should)
end
it "should create the LDAP::Mod with the property name converted to the ldap name as a string" do
@is = {:one => :yay}
@should = {:one => :yay, :two => :foo}
mod = mock 'module'
LDAP::Mod.expects(:new).with { |form, name, value| name == "dos" }.returns mod
@manager.stubs(:modify)
@manager.update(@name, @is, @should)
end
it "should create an LDAP::Mod instance of type LDAP_MOD_ADD for each attribute being added, with the attribute value converted to a string of arrays" do
@is = {:one => :yay}
@should = {:one => :yay, :two => :foo}
mod = mock 'module'
LDAP::Mod.expects(:new).with(LDAP::LDAP_MOD_ADD, "dos", ["foo"]).returns mod
@manager.stubs(:modify)
@manager.update(@name, @is, @should)
end
it "should create an LDAP::Mod instance of type LDAP_MOD_DELETE for each attribute being deleted" do
@is = {:one => :yay, :two => :foo}
@should = {:one => :yay, :two => :absent}
mod = mock 'module'
LDAP::Mod.expects(:new).with(LDAP::LDAP_MOD_DELETE, "dos", []).returns mod
@manager.stubs(:modify)
@manager.update(@name, @is, @should)
end
it "should create an LDAP::Mod instance of type LDAP_MOD_REPLACE for each attribute being modified, with the attribute converted to a string of arrays" do
@is = {:one => :yay, :two => :four}
@should = {:one => :yay, :two => :five}
mod = mock 'module'
LDAP::Mod.expects(:new).with(LDAP::LDAP_MOD_REPLACE, "dos", ["five"]).returns mod
@manager.stubs(:modify)
@manager.update(@name, @is, @should)
end
it "should pass all created Mod instances to the modify method" do
@is = {:one => :yay, :two => :foo, :three => :absent}
@should = {:one => :yay, :two => :foe, :three => :fee, :four => :fie}
LDAP::Mod.expects(:new).times(3).returns("mod1").then.returns("mod2").then.returns("mod3")
@manager.expects(:modify).with do |name, mods|
mods.sort == %w{mod1 mod2 mod3}.sort
end
@manager.update(@name, @is, @should)
end
end
end
end
diff --git a/spec/unit/util/lockfile_spec.rb b/spec/unit/util/lockfile_spec.rb
index 33755dad2..8b365e7c1 100644
--- a/spec/unit/util/lockfile_spec.rb
+++ b/spec/unit/util/lockfile_spec.rb
@@ -1,118 +1,118 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/lockfile'
module LockfileSpecHelper
def self.run_in_forks(count, &blk)
forks = {}
results = []
count.times do |i|
forks[i] = {}
forks[i][:read], forks[i][:write] = IO.pipe
forks[i][:pid] = fork do
forks[i][:read].close
res = yield
Marshal.dump(res, forks[i][:write])
exit!
end
end
count.times do |i|
forks[i][:write].close
result = forks[i][:read].read
forks[i][:read].close
Process.wait2(forks[i][:pid])
results << Marshal.load(result)
end
results
end
end
describe Puppet::Util::Lockfile do
require 'puppet_spec/files'
include PuppetSpec::Files
before(:each) do
@lockfile = tmpfile("lock")
@lock = Puppet::Util::Lockfile.new(@lockfile)
end
describe "#lock" do
it "should return true if it successfully locked" do
- @lock.lock.should be_true
+ expect(@lock.lock).to be_truthy
end
it "should return false if already locked" do
@lock.lock
- @lock.lock.should be_false
+ expect(@lock.lock).to be_falsey
end
it "should create a lock file" do
@lock.lock
- Puppet::FileSystem.exist?(@lockfile).should be_true
+ expect(Puppet::FileSystem.exist?(@lockfile)).to be_truthy
end
# We test simultaneous locks using fork which isn't supported on Windows.
it "should not be acquired by another process", :unless => Puppet.features.microsoft_windows? do
30.times do
forks = 3
results = LockfileSpecHelper.run_in_forks(forks) do
@lock.lock(Process.pid)
end
@lock.unlock
# Confirm one fork returned true and everyone else false.
- (results - [true]).size.should == forks - 1
- (results - [false]).size.should == 1
+ expect((results - [true]).size).to eq(forks - 1)
+ expect((results - [false]).size).to eq(1)
end
end
it "should create a lock file containing a string" do
data = "foofoo barbar"
@lock.lock(data)
- File.read(@lockfile).should == data
+ expect(File.read(@lockfile)).to eq(data)
end
end
describe "#unlock" do
it "should return true when unlocking" do
@lock.lock
- @lock.unlock.should be_true
+ expect(@lock.unlock).to be_truthy
end
it "should return false when not locked" do
- @lock.unlock.should be_false
+ expect(@lock.unlock).to be_falsey
end
it "should clear the lock file" do
File.open(@lockfile, 'w') { |fd| fd.print("locked") }
@lock.unlock
- Puppet::FileSystem.exist?(@lockfile).should be_false
+ expect(Puppet::FileSystem.exist?(@lockfile)).to be_falsey
end
end
it "should be locked when locked" do
@lock.lock
- @lock.should be_locked
+ expect(@lock).to be_locked
end
it "should not be locked when not locked" do
- @lock.should_not be_locked
+ expect(@lock).not_to be_locked
end
it "should not be locked when unlocked" do
@lock.lock
@lock.unlock
- @lock.should_not be_locked
+ expect(@lock).not_to be_locked
end
it "should return the lock data" do
data = "foofoo barbar"
@lock.lock(data)
- @lock.lock_data.should == data
+ expect(@lock.lock_data).to eq(data)
end
end
diff --git a/spec/unit/util/log/destinations_spec.rb b/spec/unit/util/log/destinations_spec.rb
index e48972a62..ae87d6d05 100755
--- a/spec/unit/util/log/destinations_spec.rb
+++ b/spec/unit/util/log/destinations_spec.rb
@@ -1,236 +1,236 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'json'
require 'puppet/util/log'
describe Puppet::Util::Log.desttypes[:report] do
before do
@dest = Puppet::Util::Log.desttypes[:report]
end
it "should require a report at initialization" do
- @dest.new("foo").report.should == "foo"
+ expect(@dest.new("foo").report).to eq("foo")
end
it "should send new messages to the report" do
report = mock 'report'
dest = @dest.new(report)
report.expects(:<<).with("my log")
dest.handle "my log"
end
end
describe Puppet::Util::Log.desttypes[:file] do
include PuppetSpec::Files
before do
File.stubs(:open) # prevent actually creating the file
File.stubs(:chown) # prevent chown on non existing file from failing
@class = Puppet::Util::Log.desttypes[:file]
end
it "should default to autoflush false" do
- @class.new(tmpfile('log')).autoflush.should == true
+ expect(@class.new(tmpfile('log')).autoflush).to eq(true)
end
describe "when matching" do
shared_examples_for "file destination" do
it "should match an absolute path" do
- @class.match?(abspath).should be_true
+ expect(@class.match?(abspath)).to be_truthy
end
it "should not match a relative path" do
- @class.match?(relpath).should be_false
+ expect(@class.match?(relpath)).to be_falsey
end
end
describe "on POSIX systems", :if => Puppet.features.posix? do
let (:abspath) { '/tmp/log' }
let (:relpath) { 'log' }
it_behaves_like "file destination"
it "logs an error if it can't chown the file owner & group" do
FileUtils.expects(:chown).with(Puppet[:user], Puppet[:group], abspath).raises(Errno::EPERM)
Puppet.features.expects(:root?).returns(true)
Puppet.expects(:err).with("Unable to set ownership to #{Puppet[:user]}:#{Puppet[:group]} for log file: #{abspath}")
@class.new(abspath)
end
it "doesn't attempt to chown when running as non-root" do
FileUtils.expects(:chown).with(Puppet[:user], Puppet[:group], abspath).never
Puppet.features.expects(:root?).returns(false)
@class.new(abspath)
end
end
describe "on Windows systems", :if => Puppet.features.microsoft_windows? do
let (:abspath) { 'C:\\temp\\log.txt' }
let (:relpath) { 'log.txt' }
it_behaves_like "file destination"
end
end
end
describe Puppet::Util::Log.desttypes[:syslog] do
let (:klass) { Puppet::Util::Log.desttypes[:syslog] }
# these tests can only be run when syslog is present, because
# we can't stub the top-level Syslog module
describe "when syslog is available", :if => Puppet.features.syslog? do
before :each do
Syslog.stubs(:opened?).returns(false)
Syslog.stubs(:const_get).returns("LOG_KERN").returns(0)
Syslog.stubs(:open)
end
it "should open syslog" do
Syslog.expects(:open)
klass.new
end
it "should close syslog" do
Syslog.expects(:close)
dest = klass.new
dest.close
end
it "should send messages to syslog" do
syslog = mock 'syslog'
syslog.expects(:info).with("don't panic")
Syslog.stubs(:open).returns(syslog)
msg = Puppet::Util::Log.new(:level => :info, :message => "don't panic")
dest = klass.new
dest.handle(msg)
end
end
describe "when syslog is unavailable" do
it "should not be a suitable log destination" do
Puppet.features.stubs(:syslog?).returns(false)
- klass.suitable?(:syslog).should be_false
+ expect(klass.suitable?(:syslog)).to be_falsey
end
end
end
describe Puppet::Util::Log.desttypes[:logstash_event] do
describe "when using structured log format with logstash_event schema" do
before :each do
@msg = Puppet::Util::Log.new(:level => :info, :message => "So long, and thanks for all the fish.", :source => "a dolphin")
end
it "format should fix the hash to have the correct structure" do
dest = described_class.new
result = dest.format(@msg)
- result["version"].should == 1
- result["level"].should == :info
- result["message"].should == "So long, and thanks for all the fish."
- result["source"].should == "a dolphin"
+ expect(result["version"]).to eq(1)
+ expect(result["level"]).to eq(:info)
+ expect(result["message"]).to eq("So long, and thanks for all the fish.")
+ expect(result["source"]).to eq("a dolphin")
# timestamp should be within 10 seconds
- Time.parse(result["@timestamp"]).should >= ( Time.now - 10 )
+ expect(Time.parse(result["@timestamp"])).to be >= ( Time.now - 10 )
end
it "format returns a structure that can be converted to json" do
dest = described_class.new
hash = dest.format(@msg)
JSON.parse(hash.to_json)
end
it "handle should send the output to stdout" do
$stdout.expects(:puts).once
dest = described_class.new
dest.handle(@msg)
end
end
end
describe Puppet::Util::Log.desttypes[:console] do
let (:klass) { Puppet::Util::Log.desttypes[:console] }
describe "when color is available" do
before :each do
subject.stubs(:console_has_color?).returns(true)
end
it "should support color output" do
Puppet[:color] = true
- subject.colorize(:red, 'version').should == "\e[0;31mversion\e[0m"
+ expect(subject.colorize(:red, 'version')).to eq("\e[0;31mversion\e[0m")
end
it "should withhold color output when not appropriate" do
Puppet[:color] = false
- subject.colorize(:red, 'version').should == "version"
+ expect(subject.colorize(:red, 'version')).to eq("version")
end
it "should handle multiple overlapping colors in a stack-like way" do
Puppet[:color] = true
vstring = subject.colorize(:red, 'version')
- subject.colorize(:green, "(#{vstring})").should == "\e[0;32m(\e[0;31mversion\e[0;32m)\e[0m"
+ expect(subject.colorize(:green, "(#{vstring})")).to eq("\e[0;32m(\e[0;31mversion\e[0;32m)\e[0m")
end
it "should handle resets in a stack-like way" do
Puppet[:color] = true
vstring = subject.colorize(:reset, 'version')
- subject.colorize(:green, "(#{vstring})").should == "\e[0;32m(\e[mversion\e[0;32m)\e[0m"
+ expect(subject.colorize(:green, "(#{vstring})")).to eq("\e[0;32m(\e[mversion\e[0;32m)\e[0m")
end
it "should include the log message's source/context in the output when available" do
Puppet[:color] = false
$stdout.expects(:puts).with("Info: a hitchhiker: don't panic")
msg = Puppet::Util::Log.new(:level => :info, :message => "don't panic", :source => "a hitchhiker")
dest = klass.new
dest.handle(msg)
end
end
end
describe ":eventlog", :if => Puppet::Util::Platform.windows? do
let(:klass) { Puppet::Util::Log.desttypes[:eventlog] }
def expects_message_with_type(klass, level, eventlog_type, eventlog_id)
eventlog = stub('eventlog')
eventlog.expects(:report_event).with(has_entries(:source => "Puppet", :event_type => eventlog_type, :event_id => eventlog_id, :data => "a hitchhiker: don't panic"))
Win32::EventLog.stubs(:open).returns(eventlog)
msg = Puppet::Util::Log.new(:level => level, :message => "don't panic", :source => "a hitchhiker")
dest = klass.new
dest.handle(msg)
end
it "supports the eventlog feature" do
- expect(Puppet.features.eventlog?).to be_true
+ expect(Puppet.features.eventlog?).to be_truthy
end
it "logs to the Application event log" do
eventlog = stub('eventlog')
Win32::EventLog.expects(:open).with('Application').returns(stub('eventlog'))
klass.new
end
it "logs :debug level as an information type event" do
expects_message_with_type(klass, :debug, klass::EVENTLOG_INFORMATION_TYPE, 0x1)
end
it "logs :warning level as an warning type event" do
expects_message_with_type(klass, :warning, klass::EVENTLOG_WARNING_TYPE, 0x2)
end
it "logs :err level as an error type event" do
expects_message_with_type(klass, :err, klass::EVENTLOG_ERROR_TYPE, 0x3)
end
end
diff --git a/spec/unit/util/log_spec.rb b/spec/unit/util/log_spec.rb
index bc6ecfcf0..4bd230411 100755
--- a/spec/unit/util/log_spec.rb
+++ b/spec/unit/util/log_spec.rb
@@ -1,378 +1,378 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/log'
describe Puppet::Util::Log do
include PuppetSpec::Files
def log_notice(message)
Puppet::Util::Log.new(:level => :notice, :message => message)
end
it "should write a given message to the specified destination" do
arraydest = []
Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(arraydest))
Puppet::Util::Log.new(:level => :notice, :message => "foo")
message = arraydest.last.message
- message.should == "foo"
+ expect(message).to eq("foo")
end
describe ".setup_default" do
it "should default to :syslog" do
Puppet.features.stubs(:syslog?).returns(true)
Puppet::Util::Log.expects(:newdestination).with(:syslog)
Puppet::Util::Log.setup_default
end
it "should fall back to :eventlog" do
Puppet.features.stubs(:syslog?).returns(false)
Puppet.features.stubs(:eventlog?).returns(true)
Puppet::Util::Log.expects(:newdestination).with(:eventlog)
Puppet::Util::Log.setup_default
end
it "should fall back to :file" do
Puppet.features.stubs(:syslog?).returns(false)
Puppet.features.stubs(:eventlog?).returns(false)
Puppet::Util::Log.expects(:newdestination).with(Puppet[:puppetdlog])
Puppet::Util::Log.setup_default
end
end
describe "#with_destination" do
it "does nothing when nested" do
logs = []
destination = Puppet::Test::LogCollector.new(logs)
Puppet::Util::Log.with_destination(destination) do
Puppet::Util::Log.with_destination(destination) do
log_notice("Inner block")
end
log_notice("Outer block")
end
log_notice("Outside")
expect(logs.collect(&:message)).to include("Inner block", "Outer block")
expect(logs.collect(&:message)).not_to include("Outside")
end
it "logs when called a second time" do
logs = []
destination = Puppet::Test::LogCollector.new(logs)
Puppet::Util::Log.with_destination(destination) do
log_notice("First block")
end
log_notice("Between blocks")
Puppet::Util::Log.with_destination(destination) do
log_notice("Second block")
end
expect(logs.collect(&:message)).to include("First block", "Second block")
expect(logs.collect(&:message)).not_to include("Between blocks")
end
it "doesn't close the destination if already set manually" do
logs = []
destination = Puppet::Test::LogCollector.new(logs)
Puppet::Util::Log.newdestination(destination)
Puppet::Util::Log.with_destination(destination) do
log_notice "Inner block"
end
log_notice "Outer block"
Puppet::Util::Log.close(destination)
expect(logs.collect(&:message)).to include("Inner block", "Outer block")
end
end
describe Puppet::Util::Log::DestConsole do
before do
@console = Puppet::Util::Log::DestConsole.new
@console.stubs(:console_has_color?).returns(true)
end
it "should colorize if Puppet[:color] is :ansi" do
Puppet[:color] = :ansi
- @console.colorize(:alert, "abc").should == "\e[0;31mabc\e[0m"
+ expect(@console.colorize(:alert, "abc")).to eq("\e[0;31mabc\e[0m")
end
it "should colorize if Puppet[:color] is 'yes'" do
Puppet[:color] = "yes"
- @console.colorize(:alert, "abc").should == "\e[0;31mabc\e[0m"
+ expect(@console.colorize(:alert, "abc")).to eq("\e[0;31mabc\e[0m")
end
it "should htmlize if Puppet[:color] is :html" do
Puppet[:color] = :html
- @console.colorize(:alert, "abc").should == "<span style=\"color: #FFA0A0\">abc</span>"
+ expect(@console.colorize(:alert, "abc")).to eq("<span style=\"color: #FFA0A0\">abc</span>")
end
it "should do nothing if Puppet[:color] is false" do
Puppet[:color] = false
- @console.colorize(:alert, "abc").should == "abc"
+ expect(@console.colorize(:alert, "abc")).to eq("abc")
end
it "should do nothing if Puppet[:color] is invalid" do
Puppet[:color] = "invalid option"
- @console.colorize(:alert, "abc").should == "abc"
+ expect(@console.colorize(:alert, "abc")).to eq("abc")
end
end
describe Puppet::Util::Log::DestSyslog do
before do
@syslog = Puppet::Util::Log::DestSyslog.new
end
end
describe Puppet::Util::Log::DestEventlog, :if => Puppet.features.eventlog? do
before :each do
- Win32::EventLog.stubs(:open).returns(mock 'mylog')
+ Win32::EventLog.stubs(:open).returns(stub 'mylog')
Win32::EventLog.stubs(:report_event)
Win32::EventLog.stubs(:close)
Puppet.features.stubs(:eventlog?).returns(true)
end
it "should restrict its suitability" do
Puppet.features.expects(:eventlog?).returns(false)
- Puppet::Util::Log::DestEventlog.suitable?('whatever').should == false
+ expect(Puppet::Util::Log::DestEventlog.suitable?('whatever')).to eq(false)
end
it "should open the 'Application' event log" do
Win32::EventLog.expects(:open).with('Application')
Puppet::Util::Log.newdestination(:eventlog)
end
it "should close the event log" do
- log = mock('myeventlog')
+ log = stub('myeventlog')
log.expects(:close)
Win32::EventLog.expects(:open).returns(log)
Puppet::Util::Log.newdestination(:eventlog)
Puppet::Util::Log.close(:eventlog)
end
it "should handle each puppet log level" do
log = Puppet::Util::Log::DestEventlog.new
Puppet::Util::Log.eachlevel do |level|
- log.to_native(level).should be_is_a(Array)
+ expect(log.to_native(level)).to be_is_a(Array)
end
end
end
describe "instances" do
before do
Puppet::Util::Log.stubs(:newmessage)
end
[:level, :message, :time, :remote].each do |attr|
it "should have a #{attr} attribute" do
log = Puppet::Util::Log.new :level => :notice, :message => "A test message"
- log.should respond_to(attr)
- log.should respond_to(attr.to_s + "=")
+ expect(log).to respond_to(attr)
+ expect(log).to respond_to(attr.to_s + "=")
end
end
it "should fail if created without a level" do
- lambda { Puppet::Util::Log.new(:message => "A test message") }.should raise_error(ArgumentError)
+ expect { Puppet::Util::Log.new(:message => "A test message") }.to raise_error(ArgumentError)
end
it "should fail if created without a message" do
- lambda { Puppet::Util::Log.new(:level => :notice) }.should raise_error(ArgumentError)
+ expect { Puppet::Util::Log.new(:level => :notice) }.to raise_error(ArgumentError)
end
it "should make available the level passed in at initialization" do
- Puppet::Util::Log.new(:level => :notice, :message => "A test message").level.should == :notice
+ expect(Puppet::Util::Log.new(:level => :notice, :message => "A test message").level).to eq(:notice)
end
it "should make available the message passed in at initialization" do
- Puppet::Util::Log.new(:level => :notice, :message => "A test message").message.should == "A test message"
+ expect(Puppet::Util::Log.new(:level => :notice, :message => "A test message").message).to eq("A test message")
end
# LAK:NOTE I don't know why this behavior is here, I'm just testing what's in the code,
# at least at first.
it "should always convert messages to strings" do
- Puppet::Util::Log.new(:level => :notice, :message => :foo).message.should == "foo"
+ expect(Puppet::Util::Log.new(:level => :notice, :message => :foo).message).to eq("foo")
end
it "should flush the log queue when the first destination is specified" do
Puppet::Util::Log.close_all
Puppet::Util::Log.expects(:flushqueue)
Puppet::Util::Log.newdestination(:console)
end
it "should convert the level to a symbol if it's passed in as a string" do
- Puppet::Util::Log.new(:level => "notice", :message => :foo).level.should == :notice
+ expect(Puppet::Util::Log.new(:level => "notice", :message => :foo).level).to eq(:notice)
end
it "should fail if the level is not a symbol or string" do
- lambda { Puppet::Util::Log.new(:level => 50, :message => :foo) }.should raise_error(ArgumentError)
+ expect { Puppet::Util::Log.new(:level => 50, :message => :foo) }.to raise_error(ArgumentError)
end
it "should fail if the provided level is not valid" do
Puppet::Util::Log.expects(:validlevel?).with(:notice).returns false
- lambda { Puppet::Util::Log.new(:level => :notice, :message => :foo) }.should raise_error(ArgumentError)
+ expect { Puppet::Util::Log.new(:level => :notice, :message => :foo) }.to raise_error(ArgumentError)
end
it "should set its time to the initialization time" do
time = mock 'time'
Time.expects(:now).returns time
- Puppet::Util::Log.new(:level => "notice", :message => :foo).time.should equal(time)
+ expect(Puppet::Util::Log.new(:level => "notice", :message => :foo).time).to equal(time)
end
it "should make available any passed-in tags" do
log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :tags => %w{foo bar})
- log.tags.should be_include("foo")
- log.tags.should be_include("bar")
+ expect(log.tags).to be_include("foo")
+ expect(log.tags).to be_include("bar")
end
it "should use a passed-in source" do
Puppet::Util::Log.any_instance.expects(:source=).with "foo"
Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => "foo")
end
[:file, :line].each do |attr|
it "should use #{attr} if provided" do
Puppet::Util::Log.any_instance.expects(attr.to_s + "=").with "foo"
Puppet::Util::Log.new(:level => "notice", :message => :foo, attr => "foo")
end
end
it "should default to 'Puppet' as its source" do
- Puppet::Util::Log.new(:level => "notice", :message => :foo).source.should == "Puppet"
+ expect(Puppet::Util::Log.new(:level => "notice", :message => :foo).source).to eq("Puppet")
end
it "should register itself with Log" do
Puppet::Util::Log.expects(:newmessage)
Puppet::Util::Log.new(:level => "notice", :message => :foo)
end
it "should update Log autoflush when Puppet[:autoflush] is set" do
Puppet::Util::Log.expects(:autoflush=).once.with(true)
Puppet[:autoflush] = true
end
it "should have a method for determining if a tag is present" do
- Puppet::Util::Log.new(:level => "notice", :message => :foo).should respond_to(:tagged?)
+ expect(Puppet::Util::Log.new(:level => "notice", :message => :foo)).to respond_to(:tagged?)
end
it "should match a tag if any of the tags are equivalent to the passed tag as a string" do
- Puppet::Util::Log.new(:level => "notice", :message => :foo, :tags => %w{one two}).should be_tagged(:one)
+ expect(Puppet::Util::Log.new(:level => "notice", :message => :foo, :tags => %w{one two})).to be_tagged(:one)
end
it "should tag itself with its log level" do
- Puppet::Util::Log.new(:level => "notice", :message => :foo).should be_tagged(:notice)
+ expect(Puppet::Util::Log.new(:level => "notice", :message => :foo)).to be_tagged(:notice)
end
it "should return its message when converted to a string" do
- Puppet::Util::Log.new(:level => "notice", :message => :foo).to_s.should == "foo"
+ expect(Puppet::Util::Log.new(:level => "notice", :message => :foo).to_s).to eq("foo")
end
it "should include its time, source, level, and message when prepared for reporting" do
log = Puppet::Util::Log.new(:level => "notice", :message => :foo)
report = log.to_report
- report.should be_include("notice")
- report.should be_include("foo")
- report.should be_include(log.source)
- report.should be_include(log.time.to_s)
+ expect(report).to be_include("notice")
+ expect(report).to be_include("foo")
+ expect(report).to be_include(log.source)
+ expect(report).to be_include(log.time.to_s)
end
it "should not create unsuitable log destinations" do
Puppet.features.stubs(:syslog?).returns(false)
Puppet::Util::Log::DestSyslog.expects(:suitable?)
Puppet::Util::Log::DestSyslog.expects(:new).never
Puppet::Util::Log.newdestination(:syslog)
end
describe "when setting the source as a RAL object" do
let(:path) { File.expand_path('/foo/bar') }
it "should tag itself with any tags the source has" do
source = Puppet::Type.type(:file).new :path => path
log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => source)
source.tags.each do |tag|
- log.tags.should be_include(tag)
+ expect(log.tags).to be_include(tag)
end
end
it "should set the source to 'path', when available" do
source = Puppet::Type.type(:file).new :path => path
source.tags = ["tag", "tag2"]
log = Puppet::Util::Log.new(:level => "notice", :message => :foo)
log.expects(:tag).with("file")
log.expects(:tag).with("tag")
log.expects(:tag).with("tag2")
log.source = source
- log.source.should == "/File[#{path}]"
+ expect(log.source).to eq("/File[#{path}]")
end
it "should copy over any file and line information" do
source = Puppet::Type.type(:file).new :path => path
source.file = "/my/file"
source.line = 50
log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => source)
- log.line.should == 50
- log.file.should == "/my/file"
+ expect(log.line).to eq(50)
+ expect(log.file).to eq("/my/file")
end
end
describe "when setting the source as a non-RAL object" do
it "should not try to copy over file, version, line, or tag information" do
source = mock
source.expects(:file).never
log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => source)
end
end
end
describe "to_yaml" do
it "should not include the @version attribute" do
log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :version => 100)
- log.to_yaml_properties.should_not include('@version')
+ expect(log.to_yaml_properties).not_to include('@version')
end
it "should include attributes @level, @message, @source, @tags, and @time" do
log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :version => 100)
- log.to_yaml_properties.should =~ [:@level, :@message, :@source, :@tags, :@time]
+ expect(log.to_yaml_properties).to match_array([:@level, :@message, :@source, :@tags, :@time])
end
it "should include attributes @file and @line if specified" do
log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :file => "foo", :line => 35)
- log.to_yaml_properties.should include(:@file)
- log.to_yaml_properties.should include(:@line)
+ expect(log.to_yaml_properties).to include(:@file)
+ expect(log.to_yaml_properties).to include(:@line)
end
end
it "should round trip through pson" do
log = Puppet::Util::Log.new(:level => 'notice', :message => 'hooray', :file => 'thefile', :line => 1729, :source => 'specs', :tags => ['a', 'b', 'c'])
tripped = Puppet::Util::Log.from_data_hash(PSON.parse(log.to_pson))
- tripped.file.should == log.file
- tripped.line.should == log.line
- tripped.level.should == log.level
- tripped.message.should == log.message
- tripped.source.should == log.source
- tripped.tags.should == log.tags
- tripped.time.should == log.time
+ expect(tripped.file).to eq(log.file)
+ expect(tripped.line).to eq(log.line)
+ expect(tripped.level).to eq(log.level)
+ expect(tripped.message).to eq(log.message)
+ expect(tripped.source).to eq(log.source)
+ expect(tripped.tags).to eq(log.tags)
+ expect(tripped.time).to eq(log.time)
end
end
diff --git a/spec/unit/util/logging_spec.rb b/spec/unit/util/logging_spec.rb
index fb2bca71b..f9148f7c8 100755
--- a/spec/unit/util/logging_spec.rb
+++ b/spec/unit/util/logging_spec.rb
@@ -1,322 +1,322 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/logging'
class LoggingTester
include Puppet::Util::Logging
end
describe Puppet::Util::Logging do
before do
@logger = LoggingTester.new
end
Puppet::Util::Log.eachlevel do |level|
it "should have a method for sending '#{level}' logs" do
- @logger.should respond_to(level)
+ expect(@logger).to respond_to(level)
end
end
it "should have a method for sending a log with a specified log level" do
@logger.expects(:to_s).returns "I'm a string!"
Puppet::Util::Log.expects(:create).with { |args| args[:source] == "I'm a string!" and args[:level] == "loglevel" and args[:message] == "mymessage" }
@logger.send_log "loglevel", "mymessage"
end
describe "when sending a log" do
it "should use the Log's 'create' entrance method" do
Puppet::Util::Log.expects(:create)
@logger.notice "foo"
end
it "should send itself converted to a string as the log source" do
@logger.expects(:to_s).returns "I'm a string!"
Puppet::Util::Log.expects(:create).with { |args| args[:source] == "I'm a string!" }
@logger.notice "foo"
end
it "should queue logs sent without a specified destination" do
Puppet::Util::Log.close_all
Puppet::Util::Log.expects(:queuemessage)
@logger.notice "foo"
end
it "should use the path of any provided resource type" do
resource = Puppet::Type.type(:host).new :name => "foo"
resource.expects(:path).returns "/path/to/host".to_sym
Puppet::Util::Log.expects(:create).with { |args| args[:source] == "/path/to/host" }
resource.notice "foo"
end
it "should use the path of any provided resource parameter" do
resource = Puppet::Type.type(:host).new :name => "foo"
param = resource.parameter(:name)
param.expects(:path).returns "/path/to/param".to_sym
Puppet::Util::Log.expects(:create).with { |args| args[:source] == "/path/to/param" }
param.notice "foo"
end
it "should send the provided argument as the log message" do
Puppet::Util::Log.expects(:create).with { |args| args[:message] == "foo" }
@logger.notice "foo"
end
it "should join any provided arguments into a single string for the message" do
Puppet::Util::Log.expects(:create).with { |args| args[:message] == "foo bar baz" }
@logger.notice ["foo", "bar", "baz"]
end
[:file, :line, :tags].each do |attr|
it "should include #{attr} if available" do
@logger.singleton_class.send(:attr_accessor, attr)
@logger.send(attr.to_s + "=", "myval")
Puppet::Util::Log.expects(:create).with { |args| args[attr] == "myval" }
@logger.notice "foo"
end
end
end
describe "when sending a deprecation warning" do
it "does not log a message when deprecation warnings are disabled" do
Puppet.expects(:[]).with(:disable_warnings).returns %w[deprecations]
@logger.expects(:warning).never
@logger.deprecation_warning 'foo'
end
it "logs the message with warn" do
@logger.expects(:warning).with do |msg|
msg =~ /^foo\n/
end
@logger.deprecation_warning 'foo'
end
it "only logs each offending line once" do
@logger.expects(:warning).with do |msg|
msg =~ /^foo\n/
end .once
5.times { @logger.deprecation_warning 'foo' }
end
it "ensures that deprecations from same origin are logged if their keys differ" do
@logger.expects(:warning).with(regexp_matches(/deprecated foo/)).times(5)
5.times { |i| @logger.deprecation_warning('deprecated foo', :key => "foo#{i}") }
end
it "does not duplicate deprecations for a given key" do
@logger.expects(:warning).with(regexp_matches(/deprecated foo/)).once
5.times { @logger.deprecation_warning('deprecated foo', :key => 'foo-msg') }
end
it "only logs the first 100 messages" do
(1..100).each { |i|
@logger.expects(:warning).with do |msg|
msg =~ /^#{i}\n/
end .once
# since the deprecation warning will only log each offending line once, we have to do some tomfoolery
# here in order to make it think each of these calls is coming from a unique call stack; we're basically
# mocking the method that it would normally use to find the call stack.
@logger.expects(:get_deprecation_offender).returns(["deprecation log count test ##{i}"])
@logger.deprecation_warning i
}
@logger.expects(:warning).with(101).never
@logger.deprecation_warning 101
end
end
describe "when sending a puppet_deprecation_warning" do
it "requires file and line or key options" do
expect do
@logger.puppet_deprecation_warning("foo")
end.to raise_error(Puppet::DevError, /Need either :file and :line, or :key/)
expect do
@logger.puppet_deprecation_warning("foo", :file => 'bar')
end.to raise_error(Puppet::DevError, /Need either :file and :line, or :key/)
expect do
@logger.puppet_deprecation_warning("foo", :key => 'akey')
@logger.puppet_deprecation_warning("foo", :file => 'afile', :line => 1)
end.to_not raise_error
end
it "warns with file and line" do
@logger.expects(:warning).with(regexp_matches(/deprecated foo.*afile:5/m))
@logger.puppet_deprecation_warning("deprecated foo", :file => 'afile', :line => 5)
end
it "warns keyed from file and line" do
@logger.expects(:warning).with(regexp_matches(/deprecated foo.*afile:5/m)).once
5.times do
@logger.puppet_deprecation_warning("deprecated foo", :file => 'afile', :line => 5)
end
end
it "warns with separate key only once regardless of file and line" do
@logger.expects(:warning).with(regexp_matches(/deprecated foo.*afile:5/m)).once
@logger.puppet_deprecation_warning("deprecated foo", :key => 'some_key', :file => 'afile', :line => 5)
@logger.puppet_deprecation_warning("deprecated foo", :key => 'some_key', :file => 'bfile', :line => 3)
end
it "warns with key but no file and line" do
@logger.expects(:warning).with(regexp_matches(/deprecated foo.*unknown:unknown/m))
@logger.puppet_deprecation_warning("deprecated foo", :key => 'some_key')
end
end
describe "when formatting exceptions" do
it "should be able to format a chain of exceptions" do
exc3 = Puppet::Error.new("original")
exc3.set_backtrace(["1.rb:4:in `a'","2.rb:2:in `b'","3.rb:1"])
exc2 = Puppet::Error.new("second", exc3)
exc2.set_backtrace(["4.rb:8:in `c'","5.rb:1:in `d'","6.rb:3"])
exc1 = Puppet::Error.new("third", exc2)
exc1.set_backtrace(["7.rb:31:in `e'","8.rb:22:in `f'","9.rb:9"])
# whoa ugly
- @logger.format_exception(exc1).should =~ /third
+ expect(@logger.format_exception(exc1)).to match(/third
.*7\.rb:31:in `e'
.*8\.rb:22:in `f'
.*9\.rb:9
Wrapped exception:
second
.*4\.rb:8:in `c'
.*5\.rb:1:in `d'
.*6\.rb:3
Wrapped exception:
original
.*1\.rb:4:in `a'
.*2\.rb:2:in `b'
-.*3\.rb:1/
+.*3\.rb:1/)
end
end
describe 'when Facter' do
after :each do
# Unstub these calls as there is global code run after
# each spec that may reset the log level to debug
Facter.unstub(:respond_to?)
Facter.unstub(:debugging)
end
describe 'does not support debugging' do
before :each do
Facter.stubs(:respond_to?).with(:debugging).returns false
Facter.stubs(:debugging).never
end
it 'does not enable Facter debugging for debug level' do
Puppet::Util::Log.level = :debug
end
it 'does not enable Facter debugging non-debug level' do
Puppet::Util::Log.level = :info
end
end
describe 'does support debugging' do
before :each do
Facter.stubs(:respond_to?).with(:debugging).returns true
end
it 'enables Facter debugging when debug level' do
Facter.stubs(:debugging).with(true)
Puppet::Util::Log.level = :debug
end
it 'disables Facter debugging when not debug level' do
Facter.stubs(:debugging).with(false)
Puppet::Util::Log.level = :info
end
end
describe 'does not support trace' do
before :each do
Facter.stubs(:respond_to?).with(:trace).returns false
Facter.stubs(:trace).never
end
it 'does not enable Facter trace when enabled' do
Puppet[:trace] = true
end
it 'does not enable Facter trace when disabled' do
Puppet[:trace] = false
end
end
describe 'does support trace' do
before :each do
Facter.stubs(:respond_to?).with(:trace).returns true
end
it 'enables Facter trace when enabled' do
Facter.stubs(:trace).with(true)
Puppet[:trace] = true
end
it 'disables Facter trace when disabled' do
Facter.stubs(:trace).with(false)
Puppet[:trace] = false
end
end
describe 'does not support on_message' do
before :each do
Facter.stubs(:respond_to?).with(:on_message).returns false
Facter.stubs(:on_message).never
end
it 'does not call Facter.on_message' do
- Puppet::Util::Logging::setup_facter_logging!.should be_false
+ expect(Puppet::Util::Logging::setup_facter_logging!).to be_falsey
end
end
describe 'does support on_message' do
before :each do
Facter.stubs(:respond_to?).with(:on_message).returns true
end
def setup(level, message)
Facter.stubs(:on_message).yields level, message
# Transform from Facter level to Puppet level
case level
when :trace
level = :debug
when :warn
level = :warning
when :error
level = :err
when :fatal
level = :crit
end
Puppet::Util::Log.stubs(:create).with do |options|
- options[:level].should eq(level)
- options[:message].should eq(message)
- options[:source].should eq('Facter')
+ expect(options[:level]).to eq(level)
+ expect(options[:message]).to eq(message)
+ expect(options[:source]).to eq('Facter')
end.once
end
[:trace, :debug, :info, :warn, :error, :fatal].each do |level|
it "calls Facter.on_message and handles #{level} messages" do
setup(level, "#{level} message")
- Puppet::Util::Logging::setup_facter_logging!.should be_true
+ expect(Puppet::Util::Logging::setup_facter_logging!).to be_truthy
end
end
end
end
end
diff --git a/spec/unit/util/metric_spec.rb b/spec/unit/util/metric_spec.rb
index 660e96960..eccd185b2 100755
--- a/spec/unit/util/metric_spec.rb
+++ b/spec/unit/util/metric_spec.rb
@@ -1,83 +1,83 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/metric'
describe Puppet::Util::Metric do
before do
@metric = Puppet::Util::Metric.new("foo")
end
[:type, :name, :value, :label].each do |name|
it "should have a #{name} attribute" do
- @metric.should respond_to(name)
- @metric.should respond_to(name.to_s + "=")
+ expect(@metric).to respond_to(name)
+ expect(@metric).to respond_to(name.to_s + "=")
end
end
it "should require a name at initialization" do
- lambda { Puppet::Util::Metric.new }.should raise_error(ArgumentError)
+ expect { Puppet::Util::Metric.new }.to raise_error(ArgumentError)
end
it "should always convert its name to a string" do
- Puppet::Util::Metric.new(:foo).name.should == "foo"
+ expect(Puppet::Util::Metric.new(:foo).name).to eq("foo")
end
it "should support a label" do
- Puppet::Util::Metric.new("foo", "mylabel").label.should == "mylabel"
+ expect(Puppet::Util::Metric.new("foo", "mylabel").label).to eq("mylabel")
end
it "should autogenerate a label if none is provided" do
- Puppet::Util::Metric.new("foo_bar").label.should == "Foo bar"
+ expect(Puppet::Util::Metric.new("foo_bar").label).to eq("Foo bar")
end
it "should have a method for adding values" do
- @metric.should respond_to(:newvalue)
+ expect(@metric).to respond_to(:newvalue)
end
it "should have a method for returning values" do
- @metric.should respond_to(:values)
+ expect(@metric).to respond_to(:values)
end
it "should require a name and value for its values" do
- lambda { @metric.newvalue }.should raise_error(ArgumentError)
+ expect { @metric.newvalue }.to raise_error(ArgumentError)
end
it "should support a label for values" do
@metric.newvalue("foo", 10, "label")
- @metric.values[0][1].should == "label"
+ expect(@metric.values[0][1]).to eq("label")
end
it "should autogenerate value labels if none is provided" do
@metric.newvalue("foo_bar", 10)
- @metric.values[0][1].should == "Foo bar"
+ expect(@metric.values[0][1]).to eq("Foo bar")
end
it "should return its values sorted by label" do
@metric.newvalue("foo", 10, "b")
@metric.newvalue("bar", 10, "a")
- @metric.values.should == [["bar", "a", 10], ["foo", "b", 10]]
+ expect(@metric.values).to eq([["bar", "a", 10], ["foo", "b", 10]])
end
it "should use an array indexer method to retrieve individual values" do
@metric.newvalue("foo", 10)
- @metric["foo"].should == 10
+ expect(@metric["foo"]).to eq(10)
end
it "should return nil if the named value cannot be found" do
- @metric["foo"].should == 0
+ expect(@metric["foo"]).to eq(0)
end
it "should round trip through pson" do
metric = Puppet::Util::Metric.new("foo", "mylabel")
metric.newvalue("v1", 10.1, "something")
metric.newvalue("v2", 20, "something else")
tripped = Puppet::Util::Metric.from_data_hash(PSON.parse(metric.to_pson))
- tripped.name.should == metric.name
- tripped.label.should == metric.label
- tripped.values.should == metric.values
+ expect(tripped.name).to eq(metric.name)
+ expect(tripped.label).to eq(metric.label)
+ expect(tripped.values).to eq(metric.values)
end
end
diff --git a/spec/unit/util/monkey_patches_spec.rb b/spec/unit/util/monkey_patches_spec.rb
index 4a13f4b74..6d6599a21 100755
--- a/spec/unit/util/monkey_patches_spec.rb
+++ b/spec/unit/util/monkey_patches_spec.rb
@@ -1,246 +1,219 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/monkey_patches'
describe Symbol do
it "should return self from #intern" do
symbol = :foo
- symbol.should equal symbol.intern
- end
-end
-
-
-describe "yaml deserialization" do
- it "should call yaml_initialize when deserializing objects that have that method defined" do
- class Puppet::TestYamlInitializeClass
- attr_reader :foo
-
- def yaml_initialize(tag, var)
- var.should == {'foo' => 100}
- instance_variables.should == []
- @foo = 200
- end
- end
-
- obj = YAML.load("--- !ruby/object:Puppet::TestYamlInitializeClass\n foo: 100")
- obj.foo.should == 200
- end
-
- it "should not call yaml_initialize if not defined" do
- class Puppet::TestYamlNonInitializeClass
- attr_reader :foo
- end
-
- obj = YAML.load("--- !ruby/object:Puppet::TestYamlNonInitializeClass\n foo: 100")
- obj.foo.should == 100
+ expect(symbol).to equal symbol.intern
end
end
describe IO do
include PuppetSpec::Files
let(:file) { tmpfile('io-binary') }
let(:content) { "\x01\x02\x03\x04" }
describe "::binwrite" do
it "should write in binary mode" do
- IO.binwrite(file, content).should == content.length
- File.open(file, 'rb') {|f| f.read.should == content }
+ expect(IO.binwrite(file, content)).to eq(content.length)
+ File.open(file, 'rb') {|f| expect(f.read).to eq(content) }
end
(0..10).each do |offset|
it "should write correctly using an offset of #{offset}" do
- IO.binwrite(file, content, offset).should == content.length
- File.open(file, 'rb') {|f| f.read.should == ("\x00" * offset) + content }
+ expect(IO.binwrite(file, content, offset)).to eq(content.length)
+ File.open(file, 'rb') {|f| expect(f.read).to eq(("\x00" * offset) + content) }
end
end
context "truncation" do
let :input do "welcome to paradise, population ... YOU!" end
before :each do IO.binwrite(file, input) end
it "should truncate if no offset is given" do
- IO.binwrite(file, "boo").should == 3
- File.read(file).should == "boo"
+ expect(IO.binwrite(file, "boo")).to eq(3)
+ expect(File.read(file)).to eq("boo")
end
(0..10).each do |offset|
it "should not truncate if an offset of #{offset} is given" do
expect = input.dup
expect[offset, 3] = "BAM"
- IO.binwrite(file, "BAM", offset).should == 3
- File.read(file).should == expect
+ expect(IO.binwrite(file, "BAM", offset)).to eq(3)
+ expect(File.read(file)).to eq(expect)
end
end
it "should pad with NULL bytes if writing past EOF without truncate" do
expect = input + ("\x00" * 4) + "BAM"
- IO.binwrite(file, "BAM", input.length + 4).should == 3
- File.read(file).should == expect
+ expect(IO.binwrite(file, "BAM", input.length + 4)).to eq(3)
+ expect(File.read(file)).to eq(expect)
end
end
it "should raise an error if the directory containing the file doesn't exist" do
expect { IO.binwrite('/path/does/not/exist', 'foo') }.to raise_error(Errno::ENOENT)
end
end
end
describe Range do
def do_test( range, other, expected )
result = range.intersection(other)
- result.should == expected
+ expect(result).to eq(expected)
end
it "should return expected ranges for iterable things" do
iterable_tests = {
1 .. 4 => nil, # before
11 .. 15 => nil, # after
1 .. 6 => 5 .. 6, # overlap_begin
9 .. 15 => 9 .. 10, # overlap_end
1 .. 5 => 5 .. 5, # overlap_begin_edge
10 .. 15 => 10 .. 10, # overlap_end_edge
5 .. 10 => 5 .. 10, # overlap_all
6 .. 9 => 6 .. 9, # overlap_inner
1 ... 5 => nil, # before (exclusive range)
1 ... 7 => 5 ... 7, # overlap_begin (exclusive range)
1 ... 6 => 5 ... 6, # overlap_begin_edge (exclusive range)
5 ... 11 => 5 .. 10, # overlap_all (exclusive range)
6 ... 10 => 6 ... 10, # overlap_inner (exclusive range)
}
iterable_tests.each do |other, expected|
do_test( 5..10, other, expected )
do_test( other, 5..10, expected )
end
end
it "should return expected ranges for noniterable things" do
inclusive_base_case = {
1.to_f .. 4.to_f => nil, # before
11.to_f .. 15.to_f => nil, # after
1.to_f .. 6.to_f => 5.to_f .. 6.to_f, # overlap_begin
9.to_f .. 15.to_f => 9.to_f .. 10.to_f, # overlap_end
1.to_f .. 5.to_f => 5.to_f .. 5.to_f, # overlap_begin_edge
10.to_f .. 15.to_f => 10.to_f .. 10.to_f, # overlap_end_edge
5.to_f .. 10.to_f => 5.to_f .. 10.to_f, # overlap_all
6.to_f .. 9.to_f => 6.to_f .. 9.to_f, # overlap_inner
1.to_f ... 5.to_f => nil, # before (exclusive range)
1.to_f ... 7.to_f => 5.to_f ... 7.to_f, # overlap_begin (exclusive range)
1.to_f ... 6.to_f => 5.to_f ... 6.to_f, # overlap_begin_edge (exclusive range)
5.to_f ... 11.to_f => 5.to_f .. 10.to_f, # overlap_all (exclusive range)
6.to_f ... 10.to_f => 6.to_f ... 10.to_f, # overlap_inner (exclusive range)
}
inclusive_base_case.each do |other, expected|
do_test( 5.to_f..10.to_f, other, expected )
do_test( other, 5.to_f..10.to_f, expected )
end
exclusive_base_case = {
1.to_f .. 4.to_f => nil, # before
11.to_f .. 15.to_f => nil, # after
1.to_f .. 6.to_f => 5.to_f .. 6.to_f, # overlap_begin
9.to_f .. 15.to_f => 9.to_f ... 10.to_f, # overlap_end
1.to_f .. 5.to_f => 5.to_f .. 5.to_f, # overlap_begin_edge
10.to_f .. 15.to_f => nil, # overlap_end_edge
5.to_f .. 10.to_f => 5.to_f ... 10.to_f, # overlap_all
6.to_f .. 9.to_f => 6.to_f .. 9.to_f, # overlap_inner
1.to_f ... 5.to_f => nil, # before (exclusive range)
1.to_f ... 7.to_f => 5.to_f ... 7.to_f, # overlap_begin (exclusive range)
1.to_f ... 6.to_f => 5.to_f ... 6.to_f, # overlap_begin_edge (exclusive range)
5.to_f ... 11.to_f => 5.to_f ... 10.to_f, # overlap_all (exclusive range)
6.to_f ... 10.to_f => 6.to_f ... 10.to_f, # overlap_inner (exclusive range)
}
exclusive_base_case.each do |other, expected|
do_test( 5.to_f...10.to_f, other, expected )
do_test( other, 5.to_f...10.to_f, expected )
end
end
end
describe OpenSSL::SSL::SSLContext do
it 'disables SSLv2 via the SSLContext#options bitmask' do
- (subject.options & OpenSSL::SSL::OP_NO_SSLv2).should == OpenSSL::SSL::OP_NO_SSLv2
+ expect(subject.options & OpenSSL::SSL::OP_NO_SSLv2).to eq(OpenSSL::SSL::OP_NO_SSLv2)
end
it 'disables SSLv3 via the SSLContext#options bitmask' do
- (subject.options & OpenSSL::SSL::OP_NO_SSLv3).should == OpenSSL::SSL::OP_NO_SSLv3
+ expect(subject.options & OpenSSL::SSL::OP_NO_SSLv3).to eq(OpenSSL::SSL::OP_NO_SSLv3)
end
it 'explicitly disable SSLv2 ciphers using the ! prefix so they cannot be re-added' do
cipher_str = OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:ciphers]
- cipher_str.split(':').should include('!SSLv2')
+ expect(cipher_str.split(':')).to include('!SSLv2')
end
it 'does not exclude SSLv3 ciphers shared with TLSv1' do
cipher_str = OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:ciphers]
- cipher_str.split(':').should_not include('!SSLv3')
+ expect(cipher_str.split(':')).not_to include('!SSLv3')
end
it 'sets parameters on initialization' do
described_class.any_instance.expects(:set_params)
subject
end
it 'has no ciphers with version SSLv2 enabled' do
ciphers = subject.ciphers.select do |name, version, bits, alg_bits|
/SSLv2/.match(version)
end
- ciphers.should be_empty
+ expect(ciphers).to be_empty
end
end
describe OpenSSL::X509::Store, :if => Puppet::Util::Platform.windows? do
let(:store) { described_class.new }
let(:cert) { OpenSSL::X509::Certificate.new(File.read(my_fixture('x509.pem'))) }
def with_root_certs(certs)
Puppet::Util::Windows::RootCerts.expects(:instance).returns(certs)
end
it "adds a root cert to the store" do
with_root_certs([cert])
store.set_default_paths
end
it "ignores duplicate root certs" do
with_root_certs([cert, cert])
store.expects(:add_cert).with(cert).once
store.set_default_paths
end
it "warns when adding a certificate that already exists" do
with_root_certs([cert])
store.add_cert(cert)
store.expects(:warn).with('Failed to add /DC=com/DC=microsoft/CN=Microsoft Root Certificate Authority')
store.set_default_paths
end
it "raises when adding an invalid certificate" do
with_root_certs(['notacert'])
expect {
store.set_default_paths
}.to raise_error(TypeError)
end
end
describe SecureRandom do
it 'generates a properly formatted uuid' do
- SecureRandom.uuid.should =~ /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i
+ expect(SecureRandom.uuid).to match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i)
end
end
diff --git a/spec/unit/util/nagios_maker_spec.rb b/spec/unit/util/nagios_maker_spec.rb
index e50c75305..d020cc2b8 100755
--- a/spec/unit/util/nagios_maker_spec.rb
+++ b/spec/unit/util/nagios_maker_spec.rb
@@ -1,122 +1,122 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/nagios_maker'
describe Puppet::Util::NagiosMaker do
before do
@module = Puppet::Util::NagiosMaker
@nagtype = stub 'nagios type', :parameters => [], :namevar => :name
Nagios::Base.stubs(:type).with(:test).returns(@nagtype)
@provider = stub 'provider', :nagios_type => nil
@type = stub 'type', :newparam => nil, :newproperty => nil, :provide => @provider, :desc => nil, :ensurable => nil
end
it "should be able to create a new nagios type" do
- @module.should respond_to(:create_nagios_type)
+ expect(@module).to respond_to(:create_nagios_type)
end
it "should fail if it cannot find the named Naginator type" do
Nagios::Base.stubs(:type).returns(nil)
- lambda { @module.create_nagios_type(:no_such_type) }.should raise_error(Puppet::DevError)
+ expect { @module.create_nagios_type(:no_such_type) }.to raise_error(Puppet::DevError)
end
it "should create a new RAL type with the provided name prefixed with 'nagios_'" do
Puppet::Type.expects(:newtype).with(:nagios_test).returns(@type)
@module.create_nagios_type(:test)
end
it "should mark the created type as ensurable" do
@type.expects(:ensurable)
Puppet::Type.expects(:newtype).with(:nagios_test).returns(@type)
@module.create_nagios_type(:test)
end
it "should create a namevar parameter for the nagios type's name parameter" do
@type.expects(:newparam).with(:name, :namevar => true)
Puppet::Type.expects(:newtype).with(:nagios_test).returns(@type)
@module.create_nagios_type(:test)
end
it "should create a property for all non-namevar parameters" do
@nagtype.stubs(:parameters).returns([:one, :two])
@type.expects(:newproperty).with(:one)
@type.expects(:newproperty).with(:two)
@type.expects(:newproperty).with(:target)
Puppet::Type.expects(:newtype).with(:nagios_test).returns(@type)
@module.create_nagios_type(:test)
end
it "should skip parameters that start with integers" do
@nagtype.stubs(:parameters).returns(["2dcoords".to_sym, :other])
@type.expects(:newproperty).with(:other)
@type.expects(:newproperty).with(:target)
Puppet::Type.expects(:newtype).with(:nagios_test).returns(@type)
@module.create_nagios_type(:test)
end
it "should deduplicate the parameter list" do
@nagtype.stubs(:parameters).returns([:one, :one])
@type.expects(:newproperty).with(:one)
@type.expects(:newproperty).with(:target)
Puppet::Type.expects(:newtype).with(:nagios_test).returns(@type)
@module.create_nagios_type(:test)
end
it "should create a target property" do
@type.expects(:newproperty).with(:target)
Puppet::Type.expects(:newtype).with(:nagios_test).returns(@type)
@module.create_nagios_type(:test)
end
end
describe Puppet::Util::NagiosMaker, " when creating the naginator provider" do
before do
@module = Puppet::Util::NagiosMaker
@provider = stub 'provider', :nagios_type => nil
@nagtype = stub 'nagios type', :parameters => [], :namevar => :name
Nagios::Base.stubs(:type).with(:test).returns(@nagtype)
@type = stub 'type', :newparam => nil, :ensurable => nil, :newproperty => nil, :desc => nil
Puppet::Type.stubs(:newtype).with(:nagios_test).returns(@type)
end
it "should add a naginator provider" do
@type.expects(:provide).with { |name, options| name == :naginator }.returns @provider
@module.create_nagios_type(:test)
end
it "should set Puppet::Provider::Naginator as the parent class of the provider" do
@type.expects(:provide).with { |name, options| options[:parent] == Puppet::Provider::Naginator }.returns @provider
@module.create_nagios_type(:test)
end
it "should use /etc/nagios/$name.cfg as the default target" do
@type.expects(:provide).with { |name, options| options[:default_target] == "/etc/nagios/nagios_test.cfg" }.returns @provider
@module.create_nagios_type(:test)
end
it "should trigger the lookup of the Nagios class" do
@type.expects(:provide).returns @provider
@provider.expects(:nagios_type)
@module.create_nagios_type(:test)
end
end
diff --git a/spec/unit/util/network_device/cisco/device_spec.rb b/spec/unit/util/network_device/cisco/device_spec.rb
index 2fc0c1180..62a7f87b9 100755
--- a/spec/unit/util/network_device/cisco/device_spec.rb
+++ b/spec/unit/util/network_device/cisco/device_spec.rb
@@ -1,445 +1,445 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/network_device/cisco/device'
require 'puppet/util/network_device/transport/telnet'
describe Puppet::Util::NetworkDevice::Cisco::Device do
before(:each) do
@transport = stub_everything 'transport', :is_a? => true, :command => ""
@cisco = Puppet::Util::NetworkDevice::Cisco::Device.new("telnet://user:password@localhost:23/")
@cisco.transport = @transport
end
describe "when creating the device" do
it "should find the enable password from the url" do
cisco = Puppet::Util::NetworkDevice::Cisco::Device.new("telnet://user:password@localhost:23/?enable=enable_password")
- cisco.enable_password.should == "enable_password"
+ expect(cisco.enable_password).to eq("enable_password")
end
describe "decoding the enable password" do
it "should not parse a password if no query is given" do
cisco = described_class.new("telnet://user:password@localhost:23")
- cisco.enable_password.should be_nil
+ expect(cisco.enable_password).to be_nil
end
it "should not parse a password if no enable param is given" do
cisco = described_class.new("telnet://user:password@localhost:23/?notenable=notapassword")
- cisco.enable_password.should be_nil
+ expect(cisco.enable_password).to be_nil
end
it "should decode sharps" do
cisco = described_class.new("telnet://user:password@localhost:23/?enable=enable_password%23with_a_sharp")
- cisco.enable_password.should == "enable_password#with_a_sharp"
+ expect(cisco.enable_password).to eq("enable_password#with_a_sharp")
end
it "should decode spaces" do
cisco = described_class.new("telnet://user:password@localhost:23/?enable=enable_password%20with_a_space")
- cisco.enable_password.should == "enable_password with_a_space"
+ expect(cisco.enable_password).to eq("enable_password with_a_space")
end
it "should only use the query parameter" do
cisco = described_class.new("telnet://enable=:password@localhost:23/?enable=enable_password&notenable=notapassword")
- cisco.enable_password.should == "enable_password"
+ expect(cisco.enable_password).to eq("enable_password")
end
end
it "should find the enable password from the options" do
cisco = Puppet::Util::NetworkDevice::Cisco::Device.new("telnet://user:password@localhost:23/?enable=enable_password", :enable_password => "mypass")
- cisco.enable_password.should == "mypass"
+ expect(cisco.enable_password).to eq("mypass")
end
it "should find the debug mode from the options" do
Puppet::Util::NetworkDevice::Transport::Telnet.expects(:new).with(true).returns(@transport)
cisco = Puppet::Util::NetworkDevice::Cisco::Device.new("telnet://user:password@localhost:23", :debug => true)
end
it "should set the debug mode to nil by default" do
Puppet::Util::NetworkDevice::Transport::Telnet.expects(:new).with(nil).returns(@transport)
cisco = Puppet::Util::NetworkDevice::Cisco::Device.new("telnet://user:password@localhost:23")
end
end
describe "when connecting to the physical device" do
it "should connect to the transport" do
@transport.expects(:connect)
@cisco.command
end
it "should attempt to login" do
@cisco.expects(:login)
@cisco.command
end
it "should tell the device to not page" do
@transport.expects(:command).with("terminal length 0")
@cisco.command
end
it "should enter the enable password if returned prompt is not privileged" do
@transport.stubs(:command).yields("Switch>").returns("")
@cisco.expects(:enable)
@cisco.command
end
it "should find device capabilities" do
@cisco.expects(:find_capabilities)
@cisco.command
end
it "should execute given command" do
@transport.expects(:command).with("mycommand")
@cisco.command("mycommand")
end
it "should yield to the command block if one is provided" do
@transport.expects(:command).with("mycommand")
@cisco.command do |c|
c.command("mycommand")
end
end
it "should close the device transport" do
@transport.expects(:close)
@cisco.command
end
describe "when login in" do
it "should not login if transport handles login" do
@transport.expects(:handles_login?).returns(true)
@transport.expects(:command).never
@transport.expects(:expect).never
@cisco.login
end
it "should send username if one has been provided" do
@transport.expects(:command).with("user", :prompt => /^Password:/)
@cisco.login
end
it "should send password after the username" do
@transport.expects(:command).with("user", :prompt => /^Password:/)
@transport.expects(:command).with("password")
@cisco.login
end
it "should expect the Password: prompt if no user was sent" do
@cisco.url.user = ''
@transport.expects(:expect).with(/^Password:/)
@transport.expects(:command).with("password")
@cisco.login
end
end
describe "when entering enable password" do
it "should raise an error if no enable password has been set" do
@cisco.enable_password = nil
- lambda{ @cisco.enable }.should raise_error
+ expect{ @cisco.enable }.to raise_error
end
it "should send the enable command and expect an enable prompt" do
@cisco.enable_password = 'mypass'
@transport.expects(:command).with("enable", :prompt => /^Password:/)
@cisco.enable
end
it "should send the enable password" do
@cisco.enable_password = 'mypass'
@transport.stubs(:command).with("enable", :prompt => /^Password:/)
@transport.expects(:command).with("mypass")
@cisco.enable
end
end
end
describe "when finding network device capabilities" do
it "should try to execute sh vlan brief" do
@transport.expects(:command).with("sh vlan brief").returns("")
@cisco.find_capabilities
end
it "should detect errors" do
@transport.stubs(:command).with("sh vlan brief").returns(<<eos)
Switch#sh vlan brief
% Ambiguous command: "sh vlan brief"
Switch#
eos
@cisco.find_capabilities
- @cisco.should_not be_support_vlan_brief
+ expect(@cisco).not_to be_support_vlan_brief
end
end
{
"Fa 0/1" => "FastEthernet0/1",
"Fa0/1" => "FastEthernet0/1",
"FastEth 0/1" => "FastEthernet0/1",
"Gi1" => "GigabitEthernet1",
"Te2" => "TenGigabitEthernet2",
"Di9" => "Dialer9",
"Ethernet 0/0/1" => "Ethernet0/0/1",
"E0" => "Ethernet0",
"ATM 0/1.1" => "ATM0/1.1",
"VLAN99" => "VLAN99"
}.each do |input,expected|
it "should canonicalize #{input} to #{expected}" do
- @cisco.canonalize_ifname(input).should == expected
+ expect(@cisco.canonalize_ifname(input)).to eq(expected)
end
end
describe "when updating device vlans" do
describe "when removing a vlan" do
it "should issue the no vlan command" do
@transport.expects(:command).with("no vlan 200")
@cisco.update_vlan("200", {:ensure => :present, :name => "200"}, { :ensure=> :absent})
end
end
describe "when updating a vlan" do
it "should issue the vlan command to enter global vlan modifications" do
@transport.expects(:command).with("vlan 200")
@cisco.update_vlan("200", {:ensure => :present, :name => "200"}, { :ensure=> :present, :name => "200"})
end
it "should issue the name command to modify the vlan description" do
@transport.expects(:command).with("name myvlan")
@cisco.update_vlan("200", {:ensure => :present, :name => "200"}, { :ensure=> :present, :name => "200", :description => "myvlan"})
end
end
end
describe "when parsing interface" do
it "should parse interface output" do
@cisco.expects(:parse_interface).returns({ :ensure => :present })
- @cisco.interface("FastEthernet0/1").should == { :ensure => :present }
+ expect(@cisco.interface("FastEthernet0/1")).to eq({ :ensure => :present })
end
it "should parse trunking and merge results" do
@cisco.stubs(:parse_interface).returns({ :ensure => :present })
@cisco.expects(:parse_trunking).returns({ :native_vlan => "100" })
- @cisco.interface("FastEthernet0/1").should == { :ensure => :present, :native_vlan => "100" }
+ expect(@cisco.interface("FastEthernet0/1")).to eq({ :ensure => :present, :native_vlan => "100" })
end
it "should return an absent interface if parse_interface returns nothing" do
@cisco.stubs(:parse_interface).returns({})
- @cisco.interface("FastEthernet0/1").should == { :ensure => :absent }
+ expect(@cisco.interface("FastEthernet0/1")).to eq({ :ensure => :absent })
end
it "should parse ip address information and merge results" do
@cisco.stubs(:parse_interface).returns({ :ensure => :present })
@cisco.expects(:parse_interface_config).returns({ :ipaddress => [24,IPAddr.new('192.168.0.24'), nil] })
- @cisco.interface("FastEthernet0/1").should == { :ensure => :present, :ipaddress => [24,IPAddr.new('192.168.0.24'), nil] }
+ expect(@cisco.interface("FastEthernet0/1")).to eq({ :ensure => :present, :ipaddress => [24,IPAddr.new('192.168.0.24'), nil] })
end
it "should parse the sh interface command" do
@transport.stubs(:command).with("sh interface FastEthernet0/1").returns(<<eos)
Switch#sh interfaces FastEthernet 0/1
FastEthernet0/1 is down, line protocol is down
Hardware is Fast Ethernet, address is 00d0.bbe2.19c1 (bia 00d0.bbe2.19c1)
MTU 1500 bytes, BW 100000 Kbit, DLY 100 usec,
reliability 255/255, txload 1/255, rxload 1/255
Encapsulation ARPA, loopback not set
Keepalive not set
Auto-duplex , Auto Speed , 100BaseTX/FX
ARP type: ARPA, ARP Timeout 04:00:00
Last input never, output 5d04h, output hang never
Last clearing of "show interface" counters never
Queueing strategy: fifo
Output queue 0/40, 0 drops; input queue 0/75, 0 drops
5 minute input rate 0 bits/sec, 0 packets/sec
5 minute output rate 0 bits/sec, 0 packets/sec
580 packets input, 54861 bytes
Received 6 broadcasts, 0 runts, 0 giants, 0 throttles
0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored
0 watchdog, 1 multicast
0 input packets with dribble condition detected
845 packets output, 80359 bytes, 0 underruns
0 output errors, 0 collisions, 1 interface resets
0 babbles, 0 late collision, 0 deferred
0 lost carrier, 0 no carrier
0 output buffer failures, 0 output buffers swapped out
Switch#
eos
- @cisco.parse_interface("FastEthernet0/1").should == { :ensure => :absent, :duplex => :auto, :speed => :auto }
+ expect(@cisco.parse_interface("FastEthernet0/1")).to eq({ :ensure => :absent, :duplex => :auto, :speed => :auto })
end
it "should be able to parse the sh vlan brief command output" do
@cisco.stubs(:support_vlan_brief?).returns(true)
@transport.stubs(:command).with("sh vlan brief").returns(<<eos)
Switch#sh vlan brief
VLAN Name Status Ports
---- -------------------------------- --------- -------------------------------
1 default active Fa0/3, Fa0/4, Fa0/5, Fa0/6,
Fa0/7, Fa0/8, Fa0/9, Fa0/10,
Fa0/11, Fa0/12, Fa0/13, Fa0/14,
Fa0/15, Fa0/16, Fa0/17, Fa0/18,
Fa0/23, Fa0/24
10 VLAN0010 active
100 management active Fa0/1, Fa0/2
Switch#
eos
- @cisco.parse_vlans.should == {"100"=>{:status=>"active", :interfaces=>["FastEthernet0/1", "FastEthernet0/2"], :description=>"management", :name=>"100"}, "1"=>{:status=>"active", :interfaces=>["FastEthernet0/3", "FastEthernet0/4", "FastEthernet0/5", "FastEthernet0/6", "FastEthernet0/7", "FastEthernet0/8", "FastEthernet0/9", "FastEthernet0/10", "FastEthernet0/11", "FastEthernet0/12", "FastEthernet0/13", "FastEthernet0/14", "FastEthernet0/15", "FastEthernet0/16", "FastEthernet0/17", "FastEthernet0/18", "FastEthernet0/23", "FastEthernet0/24"], :description=>"default", :name=>"1"}, "10"=>{:status=>"active", :interfaces=>[], :description=>"VLAN0010", :name=>"10"}}
+ expect(@cisco.parse_vlans).to eq({"100"=>{:status=>"active", :interfaces=>["FastEthernet0/1", "FastEthernet0/2"], :description=>"management", :name=>"100"}, "1"=>{:status=>"active", :interfaces=>["FastEthernet0/3", "FastEthernet0/4", "FastEthernet0/5", "FastEthernet0/6", "FastEthernet0/7", "FastEthernet0/8", "FastEthernet0/9", "FastEthernet0/10", "FastEthernet0/11", "FastEthernet0/12", "FastEthernet0/13", "FastEthernet0/14", "FastEthernet0/15", "FastEthernet0/16", "FastEthernet0/17", "FastEthernet0/18", "FastEthernet0/23", "FastEthernet0/24"], :description=>"default", :name=>"1"}, "10"=>{:status=>"active", :interfaces=>[], :description=>"VLAN0010", :name=>"10"}})
end
it "should parse trunk switchport information" do
@transport.stubs(:command).with("sh interface FastEthernet0/21 switchport").returns(<<eos)
Switch#sh interfaces FastEthernet 0/21 switchport
Name: Fa0/21
Switchport: Enabled
Administrative mode: trunk
Operational Mode: trunk
Administrative Trunking Encapsulation: dot1q
Operational Trunking Encapsulation: dot1q
Negotiation of Trunking: Disabled
Access Mode VLAN: 0 ((Inactive))
Trunking Native Mode VLAN: 1 (default)
Trunking VLANs Enabled: ALL
Trunking VLANs Active: 1,10,100
Pruning VLANs Enabled: 2-1001
Priority for untagged frames: 0
Override vlan tag priority: FALSE
Voice VLAN: none
Appliance trust: none
Self Loopback: No
Switch#
eos
- @cisco.parse_trunking("FastEthernet0/21").should == { :mode => :trunk, :encapsulation => :dot1q, :allowed_trunk_vlans=>:all, }
+ expect(@cisco.parse_trunking("FastEthernet0/21")).to eq({ :mode => :trunk, :encapsulation => :dot1q, :allowed_trunk_vlans=>:all, })
end
it "should parse trunk switchport information with allowed vlans" do
@transport.stubs(:command).with("sh interface GigabitEthernet 0/1 switchport").returns(<<eos)
c2960#sh interfaces GigabitEthernet 0/1 switchport
Name: Gi0/1
Switchport: Enabled
Administrative Mode: trunk
Operational Mode: trunk
Administrative Trunking Encapsulation: dot1q
Operational Trunking Encapsulation: dot1q
Negotiation of Trunking: On
Access Mode VLAN: 1 (default)
Trunking Native Mode VLAN: 1 (default)
Administrative Native VLAN tagging: enabled
Voice VLAN: none
Administrative private-vlan host-association: none
Administrative private-vlan mapping: none
Administrative private-vlan trunk native VLAN: none
Administrative private-vlan trunk Native VLAN tagging: enabled
Administrative private-vlan trunk encapsulation: dot1q
Administrative private-vlan trunk normal VLANs: none
Administrative private-vlan trunk associations: none
Administrative private-vlan trunk mappings: none
Operational private-vlan: none
Trunking VLANs Enabled: 1,99
Pruning VLANs Enabled: 2-1001
Capture Mode Disabled
Capture VLANs Allowed: ALL
Protected: false
Unknown unicast blocked: disabled
Unknown multicast blocked: disabled
Appliance trust: none
c2960#
eos
- @cisco.parse_trunking("GigabitEthernet 0/1").should == { :mode => :trunk, :encapsulation => :dot1q, :allowed_trunk_vlans=>"1,99", }
+ expect(@cisco.parse_trunking("GigabitEthernet 0/1")).to eq({ :mode => :trunk, :encapsulation => :dot1q, :allowed_trunk_vlans=>"1,99", })
end
it "should parse access switchport information" do
@transport.stubs(:command).with("sh interface FastEthernet0/1 switchport").returns(<<eos)
Switch#sh interfaces FastEthernet 0/1 switchport
Name: Fa0/1
Switchport: Enabled
Administrative mode: static access
Operational Mode: static access
Administrative Trunking Encapsulation: isl
Operational Trunking Encapsulation: isl
Negotiation of Trunking: Disabled
Access Mode VLAN: 100 (SHDSL)
Trunking Native Mode VLAN: 1 (default)
Trunking VLANs Enabled: NONE
Pruning VLANs Enabled: NONE
Priority for untagged frames: 0
Override vlan tag priority: FALSE
Voice VLAN: none
Appliance trust: none
Self Loopback: No
Switch#
eos
- @cisco.parse_trunking("FastEthernet0/1").should == { :mode => :access, :native_vlan => "100" }
+ expect(@cisco.parse_trunking("FastEthernet0/1")).to eq({ :mode => :access, :native_vlan => "100" })
end
it "should parse ip addresses" do
@transport.stubs(:command).with("sh running-config interface Vlan 1 | begin interface").returns(<<eos)
router#sh running-config interface Vlan 1 | begin interface
interface Vlan1
description $ETH-SW-LAUNCH$$INTF-INFO-HWIC 4ESW$$FW_INSIDE$
ip address 192.168.0.24 255.255.255.0 secondary
ip address 192.168.0.1 255.255.255.0
ip access-group 100 in
no ip redirects
no ip proxy-arp
ip nbar protocol-discovery
ip dns view-group dow
ip nat inside
ip virtual-reassembly
ip route-cache flow
ipv6 address 2001:7A8:71C1::/64 eui-64
ipv6 enable
ipv6 traffic-filter DENY-ACL6 out
ipv6 mtu 1280
ipv6 nd prefix 2001:7A8:71C1::/64
ipv6 nd ra interval 60
ipv6 nd ra lifetime 180
ipv6 verify unicast reverse-path
ipv6 inspect STD6 out
end
router#
eos
- @cisco.parse_interface_config("Vlan 1").should == {:ipaddress=>[[24, IPAddr.new('192.168.0.24'), 'secondary'],
+ expect(@cisco.parse_interface_config("Vlan 1")).to eq({:ipaddress=>[[24, IPAddr.new('192.168.0.24'), 'secondary'],
[24, IPAddr.new('192.168.0.1'), nil],
- [64, IPAddr.new('2001:07a8:71c1::'), "eui-64"]]}
+ [64, IPAddr.new('2001:07a8:71c1::'), "eui-64"]]})
end
it "should parse etherchannel membership" do
@transport.stubs(:command).with("sh running-config interface Gi0/17 | begin interface").returns(<<eos)
c2960#sh running-config interface Gi0/17 | begin interface
interface GigabitEthernet0/17
description member of Po1
switchport mode access
channel-protocol lacp
channel-group 1 mode passive
spanning-tree portfast
spanning-tree bpduguard enable
end
c2960#
eos
- @cisco.parse_interface_config("Gi0/17").should == {:etherchannel=>"1"}
+ expect(@cisco.parse_interface_config("Gi0/17")).to eq({:etherchannel=>"1"})
end
end
describe "when finding device facts" do
it "should delegate to the cisco facts entity" do
facts = stub 'facts'
Puppet::Util::NetworkDevice::Cisco::Facts.expects(:new).returns(facts)
facts.expects(:retrieve).returns(:facts)
- @cisco.facts.should == :facts
+ expect(@cisco.facts).to eq(:facts)
end
end
end
diff --git a/spec/unit/util/network_device/cisco/facts_spec.rb b/spec/unit/util/network_device/cisco/facts_spec.rb
index 5f0c0ccbf..d1fb7b9d6 100755
--- a/spec/unit/util/network_device/cisco/facts_spec.rb
+++ b/spec/unit/util/network_device/cisco/facts_spec.rb
@@ -1,64 +1,64 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/network_device'
require 'puppet/util/network_device/cisco/facts'
describe Puppet::Util::NetworkDevice::Cisco::Facts do
before(:each) do
@transport = stub_everything 'transport'
@facts = Puppet::Util::NetworkDevice::Cisco::Facts.new(@transport)
end
{
"cisco WS-C2924C-XL (PowerPC403GA) processor (revision 0x11) with 8192K/1024K bytes of memory." => {:hardwaremodel => "WS-C2924C-XL", :memorysize => "8192K", :processor => "PowerPC403GA", :hardwarerevision => "0x11" },
"Cisco 1841 (revision 5.0) with 355328K/37888K bytes of memory." => {:hardwaremodel=>"1841", :memorysize => "355328K", :hardwarerevision => "5.0" },
"Cisco 877 (MPC8272) processor (revision 0x200) with 118784K/12288K bytes of memory." => {:hardwaremodel=>"877", :memorysize => "118784K", :processor => "MPC8272", :hardwarerevision => "0x200" },
"cisco WS-C2960G-48TC-L (PowerPC405) processor (revision C0) with 61440K/4088K bytes of memory." => {:hardwaremodel=>"WS-C2960G-48TC-L", :memorysize => "61440K", :processor => "PowerPC405", :hardwarerevision => "C0" },
"cisco WS-C2950T-24 (RC32300) processor (revision R0) with 19959K bytes of memory." => {:hardwaremodel=>"WS-C2950T-24", :memorysize => "19959K", :processor => "RC32300", :hardwarerevision => "R0" }
}.each do |ver, expected|
it "should parse show ver output for hardware device facts" do
@transport.stubs(:command).with("sh ver").returns(<<eos)
Switch>sh ver
#{ver}
Switch>
eos
- @facts.parse_show_ver.should == expected
+ expect(@facts.parse_show_ver).to eq(expected)
end
end
{
"Switch uptime is 1 year, 12 weeks, 6 days, 22 hours, 32 minutes" => { :hostname => "Switch", :uptime => "1 year, 12 weeks, 6 days, 22 hours, 32 minutes", :uptime_seconds => 39393120, :uptime_days => 455 },
"c2950 uptime is 3 weeks, 1 day, 23 hours, 36 minutes" => { :hostname => "c2950", :uptime => "3 weeks, 1 day, 23 hours, 36 minutes", :uptime_days => 22, :uptime_seconds => 1985760},
"router uptime is 5 weeks, 1 day, 3 hours, 30 minutes" => { :hostname => "router", :uptime => "5 weeks, 1 day, 3 hours, 30 minutes", :uptime_days => 36, :uptime_seconds => 3123000 },
"c2950 uptime is 1 minute" => { :hostname => "c2950", :uptime => "1 minute", :uptime_days => 0, :uptime_seconds => 60 },
"c2950 uptime is 20 weeks, 6 minutes" => { :hostname => "c2950", :uptime=>"20 weeks, 6 minutes", :uptime_seconds=>12096360, :uptime_days=>140 },
"c2950 uptime is 2 years, 20 weeks, 6 minutes" => { :hostname => "c2950", :uptime=>"2 years, 20 weeks, 6 minutes", :uptime_seconds=>75168360, :uptime_days=>870 }
}.each do |ver, expected|
it "should parse show ver output for device uptime facts" do
@transport.stubs(:command).with("sh ver").returns(<<eos)
Switch>sh ver
#{ver}
Switch>
eos
- @facts.parse_show_ver.should == expected
+ expect(@facts.parse_show_ver).to eq(expected)
end
end
{
"IOS (tm) C2900XL Software (C2900XL-C3H2S-M), Version 12.0(5)WC10, RELEASE SOFTWARE (fc1)"=> { :operatingsystem => "IOS", :operatingsystemrelease => "12.0(5)WC10", :operatingsystemmajrelease => "12.0WC", :operatingsystemfeature => "C3H2S"},
"IOS (tm) C2950 Software (C2950-I6K2L2Q4-M), Version 12.1(22)EA8a, RELEASE SOFTWARE (fc1)"=> { :operatingsystem => "IOS", :operatingsystemrelease => "12.1(22)EA8a", :operatingsystemmajrelease => "12.1EA", :operatingsystemfeature => "I6K2L2Q4"},
"Cisco IOS Software, C2960 Software (C2960-LANBASEK9-M), Version 12.2(44)SE, RELEASE SOFTWARE (fc1)"=>{ :operatingsystem => "IOS", :operatingsystemrelease => "12.2(44)SE", :operatingsystemmajrelease => "12.2SE", :operatingsystemfeature => "LANBASEK9"},
"Cisco IOS Software, C870 Software (C870-ADVIPSERVICESK9-M), Version 12.4(11)XJ4, RELEASE SOFTWARE (fc2)"=>{ :operatingsystem => "IOS", :operatingsystemrelease => "12.4(11)XJ4", :operatingsystemmajrelease => "12.4XJ", :operatingsystemfeature => "ADVIPSERVICESK9"},
"Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 12.4(24)T4, RELEASE SOFTWARE (fc2)" =>{ :operatingsystem => "IOS", :operatingsystemrelease => "12.4(24)T4", :operatingsystemmajrelease => "12.4T", :operatingsystemfeature => "ADVSECURITYK9"},
}.each do |ver, expected|
it "should parse show ver output for device software version facts" do
@transport.stubs(:command).with("sh ver").returns(<<eos)
Switch>sh ver
#{ver}
Switch>
eos
- @facts.parse_show_ver.should == expected
+ expect(@facts.parse_show_ver).to eq(expected)
end
end
end
diff --git a/spec/unit/util/network_device/config_spec.rb b/spec/unit/util/network_device/config_spec.rb
index 06daf96fc..d099ddd1b 100755
--- a/spec/unit/util/network_device/config_spec.rb
+++ b/spec/unit/util/network_device/config_spec.rb
@@ -1,86 +1,86 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/network_device/config'
describe Puppet::Util::NetworkDevice::Config do
include PuppetSpec::Files
before(:each) do
Puppet[:deviceconfig] = tmpfile('deviceconfig')
end
describe "when parsing device" do
let(:config) { Puppet::Util::NetworkDevice::Config.new }
def write_device_config(*lines)
File.open(Puppet[:deviceconfig], 'w') {|f| f.puts lines}
end
it "should skip comments" do
write_device_config(' # comment')
- config.devices.should be_empty
+ expect(config.devices).to be_empty
end
it "should increment line number even on commented lines" do
write_device_config(' # comment','[router.puppetlabs.com]')
- config.devices.should be_include('router.puppetlabs.com')
+ expect(config.devices).to be_include('router.puppetlabs.com')
end
it "should skip blank lines" do
write_device_config(' ')
- config.devices.should be_empty
+ expect(config.devices).to be_empty
end
it "should produce the correct line number" do
write_device_config(' ', '[router.puppetlabs.com]')
- config.devices['router.puppetlabs.com'].line.should == 2
+ expect(config.devices['router.puppetlabs.com'].line).to eq(2)
end
it "should throw an error if the current device already exists" do
write_device_config('[router.puppetlabs.com]', '[router.puppetlabs.com]')
end
it "should accept device certname containing dashes" do
write_device_config('[router-1.puppetlabs.com]')
- config.devices.should include('router-1.puppetlabs.com')
+ expect(config.devices).to include('router-1.puppetlabs.com')
end
it "should create a new device for each found device line" do
write_device_config('[router.puppetlabs.com]', '[swith.puppetlabs.com]')
- config.devices.size.should == 2
+ expect(config.devices.size).to eq(2)
end
it "should parse the device type" do
write_device_config('[router.puppetlabs.com]', 'type cisco')
- config.devices['router.puppetlabs.com'].provider.should == 'cisco'
+ expect(config.devices['router.puppetlabs.com'].provider).to eq('cisco')
end
it "should parse the device url" do
write_device_config('[router.puppetlabs.com]', 'type cisco', 'url ssh://test/')
- config.devices['router.puppetlabs.com'].url.should == 'ssh://test/'
+ expect(config.devices['router.puppetlabs.com'].url).to eq('ssh://test/')
end
it "should parse the debug mode" do
write_device_config('[router.puppetlabs.com]', 'type cisco', 'url ssh://test/', 'debug')
- config.devices['router.puppetlabs.com'].options.should == { :debug => true }
+ expect(config.devices['router.puppetlabs.com'].options).to eq({ :debug => true })
end
it "should set the debug mode to false by default" do
write_device_config('[router.puppetlabs.com]', 'type cisco', 'url ssh://test/')
- config.devices['router.puppetlabs.com'].options.should == { :debug => false }
+ expect(config.devices['router.puppetlabs.com'].options).to eq({ :debug => false })
end
end
end
diff --git a/spec/unit/util/network_device/ipcalc_spec.rb b/spec/unit/util/network_device/ipcalc_spec.rb
index 676427dc6..a96bdb925 100755
--- a/spec/unit/util/network_device/ipcalc_spec.rb
+++ b/spec/unit/util/network_device/ipcalc_spec.rb
@@ -1,62 +1,62 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/network_device/ipcalc'
describe Puppet::Util::NetworkDevice::IPCalc do
class TestIPCalc
include Puppet::Util::NetworkDevice::IPCalc
end
before(:each) do
@ipcalc = TestIPCalc.new
end
describe "when parsing ip/prefix" do
it "should parse ipv4 without prefixes" do
- @ipcalc.parse('127.0.0.1').should == [32,IPAddr.new('127.0.0.1')]
+ expect(@ipcalc.parse('127.0.0.1')).to eq([32,IPAddr.new('127.0.0.1')])
end
it "should parse ipv4 with prefixes" do
- @ipcalc.parse('127.0.1.2/8').should == [8,IPAddr.new('127.0.1.2')]
+ expect(@ipcalc.parse('127.0.1.2/8')).to eq([8,IPAddr.new('127.0.1.2')])
end
it "should parse ipv6 without prefixes" do
- @ipcalc.parse('FE80::21A:2FFF:FE30:ECF0').should == [128,IPAddr.new('FE80::21A:2FFF:FE30:ECF0')]
+ expect(@ipcalc.parse('FE80::21A:2FFF:FE30:ECF0')).to eq([128,IPAddr.new('FE80::21A:2FFF:FE30:ECF0')])
end
it "should parse ipv6 with prefixes" do
- @ipcalc.parse('FE80::21A:2FFF:FE30:ECF0/56').should == [56,IPAddr.new('FE80::21A:2FFF:FE30:ECF0')]
+ expect(@ipcalc.parse('FE80::21A:2FFF:FE30:ECF0/56')).to eq([56,IPAddr.new('FE80::21A:2FFF:FE30:ECF0')])
end
end
describe "when building netmask" do
it "should produce the correct ipv4 netmask from prefix length" do
- @ipcalc.netmask(Socket::AF_INET, 27).should == IPAddr.new('255.255.255.224')
+ expect(@ipcalc.netmask(Socket::AF_INET, 27)).to eq(IPAddr.new('255.255.255.224'))
end
it "should produce the correct ipv6 netmask from prefix length" do
- @ipcalc.netmask(Socket::AF_INET6, 56).should == IPAddr.new('ffff:ffff:ffff:ff00::0')
+ expect(@ipcalc.netmask(Socket::AF_INET6, 56)).to eq(IPAddr.new('ffff:ffff:ffff:ff00::0'))
end
end
describe "when building wildmask" do
it "should produce the correct ipv4 wildmask from prefix length" do
- @ipcalc.wildmask(Socket::AF_INET, 27).should == IPAddr.new('0.0.0.31')
+ expect(@ipcalc.wildmask(Socket::AF_INET, 27)).to eq(IPAddr.new('0.0.0.31'))
end
it "should produce the correct ipv6 wildmask from prefix length" do
- @ipcalc.wildmask(Socket::AF_INET6, 126).should == IPAddr.new('::3')
+ expect(@ipcalc.wildmask(Socket::AF_INET6, 126)).to eq(IPAddr.new('::3'))
end
end
describe "when computing prefix length from netmask" do
it "should produce the correct ipv4 prefix length" do
- @ipcalc.prefix_length(IPAddr.new('255.255.255.224')).should == 27
+ expect(@ipcalc.prefix_length(IPAddr.new('255.255.255.224'))).to eq(27)
end
it "should produce the correct ipv6 prefix length" do
- @ipcalc.prefix_length(IPAddr.new('fffe::0')).should == 15
+ expect(@ipcalc.prefix_length(IPAddr.new('fffe::0'))).to eq(15)
end
end
end
diff --git a/spec/unit/util/network_device/transport/base_spec.rb b/spec/unit/util/network_device/transport/base_spec.rb
index 24354d4ba..c6df400a2 100755
--- a/spec/unit/util/network_device/transport/base_spec.rb
+++ b/spec/unit/util/network_device/transport/base_spec.rb
@@ -1,41 +1,41 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/network_device/transport/base'
describe Puppet::Util::NetworkDevice::Transport::Base do
class TestTransport < Puppet::Util::NetworkDevice::Transport::Base
end
before(:each) do
@transport = TestTransport.new
end
describe "when sending commands" do
it "should send the command to the telnet session" do
@transport.expects(:send).with("line")
@transport.command("line")
end
it "should expect an output matching the given prompt" do
@transport.expects(:expect).with(/prompt/)
@transport.command("line", :prompt => /prompt/)
end
it "should expect an output matching the default prompt" do
@transport.default_prompt = /defprompt/
@transport.expects(:expect).with(/defprompt/)
@transport.command("line")
end
it "should yield telnet output to the given block" do
@transport.expects(:expect).yields("output")
- @transport.command("line") { |out| out.should == "output" }
+ @transport.command("line") { |out| expect(out).to eq("output") }
end
it "should return telnet output to the caller" do
@transport.expects(:expect).returns("output")
- @transport.command("line").should == "output"
+ expect(@transport.command("line")).to eq("output")
end
end
end
diff --git a/spec/unit/util/network_device/transport/ssh_spec.rb b/spec/unit/util/network_device/transport/ssh_spec.rb
index d628b08f4..18bf32eaf 100755
--- a/spec/unit/util/network_device/transport/ssh_spec.rb
+++ b/spec/unit/util/network_device/transport/ssh_spec.rb
@@ -1,218 +1,218 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/network_device/transport/ssh'
describe Puppet::Util::NetworkDevice::Transport::Ssh, :if => Puppet.features.ssh? do
before(:each) do
@transport = Puppet::Util::NetworkDevice::Transport::Ssh.new()
end
it "should handle login through the transport" do
- @transport.should be_handles_login
+ expect(@transport).to be_handles_login
end
it "should connect to the given host and port" do
Net::SSH.expects(:start).with { |host, user, args| host == "localhost" && args[:port] == 22 }.returns stub_everything
@transport.host = "localhost"
@transport.port = 22
@transport.connect
end
it "should connect using the given username and password" do
Net::SSH.expects(:start).with { |host, user, args| user == "user" && args[:password] == "pass" }.returns stub_everything
@transport.user = "user"
@transport.password = "pass"
@transport.connect
end
it "should raise a Puppet::Error when encountering an authentication failure" do
Net::SSH.expects(:start).raises Net::SSH::AuthenticationFailed
@transport.host = "localhost"
@transport.user = "user"
- lambda { @transport.connect }.should raise_error Puppet::Error
+ expect { @transport.connect }.to raise_error Puppet::Error
end
describe "when connected" do
before(:each) do
@ssh = stub_everything 'ssh'
@channel = stub_everything 'channel'
Net::SSH.stubs(:start).returns @ssh
@ssh.stubs(:open_channel).yields(@channel)
@transport.stubs(:expect)
end
it "should open a channel" do
@ssh.expects(:open_channel)
@transport.connect
end
it "should request a pty" do
@channel.expects(:request_pty)
@transport.connect
end
it "should create a shell channel" do
@channel.expects(:send_channel_request).with("shell")
@transport.connect
end
it "should raise an error if shell channel creation fails" do
@channel.expects(:send_channel_request).with("shell").yields(@channel, false)
- lambda { @transport.connect }.should raise_error
+ expect { @transport.connect }.to raise_error
end
it "should register an on_data and on_extended_data callback" do
@channel.expects(:send_channel_request).with("shell").yields(@channel, true)
@channel.expects(:on_data)
@channel.expects(:on_extended_data)
@transport.connect
end
it "should accumulate data to the buffer on data" do
@channel.expects(:send_channel_request).with("shell").yields(@channel, true)
@channel.expects(:on_data).yields(@channel, "data")
@transport.connect
- @transport.buf.should == "data"
+ expect(@transport.buf).to eq("data")
end
it "should accumulate data to the buffer on extended data" do
@channel.expects(:send_channel_request).with("shell").yields(@channel, true)
@channel.expects(:on_extended_data).yields(@channel, 1, "data")
@transport.connect
- @transport.buf.should == "data"
+ expect(@transport.buf).to eq("data")
end
it "should mark eof on close" do
@channel.expects(:send_channel_request).with("shell").yields(@channel, true)
@channel.expects(:on_close).yields(@channel)
@transport.connect
- @transport.should be_eof
+ expect(@transport).to be_eof
end
it "should expect output to conform to the default prompt" do
@channel.expects(:send_channel_request).with("shell").yields(@channel, true)
@transport.expects(:default_prompt).returns("prompt")
@transport.expects(:expect).with("prompt")
@transport.connect
end
it "should start the ssh loop" do
@ssh.expects(:loop)
@transport.connect
end
end
describe "when closing" do
before(:each) do
@ssh = stub_everything 'ssh'
@channel = stub_everything 'channel'
Net::SSH.stubs(:start).returns @ssh
@ssh.stubs(:open_channel).yields(@channel)
@channel.stubs(:send_channel_request).with("shell").yields(@channel, true)
@transport.stubs(:expect)
@transport.connect
end
it "should close the channel" do
@channel.expects(:close)
@transport.close
end
it "should close the ssh session" do
@ssh.expects(:close)
@transport.close
end
end
describe "when sending commands" do
before(:each) do
@ssh = stub_everything 'ssh'
@channel = stub_everything 'channel'
Net::SSH.stubs(:start).returns @ssh
@ssh.stubs(:open_channel).yields(@channel)
@channel.stubs(:send_channel_request).with("shell").yields(@channel, true)
@transport.stubs(:expect)
@transport.connect
end
it "should send data to the ssh channel" do
@channel.expects(:send_data).with("data\n")
@transport.command("data")
end
it "should expect the default prompt afterward" do
@transport.expects(:default_prompt).returns("prompt")
@transport.expects(:expect).with("prompt")
@transport.command("data")
end
it "should expect the given prompt" do
@transport.expects(:expect).with("myprompt")
@transport.command("data", :prompt => "myprompt")
end
it "should yield the buffer output to given block" do
@transport.expects(:expect).yields("output")
@transport.command("data") do |out|
- out.should == "output"
+ expect(out).to eq("output")
end
end
it "should return buffer output" do
@transport.expects(:expect).returns("output")
- @transport.command("data").should == "output"
+ expect(@transport.command("data")).to eq("output")
end
end
describe "when expecting output" do
before(:each) do
@connection = stub_everything 'connection'
@socket = stub_everything 'socket'
transport = stub 'transport', :socket => @socket
@ssh = stub_everything 'ssh', :transport => transport
@channel = stub_everything 'channel', :connection => @connection
@transport.ssh = @ssh
@transport.channel = @channel
end
it "should process the ssh event loop" do
IO.stubs(:select)
@transport.buf = "output"
@transport.expects(:process_ssh)
@transport.expect(/output/)
end
it "should return the output" do
IO.stubs(:select)
@transport.buf = "output"
@transport.stubs(:process_ssh)
- @transport.expect(/output/).should == "output"
+ expect(@transport.expect(/output/)).to eq("output")
end
it "should return the output" do
IO.stubs(:select)
@transport.buf = "output"
@transport.stubs(:process_ssh)
- @transport.expect(/output/).should == "output"
+ expect(@transport.expect(/output/)).to eq("output")
end
describe "when processing the ssh loop" do
it "should advance one tick in the ssh event loop and exit on eof" do
@transport.buf = ''
@connection.expects(:process).then.raises(EOFError)
@transport.process_ssh
end
end
end
end
diff --git a/spec/unit/util/network_device/transport/telnet_spec.rb b/spec/unit/util/network_device/transport/telnet_spec.rb
index 3423d090e..a19a5e404 100755
--- a/spec/unit/util/network_device/transport/telnet_spec.rb
+++ b/spec/unit/util/network_device/transport/telnet_spec.rb
@@ -1,84 +1,84 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/network_device/transport/telnet'
describe Puppet::Util::NetworkDevice::Transport::Telnet do
before(:each) do
TCPSocket.stubs(:open).returns stub_everything('tcp')
@transport = Puppet::Util::NetworkDevice::Transport::Telnet.new()
end
it "should not handle login through the transport" do
- @transport.should_not be_handles_login
+ expect(@transport).not_to be_handles_login
end
it "should not open any files" do
File.expects(:open).never
@transport.host = "localhost"
@transport.port = 23
@transport.connect
end
it "should connect to the given host and port" do
Net::Telnet.expects(:new).with { |args| args["Host"] == "localhost" && args["Port"] == 23 }.returns stub_everything
@transport.host = "localhost"
@transport.port = 23
@transport.connect
end
it "should connect and specify the default prompt" do
@transport.default_prompt = "prompt"
Net::Telnet.expects(:new).with { |args| args["Prompt"] == "prompt" }.returns stub_everything
@transport.host = "localhost"
@transport.port = 23
@transport.connect
end
describe "when connected" do
before(:each) do
@telnet = stub_everything 'telnet'
Net::Telnet.stubs(:new).returns(@telnet)
@transport.connect
end
it "should send line to the telnet session" do
@telnet.expects(:puts).with("line")
@transport.send("line")
end
describe "when expecting output" do
it "should waitfor output on the telnet session" do
@telnet.expects(:waitfor).with(/regex/)
@transport.expect(/regex/)
end
it "should return telnet session output" do
@telnet.expects(:waitfor).returns("output")
- @transport.expect(/regex/).should == "output"
+ expect(@transport.expect(/regex/)).to eq("output")
end
it "should yield telnet session output to the given block" do
@telnet.expects(:waitfor).yields("output")
- @transport.expect(/regex/) { |out| out.should == "output" }
+ @transport.expect(/regex/) { |out| expect(out).to eq("output") }
end
end
end
describe "when closing" do
before(:each) do
@telnet = stub_everything 'telnet'
Net::Telnet.stubs(:new).returns(@telnet)
@transport.connect
end
it "should close the telnet session" do
@telnet.expects(:close)
@transport.close
end
end
end
diff --git a/spec/unit/util/network_device_spec.rb b/spec/unit/util/network_device_spec.rb
index beb6a7ea5..d33504a94 100644
--- a/spec/unit/util/network_device_spec.rb
+++ b/spec/unit/util/network_device_spec.rb
@@ -1,50 +1,50 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'ostruct'
require 'puppet/util/network_device'
describe Puppet::Util::NetworkDevice do
before(:each) do
@device = OpenStruct.new(:name => "name", :provider => "test", :url => "telnet://admin:password@127.0.0.1", :options => { :debug => false })
end
after(:each) do
Puppet::Util::NetworkDevice.teardown
end
class Puppet::Util::NetworkDevice::Test
class Device
def initialize(device, options)
end
end
end
describe "when initializing the remote network device singleton" do
it "should load the network device code" do
Puppet::Util::NetworkDevice.expects(:require)
Puppet::Util::NetworkDevice.init(@device)
end
it "should create a network device instance" do
Puppet::Util::NetworkDevice.stubs(:require)
Puppet::Util::NetworkDevice::Test::Device.expects(:new).with("telnet://admin:password@127.0.0.1", :debug => false)
Puppet::Util::NetworkDevice.init(@device)
end
it "should raise an error if the remote device instance can't be created" do
Puppet::Util::NetworkDevice.stubs(:require).raises("error")
- lambda { Puppet::Util::NetworkDevice.init(@device) }.should raise_error
+ expect { Puppet::Util::NetworkDevice.init(@device) }.to raise_error
end
it "should let caller to access the singleton device" do
device = stub 'device'
Puppet::Util::NetworkDevice.stubs(:require)
Puppet::Util::NetworkDevice::Test::Device.expects(:new).returns(device)
Puppet::Util::NetworkDevice.init(@device)
- Puppet::Util::NetworkDevice.current.should == device
+ expect(Puppet::Util::NetworkDevice.current).to eq(device)
end
end
end
diff --git a/spec/unit/util/package_spec.rb b/spec/unit/util/package_spec.rb
index fbee92d5f..e0748ad8c 100755
--- a/spec/unit/util/package_spec.rb
+++ b/spec/unit/util/package_spec.rb
@@ -1,20 +1,20 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/package'
describe Puppet::Util::Package, " versioncmp" do
it "should be able to be used as a module function" do
- Puppet::Util::Package.should respond_to(:versioncmp)
+ expect(Puppet::Util::Package).to respond_to(:versioncmp)
end
it "should be able to sort a long set of various unordered versions" do
ary = %w{ 1.1.6 2.3 1.1a 3.0 1.5 1 2.4 1.1-4 2.3.1 1.2 2.3.0 1.1-3 2.4b 2.4 2.40.2 2.3a.1 3.1 0002 1.1-5 1.1.a 1.06}
newary = ary.sort { |a, b| Puppet::Util::Package.versioncmp(a,b) }
- newary.should == ["0002", "1", "1.06", "1.1-3", "1.1-4", "1.1-5", "1.1.6", "1.1.a", "1.1a", "1.2", "1.5", "2.3", "2.3.0", "2.3.1", "2.3a.1", "2.4", "2.4", "2.4b", "2.40.2", "3.0", "3.1"]
+ expect(newary).to eq(["0002", "1", "1.06", "1.1-3", "1.1-4", "1.1-5", "1.1.6", "1.1.a", "1.1a", "1.2", "1.5", "2.3", "2.3.0", "2.3.1", "2.3a.1", "2.4", "2.4", "2.4b", "2.40.2", "3.0", "3.1"])
end
end
diff --git a/spec/unit/util/pidlock_spec.rb b/spec/unit/util/pidlock_spec.rb
index fcef7aa31..63ee262b5 100644
--- a/spec/unit/util/pidlock_spec.rb
+++ b/spec/unit/util/pidlock_spec.rb
@@ -1,218 +1,218 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/pidlock'
describe Puppet::Util::Pidlock do
require 'puppet_spec/files'
include PuppetSpec::Files
before(:each) do
@lockfile = tmpfile("lock")
@lock = Puppet::Util::Pidlock.new(@lockfile)
end
describe "#lock" do
it "should not be locked at start" do
- @lock.should_not be_locked
+ expect(@lock).not_to be_locked
end
it "should not be mine at start" do
- @lock.should_not be_mine
+ expect(@lock).not_to be_mine
end
it "should become locked" do
@lock.lock
- @lock.should be_locked
+ expect(@lock).to be_locked
end
it "should become mine" do
@lock.lock
- @lock.should be_mine
+ expect(@lock).to be_mine
end
it "should be possible to lock multiple times" do
@lock.lock
- lambda { @lock.lock }.should_not raise_error
+ expect { @lock.lock }.not_to raise_error
end
it "should return true when locking" do
- @lock.lock.should be_true
+ expect(@lock.lock).to be_truthy
end
it "should return true if locked by me" do
@lock.lock
- @lock.lock.should be_true
+ expect(@lock.lock).to be_truthy
end
it "should create a lock file" do
@lock.lock
- Puppet::FileSystem.exist?(@lockfile).should be_true
+ expect(Puppet::FileSystem.exist?(@lockfile)).to be_truthy
end
it 'should create an empty lock file even when pid is missing' do
Process.stubs(:pid).returns('')
@lock.lock
- Puppet::FileSystem.exist?(@lock.file_path).should be_true
- Puppet::FileSystem.read(@lock.file_path).should be_empty
+ expect(Puppet::FileSystem.exist?(@lock.file_path)).to be_truthy
+ expect(Puppet::FileSystem.read(@lock.file_path)).to be_empty
end
it 'should replace an existing empty lockfile with a pid, given a subsequent lock call made against a valid pid' do
# empty pid results in empty lockfile
Process.stubs(:pid).returns('')
@lock.lock
- Puppet::FileSystem.exist?(@lock.file_path).should be_true
+ expect(Puppet::FileSystem.exist?(@lock.file_path)).to be_truthy
# next lock call with valid pid kills existing empty lockfile
Process.stubs(:pid).returns(1234)
@lock.lock
- Puppet::FileSystem.exist?(@lock.file_path).should be_true
- Puppet::FileSystem.read(@lock.file_path).should == '1234'
+ expect(Puppet::FileSystem.exist?(@lock.file_path)).to be_truthy
+ expect(Puppet::FileSystem.read(@lock.file_path)).to eq('1234')
end
it "should expose the lock file_path" do
- @lock.file_path.should == @lockfile
+ expect(@lock.file_path).to eq(@lockfile)
end
end
describe "#unlock" do
it "should not be locked anymore" do
@lock.lock
@lock.unlock
- @lock.should_not be_locked
+ expect(@lock).not_to be_locked
end
it "should return false if not locked" do
- @lock.unlock.should be_false
+ expect(@lock.unlock).to be_falsey
end
it "should return true if properly unlocked" do
@lock.lock
- @lock.unlock.should be_true
+ expect(@lock.unlock).to be_truthy
end
it "should get rid of the lock file" do
@lock.lock
@lock.unlock
- Puppet::FileSystem.exist?(@lockfile).should be_false
+ expect(Puppet::FileSystem.exist?(@lockfile)).to be_falsey
end
end
describe "#locked?" do
it "should return true if locked" do
@lock.lock
- @lock.should be_locked
+ expect(@lock).to be_locked
end
it "should remove the lockfile when pid is missing" do
Process.stubs(:pid).returns('')
@lock.lock
- @lock.locked?.should be_false
- Puppet::FileSystem.exist?(@lock.file_path).should be_false
+ expect(@lock.locked?).to be_falsey
+ expect(Puppet::FileSystem.exist?(@lock.file_path)).to be_falsey
end
end
describe '#lock_pid' do
it 'should return nil if the pid is empty' do
# fake pid to get empty lockfile
Process.stubs(:pid).returns('')
@lock.lock
- @lock.lock_pid.should == nil
+ expect(@lock.lock_pid).to eq(nil)
end
end
describe "with a stale lock" do
before(:each) do
# fake our pid to be 1234
Process.stubs(:pid).returns(1234)
# lock the file
@lock.lock
# fake our pid to be a different pid, to simulate someone else
# holding the lock
Process.stubs(:pid).returns(6789)
Process.stubs(:kill).with(0, 6789)
Process.stubs(:kill).with(0, 1234).raises(Errno::ESRCH)
end
it "should not be locked" do
- @lock.should_not be_locked
+ expect(@lock).not_to be_locked
end
describe "#lock" do
it "should clear stale locks" do
- @lock.locked?.should be_false
- Puppet::FileSystem.exist?(@lockfile).should be_false
+ expect(@lock.locked?).to be_falsey
+ expect(Puppet::FileSystem.exist?(@lockfile)).to be_falsey
end
it "should replace with new locks" do
@lock.lock
- Puppet::FileSystem.exist?(@lockfile).should be_true
- @lock.lock_pid.should == 6789
- @lock.should be_mine
- @lock.should be_locked
+ expect(Puppet::FileSystem.exist?(@lockfile)).to be_truthy
+ expect(@lock.lock_pid).to eq(6789)
+ expect(@lock).to be_mine
+ expect(@lock).to be_locked
end
end
describe "#unlock" do
it "should not be allowed" do
- @lock.unlock.should be_false
+ expect(@lock.unlock).to be_falsey
end
it "should not remove the lock file" do
@lock.unlock
- Puppet::FileSystem.exist?(@lockfile).should be_true
+ expect(Puppet::FileSystem.exist?(@lockfile)).to be_truthy
end
end
end
describe "with another process lock" do
before(:each) do
# fake our pid to be 1234
Process.stubs(:pid).returns(1234)
# lock the file
@lock.lock
# fake our pid to be a different pid, to simulate someone else
# holding the lock
Process.stubs(:pid).returns(6789)
Process.stubs(:kill).with(0, 6789)
Process.stubs(:kill).with(0, 1234)
end
it "should be locked" do
- @lock.should be_locked
+ expect(@lock).to be_locked
end
it "should not be mine" do
- @lock.should_not be_mine
+ expect(@lock).not_to be_mine
end
describe "#lock" do
it "should not be possible" do
- @lock.lock.should be_false
+ expect(@lock.lock).to be_falsey
end
it "should not overwrite the lock" do
@lock.lock
- @lock.should_not be_mine
+ expect(@lock).not_to be_mine
end
end
describe "#unlock" do
it "should not be possible" do
- @lock.unlock.should be_false
+ expect(@lock.unlock).to be_falsey
end
it "should not remove the lock file" do
@lock.unlock
- Puppet::FileSystem.exist?(@lockfile).should be_true
+ expect(Puppet::FileSystem.exist?(@lockfile)).to be_truthy
end
it "should still not be our lock" do
@lock.unlock
- @lock.should_not be_mine
+ expect(@lock).not_to be_mine
end
end
end
end
diff --git a/spec/unit/util/posix_spec.rb b/spec/unit/util/posix_spec.rb
index cc5f960ba..7fc56dd44 100755
--- a/spec/unit/util/posix_spec.rb
+++ b/spec/unit/util/posix_spec.rb
@@ -1,251 +1,251 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/posix'
class PosixTest
include Puppet::Util::POSIX
end
describe Puppet::Util::POSIX do
before do
@posix = PosixTest.new
end
[:group, :gr].each do |name|
it "should return :gid as the field for #{name}" do
- @posix.idfield(name).should == :gid
+ expect(@posix.idfield(name)).to eq(:gid)
end
it "should return :getgrgid as the id method for #{name}" do
- @posix.methodbyid(name).should == :getgrgid
+ expect(@posix.methodbyid(name)).to eq(:getgrgid)
end
it "should return :getgrnam as the name method for #{name}" do
- @posix.methodbyname(name).should == :getgrnam
+ expect(@posix.methodbyname(name)).to eq(:getgrnam)
end
end
[:user, :pw, :passwd].each do |name|
it "should return :uid as the field for #{name}" do
- @posix.idfield(name).should == :uid
+ expect(@posix.idfield(name)).to eq(:uid)
end
it "should return :getpwuid as the id method for #{name}" do
- @posix.methodbyid(name).should == :getpwuid
+ expect(@posix.methodbyid(name)).to eq(:getpwuid)
end
it "should return :getpwnam as the name method for #{name}" do
- @posix.methodbyname(name).should == :getpwnam
+ expect(@posix.methodbyname(name)).to eq(:getpwnam)
end
end
describe "when retrieving a posix field" do
before do
@thing = stub 'thing', :field => "asdf"
end
it "should fail if no id was passed" do
- lambda { @posix.get_posix_field("asdf", "bar", nil) }.should raise_error(Puppet::DevError)
+ expect { @posix.get_posix_field("asdf", "bar", nil) }.to raise_error(Puppet::DevError)
end
describe "and the id is an integer" do
it "should log an error and return nil if the specified id is greater than the maximum allowed ID" do
Puppet[:maximum_uid] = 100
Puppet.expects(:err)
- @posix.get_posix_field("asdf", "bar", 200).should be_nil
+ expect(@posix.get_posix_field("asdf", "bar", 200)).to be_nil
end
it "should use the method return by :methodbyid and return the specified field" do
Etc.expects(:getgrgid).returns @thing
@thing.expects(:field).returns "myval"
- @posix.get_posix_field(:gr, :field, 200).should == "myval"
+ expect(@posix.get_posix_field(:gr, :field, 200)).to eq("myval")
end
it "should return nil if the method throws an exception" do
Etc.expects(:getgrgid).raises ArgumentError
@thing.expects(:field).never
- @posix.get_posix_field(:gr, :field, 200).should be_nil
+ expect(@posix.get_posix_field(:gr, :field, 200)).to be_nil
end
end
describe "and the id is not an integer" do
it "should use the method return by :methodbyid and return the specified field" do
Etc.expects(:getgrnam).returns @thing
@thing.expects(:field).returns "myval"
- @posix.get_posix_field(:gr, :field, "asdf").should == "myval"
+ expect(@posix.get_posix_field(:gr, :field, "asdf")).to eq("myval")
end
it "should return nil if the method throws an exception" do
Etc.expects(:getgrnam).raises ArgumentError
@thing.expects(:field).never
- @posix.get_posix_field(:gr, :field, "asdf").should be_nil
+ expect(@posix.get_posix_field(:gr, :field, "asdf")).to be_nil
end
end
end
describe "when returning the gid" do
before do
@posix.stubs(:get_posix_field)
end
describe "and the group is an integer" do
it "should convert integers specified as a string into an integer" do
@posix.expects(:get_posix_field).with(:group, :name, 100)
@posix.gid("100")
end
it "should look up the name for the group" do
@posix.expects(:get_posix_field).with(:group, :name, 100)
@posix.gid(100)
end
it "should return nil if the group cannot be found" do
@posix.expects(:get_posix_field).once.returns nil
@posix.expects(:search_posix_field).never
- @posix.gid(100).should be_nil
+ expect(@posix.gid(100)).to be_nil
end
it "should use the found name to look up the id" do
@posix.expects(:get_posix_field).with(:group, :name, 100).returns "asdf"
@posix.expects(:get_posix_field).with(:group, :gid, "asdf").returns 100
- @posix.gid(100).should == 100
+ expect(@posix.gid(100)).to eq(100)
end
# LAK: This is because some platforms have a broken Etc module that always return
# the same group.
it "should use :search_posix_field if the discovered id does not match the passed-in id" do
@posix.expects(:get_posix_field).with(:group, :name, 100).returns "asdf"
@posix.expects(:get_posix_field).with(:group, :gid, "asdf").returns 50
@posix.expects(:search_posix_field).with(:group, :gid, 100).returns "asdf"
- @posix.gid(100).should == "asdf"
+ expect(@posix.gid(100)).to eq("asdf")
end
end
describe "and the group is a string" do
it "should look up the gid for the group" do
@posix.expects(:get_posix_field).with(:group, :gid, "asdf")
@posix.gid("asdf")
end
it "should return nil if the group cannot be found" do
@posix.expects(:get_posix_field).once.returns nil
@posix.expects(:search_posix_field).never
- @posix.gid("asdf").should be_nil
+ expect(@posix.gid("asdf")).to be_nil
end
it "should use the found gid to look up the nam" do
@posix.expects(:get_posix_field).with(:group, :gid, "asdf").returns 100
@posix.expects(:get_posix_field).with(:group, :name, 100).returns "asdf"
- @posix.gid("asdf").should == 100
+ expect(@posix.gid("asdf")).to eq(100)
end
it "should use :search_posix_field if the discovered name does not match the passed-in name" do
@posix.expects(:get_posix_field).with(:group, :gid, "asdf").returns 100
@posix.expects(:get_posix_field).with(:group, :name, 100).returns "boo"
@posix.expects(:search_posix_field).with(:group, :gid, "asdf").returns "asdf"
- @posix.gid("asdf").should == "asdf"
+ expect(@posix.gid("asdf")).to eq("asdf")
end
end
end
describe "when returning the uid" do
before do
@posix.stubs(:get_posix_field)
end
describe "and the group is an integer" do
it "should convert integers specified as a string into an integer" do
@posix.expects(:get_posix_field).with(:passwd, :name, 100)
@posix.uid("100")
end
it "should look up the name for the group" do
@posix.expects(:get_posix_field).with(:passwd, :name, 100)
@posix.uid(100)
end
it "should return nil if the group cannot be found" do
@posix.expects(:get_posix_field).once.returns nil
@posix.expects(:search_posix_field).never
- @posix.uid(100).should be_nil
+ expect(@posix.uid(100)).to be_nil
end
it "should use the found name to look up the id" do
@posix.expects(:get_posix_field).with(:passwd, :name, 100).returns "asdf"
@posix.expects(:get_posix_field).with(:passwd, :uid, "asdf").returns 100
- @posix.uid(100).should == 100
+ expect(@posix.uid(100)).to eq(100)
end
# LAK: This is because some platforms have a broken Etc module that always return
# the same group.
it "should use :search_posix_field if the discovered id does not match the passed-in id" do
@posix.expects(:get_posix_field).with(:passwd, :name, 100).returns "asdf"
@posix.expects(:get_posix_field).with(:passwd, :uid, "asdf").returns 50
@posix.expects(:search_posix_field).with(:passwd, :uid, 100).returns "asdf"
- @posix.uid(100).should == "asdf"
+ expect(@posix.uid(100)).to eq("asdf")
end
end
describe "and the group is a string" do
it "should look up the uid for the group" do
@posix.expects(:get_posix_field).with(:passwd, :uid, "asdf")
@posix.uid("asdf")
end
it "should return nil if the group cannot be found" do
@posix.expects(:get_posix_field).once.returns nil
@posix.expects(:search_posix_field).never
- @posix.uid("asdf").should be_nil
+ expect(@posix.uid("asdf")).to be_nil
end
it "should use the found uid to look up the nam" do
@posix.expects(:get_posix_field).with(:passwd, :uid, "asdf").returns 100
@posix.expects(:get_posix_field).with(:passwd, :name, 100).returns "asdf"
- @posix.uid("asdf").should == 100
+ expect(@posix.uid("asdf")).to eq(100)
end
it "should use :search_posix_field if the discovered name does not match the passed-in name" do
@posix.expects(:get_posix_field).with(:passwd, :uid, "asdf").returns 100
@posix.expects(:get_posix_field).with(:passwd, :name, 100).returns "boo"
@posix.expects(:search_posix_field).with(:passwd, :uid, "asdf").returns "asdf"
- @posix.uid("asdf").should == "asdf"
+ expect(@posix.uid("asdf")).to eq("asdf")
end
end
end
it "should be able to iteratively search for posix values" do
- @posix.should respond_to(:search_posix_field)
+ expect(@posix).to respond_to(:search_posix_field)
end
end
diff --git a/spec/unit/util/profiler/aggregate_spec.rb b/spec/unit/util/profiler/aggregate_spec.rb
index 6a70a4b2e..0c6c5db4b 100644
--- a/spec/unit/util/profiler/aggregate_spec.rb
+++ b/spec/unit/util/profiler/aggregate_spec.rb
@@ -1,55 +1,55 @@
require 'spec_helper'
require 'puppet/util/profiler'
require 'puppet/util/profiler/around_profiler'
require 'puppet/util/profiler/aggregate'
describe Puppet::Util::Profiler::Aggregate do
let(:logger) { AggregateSimpleLog.new }
let(:profiler) { Puppet::Util::Profiler::Aggregate.new(logger, nil) }
let(:profiler_mgr) do
p = Puppet::Util::Profiler::AroundProfiler.new
p.add_profiler(profiler)
p
end
it "tracks the aggregate counts and time for the hierarchy of metrics" do
profiler_mgr.profile("Looking up hiera data in production environment", ["function", "hiera_lookup", "production"]) { sleep 0.01 }
profiler_mgr.profile("Looking up hiera data in test environment", ["function", "hiera_lookup", "test"]) {}
profiler_mgr.profile("looking up stuff for compilation", ["compiler", "lookup"]) { sleep 0.01 }
profiler_mgr.profile("COMPILING ALL OF THE THINGS!", ["compiler", "compiling"]) {}
- profiler.values["function"].count.should == 2
- profiler.values["function"].time.should be > 0
- profiler.values["function"]["hiera_lookup"].count.should == 2
- profiler.values["function"]["hiera_lookup"]["production"].count.should == 1
- profiler.values["function"]["hiera_lookup"]["test"].count.should == 1
- profiler.values["function"].time.should be >= profiler.values["function"]["hiera_lookup"]["test"].time
-
- profiler.values["compiler"].count.should == 2
- profiler.values["compiler"].time.should be > 0
- profiler.values["compiler"]["lookup"].count.should == 1
- profiler.values["compiler"]["compiling"].count.should == 1
- profiler.values["compiler"].time.should be >= profiler.values["compiler"]["lookup"].time
+ expect(profiler.values["function"].count).to eq(2)
+ expect(profiler.values["function"].time).to be > 0
+ expect(profiler.values["function"]["hiera_lookup"].count).to eq(2)
+ expect(profiler.values["function"]["hiera_lookup"]["production"].count).to eq(1)
+ expect(profiler.values["function"]["hiera_lookup"]["test"].count).to eq(1)
+ expect(profiler.values["function"].time).to be >= profiler.values["function"]["hiera_lookup"]["test"].time
+
+ expect(profiler.values["compiler"].count).to eq(2)
+ expect(profiler.values["compiler"].time).to be > 0
+ expect(profiler.values["compiler"]["lookup"].count).to eq(1)
+ expect(profiler.values["compiler"]["compiling"].count).to eq(1)
+ expect(profiler.values["compiler"].time).to be >= profiler.values["compiler"]["lookup"].time
profiler.shutdown
- logger.output.should =~ /function -> hiera_lookup: .*\(2 calls\)\nfunction -> hiera_lookup ->.*\(1 calls\)/
- logger.output.should =~ /compiler: .*\(2 calls\)\ncompiler ->.*\(1 calls\)/
+ expect(logger.output).to match(/function -> hiera_lookup: .*\(2 calls\)\nfunction -> hiera_lookup ->.*\(1 calls\)/)
+ expect(logger.output).to match(/compiler: .*\(2 calls\)\ncompiler ->.*\(1 calls\)/)
end
it "supports both symbols and strings as components of a metric id" do
profiler_mgr.profile("yo", [:foo, "bar"]) {}
end
class AggregateSimpleLog
attr_reader :output
def initialize
@output = ""
end
def call(msg)
@output << msg << "\n"
end
end
end
diff --git a/spec/unit/util/profiler/around_profiler_spec.rb b/spec/unit/util/profiler/around_profiler_spec.rb
index 0837395b5..1b1dbe569 100644
--- a/spec/unit/util/profiler/around_profiler_spec.rb
+++ b/spec/unit/util/profiler/around_profiler_spec.rb
@@ -1,61 +1,61 @@
require 'spec_helper'
require 'puppet/util/profiler'
describe Puppet::Util::Profiler::AroundProfiler do
let(:child) { TestAroundProfiler.new() }
let(:profiler) { Puppet::Util::Profiler::AroundProfiler.new }
before :each do
profiler.add_profiler(child)
end
it "returns the value of the profiled segment" do
retval = profiler.profile("Testing", ["testing"]) { "the return value" }
- retval.should == "the return value"
+ expect(retval).to eq("the return value")
end
it "propagates any errors raised in the profiled segment" do
expect do
profiler.profile("Testing", ["testing"]) { raise "a problem" }
end.to raise_error("a problem")
end
it "makes the description and the context available to the `start` and `finish` methods" do
profiler.profile("Testing", ["testing"]) { }
- child.context.should == "Testing"
- child.description.should == "Testing"
+ expect(child.context).to eq("Testing")
+ expect(child.description).to eq("Testing")
end
it "calls finish even when an error is raised" do
begin
profiler.profile("Testing", ["testing"]) { raise "a problem" }
rescue
- child.context.should == "Testing"
+ expect(child.context).to eq("Testing")
end
end
it "supports multiple profilers" do
profiler2 = TestAroundProfiler.new
profiler.add_profiler(profiler2)
profiler.profile("Testing", ["testing"]) {}
- child.context.should == "Testing"
- profiler2.context.should == "Testing"
+ expect(child.context).to eq("Testing")
+ expect(profiler2.context).to eq("Testing")
end
class TestAroundProfiler
attr_accessor :context, :description
def start(description, metric_id)
description
end
def finish(context, description, metric_id)
@context = context
@description = description
end
end
end
diff --git a/spec/unit/util/profiler/logging_spec.rb b/spec/unit/util/profiler/logging_spec.rb
index 3f6a728dd..84960e149 100644
--- a/spec/unit/util/profiler/logging_spec.rb
+++ b/spec/unit/util/profiler/logging_spec.rb
@@ -1,70 +1,70 @@
require 'spec_helper'
require 'puppet/util/profiler'
describe Puppet::Util::Profiler::Logging do
let(:logger) { SimpleLog.new }
let(:identifier) { "Profiling ID" }
let(:logging_profiler) { TestLoggingProfiler.new(logger, identifier) }
let(:profiler) do
p = Puppet::Util::Profiler::AroundProfiler.new
p.add_profiler(logging_profiler)
p
end
it "logs the explanation of the profile results" do
profiler.profile("Testing", ["test"]) { }
- logger.messages.first.should =~ /the explanation/
+ expect(logger.messages.first).to match(/the explanation/)
end
it "describes the profiled segment" do
profiler.profile("Tested measurement", ["test"]) { }
- logger.messages.first.should =~ /PROFILE \[#{identifier}\] \d Tested measurement/
+ expect(logger.messages.first).to match(/PROFILE \[#{identifier}\] \d Tested measurement/)
end
it "indicates the order in which segments are profiled" do
profiler.profile("Measurement", ["measurement"]) { }
profiler.profile("Another measurement", ["measurement"]) { }
- logger.messages[0].should =~ /1 Measurement/
- logger.messages[1].should =~ /2 Another measurement/
+ expect(logger.messages[0]).to match(/1 Measurement/)
+ expect(logger.messages[1]).to match(/2 Another measurement/)
end
it "indicates the nesting of profiled segments" do
profiler.profile("Measurement", ["measurement1"]) do
profiler.profile("Nested measurement", ["measurement2"]) { }
end
profiler.profile("Another measurement", ["measurement1"]) do
profiler.profile("Another nested measurement", ["measurement2"]) { }
end
- logger.messages[0].should =~ /1.1 Nested measurement/
- logger.messages[1].should =~ /1 Measurement/
- logger.messages[2].should =~ /2.1 Another nested measurement/
- logger.messages[3].should =~ /2 Another measurement/
+ expect(logger.messages[0]).to match(/1.1 Nested measurement/)
+ expect(logger.messages[1]).to match(/1 Measurement/)
+ expect(logger.messages[2]).to match(/2.1 Another nested measurement/)
+ expect(logger.messages[3]).to match(/2 Another measurement/)
end
class TestLoggingProfiler < Puppet::Util::Profiler::Logging
def do_start(metric, description)
"the start"
end
def do_finish(context, metric, description)
{:msg => "the explanation of #{context}"}
end
end
class SimpleLog
attr_reader :messages
def initialize
@messages = []
end
def call(msg)
@messages << msg
end
end
end
diff --git a/spec/unit/util/profiler/object_counts_spec.rb b/spec/unit/util/profiler/object_counts_spec.rb
index f0ec329ce..c5c558a99 100644
--- a/spec/unit/util/profiler/object_counts_spec.rb
+++ b/spec/unit/util/profiler/object_counts_spec.rb
@@ -1,12 +1,12 @@
require 'spec_helper'
require 'puppet/util/profiler'
describe Puppet::Util::Profiler::ObjectCounts do
it "reports the changes in the system object counts" do
profiler = Puppet::Util::Profiler::ObjectCounts.new(nil, nil)
message = profiler.finish(profiler.start)
- message.should =~ / T_STRING: \d+, /
+ expect(message).to match(/ T_STRING: \d+, /)
end
end
diff --git a/spec/unit/util/profiler/wall_clock_spec.rb b/spec/unit/util/profiler/wall_clock_spec.rb
index 1adcf0d61..484ddc21b 100644
--- a/spec/unit/util/profiler/wall_clock_spec.rb
+++ b/spec/unit/util/profiler/wall_clock_spec.rb
@@ -1,13 +1,13 @@
require 'spec_helper'
require 'puppet/util/profiler'
describe Puppet::Util::Profiler::WallClock do
it "logs the number of seconds it took to execute the segment" do
profiler = Puppet::Util::Profiler::WallClock.new(nil, nil)
message = profiler.do_finish(profiler.start(["foo", "bar"], "Testing"), ["foo", "bar"], "Testing")[:msg]
- message.should =~ /took \d\.\d{4} seconds/
+ expect(message).to match(/took \d\.\d{4} seconds/)
end
end
diff --git a/spec/unit/util/profiler_spec.rb b/spec/unit/util/profiler_spec.rb
index 7ef70c240..769351038 100644
--- a/spec/unit/util/profiler_spec.rb
+++ b/spec/unit/util/profiler_spec.rb
@@ -1,47 +1,47 @@
require 'spec_helper'
require 'puppet/util/profiler'
describe Puppet::Util::Profiler do
let(:profiler) { TestProfiler.new() }
it "supports adding profilers" do
subject.add_profiler(profiler)
- subject.current[0].should == profiler
+ expect(subject.current[0]).to eq(profiler)
end
it "supports removing profilers" do
subject.add_profiler(profiler)
subject.remove_profiler(profiler)
- subject.current.length.should == 0
+ expect(subject.current.length).to eq(0)
end
it "supports clearing profiler list" do
subject.add_profiler(profiler)
subject.clear
- subject.current.length.should == 0
+ expect(subject.current.length).to eq(0)
end
it "supports profiling" do
subject.add_profiler(profiler)
subject.profile("hi", ["mymetric"]) {}
- profiler.context[:metric_id].should == ["mymetric"]
- profiler.context[:description].should == "hi"
- profiler.description.should == "hi"
+ expect(profiler.context[:metric_id]).to eq(["mymetric"])
+ expect(profiler.context[:description]).to eq("hi")
+ expect(profiler.description).to eq("hi")
end
class TestProfiler
attr_accessor :context, :metric, :description
def start(description, metric_id)
{:metric_id => metric_id,
:description => description}
end
def finish(context, description, metric_id)
@context = context
@metric_id = metric_id
@description = description
end
end
end
diff --git a/spec/unit/util/reference_spec.rb b/spec/unit/util/reference_spec.rb
index 8eb1e3147..bd034e8f6 100644
--- a/spec/unit/util/reference_spec.rb
+++ b/spec/unit/util/reference_spec.rb
@@ -1,39 +1,39 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/reference'
describe Puppet::Util::Reference do
it "should create valid Markdown extension definition lists" do
my_fragment = nil
Puppet::Util::Reference.newreference :testreference, :doc => "A peer of the type and configuration references, but with no useful information" do
my_term = "A term"
my_definition = <<-EOT
The definition of this term, marked by a colon and a space.
We should be able to handle multi-line definitions. Each subsequent
line should left-align with the first word character after the colon
used as the definition marker.
We should be able to handle multi-paragraph definitions.
Leading indentation should be stripped from the definition, which allows
us to indent the source string for cosmetic purposes.
EOT
my_fragment = markdown_definitionlist(my_term, my_definition)
end
Puppet::Util::Reference.reference(:testreference).send(:to_markdown, true)
- my_fragment.should == <<-EOT
+ expect(my_fragment).to eq <<-EOT
A term
: The definition of this term, marked by a colon and a space.
We should be able to handle multi-line definitions. Each subsequent
line should left-align with the first word character after the colon
used as the definition marker.
We should be able to handle multi-paragraph definitions.
Leading indentation should be stripped from the definition, which allows
us to indent the source string for cosmetic purposes.
EOT
end
end
diff --git a/spec/unit/util/resource_template_spec.rb b/spec/unit/util/resource_template_spec.rb
index 182a78ab0..5b71614f4 100755
--- a/spec/unit/util/resource_template_spec.rb
+++ b/spec/unit/util/resource_template_spec.rb
@@ -1,57 +1,57 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/resource_template'
describe Puppet::Util::ResourceTemplate do
describe "when initializing" do
it "should fail if the template does not exist" do
Puppet::FileSystem.expects(:exist?).with("/my/template").returns false
- lambda { Puppet::Util::ResourceTemplate.new("/my/template", mock('resource')) }.should raise_error(ArgumentError)
+ expect { Puppet::Util::ResourceTemplate.new("/my/template", mock('resource')) }.to raise_error(ArgumentError)
end
it "should not create the ERB template" do
ERB.expects(:new).never
Puppet::FileSystem.expects(:exist?).with("/my/template").returns true
Puppet::Util::ResourceTemplate.new("/my/template", mock('resource'))
end
end
describe "when evaluating" do
before do
Puppet::FileSystem.stubs(:exist?).returns true
File.stubs(:read).returns "eh"
@template = stub 'template', :result => nil
ERB.stubs(:new).returns @template
@resource = mock 'resource'
@wrapper = Puppet::Util::ResourceTemplate.new("/my/template", @resource)
end
it "should set all of the resource's parameters as instance variables" do
@resource.expects(:to_hash).returns(:one => "uno", :two => "dos")
@template.expects(:result).with do |bind|
eval("@one", bind) == "uno" and eval("@two", bind) == "dos"
end
@wrapper.evaluate
end
it "should create a template instance with the contents of the file" do
File.expects(:read).with("/my/template").returns "yay"
ERB.expects(:new).with("yay", 0, "-").returns(@template)
@wrapper.stubs :set_resource_variables
@wrapper.evaluate
end
it "should return the result of the template" do
@wrapper.stubs :set_resource_variables
@wrapper.expects(:binding).returns "mybinding"
@template.expects(:result).with("mybinding").returns "myresult"
- @wrapper.evaluate.should == "myresult"
+ expect(@wrapper.evaluate).to eq("myresult")
end
end
end
diff --git a/spec/unit/util/rubygems_spec.rb b/spec/unit/util/rubygems_spec.rb
index b40600206..f781e89a4 100644
--- a/spec/unit/util/rubygems_spec.rb
+++ b/spec/unit/util/rubygems_spec.rb
@@ -1,82 +1,82 @@
require 'spec_helper'
require 'puppet/util/rubygems'
describe Puppet::Util::RubyGems::Source do
let(:gem_path) { File.expand_path('/foo/gems') }
let(:gem_lib) { File.join(gem_path, 'lib') }
let(:fake_gem) { stub(:full_gem_path => gem_path) }
describe "::new" do
it "returns NoGemsSource if rubygems is not present" do
described_class.expects(:has_rubygems?).returns(false)
- described_class.new.should be_kind_of(Puppet::Util::RubyGems::NoGemsSource)
+ expect(described_class.new).to be_kind_of(Puppet::Util::RubyGems::NoGemsSource)
end
it "returns Gems18Source if Gem::Specification responds to latest_specs" do
described_class.expects(:has_rubygems?).returns(true)
Gem::Specification.expects(:respond_to?).with(:latest_specs).returns(true)
- described_class.new.should be_kind_of(Puppet::Util::RubyGems::Gems18Source)
+ expect(described_class.new).to be_kind_of(Puppet::Util::RubyGems::Gems18Source)
end
it "returns Gems18Source if Gem::Specification does not respond to latest_specs" do
described_class.expects(:has_rubygems?).returns(true)
Gem::Specification.expects(:respond_to?).with(:latest_specs).returns(false)
- described_class.new.should be_kind_of(Puppet::Util::RubyGems::OldGemsSource)
+ expect(described_class.new).to be_kind_of(Puppet::Util::RubyGems::OldGemsSource)
end
end
describe '::NoGemsSource' do
before(:each) { described_class.stubs(:source).returns(Puppet::Util::RubyGems::NoGemsSource) }
it "#directories returns an empty list" do
- described_class.new.directories.should == []
+ expect(described_class.new.directories).to eq([])
end
it "#clear_paths returns nil" do
- described_class.new.clear_paths.should be_nil
+ expect(described_class.new.clear_paths).to be_nil
end
end
describe '::Gems18Source' do
before(:each) { described_class.stubs(:source).returns(Puppet::Util::RubyGems::Gems18Source) }
it "#directories returns the lib subdirs of Gem::Specification.latest_specs" do
Gem::Specification.expects(:latest_specs).with(true).returns([fake_gem])
- described_class.new.directories.should == [gem_lib]
+ expect(described_class.new.directories).to eq([gem_lib])
end
it "#clear_paths calls Gem.clear_paths" do
Gem.expects(:clear_paths)
described_class.new.clear_paths
end
end
describe '::OldGemsSource' do
before(:each) { described_class.stubs(:source).returns(Puppet::Util::RubyGems::OldGemsSource) }
it "#directories returns the contents of Gem.latest_load_paths" do
Gem.expects(:latest_load_paths).returns([gem_lib])
- described_class.new.directories.should == [gem_lib]
+ expect(described_class.new.directories).to eq([gem_lib])
end
# Older rubygems seem to have a problem with rescanning the gem paths in which they
# look for a file in the wrong place and expect it to be there. By caching the first
# set of results we don't trigger this bug. This behavior was seen on ruby 1.8.7-p334
# using rubygems v1.6.2
it "caches the gem paths (works around a bug in older rubygems)" do
Gem.expects(:latest_load_paths).returns([gem_lib]).once
source = described_class.new
- source.directories.should == [gem_lib]
+ expect(source.directories).to eq([gem_lib])
end
it "#clear_paths calls Gem.clear_paths" do
Gem.expects(:clear_paths)
described_class.new.clear_paths
end
end
end
diff --git a/spec/unit/util/run_mode_spec.rb b/spec/unit/util/run_mode_spec.rb
index 1fb66e779..d6e680ba0 100755
--- a/spec/unit/util/run_mode_spec.rb
+++ b/spec/unit/util/run_mode_spec.rb
@@ -1,145 +1,145 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Util::RunMode do
before do
@run_mode = Puppet::Util::RunMode.new('fake')
end
it "has rundir depend on vardir" do
- @run_mode.run_dir.should == '$vardir/run'
+ expect(@run_mode.run_dir).to eq('$vardir/run')
end
describe Puppet::Util::UnixRunMode, :unless => Puppet.features.microsoft_windows? do
before do
@run_mode = Puppet::Util::UnixRunMode.new('fake')
end
describe "#conf_dir" do
it "has confdir /etc/puppet when run as root" do
- as_root { @run_mode.conf_dir.should == File.expand_path('/etc/puppet') }
+ as_root { expect(@run_mode.conf_dir).to eq(File.expand_path('/etc/puppet')) }
end
it "has confdir ~/.puppet when run as non-root" do
- as_non_root { @run_mode.conf_dir.should == File.expand_path('~/.puppet') }
+ as_non_root { expect(@run_mode.conf_dir).to eq(File.expand_path('~/.puppet')) }
end
context "master run mode" do
before do
@run_mode = Puppet::Util::UnixRunMode.new('master')
end
it "has confdir ~/.puppet when run as non-root and master run mode (#16337)" do
- as_non_root { @run_mode.conf_dir.should == File.expand_path('~/.puppet') }
+ as_non_root { expect(@run_mode.conf_dir).to eq(File.expand_path('~/.puppet')) }
end
end
it "fails when asking for the conf_dir as non-root and there is no $HOME" do
as_non_root do
without_home do
expect { @run_mode.conf_dir }.to raise_error ArgumentError, /couldn't find HOME/
end
end
end
end
describe "#var_dir" do
it "has vardir /var/lib/puppet when run as root" do
- as_root { @run_mode.var_dir.should == File.expand_path('/var/lib/puppet') }
+ as_root { expect(@run_mode.var_dir).to eq(File.expand_path('/var/lib/puppet')) }
end
it "has vardir ~/.puppet/var when run as non-root" do
- as_non_root { @run_mode.var_dir.should == File.expand_path('~/.puppet/var') }
+ as_non_root { expect(@run_mode.var_dir).to eq(File.expand_path('~/.puppet/var')) }
end
it "fails when asking for the var_dir as non-root and there is no $HOME" do
as_non_root do
without_home do
expect { @run_mode.var_dir }.to raise_error ArgumentError, /couldn't find HOME/
end
end
end
end
end
describe Puppet::Util::WindowsRunMode, :if => Puppet.features.microsoft_windows? do
before do
if not Dir.const_defined? :COMMON_APPDATA
Dir.const_set :COMMON_APPDATA, "/CommonFakeBase"
@remove_const = true
end
@run_mode = Puppet::Util::WindowsRunMode.new('fake')
end
after do
if @remove_const
Dir.send :remove_const, :COMMON_APPDATA
end
end
describe "#conf_dir" do
it "has confdir /etc/puppet when run as root" do
- as_root { @run_mode.conf_dir.should == File.expand_path(File.join(Dir::COMMON_APPDATA, "PuppetLabs", "puppet", "etc")) }
+ as_root { expect(@run_mode.conf_dir).to eq(File.expand_path(File.join(Dir::COMMON_APPDATA, "PuppetLabs", "puppet", "etc"))) }
end
it "has confdir in ~/.puppet when run as non-root" do
- as_non_root { @run_mode.conf_dir.should == File.expand_path("~/.puppet") }
+ as_non_root { expect(@run_mode.conf_dir).to eq(File.expand_path("~/.puppet")) }
end
it "fails when asking for the conf_dir as non-root and there is no %HOME%, %HOMEDRIVE%, and %USERPROFILE%" do
as_non_root do
without_env('HOME') do
without_env('HOMEDRIVE') do
without_env('USERPROFILE') do
expect { @run_mode.conf_dir }.to raise_error ArgumentError, /couldn't find HOME/
end
end
end
end
end
end
describe "#var_dir" do
it "has vardir /var/lib/puppet when run as root" do
- as_root { @run_mode.var_dir.should == File.expand_path(File.join(Dir::COMMON_APPDATA, "PuppetLabs", "puppet", "var")) }
+ as_root { expect(@run_mode.var_dir).to eq(File.expand_path(File.join(Dir::COMMON_APPDATA, "PuppetLabs", "puppet", "var"))) }
end
it "has vardir in ~/.puppet/var when run as non-root" do
- as_non_root { @run_mode.var_dir.should == File.expand_path("~/.puppet/var") }
+ as_non_root { expect(@run_mode.var_dir).to eq(File.expand_path("~/.puppet/var")) }
end
it "fails when asking for the conf_dir as non-root and there is no %HOME%, %HOMEDRIVE%, and %USERPROFILE%" do
as_non_root do
without_env('HOME') do
without_env('HOMEDRIVE') do
without_env('USERPROFILE') do
expect { @run_mode.var_dir }.to raise_error ArgumentError, /couldn't find HOME/
end
end
end
end
end
end
end
def as_root
Puppet.features.stubs(:root?).returns(true)
yield
end
def as_non_root
Puppet.features.stubs(:root?).returns(false)
yield
end
def without_env(name, &block)
saved = ENV[name]
ENV.delete name
yield
ensure
ENV[name] = saved
end
def without_home(&block)
without_env('HOME', &block)
end
end
diff --git a/spec/unit/util/selinux_spec.rb b/spec/unit/util/selinux_spec.rb
index 28db297bb..625c947c7 100755
--- a/spec/unit/util/selinux_spec.rb
+++ b/spec/unit/util/selinux_spec.rb
@@ -1,311 +1,311 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'pathname'
require 'puppet/util/selinux'
include Puppet::Util::SELinux
unless defined?(Selinux)
module Selinux
def self.is_selinux_enabled
false
end
end
end
describe Puppet::Util::SELinux do
describe "selinux_support?" do
before do
end
it "should return :true if this system has SELinux enabled" do
Selinux.expects(:is_selinux_enabled).returns 1
- selinux_support?.should be_true
+ expect(selinux_support?).to be_truthy
end
it "should return :false if this system lacks SELinux" do
Selinux.expects(:is_selinux_enabled).returns 0
- selinux_support?.should be_false
+ expect(selinux_support?).to be_falsey
end
it "should return nil if /proc/mounts does not exist" do
File.stubs(:open).with("/proc/mounts").raises("No such file or directory - /proc/mounts")
- read_mounts.should == nil
+ expect(read_mounts).to eq(nil)
end
end
describe "read_mounts" do
before :each do
fh = stub 'fh', :close => nil
File.stubs(:open).with("/proc/mounts").returns fh
fh.expects(:read_nonblock).times(2).returns("rootfs / rootfs rw 0 0\n/dev/root / ext3 rw,relatime,errors=continue,user_xattr,acl,data=ordered 0 0\n/dev /dev tmpfs rw,relatime,mode=755 0 0\n/proc /proc proc rw,relatime 0 0\n/sys /sys sysfs rw,relatime 0 0\n192.168.1.1:/var/export /mnt/nfs nfs rw,relatime,vers=3,rsize=32768,wsize=32768,namlen=255,hard,nointr,proto=tcp,timeo=600,retrans=2,sec=sys,mountaddr=192.168.1.1,mountvers=3,mountproto=udp,addr=192.168.1.1 0 0\n").then.raises EOFError
end
it "should parse the contents of /proc/mounts" do
- read_mounts.should == {
+ expect(read_mounts).to eq({
'/' => 'ext3',
'/sys' => 'sysfs',
'/mnt/nfs' => 'nfs',
'/proc' => 'proc',
- '/dev' => 'tmpfs' }
+ '/dev' => 'tmpfs' })
end
end
describe "filesystem detection" do
before :each do
self.stubs(:read_mounts).returns({
'/' => 'ext3',
'/sys' => 'sysfs',
'/mnt/nfs' => 'nfs',
'/proc' => 'proc',
'/dev' => 'tmpfs' })
end
it "should match a path on / to ext3" do
- find_fs('/etc/puppet/testfile').should == "ext3"
+ expect(find_fs('/etc/puppet/testfile')).to eq("ext3")
end
it "should match a path on /mnt/nfs to nfs" do
- find_fs('/mnt/nfs/testfile/foobar').should == "nfs"
+ expect(find_fs('/mnt/nfs/testfile/foobar')).to eq("nfs")
end
it "should return true for a capable filesystem" do
- selinux_label_support?('/etc/puppet/testfile').should be_true
+ expect(selinux_label_support?('/etc/puppet/testfile')).to be_truthy
end
it "should return false for a noncapable filesystem" do
- selinux_label_support?('/mnt/nfs/testfile').should be_false
+ expect(selinux_label_support?('/mnt/nfs/testfile')).to be_falsey
end
it "(#8714) don't follow symlinks when determining file systems", :unless => Puppet.features.microsoft_windows? do
scratch = Pathname(PuppetSpec::Files.tmpdir('selinux'))
self.stubs(:read_mounts).returns({
'/' => 'ext3',
scratch + 'nfs' => 'nfs',
})
(scratch + 'foo').make_symlink('nfs/bar')
- selinux_label_support?(scratch + 'foo').should be_true
+ expect(selinux_label_support?(scratch + 'foo')).to be_truthy
end
it "should handle files that don't exist" do
scratch = Pathname(PuppetSpec::Files.tmpdir('selinux'))
- selinux_label_support?(scratch + 'nonesuch').should be_true
+ expect(selinux_label_support?(scratch + 'nonesuch')).to be_truthy
end
end
describe "get_selinux_current_context" do
it "should return nil if no SELinux support" do
self.expects(:selinux_support?).returns false
- get_selinux_current_context("/foo").should be_nil
+ expect(get_selinux_current_context("/foo")).to be_nil
end
it "should return a context" do
self.expects(:selinux_support?).returns true
Selinux.expects(:lgetfilecon).with("/foo").returns [0, "user_u:role_r:type_t:s0"]
- get_selinux_current_context("/foo").should == "user_u:role_r:type_t:s0"
+ expect(get_selinux_current_context("/foo")).to eq("user_u:role_r:type_t:s0")
end
it "should return nil if lgetfilecon fails" do
self.expects(:selinux_support?).returns true
Selinux.expects(:lgetfilecon).with("/foo").returns -1
- get_selinux_current_context("/foo").should be_nil
+ expect(get_selinux_current_context("/foo")).to be_nil
end
end
describe "get_selinux_default_context" do
it "should return nil if no SELinux support" do
self.expects(:selinux_support?).returns false
- get_selinux_default_context("/foo").should be_nil
+ expect(get_selinux_default_context("/foo")).to be_nil
end
it "should return a context if a default context exists" do
self.expects(:selinux_support?).returns true
fstat = stub 'File::Stat', :mode => 0
Puppet::FileSystem.expects(:lstat).with('/foo').returns(fstat)
self.expects(:find_fs).with("/foo").returns "ext3"
Selinux.expects(:matchpathcon).with("/foo", 0).returns [0, "user_u:role_r:type_t:s0"]
- get_selinux_default_context("/foo").should == "user_u:role_r:type_t:s0"
+ expect(get_selinux_default_context("/foo")).to eq("user_u:role_r:type_t:s0")
end
it "handles permission denied errors by issuing a warning" do
self.stubs(:selinux_support?).returns true
self.stubs(:selinux_label_support?).returns true
Selinux.stubs(:matchpathcon).with("/root/chuj", 0).returns(-1)
self.stubs(:file_lstat).with("/root/chuj").raises(Errno::EACCES, "/root/chuj")
- get_selinux_default_context("/root/chuj").should be_nil
+ expect(get_selinux_default_context("/root/chuj")).to be_nil
end
it "handles no such file or directory errors by issuing a warning" do
self.stubs(:selinux_support?).returns true
self.stubs(:selinux_label_support?).returns true
Selinux.stubs(:matchpathcon).with("/root/chuj", 0).returns(-1)
self.stubs(:file_lstat).with("/root/chuj").raises(Errno::ENOENT, "/root/chuj")
- get_selinux_default_context("/root/chuj").should be_nil
+ expect(get_selinux_default_context("/root/chuj")).to be_nil
end
it "should return nil if matchpathcon returns failure" do
self.expects(:selinux_support?).returns true
fstat = stub 'File::Stat', :mode => 0
Puppet::FileSystem.expects(:lstat).with('/foo').returns(fstat)
self.expects(:find_fs).with("/foo").returns "ext3"
Selinux.expects(:matchpathcon).with("/foo", 0).returns -1
- get_selinux_default_context("/foo").should be_nil
+ expect(get_selinux_default_context("/foo")).to be_nil
end
it "should return nil if selinux_label_support returns false" do
self.expects(:selinux_support?).returns true
self.expects(:find_fs).with("/foo").returns "nfs"
- get_selinux_default_context("/foo").should be_nil
+ expect(get_selinux_default_context("/foo")).to be_nil
end
end
describe "parse_selinux_context" do
it "should return nil if no context is passed" do
- parse_selinux_context(:seluser, nil).should be_nil
+ expect(parse_selinux_context(:seluser, nil)).to be_nil
end
it "should return nil if the context is 'unlabeled'" do
- parse_selinux_context(:seluser, "unlabeled").should be_nil
+ expect(parse_selinux_context(:seluser, "unlabeled")).to be_nil
end
it "should return the user type when called with :seluser" do
- parse_selinux_context(:seluser, "user_u:role_r:type_t:s0").should == "user_u"
- parse_selinux_context(:seluser, "user-withdash_u:role_r:type_t:s0").should == "user-withdash_u"
+ expect(parse_selinux_context(:seluser, "user_u:role_r:type_t:s0")).to eq("user_u")
+ expect(parse_selinux_context(:seluser, "user-withdash_u:role_r:type_t:s0")).to eq("user-withdash_u")
end
it "should return the role type when called with :selrole" do
- parse_selinux_context(:selrole, "user_u:role_r:type_t:s0").should == "role_r"
- parse_selinux_context(:selrole, "user_u:role-withdash_r:type_t:s0").should == "role-withdash_r"
+ expect(parse_selinux_context(:selrole, "user_u:role_r:type_t:s0")).to eq("role_r")
+ expect(parse_selinux_context(:selrole, "user_u:role-withdash_r:type_t:s0")).to eq("role-withdash_r")
end
it "should return the type type when called with :seltype" do
- parse_selinux_context(:seltype, "user_u:role_r:type_t:s0").should == "type_t"
- parse_selinux_context(:seltype, "user_u:role_r:type-withdash_t:s0").should == "type-withdash_t"
+ expect(parse_selinux_context(:seltype, "user_u:role_r:type_t:s0")).to eq("type_t")
+ expect(parse_selinux_context(:seltype, "user_u:role_r:type-withdash_t:s0")).to eq("type-withdash_t")
end
describe "with spaces in the components" do
it "should raise when user contains a space" do
expect{parse_selinux_context(:seluser, "user with space_u:role_r:type_t:s0")}.to raise_error Puppet::Error
end
it "should raise when role contains a space" do
expect{parse_selinux_context(:selrole, "user_u:role with space_r:type_t:s0")}.to raise_error Puppet::Error
end
it "should raise when type contains a space" do
expect{parse_selinux_context(:seltype, "user_u:role_r:type with space_t:s0")}.to raise_error Puppet::Error
end
it "should return the range when range contains a space" do
- parse_selinux_context(:selrange, "user_u:role_r:type_t:s0 s1").should == "s0 s1"
+ expect(parse_selinux_context(:selrange, "user_u:role_r:type_t:s0 s1")).to eq("s0 s1")
end
end
it "should return nil for :selrange when no range is returned" do
- parse_selinux_context(:selrange, "user_u:role_r:type_t").should be_nil
+ expect(parse_selinux_context(:selrange, "user_u:role_r:type_t")).to be_nil
end
it "should return the range type when called with :selrange" do
- parse_selinux_context(:selrange, "user_u:role_r:type_t:s0").should == "s0"
- parse_selinux_context(:selrange, "user_u:role_r:type-withdash_t:s0").should == "s0"
+ expect(parse_selinux_context(:selrange, "user_u:role_r:type_t:s0")).to eq("s0")
+ expect(parse_selinux_context(:selrange, "user_u:role_r:type-withdash_t:s0")).to eq("s0")
end
describe "with a variety of SELinux range formats" do
['s0', 's0:c3', 's0:c3.c123', 's0:c3,c5,c8', 'TopSecret', 'TopSecret,Classified', 'Patient_Record'].each do |range|
it "should parse range '#{range}'" do
- parse_selinux_context(:selrange, "user_u:role_r:type_t:#{range}").should == range
+ expect(parse_selinux_context(:selrange, "user_u:role_r:type_t:#{range}")).to eq(range)
end
end
end
end
describe "set_selinux_context" do
before :each do
fh = stub 'fh', :close => nil
File.stubs(:open).with("/proc/mounts").returns fh
fh.stubs(:read_nonblock).returns(
"rootfs / rootfs rw 0 0\n/dev/root / ext3 rw,relatime,errors=continue,user_xattr,acl,data=ordered 0 0\n"+
"/dev /dev tmpfs rw,relatime,mode=755 0 0\n/proc /proc proc rw,relatime 0 0\n"+
"/sys /sys sysfs rw,relatime 0 0\n"
).then.raises EOFError
end
it "should return nil if there is no SELinux support" do
self.expects(:selinux_support?).returns false
- set_selinux_context("/foo", "user_u:role_r:type_t:s0").should be_nil
+ expect(set_selinux_context("/foo", "user_u:role_r:type_t:s0")).to be_nil
end
it "should return nil if selinux_label_support returns false" do
self.expects(:selinux_support?).returns true
self.expects(:selinux_label_support?).with("/foo").returns false
- set_selinux_context("/foo", "user_u:role_r:type_t:s0").should be_nil
+ expect(set_selinux_context("/foo", "user_u:role_r:type_t:s0")).to be_nil
end
it "should use lsetfilecon to set a context" do
self.expects(:selinux_support?).returns true
Selinux.expects(:lsetfilecon).with("/foo", "user_u:role_r:type_t:s0").returns 0
- set_selinux_context("/foo", "user_u:role_r:type_t:s0").should be_true
+ expect(set_selinux_context("/foo", "user_u:role_r:type_t:s0")).to be_truthy
end
it "should use lsetfilecon to set user_u user context" do
self.expects(:selinux_support?).returns true
Selinux.expects(:lgetfilecon).with("/foo").returns [0, "foo:role_r:type_t:s0"]
Selinux.expects(:lsetfilecon).with("/foo", "user_u:role_r:type_t:s0").returns 0
- set_selinux_context("/foo", "user_u", :seluser).should be_true
+ expect(set_selinux_context("/foo", "user_u", :seluser)).to be_truthy
end
it "should use lsetfilecon to set role_r role context" do
self.expects(:selinux_support?).returns true
Selinux.expects(:lgetfilecon).with("/foo").returns [0, "user_u:foo:type_t:s0"]
Selinux.expects(:lsetfilecon).with("/foo", "user_u:role_r:type_t:s0").returns 0
- set_selinux_context("/foo", "role_r", :selrole).should be_true
+ expect(set_selinux_context("/foo", "role_r", :selrole)).to be_truthy
end
it "should use lsetfilecon to set type_t type context" do
self.expects(:selinux_support?).returns true
Selinux.expects(:lgetfilecon).with("/foo").returns [0, "user_u:role_r:foo:s0"]
Selinux.expects(:lsetfilecon).with("/foo", "user_u:role_r:type_t:s0").returns 0
- set_selinux_context("/foo", "type_t", :seltype).should be_true
+ expect(set_selinux_context("/foo", "type_t", :seltype)).to be_truthy
end
it "should use lsetfilecon to set s0:c3,c5 range context" do
self.expects(:selinux_support?).returns true
Selinux.expects(:lgetfilecon).with("/foo").returns [0, "user_u:role_r:type_t:s0"]
Selinux.expects(:lsetfilecon).with("/foo", "user_u:role_r:type_t:s0:c3,c5").returns 0
- set_selinux_context("/foo", "s0:c3,c5", :selrange).should be_true
+ expect(set_selinux_context("/foo", "s0:c3,c5", :selrange)).to be_truthy
end
end
describe "set_selinux_default_context" do
it "should return nil if there is no SELinux support" do
self.expects(:selinux_support?).returns false
- set_selinux_default_context("/foo").should be_nil
+ expect(set_selinux_default_context("/foo")).to be_nil
end
it "should return nil if no default context exists" do
self.expects(:get_selinux_default_context).with("/foo").returns nil
- set_selinux_default_context("/foo").should be_nil
+ expect(set_selinux_default_context("/foo")).to be_nil
end
it "should do nothing and return nil if the current context matches the default context" do
self.expects(:get_selinux_default_context).with("/foo").returns "user_u:role_r:type_t"
self.expects(:get_selinux_current_context).with("/foo").returns "user_u:role_r:type_t"
- set_selinux_default_context("/foo").should be_nil
+ expect(set_selinux_default_context("/foo")).to be_nil
end
it "should set and return the default context if current and default do not match" do
self.expects(:get_selinux_default_context).with("/foo").returns "user_u:role_r:type_t"
self.expects(:get_selinux_current_context).with("/foo").returns "olduser_u:role_r:type_t"
self.expects(:set_selinux_context).with("/foo", "user_u:role_r:type_t").returns true
- set_selinux_default_context("/foo").should == "user_u:role_r:type_t"
+ expect(set_selinux_default_context("/foo")).to eq("user_u:role_r:type_t")
end
end
end
diff --git a/spec/unit/util/ssl_spec.rb b/spec/unit/util/ssl_spec.rb
index a467a6b78..c89bfe73d 100644
--- a/spec/unit/util/ssl_spec.rb
+++ b/spec/unit/util/ssl_spec.rb
@@ -1,92 +1,92 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'openssl'
require 'puppet/util/ssl'
describe Puppet::Util::SSL do
def parse(dn)
Puppet::Util::SSL.subject_from_dn(dn)
end
describe "when getting a subject from a DN" do
RSpec::Matchers.define :be_a_subject_with do |expected|
match do |actual|
parts = actual.to_a.map { |part| part[0..1] }.flatten
Hash[*parts] == expected
end
end
NO_PARTS = {}
it "parses a DN with a single part" do
- parse('CN=client.example.org').should be_a_subject_with({
+ expect(parse('CN=client.example.org')).to be_a_subject_with({
'CN' => 'client.example.org'
})
end
it "parses a DN with parts separated by slashes" do
- parse('/CN=Root CA/OU=Server Operations/O=Example Org').should be_a_subject_with({
+ expect(parse('/CN=Root CA/OU=Server Operations/O=Example Org')).to be_a_subject_with({
'CN' => 'Root CA',
'OU' => 'Server Operations',
'O' => 'Example Org'
})
end
it "parses a DN with a single part preceded by a slash" do
- parse('/CN=client.example.org').should be_a_subject_with({
+ expect(parse('/CN=client.example.org')).to be_a_subject_with({
'CN' => 'client.example.org'
})
end
it "parses a DN with parts separated by commas" do
- parse('O=Foo\, Inc,CN=client2a.example.org').should be_a_subject_with({
+ expect(parse('O=Foo\, Inc,CN=client2a.example.org')).to be_a_subject_with({
'O' => 'Foo, Inc',
'CN' => 'client2a.example.org'
})
end
it "finds no parts in something that is not a DN" do
- parse('(no)').should be_a_subject_with(NO_PARTS)
+ expect(parse('(no)')).to be_a_subject_with(NO_PARTS)
end
it "finds no parts in a DN with an invalid part" do
- parse('no=yes,CN=Root CA').should be_a_subject_with(NO_PARTS)
+ expect(parse('no=yes,CN=Root CA')).to be_a_subject_with(NO_PARTS)
end
it "finds no parts in an empty DN" do
- parse('').should be_a_subject_with(NO_PARTS)
+ expect(parse('')).to be_a_subject_with(NO_PARTS)
end
end
describe "when getting a CN from a subject" do
def cn_from(subject)
Puppet::Util::SSL.cn_from_subject(subject)
end
it "should correctly parse a subject containing only a CN" do
subj = parse('/CN=foo')
- cn_from(subj).should == 'foo'
+ expect(cn_from(subj)).to eq('foo')
end
it "should correctly parse a subject containing other components" do
subj = parse('/CN=Root CA/OU=Server Operations/O=Example Org')
- cn_from(subj).should == 'Root CA'
+ expect(cn_from(subj)).to eq('Root CA')
end
it "should correctly parse a subject containing other components with CN not first" do
subj = parse('/emailAddress=foo@bar.com/CN=foo.bar.com/O=Example Org')
- cn_from(subj).should == 'foo.bar.com'
+ expect(cn_from(subj)).to eq('foo.bar.com')
end
it "should return nil for a subject with no CN" do
subj = parse('/OU=Server Operations/O=Example Org')
- cn_from(subj).should == nil
+ expect(cn_from(subj)).to eq(nil)
end
it "should return nil for a bare string" do
- cn_from("/CN=foo").should == nil
+ expect(cn_from("/CN=foo")).to eq(nil)
end
end
end
diff --git a/spec/unit/util/storage_spec.rb b/spec/unit/util/storage_spec.rb
index fe6b422c9..e9e4c13fe 100755
--- a/spec/unit/util/storage_spec.rb
+++ b/spec/unit/util/storage_spec.rb
@@ -1,210 +1,210 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'yaml'
require 'fileutils'
require 'puppet/util/storage'
describe Puppet::Util::Storage do
include PuppetSpec::Files
before(:each) do
@basepath = File.expand_path("/somepath")
end
describe "when caching a symbol" do
it "should return an empty hash" do
- Puppet::Util::Storage.cache(:yayness).should == {}
- Puppet::Util::Storage.cache(:more_yayness).should == {}
+ expect(Puppet::Util::Storage.cache(:yayness)).to eq({})
+ expect(Puppet::Util::Storage.cache(:more_yayness)).to eq({})
end
it "should add the symbol to its internal state" do
Puppet::Util::Storage.cache(:yayness)
- Puppet::Util::Storage.state.should == {:yayness=>{}}
+ expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
end
it "should not clobber existing state when caching additional objects" do
Puppet::Util::Storage.cache(:yayness)
- Puppet::Util::Storage.state.should == {:yayness=>{}}
+ expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
Puppet::Util::Storage.cache(:bubblyness)
- Puppet::Util::Storage.state.should == {:yayness=>{},:bubblyness=>{}}
+ expect(Puppet::Util::Storage.state).to eq({:yayness=>{},:bubblyness=>{}})
end
end
describe "when caching a Puppet::Type" do
before(:each) do
@file_test = Puppet::Type.type(:file).new(:name => @basepath+"/yayness", :audit => %w{checksum type})
@exec_test = Puppet::Type.type(:exec).new(:name => @basepath+"/bin/ls /yayness")
end
it "should return an empty hash" do
- Puppet::Util::Storage.cache(@file_test).should == {}
- Puppet::Util::Storage.cache(@exec_test).should == {}
+ expect(Puppet::Util::Storage.cache(@file_test)).to eq({})
+ expect(Puppet::Util::Storage.cache(@exec_test)).to eq({})
end
it "should add the resource ref to its internal state" do
- Puppet::Util::Storage.state.should == {}
+ expect(Puppet::Util::Storage.state).to eq({})
Puppet::Util::Storage.cache(@file_test)
- Puppet::Util::Storage.state.should == {"File[#{@basepath}/yayness]"=>{}}
+ expect(Puppet::Util::Storage.state).to eq({"File[#{@basepath}/yayness]"=>{}})
Puppet::Util::Storage.cache(@exec_test)
- Puppet::Util::Storage.state.should == {"File[#{@basepath}/yayness]"=>{}, "Exec[#{@basepath}/bin/ls /yayness]"=>{}}
+ expect(Puppet::Util::Storage.state).to eq({"File[#{@basepath}/yayness]"=>{}, "Exec[#{@basepath}/bin/ls /yayness]"=>{}})
end
end
describe "when caching something other than a resource or symbol" do
it "should cache by converting to a string" do
data = Puppet::Util::Storage.cache(42)
data[:yay] = true
- Puppet::Util::Storage.cache("42")[:yay].should be_true
+ expect(Puppet::Util::Storage.cache("42")[:yay]).to be_truthy
end
end
it "should clear its internal state when clear() is called" do
Puppet::Util::Storage.cache(:yayness)
- Puppet::Util::Storage.state.should == {:yayness=>{}}
+ expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
Puppet::Util::Storage.clear
- Puppet::Util::Storage.state.should == {}
+ expect(Puppet::Util::Storage.state).to eq({})
end
describe "when loading from the state file" do
before do
Puppet.settings.stubs(:use).returns(true)
end
describe "when the state file/directory does not exist" do
before(:each) do
@path = tmpfile('storage_test')
end
it "should not fail to load" do
- Puppet::FileSystem.exist?(@path).should be_false
+ expect(Puppet::FileSystem.exist?(@path)).to be_falsey
Puppet[:statedir] = @path
Puppet::Util::Storage.load
Puppet[:statefile] = @path
Puppet::Util::Storage.load
end
it "should not lose its internal state when load() is called" do
- Puppet::FileSystem.exist?(@path).should be_false
+ expect(Puppet::FileSystem.exist?(@path)).to be_falsey
Puppet::Util::Storage.cache(:yayness)
- Puppet::Util::Storage.state.should == {:yayness=>{}}
+ expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
Puppet[:statefile] = @path
Puppet::Util::Storage.load
- Puppet::Util::Storage.state.should == {:yayness=>{}}
+ expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
end
end
describe "when the state file/directory exists" do
before(:each) do
@state_file = tmpfile('storage_test')
FileUtils.touch(@state_file)
Puppet[:statefile] = @state_file
end
def write_state_file(contents)
File.open(@state_file, 'w') { |f| f.write(contents) }
end
it "should overwrite its internal state if load() is called" do
# Should the state be overwritten even if Puppet[:statefile] is not valid YAML?
Puppet::Util::Storage.cache(:yayness)
- Puppet::Util::Storage.state.should == {:yayness=>{}}
+ expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
Puppet::Util::Storage.load
- Puppet::Util::Storage.state.should == {}
+ expect(Puppet::Util::Storage.state).to eq({})
end
it "should restore its internal state if the state file contains valid YAML" do
test_yaml = {'File["/yayness"]'=>{"name"=>{:a=>:b,:c=>:d}}}
write_state_file(test_yaml.to_yaml)
Puppet::Util::Storage.load
- Puppet::Util::Storage.state.should == test_yaml
+ expect(Puppet::Util::Storage.state).to eq(test_yaml)
end
it "should initialize with a clear internal state if the state file does not contain valid YAML" do
write_state_file('{ invalid')
Puppet::Util::Storage.load
- Puppet::Util::Storage.state.should == {}
+ expect(Puppet::Util::Storage.state).to eq({})
end
it "should initialize with a clear internal state if the state file does not contain a hash of data" do
write_state_file("not_a_hash")
Puppet::Util::Storage.load
- Puppet::Util::Storage.state.should == {}
+ expect(Puppet::Util::Storage.state).to eq({})
end
it "should raise an error if the state file does not contain valid YAML and cannot be renamed" do
write_state_file('{ invalid')
File.expects(:rename).raises(SystemCallError)
expect { Puppet::Util::Storage.load }.to raise_error(Puppet::Error, /Could not rename/)
end
it "should attempt to rename the state file if the file is corrupted" do
write_state_file('{ invalid')
File.expects(:rename).at_least_once
Puppet::Util::Storage.load
end
it "should fail gracefully on load() if the state file is not a regular file" do
FileUtils.rm_f(@state_file)
Dir.mkdir(@state_file)
Puppet::Util::Storage.load
end
end
end
describe "when storing to the state file" do
before(:each) do
@state_file = tmpfile('storage_test')
@saved_statefile = Puppet[:statefile]
Puppet[:statefile] = @state_file
end
it "should create the state file if it does not exist" do
- Puppet::FileSystem.exist?(Puppet[:statefile]).should be_false
+ expect(Puppet::FileSystem.exist?(Puppet[:statefile])).to be_falsey
Puppet::Util::Storage.cache(:yayness)
Puppet::Util::Storage.store
- Puppet::FileSystem.exist?(Puppet[:statefile]).should be_true
+ expect(Puppet::FileSystem.exist?(Puppet[:statefile])).to be_truthy
end
it "should raise an exception if the state file is not a regular file" do
Dir.mkdir(Puppet[:statefile])
Puppet::Util::Storage.cache(:yayness)
expect { Puppet::Util::Storage.store }.to raise_error
Dir.rmdir(Puppet[:statefile])
end
it "should load() the same information that it store()s" do
Puppet::Util::Storage.cache(:yayness)
- Puppet::Util::Storage.state.should == {:yayness=>{}}
+ expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
Puppet::Util::Storage.store
Puppet::Util::Storage.clear
- Puppet::Util::Storage.state.should == {}
+ expect(Puppet::Util::Storage.state).to eq({})
Puppet::Util::Storage.load
- Puppet::Util::Storage.state.should == {:yayness=>{}}
+ expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
end
end
end
diff --git a/spec/unit/util/suidmanager_spec.rb b/spec/unit/util/suidmanager_spec.rb
index cfe10f2a1..274662854 100755
--- a/spec/unit/util/suidmanager_spec.rb
+++ b/spec/unit/util/suidmanager_spec.rb
@@ -1,286 +1,286 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Util::SUIDManager do
let :user do
Puppet::Type.type(:user).new(:name => 'name', :uid => 42, :gid => 42)
end
let :xids do
Hash.new {|h,k| 0}
end
before :each do
Puppet::Util::SUIDManager.stubs(:convert_xid).returns(42)
pwent = stub('pwent', :name => 'fred', :uid => 42, :gid => 42)
Etc.stubs(:getpwuid).with(42).returns(pwent)
[:euid, :egid, :uid, :gid, :groups].each do |id|
Process.stubs("#{id}=").with {|value| xids[id] = value }
end
end
describe "#initgroups" do
it "should use the primary group of the user as the 'basegid'" do
Process.expects(:initgroups).with('fred', 42)
described_class.initgroups(42)
end
end
describe "#uid" do
it "should allow setting euid/egid" do
Puppet::Util::SUIDManager.egid = user[:gid]
Puppet::Util::SUIDManager.euid = user[:uid]
- xids[:egid].should == user[:gid]
- xids[:euid].should == user[:uid]
+ expect(xids[:egid]).to eq(user[:gid])
+ expect(xids[:euid]).to eq(user[:uid])
end
end
describe "#asuser" do
it "should not get or set euid/egid when not root" do
Puppet.features.stubs(:microsoft_windows?).returns(false)
Process.stubs(:uid).returns(1)
Process.stubs(:egid).returns(51)
Process.stubs(:euid).returns(50)
Puppet::Util::SUIDManager.asuser(user[:uid], user[:gid]) {}
- xids.should be_empty
+ expect(xids).to be_empty
end
context "when root and not windows" do
before :each do
Process.stubs(:uid).returns(0)
Puppet.features.stubs(:microsoft_windows?).returns(false)
end
it "should set euid/egid" do
Process.stubs(:egid).returns(51).then.returns(51).then.returns(user[:gid])
Process.stubs(:euid).returns(50).then.returns(50).then.returns(user[:uid])
Puppet::Util::SUIDManager.stubs(:convert_xid).with(:gid, 51).returns(51)
Puppet::Util::SUIDManager.stubs(:convert_xid).with(:uid, 50).returns(50)
Puppet::Util::SUIDManager.stubs(:initgroups).returns([])
yielded = false
Puppet::Util::SUIDManager.asuser(user[:uid], user[:gid]) do
- xids[:egid].should == user[:gid]
- xids[:euid].should == user[:uid]
+ expect(xids[:egid]).to eq(user[:gid])
+ expect(xids[:euid]).to eq(user[:uid])
yielded = true
end
- xids[:egid].should == 51
- xids[:euid].should == 50
+ expect(xids[:egid]).to eq(51)
+ expect(xids[:euid]).to eq(50)
# It's possible asuser could simply not yield, so the assertions in the
# block wouldn't fail. So verify those actually got checked.
- yielded.should be_true
+ expect(yielded).to be_truthy
end
it "should just yield if user and group are nil" do
yielded = false
Puppet::Util::SUIDManager.asuser(nil, nil) { yielded = true }
- yielded.should be_true
- xids.should == {}
+ expect(yielded).to be_truthy
+ expect(xids).to eq({})
end
it "should just change group if only group is given" do
yielded = false
Puppet::Util::SUIDManager.asuser(nil, 42) { yielded = true }
- yielded.should be_true
- xids.should == { :egid => 42 }
+ expect(yielded).to be_truthy
+ expect(xids).to eq({ :egid => 42 })
end
it "should change gid to the primary group of uid by default" do
Process.stubs(:initgroups)
yielded = false
Puppet::Util::SUIDManager.asuser(42) { yielded = true }
- yielded.should be_true
- xids.should == { :euid => 42, :egid => 42 }
+ expect(yielded).to be_truthy
+ expect(xids).to eq({ :euid => 42, :egid => 42 })
end
it "should change both uid and gid if given" do
# I don't like the sequence, but it is the only way to assert on the
# internal behaviour in a reliable fashion, given we need multiple
# sequenced calls to the same methods. --daniel 2012-02-05
horror = sequence('of user and group changes')
Puppet::Util::SUIDManager.expects(:change_group).with(43, false).in_sequence(horror)
Puppet::Util::SUIDManager.expects(:change_user).with(42, false).in_sequence(horror)
Puppet::Util::SUIDManager.expects(:change_group).
with(Puppet::Util::SUIDManager.egid, false).in_sequence(horror)
Puppet::Util::SUIDManager.expects(:change_user).
with(Puppet::Util::SUIDManager.euid, false).in_sequence(horror)
yielded = false
Puppet::Util::SUIDManager.asuser(42, 43) { yielded = true }
- yielded.should be_true
+ expect(yielded).to be_truthy
end
end
it "should not get or set euid/egid on Windows" do
Puppet.features.stubs(:microsoft_windows?).returns true
Puppet::Util::SUIDManager.asuser(user[:uid], user[:gid]) {}
- xids.should be_empty
+ expect(xids).to be_empty
end
end
describe "#change_group" do
describe "when changing permanently" do
it "should change_privilege" do
Process::GID.expects(:change_privilege).with do |gid|
Process.gid = gid
Process.egid = gid
end
Puppet::Util::SUIDManager.change_group(42, true)
- xids[:egid].should == 42
- xids[:gid].should == 42
+ expect(xids[:egid]).to eq(42)
+ expect(xids[:gid]).to eq(42)
end
it "should not change_privilege when gid already matches" do
Process::GID.expects(:change_privilege).with do |gid|
Process.gid = 42
Process.egid = 42
end
Puppet::Util::SUIDManager.change_group(42, true)
- xids[:egid].should == 42
- xids[:gid].should == 42
+ expect(xids[:egid]).to eq(42)
+ expect(xids[:gid]).to eq(42)
end
end
describe "when changing temporarily" do
it "should change only egid" do
Puppet::Util::SUIDManager.change_group(42, false)
- xids[:egid].should == 42
- xids[:gid].should == 0
+ expect(xids[:egid]).to eq(42)
+ expect(xids[:gid]).to eq(0)
end
end
end
describe "#change_user" do
describe "when changing permanently" do
it "should change_privilege" do
Process::UID.expects(:change_privilege).with do |uid|
Process.uid = uid
Process.euid = uid
end
Puppet::Util::SUIDManager.expects(:initgroups).with(42)
Puppet::Util::SUIDManager.change_user(42, true)
- xids[:euid].should == 42
- xids[:uid].should == 42
+ expect(xids[:euid]).to eq(42)
+ expect(xids[:uid]).to eq(42)
end
it "should not change_privilege when uid already matches" do
Process::UID.expects(:change_privilege).with do |uid|
Process.uid = 42
Process.euid = 42
end
Puppet::Util::SUIDManager.expects(:initgroups).with(42)
Puppet::Util::SUIDManager.change_user(42, true)
- xids[:euid].should == 42
- xids[:uid].should == 42
+ expect(xids[:euid]).to eq(42)
+ expect(xids[:uid]).to eq(42)
end
end
describe "when changing temporarily" do
it "should change only euid and groups" do
Puppet::Util::SUIDManager.stubs(:initgroups).returns([])
Puppet::Util::SUIDManager.change_user(42, false)
- xids[:euid].should == 42
- xids[:uid].should == 0
+ expect(xids[:euid]).to eq(42)
+ expect(xids[:uid]).to eq(0)
end
it "should set euid before groups if changing to root" do
Process.stubs(:euid).returns 50
when_not_root = sequence 'when_not_root'
Process.expects(:euid=).in_sequence(when_not_root)
Puppet::Util::SUIDManager.expects(:initgroups).in_sequence(when_not_root)
Puppet::Util::SUIDManager.change_user(0, false)
end
it "should set groups before euid if changing from root" do
Process.stubs(:euid).returns 0
when_root = sequence 'when_root'
Puppet::Util::SUIDManager.expects(:initgroups).in_sequence(when_root)
Process.expects(:euid=).in_sequence(when_root)
Puppet::Util::SUIDManager.change_user(50, false)
end
end
end
describe "#root?" do
describe "on POSIX systems" do
before :each do
Puppet.features.stubs(:posix?).returns(true)
Puppet.features.stubs(:microsoft_windows?).returns(false)
end
it "should be root if uid is 0" do
Process.stubs(:uid).returns(0)
- Puppet::Util::SUIDManager.should be_root
+ expect(Puppet::Util::SUIDManager).to be_root
end
it "should not be root if uid is not 0" do
Process.stubs(:uid).returns(1)
- Puppet::Util::SUIDManager.should_not be_root
+ expect(Puppet::Util::SUIDManager).not_to be_root
end
end
describe "on Microsoft Windows", :if => Puppet.features.microsoft_windows? do
it "should be root if user is privileged" do
Puppet::Util::Windows::User.stubs(:admin?).returns true
- Puppet::Util::SUIDManager.should be_root
+ expect(Puppet::Util::SUIDManager).to be_root
end
it "should not be root if user is not privileged" do
Puppet::Util::Windows::User.stubs(:admin?).returns false
- Puppet::Util::SUIDManager.should_not be_root
+ expect(Puppet::Util::SUIDManager).not_to be_root
end
end
end
end
describe 'Puppet::Util::SUIDManager#groups=' do
subject do
Puppet::Util::SUIDManager
end
it "(#3419) should rescue Errno::EINVAL on OS X" do
Process.expects(:groups=).raises(Errno::EINVAL, 'blew up')
subject.expects(:osx_maj_ver).returns('10.7').twice
subject.groups = ['list', 'of', 'groups']
end
it "(#3419) should fail if an Errno::EINVAL is raised NOT on OS X" do
Process.expects(:groups=).raises(Errno::EINVAL, 'blew up')
subject.expects(:osx_maj_ver).returns(false)
expect { subject.groups = ['list', 'of', 'groups'] }.to raise_error(Errno::EINVAL)
end
end
diff --git a/spec/unit/util/symbolic_file_mode_spec.rb b/spec/unit/util/symbolic_file_mode_spec.rb
index 5346c3a08..d2b3a0300 100755
--- a/spec/unit/util/symbolic_file_mode_spec.rb
+++ b/spec/unit/util/symbolic_file_mode_spec.rb
@@ -1,182 +1,182 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/symbolic_file_mode'
describe Puppet::Util::SymbolicFileMode do
include Puppet::Util::SymbolicFileMode
describe "#valid_symbolic_mode?" do
%w{
0 0000 1 1 7 11 77 111 777 11
0 00000 01 01 07 011 077 0111 0777 011
= - + u= g= o= a= u+ g+ o+ a+ u- g- o- a- ugo= ugoa= ugugug=
a=,u=,g= a=,g+
=rwx +rwx -rwx
644 go-w =rw,+X +X 755 u=rwx,go=rx u=rwx,go=u-w go= g=u-w
755 0755
}.each do |input|
it "should treat #{input.inspect} as valid" do
- valid_symbolic_mode?(input).should be_true
+ expect(valid_symbolic_mode?(input)).to be_truthy
end
end
[0000, 0111, 0640, 0755, 0777].each do |input|
it "should treat the int #{input.to_s(8)} as value" do
- valid_symbolic_mode?(input).should be_true
+ expect(valid_symbolic_mode?(input)).to be_truthy
end
end
%w{
-1 -8 8 9 18 19 91 81 000000 11111 77777
0-1 0-8 08 09 018 019 091 081 0000000 011111 077777
u g o a ug uo ua ag
}.each do |input|
it "should treat #{input.inspect} as invalid" do
- valid_symbolic_mode?(input).should be_false
+ expect(valid_symbolic_mode?(input)).to be_falsey
end
end
end
describe "#normalize_symbolic_mode" do
it "should turn an int into a string" do
- normalize_symbolic_mode(12).should be_an_instance_of String
+ expect(normalize_symbolic_mode(12)).to be_an_instance_of String
end
it "should not add a leading zero to an int" do
- normalize_symbolic_mode(12).should_not =~ /^0/
+ expect(normalize_symbolic_mode(12)).not_to match(/^0/)
end
it "should not add a leading zero to a string with a number" do
- normalize_symbolic_mode("12").should_not =~ /^0/
+ expect(normalize_symbolic_mode("12")).not_to match(/^0/)
end
it "should string a leading zero from a number" do
- normalize_symbolic_mode("012").should == '12'
+ expect(normalize_symbolic_mode("012")).to eq('12')
end
it "should pass through any other string" do
- normalize_symbolic_mode("u=rwx").should == 'u=rwx'
+ expect(normalize_symbolic_mode("u=rwx")).to eq('u=rwx')
end
end
describe "#symbolic_mode_to_int" do
{
"0654" => 00654,
"u+r" => 00400,
"g+r" => 00040,
"a+r" => 00444,
"a+x" => 00111,
"o+t" => 01000,
"o+t" => 01000,
["o-t", 07777] => 06777,
["a-x", 07777] => 07666,
["a-rwx", 07777] => 07000,
["ug-rwx", 07777] => 07007,
"a+x,ug-rwx" => 00001,
# My experimentation on debian suggests that +g ignores the sgid flag
["a+g", 02060] => 02666,
# My experimentation on debian suggests that -g ignores the sgid flag
["a-g", 02666] => 02000,
"g+x,a+g" => 00111,
# +X without exec set in the original should not set anything
"u+x,g+X" => 00100,
"g+X" => 00000,
# +X only refers to the original, *unmodified* file mode!
["u+x,a+X", 0600] => 00700,
# Examples from the MacOS chmod(1) manpage
"0644" => 00644,
["go-w", 07777] => 07755,
["=rw,+X", 07777] => 07777,
["=rw,+X", 07766] => 07777,
["=rw,+X", 07676] => 07777,
["=rw,+X", 07667] => 07777,
["=rw,+X", 07666] => 07666,
"0755" => 00755,
"u=rwx,go=rx" => 00755,
"u=rwx,go=u-w" => 00755,
["go=", 07777] => 07700,
["g=u-w", 07777] => 07757,
["g=u-w", 00700] => 00750,
["g=u-w", 00600] => 00640,
["g=u-w", 00500] => 00550,
["g=u-w", 00400] => 00440,
["g=u-w", 00300] => 00310,
["g=u-w", 00200] => 00200,
["g=u-w", 00100] => 00110,
["g=u-w", 00000] => 00000,
# Cruel, but legal, use of the action set.
["g=u+r-w", 0300] => 00350,
# Empty assignments.
["u=", 00000] => 00000,
["u=", 00600] => 00000,
["ug=", 00000] => 00000,
["ug=", 00600] => 00000,
["ug=", 00660] => 00000,
["ug=", 00666] => 00006,
["=", 00000] => 00000,
["=", 00666] => 00000,
["+", 00000] => 00000,
["+", 00124] => 00124,
["-", 00000] => 00000,
["-", 00124] => 00124,
}.each do |input, result|
from = input.is_a?(Array) ? "#{input[0]}, 0#{input[1].to_s(8)}" : input
it "should map #{from.inspect} to #{result.inspect}" do
- symbolic_mode_to_int(*input).should == result
+ expect(symbolic_mode_to_int(*input)).to eq(result)
end
end
# Now, test some failure modes.
it "should fail if no mode is given" do
expect { symbolic_mode_to_int('') }.
to raise_error Puppet::Error, /empty mode string/
end
%w{u g o ug uo go ugo a uu u/x u!x u=r,,g=r}.each do |input|
it "should fail if no (valid) action is given: #{input.inspect}" do
expect { symbolic_mode_to_int(input) }.
to raise_error Puppet::Error, /Missing action/
end
end
%w{u+q u-rwF u+rw,g+rw,o+RW}.each do |input|
it "should fail with unknown op #{input.inspect}" do
expect { symbolic_mode_to_int(input) }.
to raise_error Puppet::Error, /Unknown operation/
end
end
it "should refuse to subtract the conditional execute op" do
expect { symbolic_mode_to_int("o-rwX") }.
to raise_error Puppet::Error, /only works with/
end
it "should refuse to set to the conditional execute op" do
expect { symbolic_mode_to_int("o=rwX") }.
to raise_error Puppet::Error, /only works with/
end
%w{8 08 9 09 118 119}.each do |input|
it "should fail for decimal modes: #{input.inspect}" do
expect { symbolic_mode_to_int(input) }.
to raise_error Puppet::Error, /octal/
end
end
it "should set the execute bit on a directory, without exec in original" do
- symbolic_mode_to_int("u+X", 0444, true).to_s(8).should == "544"
- symbolic_mode_to_int("g+X", 0444, true).to_s(8).should == "454"
- symbolic_mode_to_int("o+X", 0444, true).to_s(8).should == "445"
- symbolic_mode_to_int("+X", 0444, true).to_s(8).should == "555"
+ expect(symbolic_mode_to_int("u+X", 0444, true).to_s(8)).to eq("544")
+ expect(symbolic_mode_to_int("g+X", 0444, true).to_s(8)).to eq("454")
+ expect(symbolic_mode_to_int("o+X", 0444, true).to_s(8)).to eq("445")
+ expect(symbolic_mode_to_int("+X", 0444, true).to_s(8)).to eq("555")
end
it "should set the execute bit on a file with exec in the original" do
- symbolic_mode_to_int("+X", 0544).to_s(8).should == "555"
+ expect(symbolic_mode_to_int("+X", 0544).to_s(8)).to eq("555")
end
it "should not set the execute bit on a file without exec on the original even if set by earlier DSL" do
- symbolic_mode_to_int("u+x,go+X", 0444).to_s(8).should == "544"
+ expect(symbolic_mode_to_int("u+x,go+X", 0444).to_s(8)).to eq("544")
end
end
end
diff --git a/spec/unit/util/tag_set_spec.rb b/spec/unit/util/tag_set_spec.rb
index 5d6d36dfe..550277779 100644
--- a/spec/unit/util/tag_set_spec.rb
+++ b/spec/unit/util/tag_set_spec.rb
@@ -1,46 +1,46 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/tag_set'
RSpec::Matchers.define :be_one_of do |*expected|
match do |actual|
expected.include? actual
end
- failure_message_for_should do |actual|
+ failure_message do |actual|
"expected #{actual.inspect} to be one of #{expected.map(&:inspect).join(' or ')}"
end
end
describe Puppet::Util::TagSet do
let(:set) { Puppet::Util::TagSet.new }
it 'serializes to yaml as an array' do
array = ['a', :b, 1, 5.4]
set.merge(array)
- Set.new(YAML.load(set.to_yaml)).should == Set.new(array)
+ expect(Set.new(YAML.load(set.to_yaml))).to eq(Set.new(array))
end
it 'deserializes from a yaml array' do
array = ['a', :b, 1, 5.4]
- Puppet::Util::TagSet.from_yaml(array.to_yaml).should == Puppet::Util::TagSet.new(array)
+ expect(Puppet::Util::TagSet.from_yaml(array.to_yaml)).to eq(Puppet::Util::TagSet.new(array))
end
it 'round trips through pson' do
array = ['a', 'b', 1, 5.4]
set.merge(array)
tes = Puppet::Util::TagSet.from_data_hash(PSON.parse(set.to_pson))
- tes.should == set
+ expect(tes).to eq(set)
end
it 'can join its elements with a string separator' do
array = ['a', 'b']
set.merge(array)
- set.join(', ').should be_one_of('a, b', 'b, a')
+ expect(set.join(', ')).to be_one_of('a, b', 'b, a')
end
end
diff --git a/spec/unit/util/terminal_spec.rb b/spec/unit/util/terminal_spec.rb
index bbbb4dad6..b58fca085 100644
--- a/spec/unit/util/terminal_spec.rb
+++ b/spec/unit/util/terminal_spec.rb
@@ -1,42 +1,42 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/terminal'
describe Puppet::Util::Terminal do
describe '.width' do
before { Puppet.features.stubs(:posix?).returns(true) }
it 'should invoke `stty` and return the width' do
height, width = 100, 200
subject.expects(:`).with('stty size 2>/dev/null').returns("#{height} #{width}\n")
- subject.width.should == width
+ expect(subject.width).to eq(width)
end
it 'should use `tput` if `stty` is unavailable' do
width = 200
subject.expects(:`).with('stty size 2>/dev/null').returns("\n")
subject.expects(:`).with('tput cols 2>/dev/null').returns("#{width}\n")
- subject.width.should == width
+ expect(subject.width).to eq(width)
end
it 'should default to 80 columns if `tput` and `stty` are unavailable' do
width = 80
subject.expects(:`).with('stty size 2>/dev/null').returns("\n")
subject.expects(:`).with('tput cols 2>/dev/null').returns("\n")
- subject.width.should == width
+ expect(subject.width).to eq(width)
end
it 'should default to 80 columns if `tput` or `stty` raise exceptions' do
width = 80
subject.expects(:`).with('stty size 2>/dev/null').raises()
subject.stubs(:`).with('tput cols 2>/dev/null').returns("#{width + 1000}\n")
- subject.width.should == width
+ expect(subject.width).to eq(width)
end
it 'should default to 80 columns if not in a POSIX environment' do
width = 80
Puppet.features.stubs(:posix?).returns(false)
- subject.width.should == width
+ expect(subject.width).to eq(width)
end
end
end
diff --git a/spec/unit/util/user_attr_spec.rb b/spec/unit/util/user_attr_spec.rb
index 73c971903..1f15de4fd 100755
--- a/spec/unit/util/user_attr_spec.rb
+++ b/spec/unit/util/user_attr_spec.rb
@@ -1,46 +1,46 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/user_attr'
describe UserAttr do
before do
user_attr = ["foo::::type=role", "bar::::type=normal;profile=foobar"]
File.stubs(:readlines).returns(user_attr)
end
describe "when getting attributes by name" do
it "should return nil if there is no entry for that name" do
- UserAttr.get_attributes_by_name('baz').should == nil
+ expect(UserAttr.get_attributes_by_name('baz')).to eq(nil)
end
it "should return a hash if there is an entry in /etc/user_attr" do
- UserAttr.get_attributes_by_name('foo').class.should == Hash
+ expect(UserAttr.get_attributes_by_name('foo').class).to eq(Hash)
end
it "should return a hash with the name value from /etc/user_attr" do
- UserAttr.get_attributes_by_name('foo')[:name].should == 'foo'
+ expect(UserAttr.get_attributes_by_name('foo')[:name]).to eq('foo')
end
#this test is contrived
#there are a bunch of possible parameters that could be in the hash
#the role/normal is just a the convention of the file
describe "when the name is a role" do
it "should contain :type = role" do
- UserAttr.get_attributes_by_name('foo')[:type].should == 'role'
+ expect(UserAttr.get_attributes_by_name('foo')[:type]).to eq('role')
end
end
describe "when the name is not a role" do
it "should contain :type = normal" do
- UserAttr.get_attributes_by_name('bar')[:type].should == 'normal'
+ expect(UserAttr.get_attributes_by_name('bar')[:type]).to eq('normal')
end
end
describe "when the name has more attributes" do
it "should contain all the attributes" do
- UserAttr.get_attributes_by_name('bar')[:profile].should == 'foobar'
+ expect(UserAttr.get_attributes_by_name('bar')[:profile]).to eq('foobar')
end
end
end
end
diff --git a/spec/unit/util/warnings_spec.rb b/spec/unit/util/warnings_spec.rb
index 492c3540b..b2d7443a6 100755
--- a/spec/unit/util/warnings_spec.rb
+++ b/spec/unit/util/warnings_spec.rb
@@ -1,46 +1,46 @@
#! /usr/bin/env ruby
require 'spec_helper'
describe Puppet::Util::Warnings do
before(:all) do
@msg1 = "booness"
@msg2 = "more booness"
end
before(:each) do
Puppet.debug = true
end
after (:each) do
Puppet.debug = false
end
{:notice => "notice_once", :warning => "warnonce", :debug => "debug_once"}.each do |log, method|
describe "when registring '#{log}' messages" do
it "should always return nil" do
- Puppet::Util::Warnings.send(method, @msg1).should be(nil)
+ expect(Puppet::Util::Warnings.send(method, @msg1)).to be(nil)
end
it "should issue a warning" do
Puppet.expects(log).with(@msg1)
Puppet::Util::Warnings.send(method, @msg1)
end
it "should issue a warning exactly once per unique message" do
Puppet.expects(log).with(@msg1).once
Puppet::Util::Warnings.send(method, @msg1)
Puppet::Util::Warnings.send(method, @msg1)
end
it "should issue multiple warnings for multiple unique messages" do
Puppet.expects(log).times(2)
Puppet::Util::Warnings.send(method, @msg1)
Puppet::Util::Warnings.send(method, @msg2)
end
end
end
after(:each) do
Puppet::Util::Warnings.clear_warnings
end
end
diff --git a/spec/unit/util/windows/access_control_entry_spec.rb b/spec/unit/util/windows/access_control_entry_spec.rb
index 8d3f51c8a..983b374b6 100644
--- a/spec/unit/util/windows/access_control_entry_spec.rb
+++ b/spec/unit/util/windows/access_control_entry_spec.rb
@@ -1,67 +1,67 @@
#!/usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/windows'
describe "Puppet::Util::Windows::AccessControlEntry", :if => Puppet.features.microsoft_windows? do
let(:klass) { Puppet::Util::Windows::AccessControlEntry }
let(:sid) { 'S-1-5-18' }
let(:mask) { Puppet::Util::Windows::File::FILE_ALL_ACCESS }
it "creates an access allowed ace" do
ace = klass.new(sid, mask)
- ace.type.should == klass::ACCESS_ALLOWED_ACE_TYPE
+ expect(ace.type).to eq(klass::ACCESS_ALLOWED_ACE_TYPE)
end
it "creates an access denied ace" do
ace = klass.new(sid, mask, 0, klass::ACCESS_DENIED_ACE_TYPE)
- ace.type.should == klass::ACCESS_DENIED_ACE_TYPE
+ expect(ace.type).to eq(klass::ACCESS_DENIED_ACE_TYPE)
end
it "creates a non-inherited ace by default" do
ace = klass.new(sid, mask)
- ace.should_not be_inherited
+ expect(ace).not_to be_inherited
end
it "creates an inherited ace" do
ace = klass.new(sid, mask, klass::INHERITED_ACE)
- ace.should be_inherited
+ expect(ace).to be_inherited
end
it "creates a non-inherit-only ace by default" do
ace = klass.new(sid, mask)
- ace.should_not be_inherit_only
+ expect(ace).not_to be_inherit_only
end
it "creates an inherit-only ace" do
ace = klass.new(sid, mask, klass::INHERIT_ONLY_ACE)
- ace.should be_inherit_only
+ expect(ace).to be_inherit_only
end
context "when comparing aces" do
let(:ace1) { klass.new(sid, mask, klass::INHERIT_ONLY_ACE, klass::ACCESS_DENIED_ACE_TYPE) }
let(:ace2) { klass.new(sid, mask, klass::INHERIT_ONLY_ACE, klass::ACCESS_DENIED_ACE_TYPE) }
it "returns true if different objects have the same set of values" do
- ace1.should == ace2
+ expect(ace1).to eq(ace2)
end
it "returns false if different objects have different sets of values" do
ace = klass.new(sid, mask)
- ace.should_not == ace1
+ expect(ace).not_to eq(ace1)
end
it "returns true when testing if two objects are eql?" do
ace1.eql?(ace2)
end
it "returns false when comparing object identity" do
- ace1.should_not be_equal(ace2)
+ expect(ace1).not_to be_equal(ace2)
end
end
end
diff --git a/spec/unit/util/windows/access_control_list_spec.rb b/spec/unit/util/windows/access_control_list_spec.rb
index 66c917b29..0c2987fe3 100644
--- a/spec/unit/util/windows/access_control_list_spec.rb
+++ b/spec/unit/util/windows/access_control_list_spec.rb
@@ -1,133 +1,133 @@
#!/usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/windows'
describe "Puppet::Util::Windows::AccessControlList", :if => Puppet.features.microsoft_windows? do
let(:klass) { Puppet::Util::Windows::AccessControlList }
let(:system_sid) { 'S-1-5-18' }
let(:admins_sid) { 'S-1-5-544' }
let(:none_sid) { 'S-1-0-0' }
let(:system_ace) do
Puppet::Util::Windows::AccessControlEntry.new(system_sid, 0x1)
end
let(:admins_ace) do
Puppet::Util::Windows::AccessControlEntry.new(admins_sid, 0x2)
end
let(:none_ace) do
Puppet::Util::Windows::AccessControlEntry.new(none_sid, 0x3)
end
it "constructs an empty list" do
acl = klass.new
- acl.to_a.should be_empty
+ expect(acl.to_a).to be_empty
end
it "supports copy constructor" do
aces = klass.new([system_ace]).to_a
- aces.to_a.should == [system_ace]
+ expect(aces.to_a).to eq([system_ace])
end
context "appending" do
it "appends an allow ace" do
acl = klass.new
acl.allow(system_sid, 0x1, 0x2)
- acl.first.type.should == klass::ACCESS_ALLOWED_ACE_TYPE
+ expect(acl.first.type).to eq(klass::ACCESS_ALLOWED_ACE_TYPE)
end
it "appends a deny ace" do
acl = klass.new
acl.deny(system_sid, 0x1, 0x2)
- acl.first.type.should == klass::ACCESS_DENIED_ACE_TYPE
+ expect(acl.first.type).to eq(klass::ACCESS_DENIED_ACE_TYPE)
end
it "always appends, never overwrites an ACE" do
acl = klass.new([system_ace])
acl.allow(admins_sid, admins_ace.mask, admins_ace.flags)
aces = acl.to_a
- aces.size.should == 2
- aces[0].should == system_ace
- aces[1].sid.should == admins_sid
- aces[1].mask.should == admins_ace.mask
- aces[1].flags.should == admins_ace.flags
+ expect(aces.size).to eq(2)
+ expect(aces[0]).to eq(system_ace)
+ expect(aces[1].sid).to eq(admins_sid)
+ expect(aces[1].mask).to eq(admins_ace.mask)
+ expect(aces[1].flags).to eq(admins_ace.flags)
end
end
context "reassigning" do
it "preserves the mask from the old sid when reassigning to the new sid" do
dacl = klass.new([system_ace])
dacl.reassign!(system_ace.sid, admins_ace.sid)
# we removed system, so ignore prepended ace
ace = dacl.to_a[1]
- ace.sid.should == admins_sid
- ace.mask.should == system_ace.mask
+ expect(ace.sid).to eq(admins_sid)
+ expect(ace.mask).to eq(system_ace.mask)
end
it "matches multiple sids" do
dacl = klass.new([system_ace, system_ace])
dacl.reassign!(system_ace.sid, admins_ace.sid)
# we removed system, so ignore prepended ace
aces = dacl.to_a
- aces.size.should == 3
+ expect(aces.size).to eq(3)
aces.to_a[1,2].each do |ace|
- ace.sid.should == admins_ace.sid
+ expect(ace.sid).to eq(admins_ace.sid)
end
end
it "preserves aces for sids that don't match, in their original order" do
dacl = klass.new([system_ace, admins_ace])
dacl.reassign!(system_sid, none_sid)
aces = dacl.to_a
aces[1].sid == admins_ace.sid
end
it "preserves inherited aces, even if the sids match" do
flags = Puppet::Util::Windows::AccessControlEntry::INHERITED_ACE
inherited_ace = Puppet::Util::Windows::AccessControlEntry.new(system_sid, 0x1, flags)
dacl = klass.new([inherited_ace, system_ace])
dacl.reassign!(system_sid, none_sid)
aces = dacl.to_a
- aces[0].sid.should == system_sid
+ expect(aces[0].sid).to eq(system_sid)
end
it "prepends an explicit ace for the new sid with the same mask and basic inheritance as the inherited ace" do
expected_flags =
Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE |
Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE |
Puppet::Util::Windows::AccessControlEntry::INHERIT_ONLY_ACE
flags = Puppet::Util::Windows::AccessControlEntry::INHERITED_ACE | expected_flags
inherited_ace = Puppet::Util::Windows::AccessControlEntry.new(system_sid, 0x1, flags)
dacl = klass.new([inherited_ace])
dacl.reassign!(system_sid, none_sid)
aces = dacl.to_a
- aces.size.should == 2
- aces[0].sid.should == none_sid
- aces[0].should_not be_inherited
- aces[0].flags.should == expected_flags
+ expect(aces.size).to eq(2)
+ expect(aces[0].sid).to eq(none_sid)
+ expect(aces[0]).not_to be_inherited
+ expect(aces[0].flags).to eq(expected_flags)
- aces[1].sid.should == system_sid
- aces[1].should be_inherited
+ expect(aces[1].sid).to eq(system_sid)
+ expect(aces[1]).to be_inherited
end
it "makes a copy of the ace prior to modifying it" do
arr = [system_ace]
acl = klass.new(arr)
acl.reassign!(system_sid, none_sid)
- arr[0].sid.should == system_sid
+ expect(arr[0].sid).to eq(system_sid)
end
end
end
diff --git a/spec/unit/util/windows/adsi_spec.rb b/spec/unit/util/windows/adsi_spec.rb
index 593c73256..64a4cc707 100755
--- a/spec/unit/util/windows/adsi_spec.rb
+++ b/spec/unit/util/windows/adsi_spec.rb
@@ -1,395 +1,395 @@
#!/usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/windows'
describe Puppet::Util::Windows::ADSI, :if => Puppet.features.microsoft_windows? do
let(:connection) { stub 'connection' }
before(:each) do
Puppet::Util::Windows::ADSI.instance_variable_set(:@computer_name, 'testcomputername')
Puppet::Util::Windows::ADSI.stubs(:connect).returns connection
end
after(:each) do
Puppet::Util::Windows::ADSI.instance_variable_set(:@computer_name, nil)
end
it "should generate the correct URI for a resource" do
- Puppet::Util::Windows::ADSI.uri('test', 'user').should == "WinNT://./test,user"
+ expect(Puppet::Util::Windows::ADSI.uri('test', 'user')).to eq("WinNT://./test,user")
end
it "should be able to get the name of the computer" do
- Puppet::Util::Windows::ADSI.computer_name.should == 'testcomputername'
+ expect(Puppet::Util::Windows::ADSI.computer_name).to eq('testcomputername')
end
it "should be able to provide the correct WinNT base URI for the computer" do
- Puppet::Util::Windows::ADSI.computer_uri.should == "WinNT://."
+ expect(Puppet::Util::Windows::ADSI.computer_uri).to eq("WinNT://.")
end
it "should generate a fully qualified WinNT URI" do
- Puppet::Util::Windows::ADSI.computer_uri('testcomputername').should == "WinNT://testcomputername"
+ expect(Puppet::Util::Windows::ADSI.computer_uri('testcomputername')).to eq("WinNT://testcomputername")
end
describe ".computer_name" do
it "should return a non-empty ComputerName string" do
Puppet::Util::Windows::ADSI.instance_variable_set(:@computer_name, nil)
- Puppet::Util::Windows::ADSI.computer_name.should_not be_empty
+ expect(Puppet::Util::Windows::ADSI.computer_name).not_to be_empty
end
end
describe ".sid_uri" do
it "should raise an error when the input is not a SID object" do
[Object.new, {}, 1, :symbol, '', nil].each do |input|
expect {
Puppet::Util::Windows::ADSI.sid_uri(input)
}.to raise_error(Puppet::Error, /Must use a valid SID object/)
end
end
it "should return a SID uri for a well-known SID (SYSTEM)" do
sid = Win32::Security::SID.new('SYSTEM')
- Puppet::Util::Windows::ADSI.sid_uri(sid).should == 'WinNT://S-1-5-18'
+ expect(Puppet::Util::Windows::ADSI.sid_uri(sid)).to eq('WinNT://S-1-5-18')
end
end
describe Puppet::Util::Windows::ADSI::User do
let(:username) { 'testuser' }
let(:domain) { 'DOMAIN' }
let(:domain_username) { "#{domain}\\#{username}"}
it "should generate the correct URI" do
Puppet::Util::Windows::ADSI.stubs(:sid_uri_safe).returns(nil)
- Puppet::Util::Windows::ADSI::User.uri(username).should == "WinNT://./#{username},user"
+ expect(Puppet::Util::Windows::ADSI::User.uri(username)).to eq("WinNT://./#{username},user")
end
it "should generate the correct URI for a user with a domain" do
Puppet::Util::Windows::ADSI.stubs(:sid_uri_safe).returns(nil)
- Puppet::Util::Windows::ADSI::User.uri(username, domain).should == "WinNT://#{domain}/#{username},user"
+ expect(Puppet::Util::Windows::ADSI::User.uri(username, domain)).to eq("WinNT://#{domain}/#{username},user")
end
it "should be able to parse a username without a domain" do
- Puppet::Util::Windows::ADSI::User.parse_name(username).should == [username, '.']
+ expect(Puppet::Util::Windows::ADSI::User.parse_name(username)).to eq([username, '.'])
end
it "should be able to parse a username with a domain" do
- Puppet::Util::Windows::ADSI::User.parse_name(domain_username).should == [username, domain]
+ expect(Puppet::Util::Windows::ADSI::User.parse_name(domain_username)).to eq([username, domain])
end
it "should raise an error with a username that contains a /" do
expect {
Puppet::Util::Windows::ADSI::User.parse_name("#{domain}/#{username}")
}.to raise_error(Puppet::Error, /Value must be in DOMAIN\\user style syntax/)
end
it "should be able to create a user" do
adsi_user = stub('adsi')
connection.expects(:Create).with('user', username).returns(adsi_user)
Puppet::Util::Windows::ADSI::Group.expects(:exists?).with(username).returns(false)
user = Puppet::Util::Windows::ADSI::User.create(username)
- user.should be_a(Puppet::Util::Windows::ADSI::User)
- user.native_user.should == adsi_user
+ expect(user).to be_a(Puppet::Util::Windows::ADSI::User)
+ expect(user.native_user).to eq(adsi_user)
end
it "should be able to check the existence of a user" do
Puppet::Util::Windows::ADSI.stubs(:sid_uri_safe).returns(nil)
Puppet::Util::Windows::ADSI.expects(:connect).with("WinNT://./#{username},user").returns connection
- Puppet::Util::Windows::ADSI::User.exists?(username).should be_true
+ expect(Puppet::Util::Windows::ADSI::User.exists?(username)).to be_truthy
end
it "should be able to check the existence of a domain user" do
Puppet::Util::Windows::ADSI.stubs(:sid_uri_safe).returns(nil)
Puppet::Util::Windows::ADSI.expects(:connect).with("WinNT://#{domain}/#{username},user").returns connection
- Puppet::Util::Windows::ADSI::User.exists?(domain_username).should be_true
+ expect(Puppet::Util::Windows::ADSI::User.exists?(domain_username)).to be_truthy
end
it "should be able to confirm the existence of a user with a well-known SID" do
system_user = Win32::Security::SID::LocalSystem
# ensure that the underlying OS is queried here
Puppet::Util::Windows::ADSI.unstub(:connect)
- Puppet::Util::Windows::ADSI::User.exists?(system_user).should be_true
+ expect(Puppet::Util::Windows::ADSI::User.exists?(system_user)).to be_truthy
end
it "should return nil with an unknown SID" do
bogus_sid = 'S-1-2-3-4'
# ensure that the underlying OS is queried here
Puppet::Util::Windows::ADSI.unstub(:connect)
- Puppet::Util::Windows::ADSI::User.exists?(bogus_sid).should be_false
+ expect(Puppet::Util::Windows::ADSI::User.exists?(bogus_sid)).to be_falsey
end
it "should be able to delete a user" do
connection.expects(:Delete).with('user', username)
Puppet::Util::Windows::ADSI::User.delete(username)
end
it "should return an enumeration of IADsUser wrapped objects" do
Puppet::Util::Windows::ADSI.stubs(:sid_uri_safe).returns(nil)
name = 'Administrator'
wmi_users = [stub('WMI', :name => name)]
Puppet::Util::Windows::ADSI.expects(:execquery).with('select name from win32_useraccount where localaccount = "TRUE"').returns(wmi_users)
native_user = stub('IADsUser')
homedir = "C:\\Users\\#{name}"
native_user.expects(:Get).with('HomeDirectory').returns(homedir)
Puppet::Util::Windows::ADSI.expects(:connect).with("WinNT://./#{name},user").returns(native_user)
users = Puppet::Util::Windows::ADSI::User.to_a
- users.length.should == 1
- users[0].name.should == name
- users[0]['HomeDirectory'].should == homedir
+ expect(users.length).to eq(1)
+ expect(users[0].name).to eq(name)
+ expect(users[0]['HomeDirectory']).to eq(homedir)
end
describe "an instance" do
let(:adsi_user) { stub('user', :objectSID => []) }
let(:sid) { stub(:account => username, :domain => 'testcomputername') }
let(:user) { Puppet::Util::Windows::ADSI::User.new(username, adsi_user) }
it "should provide its groups as a list of names" do
names = ["group1", "group2"]
- groups = names.map { |name| mock('group', :Name => name) }
+ groups = names.map { |name| stub('group', :Name => name) }
adsi_user.expects(:Groups).returns(groups)
- user.groups.should =~ names
+ expect(user.groups).to match(names)
end
it "should be able to test whether a given password is correct" do
Puppet::Util::Windows::ADSI::User.expects(:logon).with(username, 'pwdwrong').returns(false)
Puppet::Util::Windows::ADSI::User.expects(:logon).with(username, 'pwdright').returns(true)
- user.password_is?('pwdwrong').should be_false
- user.password_is?('pwdright').should be_true
+ expect(user.password_is?('pwdwrong')).to be_falsey
+ expect(user.password_is?('pwdright')).to be_truthy
end
it "should be able to set a password" do
adsi_user.expects(:SetPassword).with('pwd')
adsi_user.expects(:SetInfo).at_least_once
flagname = "UserFlags"
fADS_UF_DONT_EXPIRE_PASSWD = 0x10000
adsi_user.expects(:Get).with(flagname).returns(0)
adsi_user.expects(:Put).with(flagname, fADS_UF_DONT_EXPIRE_PASSWD)
user.password = 'pwd'
end
it "should generate the correct URI" do
Puppet::Util::Windows::SID.stubs(:octet_string_to_sid_object).returns(sid)
- user.uri.should == "WinNT://testcomputername/#{username},user"
+ expect(user.uri).to eq("WinNT://testcomputername/#{username},user")
end
describe "when given a set of groups to which to add the user" do
let(:groups_to_set) { 'group1,group2' }
before(:each) do
Puppet::Util::Windows::SID.stubs(:octet_string_to_sid_object).returns(sid)
user.expects(:groups).returns ['group2', 'group3']
end
describe "if membership is specified as inclusive" do
it "should add the user to those groups, and remove it from groups not in the list" do
group1 = stub 'group1'
group1.expects(:Add).with("WinNT://testcomputername/#{username},user")
group3 = stub 'group1'
group3.expects(:Remove).with("WinNT://testcomputername/#{username},user")
Puppet::Util::Windows::ADSI.expects(:sid_uri).with(sid).returns("WinNT://testcomputername/#{username},user").twice
Puppet::Util::Windows::ADSI.expects(:connect).with('WinNT://./group1,group').returns group1
Puppet::Util::Windows::ADSI.expects(:connect).with('WinNT://./group3,group').returns group3
user.set_groups(groups_to_set, false)
end
end
describe "if membership is specified as minimum" do
it "should add the user to the specified groups without affecting its other memberships" do
group1 = stub 'group1'
group1.expects(:Add).with("WinNT://testcomputername/#{username},user")
Puppet::Util::Windows::ADSI.expects(:sid_uri).with(sid).returns("WinNT://testcomputername/#{username},user")
Puppet::Util::Windows::ADSI.expects(:connect).with('WinNT://./group1,group').returns group1
user.set_groups(groups_to_set, true)
end
end
end
end
end
describe Puppet::Util::Windows::ADSI::Group do
let(:groupname) { 'testgroup' }
describe "an instance" do
let(:adsi_group) { stub 'group' }
let(:group) { Puppet::Util::Windows::ADSI::Group.new(groupname, adsi_group) }
let(:someone_sid){ stub(:account => 'someone', :domain => 'testcomputername')}
describe "should be able to use SID objects" do
let(:system) { Puppet::Util::Windows::SID.name_to_sid_object('SYSTEM') }
let(:invalid) { Puppet::Util::Windows::SID.name_to_sid_object('foobar') }
it "to add a member" do
adsi_group.expects(:Add).with("WinNT://S-1-5-18")
group.add_member_sids(system)
end
it "and raise when passed a non-SID object to add" do
expect{ group.add_member_sids(invalid)}.to raise_error(Puppet::Error, /Must use a valid SID object/)
end
it "to remove a member" do
adsi_group.expects(:Remove).with("WinNT://S-1-5-18")
group.remove_member_sids(system)
end
it "and raise when passed a non-SID object to remove" do
expect{ group.remove_member_sids(invalid)}.to raise_error(Puppet::Error, /Must use a valid SID object/)
end
end
it "should provide its groups as a list of names" do
names = ['user1', 'user2']
- users = names.map { |name| mock('user', :Name => name) }
+ users = names.map { |name| stub('user', :Name => name) }
adsi_group.expects(:Members).returns(users)
- group.members.should =~ names
+ expect(group.members).to match(names)
end
it "should be able to add a list of users to a group" do
names = ['DOMAIN\user1', 'user2']
sids = [
stub(:account => 'user1', :domain => 'DOMAIN'),
stub(:account => 'user2', :domain => 'testcomputername'),
stub(:account => 'user3', :domain => 'DOMAIN2'),
]
# use stubbed objectSid on member to return stubbed SID
Puppet::Util::Windows::SID.expects(:octet_string_to_sid_object).with([0]).returns(sids[0])
Puppet::Util::Windows::SID.expects(:octet_string_to_sid_object).with([1]).returns(sids[1])
Puppet::Util::Windows::SID.expects(:name_to_sid_object).with('user2').returns(sids[1])
Puppet::Util::Windows::SID.expects(:name_to_sid_object).with('DOMAIN2\user3').returns(sids[2])
Puppet::Util::Windows::ADSI.expects(:sid_uri).with(sids[0]).returns("WinNT://DOMAIN/user1,user")
Puppet::Util::Windows::ADSI.expects(:sid_uri).with(sids[2]).returns("WinNT://DOMAIN2/user3,user")
members = names.each_with_index.map{|n,i| stub(:Name => n, :objectSID => [i])}
adsi_group.expects(:Members).returns members
adsi_group.expects(:Remove).with('WinNT://DOMAIN/user1,user')
adsi_group.expects(:Add).with('WinNT://DOMAIN2/user3,user')
group.set_members(['user2', 'DOMAIN2\user3'])
end
it "should raise an error when a username does not resolve to a SID" do
expect {
adsi_group.expects(:Members).returns []
group.set_members(['foobar'])
}.to raise_error(Puppet::Error, /Could not resolve username: foobar/)
end
it "should generate the correct URI" do
Puppet::Util::Windows::ADSI.stubs(:sid_uri_safe).returns(nil)
- group.uri.should == "WinNT://./#{groupname},group"
+ expect(group.uri).to eq("WinNT://./#{groupname},group")
end
end
it "should generate the correct URI" do
Puppet::Util::Windows::ADSI.stubs(:sid_uri_safe).returns(nil)
- Puppet::Util::Windows::ADSI::Group.uri("people").should == "WinNT://./people,group"
+ expect(Puppet::Util::Windows::ADSI::Group.uri("people")).to eq("WinNT://./people,group")
end
it "should be able to create a group" do
adsi_group = stub("adsi")
connection.expects(:Create).with('group', groupname).returns(adsi_group)
Puppet::Util::Windows::ADSI::User.expects(:exists?).with(groupname).returns(false)
group = Puppet::Util::Windows::ADSI::Group.create(groupname)
- group.should be_a(Puppet::Util::Windows::ADSI::Group)
- group.native_group.should == adsi_group
+ expect(group).to be_a(Puppet::Util::Windows::ADSI::Group)
+ expect(group.native_group).to eq(adsi_group)
end
it "should be able to confirm the existence of a group" do
Puppet::Util::Windows::ADSI.stubs(:sid_uri_safe).returns(nil)
Puppet::Util::Windows::ADSI.expects(:connect).with("WinNT://./#{groupname},group").returns connection
- Puppet::Util::Windows::ADSI::Group.exists?(groupname).should be_true
+ expect(Puppet::Util::Windows::ADSI::Group.exists?(groupname)).to be_truthy
end
it "should be able to confirm the existence of a group with a well-known SID" do
service_group = Win32::Security::SID::Service
# ensure that the underlying OS is queried here
Puppet::Util::Windows::ADSI.unstub(:connect)
- Puppet::Util::Windows::ADSI::Group.exists?(service_group).should be_true
+ expect(Puppet::Util::Windows::ADSI::Group.exists?(service_group)).to be_truthy
end
it "should return nil with an unknown SID" do
bogus_sid = 'S-1-2-3-4'
# ensure that the underlying OS is queried here
Puppet::Util::Windows::ADSI.unstub(:connect)
- Puppet::Util::Windows::ADSI::Group.exists?(bogus_sid).should be_false
+ expect(Puppet::Util::Windows::ADSI::Group.exists?(bogus_sid)).to be_falsey
end
it "should be able to delete a group" do
connection.expects(:Delete).with('group', groupname)
Puppet::Util::Windows::ADSI::Group.delete(groupname)
end
it "should return an enumeration of IADsGroup wrapped objects" do
Puppet::Util::Windows::ADSI.stubs(:sid_uri_safe).returns(nil)
name = 'Administrators'
wmi_groups = [stub('WMI', :name => name)]
Puppet::Util::Windows::ADSI.expects(:execquery).with('select name from win32_group where localaccount = "TRUE"').returns(wmi_groups)
native_group = stub('IADsGroup')
native_group.expects(:Members).returns([stub(:Name => 'Administrator')])
Puppet::Util::Windows::ADSI.expects(:connect).with("WinNT://./#{name},group").returns(native_group)
groups = Puppet::Util::Windows::ADSI::Group.to_a
- groups.length.should == 1
- groups[0].name.should == name
- groups[0].members.should == ['Administrator']
+ expect(groups.length).to eq(1)
+ expect(groups[0].name).to eq(name)
+ expect(groups[0].members).to eq(['Administrator'])
end
end
describe Puppet::Util::Windows::ADSI::UserProfile do
it "should be able to delete a user profile" do
connection.expects(:Delete).with("Win32_UserProfile.SID='S-A-B-C'")
Puppet::Util::Windows::ADSI::UserProfile.delete('S-A-B-C')
end
it "should warn on 2003" do
connection.expects(:Delete).raises(RuntimeError,
"Delete (WIN32OLERuntimeError)
OLE error code:80041010 in SWbemServicesEx
Invalid class
HRESULT error code:0x80020009
Exception occurred.")
Puppet.expects(:warning).with("Cannot delete user profile for 'S-A-B-C' prior to Vista SP1")
Puppet::Util::Windows::ADSI::UserProfile.delete('S-A-B-C')
end
end
end
diff --git a/spec/unit/util/windows/api_types_spec.rb b/spec/unit/util/windows/api_types_spec.rb
index a1e1c76c9..c1111851c 100644
--- a/spec/unit/util/windows/api_types_spec.rb
+++ b/spec/unit/util/windows/api_types_spec.rb
@@ -1,28 +1,28 @@
# encoding: UTF-8
#!/usr/bin/env ruby
require 'spec_helper'
describe "FFI::MemoryPointer", :if => Puppet.features.microsoft_windows? do
context "read_wide_string" do
let (:string) { "foo_bar" }
it "should properly roundtrip a given string" do
read_string = nil
FFI::MemoryPointer.from_string_to_wide_string(string) do |ptr|
read_string = ptr.read_wide_string(string.length)
end
- read_string.should == string
+ expect(read_string).to eq(string)
end
it "should return a given string in the default encoding" do
read_string = nil
FFI::MemoryPointer.from_string_to_wide_string(string) do |ptr|
read_string = ptr.read_wide_string(string.length)
end
- read_string.encoding.should == Encoding.default_external
+ expect(read_string.encoding).to eq(Encoding.default_external)
end
end
end
diff --git a/spec/unit/util/windows/registry_spec.rb b/spec/unit/util/windows/registry_spec.rb
index ed52539a5..76fd5da68 100755
--- a/spec/unit/util/windows/registry_spec.rb
+++ b/spec/unit/util/windows/registry_spec.rb
@@ -1,141 +1,141 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/windows'
describe Puppet::Util::Windows::Registry, :if => Puppet::Util::Platform.windows? do
subject do
class TestRegistry
include Puppet::Util::Windows::Registry
end
TestRegistry.new
end
let(:name) { 'HKEY_LOCAL_MACHINE' }
let(:path) { 'Software\Microsoft' }
context "#root" do
it "should lookup the root hkey" do
- subject.root(name).should be_instance_of(Win32::Registry::PredefinedKey)
+ expect(subject.root(name)).to be_instance_of(Win32::Registry::PredefinedKey)
end
it "should raise for unknown root keys" do
expect { subject.root('HKEY_BOGUS') }.to raise_error(Puppet::Error, /Invalid registry key/)
end
end
context "#open" do
- let(:hkey) { mock 'hklm' }
+ let(:hkey) { stub 'hklm' }
let(:subkey) { stub 'subkey' }
before :each do
subject.stubs(:root).returns(hkey)
end
it "should yield the opened the subkey" do
hkey.expects(:open).with do |p, _|
- p.should == path
+ expect(p).to eq(path)
end.yields(subkey)
yielded = nil
subject.open(name, path) {|reg| yielded = reg}
- yielded.should == subkey
+ expect(yielded).to eq(subkey)
end
if Puppet::Util::Platform.windows?
[described_class::KEY64, described_class::KEY32].each do |access|
it "should open the key for read access 0x#{access.to_s(16)}" do
mode = described_class::KEY_READ | access
hkey.expects(:open).with(path, mode)
subject.open(name, path, mode) {|reg| }
end
end
end
it "should default to KEY64" do
hkey.expects(:open).with(path, described_class::KEY_READ | described_class::KEY64)
subject.open(hkey, path) {|hkey| }
end
it "should raise for a path that doesn't exist" do
hkey.expects(:keyname).returns('HKEY_LOCAL_MACHINE')
hkey.expects(:open).raises(Win32::Registry::Error.new(2)) # file not found
expect do
subject.open(hkey, 'doesnotexist') {|hkey| }
end.to raise_error(Puppet::Error, /Failed to open registry key 'HKEY_LOCAL_MACHINE\\doesnotexist'/)
end
end
context "#values" do
let(:key) { stub('uninstall') }
it "should return each value's name and data" do
key.expects(:each_value).multiple_yields(
['string', 1, 'foo'], ['dword', 4, 0]
)
- subject.values(key).should == { 'string' => 'foo', 'dword' => 0 }
+ expect(subject.values(key)).to eq({ 'string' => 'foo', 'dword' => 0 })
end
it "should return an empty hash if there are no values" do
key.expects(:each_value)
- subject.values(key).should == {}
+ expect(subject.values(key)).to eq({})
end
context "when reading non-ASCII values" do
# registered trademark symbol
let(:data) do
str = [0xAE].pack("C")
str.force_encoding('US-ASCII')
str
end
def expects_registry_value(array)
key.expects(:each_value).multiple_yields(array)
subject.values(key).first[1]
end
# The win32console gem applies this regex to strip out ANSI escape
# sequences. If the registered trademark had encoding US-ASCII,
# the regex would fail with 'invalid byte sequence in US-ASCII'
def strip_ansi_escapes(value)
value.sub(/([^\e]*)?\e([\[\(])([0-9\;\=]*)([a-zA-Z@])(.*)/, '\5')
end
it "encodes REG_SZ according to the current code page" do
reg_value = ['string', Win32::Registry::REG_SZ, data]
value = expects_registry_value(reg_value)
strip_ansi_escapes(value)
end
it "encodes REG_EXPAND_SZ based on the current code page" do
reg_value = ['expand', Win32::Registry::REG_EXPAND_SZ, "%SYSTEMROOT%\\#{data}"]
value = expects_registry_value(reg_value)
strip_ansi_escapes(value)
end
it "encodes REG_MULTI_SZ based on the current code page" do
reg_value = ['multi', Win32::Registry::REG_MULTI_SZ, ["one#{data}", "two#{data}"]]
value = expects_registry_value(reg_value)
value.each { |str| strip_ansi_escapes(str) }
end
it "passes REG_DWORD through" do
reg_value = ['dword', Win32::Registry::REG_DWORD, '1']
value = expects_registry_value(reg_value)
- Integer(value).should == 1
+ expect(Integer(value)).to eq(1)
end
end
end
end
diff --git a/spec/unit/util/windows/root_certs_spec.rb b/spec/unit/util/windows/root_certs_spec.rb
index 6b1d9891e..f2ea16f25 100755
--- a/spec/unit/util/windows/root_certs_spec.rb
+++ b/spec/unit/util/windows/root_certs_spec.rb
@@ -1,17 +1,17 @@
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/windows'
describe "Puppet::Util::Windows::RootCerts", :if => Puppet::Util::Platform.windows? do
let(:x509_store) { Puppet::Util::Windows::RootCerts.instance.to_a }
it "should return at least one X509 certificate" do
- expect(x509_store.to_a).to have_at_least(1).items
+ expect(x509_store.to_a.size).to be >= 1
end
it "should return an X509 certificate with a subject" do
x509 = x509_store.first
expect(x509.subject.to_s).to match(/CN=.*/)
end
end
diff --git a/spec/unit/util/windows/security_descriptor_spec.rb b/spec/unit/util/windows/security_descriptor_spec.rb
index 61db2f598..270d3cef9 100644
--- a/spec/unit/util/windows/security_descriptor_spec.rb
+++ b/spec/unit/util/windows/security_descriptor_spec.rb
@@ -1,117 +1,117 @@
#!/usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/windows'
describe "Puppet::Util::Windows::SecurityDescriptor", :if => Puppet.features.microsoft_windows? do
let(:system_sid) { Win32::Security::SID::LocalSystem }
let(:admins_sid) { Win32::Security::SID::BuiltinAdministrators }
let(:group_sid) { Win32::Security::SID::Nobody }
let(:new_sid) { 'S-1-5-32-500-1-2-3' }
def empty_dacl
Puppet::Util::Windows::AccessControlList.new
end
def system_ace_dacl
dacl = Puppet::Util::Windows::AccessControlList.new
dacl.allow(system_sid, 0x1)
dacl
end
context "owner" do
it "changes the owner" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, system_ace_dacl)
sd.owner = new_sid
- sd.owner.should == new_sid
+ expect(sd.owner).to eq(new_sid)
end
it "performs a noop if the new owner is the same as the old one" do
dacl = system_ace_dacl
sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, dacl)
sd.owner = sd.owner
- sd.dacl.object_id.should == dacl.object_id
+ expect(sd.dacl.object_id).to eq(dacl.object_id)
end
it "prepends SYSTEM when security descriptor owner is no longer SYSTEM" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, system_ace_dacl)
sd.owner = new_sid
aces = sd.dacl.to_a
- aces.size.should == 2
- aces[0].sid.should == system_sid
- aces[1].sid.should == new_sid
+ expect(aces.size).to eq(2)
+ expect(aces[0].sid).to eq(system_sid)
+ expect(aces[1].sid).to eq(new_sid)
end
it "does not prepend SYSTEM when DACL already contains inherited SYSTEM ace" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(admins_sid, system_sid, empty_dacl)
sd.dacl.allow(admins_sid, 0x1)
sd.dacl.allow(system_sid, 0x1, Puppet::Util::Windows::AccessControlEntry::INHERITED_ACE)
sd.owner = new_sid
aces = sd.dacl.to_a
- aces.size.should == 2
- aces[0].sid.should == new_sid
+ expect(aces.size).to eq(2)
+ expect(aces[0].sid).to eq(new_sid)
end
it "does not prepend SYSTEM when security descriptor owner wasn't SYSTEM" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(group_sid, group_sid, empty_dacl)
sd.dacl.allow(group_sid, 0x1)
sd.owner = new_sid
aces = sd.dacl.to_a
- aces.size.should == 1
- aces[0].sid.should == new_sid
+ expect(aces.size).to eq(1)
+ expect(aces[0].sid).to eq(new_sid)
end
end
context "group" do
it "changes the group" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, system_ace_dacl)
sd.group = new_sid
- sd.group.should == new_sid
+ expect(sd.group).to eq(new_sid)
end
it "performs a noop if the new group is the same as the old one" do
dacl = system_ace_dacl
sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, dacl)
sd.group = sd.group
- sd.dacl.object_id.should == dacl.object_id
+ expect(sd.dacl.object_id).to eq(dacl.object_id)
end
it "prepends SYSTEM when security descriptor group is no longer SYSTEM" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(new_sid, system_sid, system_ace_dacl)
sd.group = new_sid
aces = sd.dacl.to_a
- aces.size.should == 2
- aces[0].sid.should == system_sid
- aces[1].sid.should == new_sid
+ expect(aces.size).to eq(2)
+ expect(aces[0].sid).to eq(system_sid)
+ expect(aces[1].sid).to eq(new_sid)
end
it "does not prepend SYSTEM when DACL already contains inherited SYSTEM ace" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(admins_sid, admins_sid, empty_dacl)
sd.dacl.allow(admins_sid, 0x1)
sd.dacl.allow(system_sid, 0x1, Puppet::Util::Windows::AccessControlEntry::INHERITED_ACE)
sd.group = new_sid
aces = sd.dacl.to_a
- aces.size.should == 2
- aces[0].sid.should == new_sid
+ expect(aces.size).to eq(2)
+ expect(aces[0].sid).to eq(new_sid)
end
it "does not prepend SYSTEM when security descriptor group wasn't SYSTEM" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(group_sid, group_sid, empty_dacl)
sd.dacl.allow(group_sid, 0x1)
sd.group = new_sid
aces = sd.dacl.to_a
- aces.size.should == 1
- aces[0].sid.should == new_sid
+ expect(aces.size).to eq(1)
+ expect(aces[0].sid).to eq(new_sid)
end
end
end
diff --git a/spec/unit/util/windows/sid_spec.rb b/spec/unit/util/windows/sid_spec.rb
index 1e9f44070..5c47d9abf 100755
--- a/spec/unit/util/windows/sid_spec.rb
+++ b/spec/unit/util/windows/sid_spec.rb
@@ -1,176 +1,176 @@
#!/usr/bin/env ruby
require 'spec_helper'
describe "Puppet::Util::Windows::SID", :if => Puppet.features.microsoft_windows? do
if Puppet.features.microsoft_windows?
require 'puppet/util/windows'
end
let(:subject) { Puppet::Util::Windows::SID }
let(:sid) { Win32::Security::SID::LocalSystem }
let(:invalid_sid) { 'bogus' }
let(:unknown_sid) { 'S-0-0-0' }
let(:unknown_name) { 'chewbacca' }
context "#octet_string_to_sid_object" do
it "should properly convert an array of bytes for the local Administrator SID" do
host = '.'
username = 'Administrator'
admin = WIN32OLE.connect("WinNT://#{host}/#{username},user")
converted = subject.octet_string_to_sid_object(admin.objectSID)
- converted.should == Win32::Security::SID.new(username, host)
- converted.should be_an_instance_of Win32::Security::SID
+ expect(converted).to eq(Win32::Security::SID.new(username, host))
+ expect(converted).to be_an_instance_of Win32::Security::SID
end
it "should properly convert an array of bytes for a well-known SID" do
bytes = [1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0]
converted = subject.octet_string_to_sid_object(bytes)
- converted.should == Win32::Security::SID.new('SYSTEM')
- converted.should be_an_instance_of Win32::Security::SID
+ expect(converted).to eq(Win32::Security::SID.new('SYSTEM'))
+ expect(converted).to be_an_instance_of Win32::Security::SID
end
it "should raise an error for non-array input" do
expect {
subject.octet_string_to_sid_object(invalid_sid)
}.to raise_error(Puppet::Error, /Octet string must be an array of bytes/)
end
it "should raise an error for an empty byte array" do
expect {
subject.octet_string_to_sid_object([])
}.to raise_error(Puppet::Error, /Octet string must be an array of bytes/)
end
it "should raise an error for a malformed byte array" do
expect {
invalid_octet = [1]
subject.octet_string_to_sid_object(invalid_octet)
}.to raise_error(SystemCallError, /No mapping between account names and security IDs was done./)
end
end
context "#name_to_sid" do
it "should return nil if the account does not exist" do
- subject.name_to_sid(unknown_name).should be_nil
+ expect(subject.name_to_sid(unknown_name)).to be_nil
end
it "should accept unqualified account name" do
- subject.name_to_sid('SYSTEM').should == sid
+ expect(subject.name_to_sid('SYSTEM')).to eq(sid)
end
it "should return a SID for a passed user or group name" do
subject.expects(:name_to_sid_object).with('testers').returns 'S-1-5-32-547'
- subject.name_to_sid('testers').should == 'S-1-5-32-547'
+ expect(subject.name_to_sid('testers')).to eq('S-1-5-32-547')
end
it "should return a SID for a passed fully-qualified user or group name" do
subject.expects(:name_to_sid_object).with('MACHINE\testers').returns 'S-1-5-32-547'
- subject.name_to_sid('MACHINE\testers').should == 'S-1-5-32-547'
+ expect(subject.name_to_sid('MACHINE\testers')).to eq('S-1-5-32-547')
end
it "should be case-insensitive" do
- subject.name_to_sid('SYSTEM').should == subject.name_to_sid('system')
+ expect(subject.name_to_sid('SYSTEM')).to eq(subject.name_to_sid('system'))
end
it "should be leading and trailing whitespace-insensitive" do
- subject.name_to_sid('SYSTEM').should == subject.name_to_sid(' SYSTEM ')
+ expect(subject.name_to_sid('SYSTEM')).to eq(subject.name_to_sid(' SYSTEM '))
end
it "should accept domain qualified account names" do
- subject.name_to_sid('NT AUTHORITY\SYSTEM').should == sid
+ expect(subject.name_to_sid('NT AUTHORITY\SYSTEM')).to eq(sid)
end
it "should be the identity function for any sid" do
- subject.name_to_sid(sid).should == sid
+ expect(subject.name_to_sid(sid)).to eq(sid)
end
end
context "#name_to_sid_object" do
it "should return nil if the account does not exist" do
- subject.name_to_sid_object(unknown_name).should be_nil
+ expect(subject.name_to_sid_object(unknown_name)).to be_nil
end
it "should return a Win32::Security::SID instance for any valid sid" do
- subject.name_to_sid_object(sid).should be_an_instance_of(Win32::Security::SID)
+ expect(subject.name_to_sid_object(sid)).to be_an_instance_of(Win32::Security::SID)
end
it "should accept unqualified account name" do
- subject.name_to_sid_object('SYSTEM').to_s.should == sid
+ expect(subject.name_to_sid_object('SYSTEM').to_s).to eq(sid)
end
it "should be case-insensitive" do
- subject.name_to_sid_object('SYSTEM').should == subject.name_to_sid_object('system')
+ expect(subject.name_to_sid_object('SYSTEM')).to eq(subject.name_to_sid_object('system'))
end
it "should be leading and trailing whitespace-insensitive" do
- subject.name_to_sid_object('SYSTEM').should == subject.name_to_sid_object(' SYSTEM ')
+ expect(subject.name_to_sid_object('SYSTEM')).to eq(subject.name_to_sid_object(' SYSTEM '))
end
it "should accept domain qualified account names" do
- subject.name_to_sid_object('NT AUTHORITY\SYSTEM').to_s.should == sid
+ expect(subject.name_to_sid_object('NT AUTHORITY\SYSTEM').to_s).to eq(sid)
end
end
context "#sid_to_name" do
it "should return nil if given a sid for an account that doesn't exist" do
- subject.sid_to_name(unknown_sid).should be_nil
+ expect(subject.sid_to_name(unknown_sid)).to be_nil
end
it "should accept a sid" do
- subject.sid_to_name(sid).should == "NT AUTHORITY\\SYSTEM"
+ expect(subject.sid_to_name(sid)).to eq("NT AUTHORITY\\SYSTEM")
end
end
context "#sid_ptr_to_string" do
it "should raise if given an invalid sid" do
expect {
subject.sid_ptr_to_string(nil)
}.to raise_error(Puppet::Error, /Invalid SID/)
end
it "should yield a valid sid pointer" do
string = nil
subject.string_to_sid_ptr(sid) do |ptr|
string = subject.sid_ptr_to_string(ptr)
end
- string.should == sid
+ expect(string).to eq(sid)
end
end
context "#string_to_sid_ptr" do
it "should yield sid_ptr" do
ptr = nil
subject.string_to_sid_ptr(sid) do |p|
ptr = p
end
- ptr.should_not be_nil
+ expect(ptr).not_to be_nil
end
it "should raise on an invalid sid" do
expect {
subject.string_to_sid_ptr(invalid_sid)
}.to raise_error(Puppet::Error, /Failed to convert string SID/)
end
end
context "#valid_sid?" do
it "should return true for a valid SID" do
- subject.valid_sid?(sid).should be_true
+ expect(subject.valid_sid?(sid)).to be_truthy
end
it "should return false for an invalid SID" do
- subject.valid_sid?(invalid_sid).should be_false
+ expect(subject.valid_sid?(invalid_sid)).to be_falsey
end
it "should raise if the conversion fails" do
subject.expects(:string_to_sid_ptr).with(sid).
raises(Puppet::Util::Windows::Error.new("Failed to convert string SID: #{sid}", Puppet::Util::Windows::Error::ERROR_ACCESS_DENIED))
expect {
subject.string_to_sid_ptr(sid) {|ptr| }
}.to raise_error(Puppet::Util::Windows::Error, /Failed to convert string SID: #{sid}/)
end
end
end
diff --git a/spec/unit/util/windows/string_spec.rb b/spec/unit/util/windows/string_spec.rb
index 5c6473e70..6a21e4e0c 100644
--- a/spec/unit/util/windows/string_spec.rb
+++ b/spec/unit/util/windows/string_spec.rb
@@ -1,58 +1,58 @@
# encoding: UTF-8
#!/usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/windows'
describe "Puppet::Util::Windows::String", :if => Puppet.features.microsoft_windows? do
UTF16_NULL = [0, 0]
def wide_string(str)
Puppet::Util::Windows::String.wide_string(str)
end
def converts_to_wide_string(string_value)
expected = string_value.encode(Encoding::UTF_16LE)
expected_bytes = expected.bytes.to_a + UTF16_NULL
- wide_string(string_value).bytes.to_a.should == expected_bytes
+ expect(wide_string(string_value).bytes.to_a).to eq(expected_bytes)
end
context "wide_string" do
it "should return encoding of UTF-16LE" do
- wide_string("bob").encoding.should == Encoding::UTF_16LE
+ expect(wide_string("bob").encoding).to eq(Encoding::UTF_16LE)
end
it "should return valid encoding" do
- wide_string("bob").valid_encoding?.should be_true
+ expect(wide_string("bob").valid_encoding?).to be_truthy
end
it "should convert an ASCII string" do
converts_to_wide_string("bob".encode(Encoding::US_ASCII))
end
it "should convert a UTF-8 string" do
converts_to_wide_string("bob".encode(Encoding::UTF_8))
end
it "should convert a UTF-16LE string" do
converts_to_wide_string("bob\u00E8".encode(Encoding::UTF_16LE))
end
it "should convert a UTF-16BE string" do
converts_to_wide_string("bob\u00E8".encode(Encoding::UTF_16BE))
end
it "should convert an UTF-32LE string" do
converts_to_wide_string("bob\u00E8".encode(Encoding::UTF_32LE))
end
it "should convert an UTF-32BE string" do
converts_to_wide_string("bob\u00E8".encode(Encoding::UTF_32BE))
end
it "should return a nil when given a nil" do
- wide_string(nil).should == nil
+ expect(wide_string(nil)).to eq(nil)
end
end
end
diff --git a/spec/unit/util/yaml_spec.rb b/spec/unit/util/yaml_spec.rb
index a535d79c7..6472dfd44 100644
--- a/spec/unit/util/yaml_spec.rb
+++ b/spec/unit/util/yaml_spec.rb
@@ -1,55 +1,55 @@
require 'spec_helper'
require 'puppet/util/yaml'
describe Puppet::Util::Yaml do
include PuppetSpec::Files
let(:filename) { tmpfile("yaml") }
it "reads a YAML file from disk" do
write_file(filename, YAML.dump({ "my" => "data" }))
expect(Puppet::Util::Yaml.load_file(filename)).to eq({ "my" => "data" })
end
it "writes data formatted as YAML to disk" do
Puppet::Util::Yaml.dump({ "my" => "data" }, filename)
expect(Puppet::Util::Yaml.load_file(filename)).to eq({ "my" => "data" })
end
it "raises an error when the file is invalid YAML" do
write_file(filename, "{ invalid")
expect { Puppet::Util::Yaml.load_file(filename) }.to raise_error(Puppet::Util::Yaml::YamlLoadError)
end
it "raises an error when the file does not exist" do
expect { Puppet::Util::Yaml.load_file("no") }.to raise_error(Puppet::Util::Yaml::YamlLoadError, /No such file or directory/)
end
it "raises an error when the filename is illegal" do
expect { Puppet::Util::Yaml.load_file("not\0allowed") }.to raise_error(Puppet::Util::Yaml::YamlLoadError, /null byte/)
end
context "when the file is empty" do
it "returns false" do
Puppet::FileSystem.touch(filename)
- expect(Puppet::Util::Yaml.load_file(filename)).to be_false
+ expect(Puppet::Util::Yaml.load_file(filename)).to be_falsey
end
it "allows return value to be overridden" do
Puppet::FileSystem.touch(filename)
expect(Puppet::Util::Yaml.load_file(filename, {})).to eq({})
end
end
def write_file(name, contents)
File.open(name, "w") do |fh|
fh.write(contents)
end
end
end
diff --git a/spec/unit/util_spec.rb b/spec/unit/util_spec.rb
index d59e78a52..8b9eeae4b 100755
--- a/spec/unit/util_spec.rb
+++ b/spec/unit/util_spec.rb
@@ -1,545 +1,545 @@
#!/usr/bin/env ruby
require 'spec_helper'
describe Puppet::Util do
include PuppetSpec::Files
if Puppet.features.microsoft_windows?
def set_mode(mode, file)
Puppet::Util::Windows::Security.set_mode(mode, file)
end
def get_mode(file)
Puppet::Util::Windows::Security.get_mode(file) & 07777
end
else
def set_mode(mode, file)
File.chmod(mode, file)
end
def get_mode(file)
Puppet::FileSystem.lstat(file).mode & 07777
end
end
describe "#withenv" do
before :each do
@original_path = ENV["PATH"]
@new_env = {:PATH => "/some/bogus/path"}
end
it "should change environment variables within the block then reset environment variables to their original values" do
Puppet::Util.withenv @new_env do
- ENV["PATH"].should == "/some/bogus/path"
+ expect(ENV["PATH"]).to eq("/some/bogus/path")
end
- ENV["PATH"].should == @original_path
+ expect(ENV["PATH"]).to eq(@original_path)
end
it "should reset environment variables to their original values even if the block fails" do
begin
Puppet::Util.withenv @new_env do
- ENV["PATH"].should == "/some/bogus/path"
+ expect(ENV["PATH"]).to eq("/some/bogus/path")
raise "This is a failure"
end
rescue
end
- ENV["PATH"].should == @original_path
+ expect(ENV["PATH"]).to eq(@original_path)
end
it "should reset environment variables even when they are set twice" do
# Setting Path & Environment parameters in Exec type can cause weirdness
@new_env["PATH"] = "/someother/bogus/path"
Puppet::Util.withenv @new_env do
# When assigning duplicate keys, can't guarantee order of evaluation
- ENV["PATH"].should =~ /\/some.*\/bogus\/path/
+ expect(ENV["PATH"]).to match(/\/some.*\/bogus\/path/)
end
- ENV["PATH"].should == @original_path
+ expect(ENV["PATH"]).to eq(@original_path)
end
it "should remove any new environment variables after the block ends" do
@new_env[:FOO] = "bar"
ENV["FOO"] = nil
Puppet::Util.withenv @new_env do
- ENV["FOO"].should == "bar"
+ expect(ENV["FOO"]).to eq("bar")
end
- ENV["FOO"].should == nil
+ expect(ENV["FOO"]).to eq(nil)
end
end
describe "#absolute_path?" do
describe "on posix systems", :if => Puppet.features.posix? do
it "should default to the platform of the local system" do
- Puppet::Util.should be_absolute_path('/foo')
- Puppet::Util.should_not be_absolute_path('C:/foo')
+ expect(Puppet::Util).to be_absolute_path('/foo')
+ expect(Puppet::Util).not_to be_absolute_path('C:/foo')
end
end
describe "on windows", :if => Puppet.features.microsoft_windows? do
it "should default to the platform of the local system" do
- Puppet::Util.should be_absolute_path('C:/foo')
- Puppet::Util.should_not be_absolute_path('/foo')
+ expect(Puppet::Util).to be_absolute_path('C:/foo')
+ expect(Puppet::Util).not_to be_absolute_path('/foo')
end
end
describe "when using platform :posix" do
%w[/ /foo /foo/../bar //foo //Server/Foo/Bar //?/C:/foo/bar /\Server/Foo /foo//bar/baz].each do |path|
it "should return true for #{path}" do
- Puppet::Util.should be_absolute_path(path, :posix)
+ expect(Puppet::Util).to be_absolute_path(path, :posix)
end
end
%w[. ./foo \foo C:/foo \\Server\Foo\Bar \\?\C:\foo\bar \/?/foo\bar \/Server/foo foo//bar/baz].each do |path|
it "should return false for #{path}" do
- Puppet::Util.should_not be_absolute_path(path, :posix)
+ expect(Puppet::Util).not_to be_absolute_path(path, :posix)
end
end
end
describe "when using platform :windows" do
%w[C:/foo C:\foo \\\\Server\Foo\Bar \\\\?\C:\foo\bar //Server/Foo/Bar //?/C:/foo/bar /\?\C:/foo\bar \/Server\Foo/Bar c:/foo//bar//baz].each do |path|
it "should return true for #{path}" do
- Puppet::Util.should be_absolute_path(path, :windows)
+ expect(Puppet::Util).to be_absolute_path(path, :windows)
end
end
%w[/ . ./foo \foo /foo /foo/../bar //foo C:foo/bar foo//bar/baz].each do |path|
it "should return false for #{path}" do
- Puppet::Util.should_not be_absolute_path(path, :windows)
+ expect(Puppet::Util).not_to be_absolute_path(path, :windows)
end
end
end
end
describe "#path_to_uri" do
%w[. .. foo foo/bar foo/../bar].each do |path|
it "should reject relative path: #{path}" do
- lambda { Puppet::Util.path_to_uri(path) }.should raise_error(Puppet::Error)
+ expect { Puppet::Util.path_to_uri(path) }.to raise_error(Puppet::Error)
end
end
it "should perform URI escaping" do
- Puppet::Util.path_to_uri("/foo bar").path.should == "/foo%20bar"
+ expect(Puppet::Util.path_to_uri("/foo bar").path).to eq("/foo%20bar")
end
describe "when using platform :posix" do
before :each do
Puppet.features.stubs(:posix).returns true
Puppet.features.stubs(:microsoft_windows?).returns false
end
%w[/ /foo /foo/../bar].each do |path|
it "should convert #{path} to URI" do
- Puppet::Util.path_to_uri(path).path.should == path
+ expect(Puppet::Util.path_to_uri(path).path).to eq(path)
end
end
end
describe "when using platform :windows" do
before :each do
Puppet.features.stubs(:posix).returns false
Puppet.features.stubs(:microsoft_windows?).returns true
end
it "should normalize backslashes" do
- Puppet::Util.path_to_uri('c:\\foo\\bar\\baz').path.should == '/' + 'c:/foo/bar/baz'
+ expect(Puppet::Util.path_to_uri('c:\\foo\\bar\\baz').path).to eq('/' + 'c:/foo/bar/baz')
end
%w[C:/ C:/foo/bar].each do |path|
it "should convert #{path} to absolute URI" do
- Puppet::Util.path_to_uri(path).path.should == '/' + path
+ expect(Puppet::Util.path_to_uri(path).path).to eq('/' + path)
end
end
%w[share C$].each do |path|
it "should convert UNC #{path} to absolute URI" do
uri = Puppet::Util.path_to_uri("\\\\server\\#{path}")
- uri.host.should == 'server'
- uri.path.should == '/' + path
+ expect(uri.host).to eq('server')
+ expect(uri.path).to eq('/' + path)
end
end
end
end
describe ".uri_to_path" do
require 'uri'
it "should strip host component" do
- Puppet::Util.uri_to_path(URI.parse('http://foo/bar')).should == '/bar'
+ expect(Puppet::Util.uri_to_path(URI.parse('http://foo/bar'))).to eq('/bar')
end
it "should accept puppet URLs" do
- Puppet::Util.uri_to_path(URI.parse('puppet:///modules/foo')).should == '/modules/foo'
+ expect(Puppet::Util.uri_to_path(URI.parse('puppet:///modules/foo'))).to eq('/modules/foo')
end
it "should return unencoded path" do
- Puppet::Util.uri_to_path(URI.parse('http://foo/bar%20baz')).should == '/bar baz'
+ expect(Puppet::Util.uri_to_path(URI.parse('http://foo/bar%20baz'))).to eq('/bar baz')
end
it "should be nil-safe" do
- Puppet::Util.uri_to_path(nil).should be_nil
+ expect(Puppet::Util.uri_to_path(nil)).to be_nil
end
describe "when using platform :posix",:if => Puppet.features.posix? do
it "should accept root" do
- Puppet::Util.uri_to_path(URI.parse('file:/')).should == '/'
+ expect(Puppet::Util.uri_to_path(URI.parse('file:/'))).to eq('/')
end
it "should accept single slash" do
- Puppet::Util.uri_to_path(URI.parse('file:/foo/bar')).should == '/foo/bar'
+ expect(Puppet::Util.uri_to_path(URI.parse('file:/foo/bar'))).to eq('/foo/bar')
end
it "should accept triple slashes" do
- Puppet::Util.uri_to_path(URI.parse('file:///foo/bar')).should == '/foo/bar'
+ expect(Puppet::Util.uri_to_path(URI.parse('file:///foo/bar'))).to eq('/foo/bar')
end
end
describe "when using platform :windows", :if => Puppet.features.microsoft_windows? do
it "should accept root" do
- Puppet::Util.uri_to_path(URI.parse('file:/C:/')).should == 'C:/'
+ expect(Puppet::Util.uri_to_path(URI.parse('file:/C:/'))).to eq('C:/')
end
it "should accept single slash" do
- Puppet::Util.uri_to_path(URI.parse('file:/C:/foo/bar')).should == 'C:/foo/bar'
+ expect(Puppet::Util.uri_to_path(URI.parse('file:/C:/foo/bar'))).to eq('C:/foo/bar')
end
it "should accept triple slashes" do
- Puppet::Util.uri_to_path(URI.parse('file:///C:/foo/bar')).should == 'C:/foo/bar'
+ expect(Puppet::Util.uri_to_path(URI.parse('file:///C:/foo/bar'))).to eq('C:/foo/bar')
end
it "should accept file scheme with double slashes as a UNC path" do
- Puppet::Util.uri_to_path(URI.parse('file://host/share/file')).should == '//host/share/file'
+ expect(Puppet::Util.uri_to_path(URI.parse('file://host/share/file'))).to eq('//host/share/file')
end
end
end
describe "safe_posix_fork" do
let(:pid) { 5501 }
before :each do
# Most of the things this method does are bad to do during specs. :/
Kernel.stubs(:fork).returns(pid).yields
$stdin.stubs(:reopen)
$stdout.stubs(:reopen)
$stderr.stubs(:reopen)
# ensure that we don't really close anything!
(0..256).each {|n| IO.stubs(:new) }
end
it "should close all open file descriptors except stdin/stdout/stderr" do
# This is ugly, but I can't really think of a better way to do it without
# letting it actually close fds, which seems risky
(0..2).each {|n| IO.expects(:new).with(n).never}
(3..256).each {|n| IO.expects(:new).with(n).returns mock('io', :close) }
Puppet::Util.safe_posix_fork
end
it "should fork a child process to execute the block" do
Kernel.expects(:fork).returns(pid).yields
Puppet::Util.safe_posix_fork do
message = "Fork this!"
end
end
it "should return the pid of the child process" do
- Puppet::Util.safe_posix_fork.should == pid
+ expect(Puppet::Util.safe_posix_fork).to eq(pid)
end
end
describe "#which" do
let(:base) { File.expand_path('/bin') }
let(:path) { File.join(base, 'foo') }
before :each do
FileTest.stubs(:file?).returns false
FileTest.stubs(:file?).with(path).returns true
FileTest.stubs(:executable?).returns false
FileTest.stubs(:executable?).with(path).returns true
end
it "should accept absolute paths" do
- Puppet::Util.which(path).should == path
+ expect(Puppet::Util.which(path)).to eq(path)
end
it "should return nil if no executable found" do
- Puppet::Util.which('doesnotexist').should be_nil
+ expect(Puppet::Util.which('doesnotexist')).to be_nil
end
it "should warn if the user's HOME is not set but their PATH contains a ~" do
env_path = %w[~/bin /usr/bin /bin].join(File::PATH_SEPARATOR)
env = {:HOME => nil, :PATH => env_path}
env.merge!({:HOMEDRIVE => nil, :USERPROFILE => nil}) if Puppet.features.microsoft_windows?
Puppet::Util.withenv(env) do
Puppet::Util::Warnings.expects(:warnonce).once
Puppet::Util.which('foo')
end
end
it "should reject directories" do
- Puppet::Util.which(base).should be_nil
+ expect(Puppet::Util.which(base)).to be_nil
end
it "should ignore ~user directories if the user doesn't exist" do
# Windows treats *any* user as a "user that doesn't exist", which means
# that this will work correctly across all our platforms, and should
# behave consistently. If they ever implement it correctly (eg: to do
# the lookup for real) it should just work transparently.
baduser = 'if_this_user_exists_I_will_eat_my_hat'
Puppet::Util.withenv("PATH" => "~#{baduser}#{File::PATH_SEPARATOR}#{base}") do
- Puppet::Util.which('foo').should == path
+ expect(Puppet::Util.which('foo')).to eq(path)
end
end
describe "on POSIX systems" do
before :each do
Puppet.features.stubs(:posix?).returns true
Puppet.features.stubs(:microsoft_windows?).returns false
end
it "should walk the search PATH returning the first executable" do
ENV.stubs(:[]).with('PATH').returns(File.expand_path('/bin'))
- Puppet::Util.which('foo').should == path
+ expect(Puppet::Util.which('foo')).to eq(path)
end
end
describe "on Windows systems" do
let(:path) { File.expand_path(File.join(base, 'foo.CMD')) }
before :each do
Puppet.features.stubs(:posix?).returns false
Puppet.features.stubs(:microsoft_windows?).returns true
end
describe "when a file extension is specified" do
it "should walk each directory in PATH ignoring PATHEXT" do
ENV.stubs(:[]).with('PATH').returns(%w[/bar /bin].map{|dir| File.expand_path(dir)}.join(File::PATH_SEPARATOR))
FileTest.expects(:file?).with(File.join(File.expand_path('/bar'), 'foo.CMD')).returns false
ENV.expects(:[]).with('PATHEXT').never
- Puppet::Util.which('foo.CMD').should == path
+ expect(Puppet::Util.which('foo.CMD')).to eq(path)
end
end
describe "when a file extension is not specified" do
it "should walk each extension in PATHEXT until an executable is found" do
bar = File.expand_path('/bar')
ENV.stubs(:[]).with('PATH').returns("#{bar}#{File::PATH_SEPARATOR}#{base}")
ENV.stubs(:[]).with('PATHEXT').returns(".EXE#{File::PATH_SEPARATOR}.CMD")
exts = sequence('extensions')
FileTest.expects(:file?).in_sequence(exts).with(File.join(bar, 'foo.EXE')).returns false
FileTest.expects(:file?).in_sequence(exts).with(File.join(bar, 'foo.CMD')).returns false
FileTest.expects(:file?).in_sequence(exts).with(File.join(base, 'foo.EXE')).returns false
FileTest.expects(:file?).in_sequence(exts).with(path).returns true
- Puppet::Util.which('foo').should == path
+ expect(Puppet::Util.which('foo')).to eq(path)
end
it "should walk the default extension path if the environment variable is not defined" do
ENV.stubs(:[]).with('PATH').returns(base)
ENV.stubs(:[]).with('PATHEXT').returns(nil)
exts = sequence('extensions')
%w[.COM .EXE .BAT].each do |ext|
FileTest.expects(:file?).in_sequence(exts).with(File.join(base, "foo#{ext}")).returns false
end
FileTest.expects(:file?).in_sequence(exts).with(path).returns true
- Puppet::Util.which('foo').should == path
+ expect(Puppet::Util.which('foo')).to eq(path)
end
it "should fall back if no extension matches" do
ENV.stubs(:[]).with('PATH').returns(base)
ENV.stubs(:[]).with('PATHEXT').returns(".EXE")
FileTest.stubs(:file?).with(File.join(base, 'foo.EXE')).returns false
FileTest.stubs(:file?).with(File.join(base, 'foo')).returns true
FileTest.stubs(:executable?).with(File.join(base, 'foo')).returns true
- Puppet::Util.which('foo').should == File.join(base, 'foo')
+ expect(Puppet::Util.which('foo')).to eq(File.join(base, 'foo'))
end
end
end
end
describe "hash symbolizing functions" do
let (:myhash) { { "foo" => "bar", :baz => "bam" } }
let (:resulthash) { { :foo => "bar", :baz => "bam" } }
describe "#symbolizehash" do
it "should return a symbolized hash" do
newhash = Puppet::Util.symbolizehash(myhash)
- newhash.should == resulthash
+ expect(newhash).to eq(resulthash)
end
end
end
context "#replace_file" do
subject { Puppet::Util }
- it { should respond_to :replace_file }
+ it { is_expected.to respond_to :replace_file }
let :target do
target = Tempfile.new("puppet-util-replace-file")
target.puts("hello, world")
target.flush # make sure content is on disk.
target.fsync rescue nil
target.close
target
end
it "should fail if no block is given" do
expect { subject.replace_file(target.path, 0600) }.to raise_error /block/
end
it "should replace a file when invoked" do
# Check that our file has the expected content.
- File.read(target.path).should == "hello, world\n"
+ expect(File.read(target.path)).to eq("hello, world\n")
# Replace the file.
subject.replace_file(target.path, 0600) do |fh|
fh.puts "I am the passenger..."
end
# ...and check the replacement was complete.
- File.read(target.path).should == "I am the passenger...\n"
+ expect(File.read(target.path)).to eq("I am the passenger...\n")
end
# When running with the same user and group sid, which is the default,
# Windows collapses the owner and group modes into a single ACE, resulting
# in set(0600) => get(0660) and so forth. --daniel 2012-03-30
modes = [0555, 0660, 0770]
modes += [0600, 0700] unless Puppet.features.microsoft_windows?
modes.each do |mode|
it "should copy 0#{mode.to_s(8)} permissions from the target file by default" do
set_mode(mode, target.path)
- get_mode(target.path).should == mode
+ expect(get_mode(target.path)).to eq(mode)
subject.replace_file(target.path, 0000) {|fh| fh.puts "bazam" }
- get_mode(target.path).should == mode
- File.read(target.path).should == "bazam\n"
+ expect(get_mode(target.path)).to eq(mode)
+ expect(File.read(target.path)).to eq("bazam\n")
end
end
it "should copy the permissions of the source file before yielding on Unix", :if => !Puppet.features.microsoft_windows? do
set_mode(0555, target.path)
inode = Puppet::FileSystem.stat(target.path).ino
yielded = false
subject.replace_file(target.path, 0600) do |fh|
- get_mode(fh.path).should == 0555
+ expect(get_mode(fh.path)).to eq(0555)
yielded = true
end
- yielded.should be_true
+ expect(yielded).to be_truthy
- Puppet::FileSystem.stat(target.path).ino.should_not == inode
- get_mode(target.path).should == 0555
+ expect(Puppet::FileSystem.stat(target.path).ino).not_to eq(inode)
+ expect(get_mode(target.path)).to eq(0555)
end
it "should use the default permissions if the source file doesn't exist" do
new_target = target.path + '.foo'
- Puppet::FileSystem.exist?(new_target).should be_false
+ expect(Puppet::FileSystem.exist?(new_target)).to be_falsey
begin
subject.replace_file(new_target, 0555) {|fh| fh.puts "foo" }
- get_mode(new_target).should == 0555
+ expect(get_mode(new_target)).to eq(0555)
ensure
Puppet::FileSystem.unlink(new_target) if Puppet::FileSystem.exist?(new_target)
end
end
it "should not replace the file if an exception is thrown in the block" do
yielded = false
threw = false
begin
subject.replace_file(target.path, 0600) do |fh|
yielded = true
fh.puts "different content written, then..."
raise "...throw some random failure"
end
rescue Exception => e
if e.to_s =~ /some random failure/
threw = true
else
raise
end
end
- yielded.should be_true
- threw.should be_true
+ expect(yielded).to be_truthy
+ expect(threw).to be_truthy
# ...and check the replacement was complete.
- File.read(target.path).should == "hello, world\n"
+ expect(File.read(target.path)).to eq("hello, world\n")
end
{:string => '664', :number => 0664, :symbolic => "ug=rw-,o=r--" }.each do |label,mode|
it "should support #{label} format permissions" do
new_target = target.path + "#{mode}.foo"
- Puppet::FileSystem.exist?(new_target).should be_false
+ expect(Puppet::FileSystem.exist?(new_target)).to be_falsey
begin
subject.replace_file(new_target, mode) {|fh| fh.puts "this is an interesting content" }
- get_mode(new_target).should == 0664
+ expect(get_mode(new_target)).to eq(0664)
ensure
Puppet::FileSystem.unlink(new_target) if Puppet::FileSystem.exist?(new_target)
end
end
end
end
describe "#pretty_backtrace" do
it "should include lines that don't match the standard backtrace pattern" do
line = "non-standard line\n"
trace = caller[0..2] + [line] + caller[3..-1]
- Puppet::Util.pretty_backtrace(trace).should =~ /#{line}/
+ expect(Puppet::Util.pretty_backtrace(trace)).to match(/#{line}/)
end
it "should include function names" do
- Puppet::Util.pretty_backtrace.should =~ /:in `\w+'/
+ expect(Puppet::Util.pretty_backtrace).to match(/:in `\w+'/)
end
it "should work with Windows paths" do
- Puppet::Util.pretty_backtrace(["C:/work/puppet/c.rb:12:in `foo'\n"]).
- should == "C:/work/puppet/c.rb:12:in `foo'"
+ expect(Puppet::Util.pretty_backtrace(["C:/work/puppet/c.rb:12:in `foo'\n"])).
+ to eq("C:/work/puppet/c.rb:12:in `foo'")
end
end
describe "#deterministic_rand" do
it "should not fiddle with future rand calls" do
Puppet::Util.deterministic_rand(123,20)
rand_one = rand()
Puppet::Util.deterministic_rand(123,20)
- rand().should_not eql(rand_one)
+ expect(rand()).not_to eql(rand_one)
end
if defined?(Random) == 'constant' && Random.class == Class
it "should not fiddle with the global seed" do
srand(1234)
Puppet::Util.deterministic_rand(123,20)
- srand().should eql(1234)
+ expect(srand()).to eql(1234)
end
# ruby below 1.9.2 variant
else
it "should set a new global seed" do
srand(1234)
Puppet::Util.deterministic_rand(123,20)
- srand().should_not eql(1234)
+ expect(srand()).not_to eql(1234)
end
end
end
end
diff --git a/spec/unit/version_spec.rb b/spec/unit/version_spec.rb
index d2e8b5138..aa5e7d581 100644
--- a/spec/unit/version_spec.rb
+++ b/spec/unit/version_spec.rb
@@ -1,42 +1,42 @@
require "spec_helper"
require "puppet/version"
require 'pathname'
describe "Puppet.version Public API" do
before :each do
Puppet.instance_eval do
if @puppet_version
@puppet_version = nil
end
end
end
context "without a VERSION file" do
before :each do
Puppet.stubs(:read_version_file).returns(nil)
end
it "is Puppet::PUPPETVERSION" do
- Puppet.version.should == Puppet::PUPPETVERSION
+ expect(Puppet.version).to eq(Puppet::PUPPETVERSION)
end
it "respects the version= setter" do
Puppet.version = '1.2.3'
- Puppet.version.should == '1.2.3'
+ expect(Puppet.version).to eq('1.2.3')
end
end
context "with a VERSION file" do
it "is the content of the file" do
Puppet.expects(:read_version_file).with() do |path|
pathname = Pathname.new(path)
pathname.basename.to_s == "VERSION"
end.returns('3.0.1-260-g9ca4e54')
- Puppet.version.should == '3.0.1-260-g9ca4e54'
+ expect(Puppet.version).to eq('3.0.1-260-g9ca4e54')
end
it "respects the version= setter" do
Puppet.version = '1.2.3'
- Puppet.version.should == '1.2.3'
+ expect(Puppet.version).to eq('1.2.3')
end
end
end
diff --git a/tasks/parallel.rake b/tasks/parallel.rake
index 67e515d69..b0cc0f65c 100644
--- a/tasks/parallel.rake
+++ b/tasks/parallel.rake
@@ -1,408 +1,405 @@
# encoding: utf-8
require 'rubygems'
require 'thread'
begin
require 'rspec'
require 'rspec/core/formatters/helpers'
require 'facter'
rescue LoadError
# Don't define the task if we don't have rspec or facter present
else
module Parallel
module RSpec
#
# Responsible for buffering the output of RSpec's progress formatter.
#
class ProgressFormatBuffer
attr_reader :pending_lines
attr_reader :failure_lines
attr_reader :examples
attr_reader :failures
attr_reader :pending
attr_reader :failed_example_lines
attr_reader :state
module OutputState
HEADER = 1
PROGRESS = 2
SUMMARY = 3
PENDING = 4
FAILURES = 5
DURATION = 6
COUNTS = 7
FAILED_EXAMPLES = 8
end
def initialize(io, color)
@io = io
@color = color
@state = OutputState::HEADER
@pending_lines = []
@failure_lines = []
@examples = 0
@failures = 0
@pending = 0
@failed_example_lines = []
end
def color?
@color
end
def read
# Parse and ignore the one line header
if @state == OutputState::HEADER
begin
@io.readline
rescue EOFError
return nil
end
@state = OutputState::PROGRESS
return ''
end
# If the progress has been read, parse the summary
if @state == OutputState::SUMMARY
parse_summary
return nil
end
# Read the progress output up to 128 bytes at a time
# 128 is a small enough number to show some progress, but not too small that
# we're constantly writing synchronized output
data = @io.read(128)
return nil unless data
data = @remainder + data if @remainder
# Check for the end of the progress line
if (index = data.index "\n")
@state = OutputState::SUMMARY
@remainder = data[(index+1)..-1]
data = data[0...index]
# Check for partial ANSI escape codes in colorized output
elsif @color && !data.end_with?("\e[0m") && (index = data.rindex("\e[", -6))
@remainder = data[index..-1]
data = data[0...index]
else
@remainder = nil
end
data
end
private
def parse_summary
# If there is a remainder, concat it with the next line and handle each line
unless @remainder.empty?
lines = @remainder
eof = false
begin
lines += @io.readline
rescue EOFError
eof = true
end
lines.each_line do |line|
parse_summary_line line
end
return if eof
end
# Process the rest of the lines
begin
@io.each_line do |line|
parse_summary_line line
end
rescue EOFError
end
end
def parse_summary_line(line)
line.chomp!
return if line.empty?
if line == 'Pending:'
@status = OutputState::PENDING
return
elsif line == 'Failures:'
@status = OutputState::FAILURES
return
elsif line == 'Failed examples:'
@status = OutputState::FAILED_EXAMPLES
return
elsif (line.match /^Finished in ((\d+\.?\d*) minutes?)? ?(\d+\.?\d*) seconds?$/)
@status = OutputState::DURATION
return
elsif (match = line.gsub(/\e\[\d+m/, '').match /^(\d+) examples?, (\d+) failures?(, (\d+) pending)?$/)
@status = OutputState::COUNTS
@examples = match[1].to_i
@failures = match[2].to_i
@pending = (match[4] || 0).to_i
return
end
case @status
when OutputState::PENDING
@pending_lines << line
when OutputState::FAILURES
@failure_lines << line
when OutputState::FAILED_EXAMPLES
@failed_example_lines << line
end
end
end
#
# Responsible for parallelizing spec testing.
#
class Parallelizer
- include ::RSpec::Core::Formatters::Helpers
-
# Number of processes to use
attr_reader :process_count
# Approximate size of each group of tests
attr_reader :group_size
def initialize(process_count, group_size, color)
@process_count = process_count
@group_size = group_size
@color = color
end
def color?
@color
end
def run
@start_time = Time.now
groups = group_specs
fail red('error: no specs were found') if groups.length == 0
begin
run_specs groups
ensure
groups.each do |file|
File.unlink(file)
end
end
end
private
def group_specs
# Spawn the rspec_grouper utility to perform the test grouping
# We do this in a separate process to limit this processes' long-running footprint
io = IO.popen("ruby util/rspec_grouper #{@group_size}")
header = true
spec_group_files = []
io.each_line do |line|
line.chomp!
header = false if line.empty?
next if header || line.empty?
spec_group_files << line
end
_, status = Process.waitpid2(io.pid)
io.close
fail red('error: no specs were found.') unless status.success?
spec_group_files
end
def run_specs(groups)
puts "Processing #{groups.length} spec group(s) with #{@process_count} worker(s)"
interrupted = false
success = true
worker_threads = []
group_index = -1
pids = Array.new(@process_count)
mutex = Mutex.new
# Handle SIGINT by killing child processes
original_handler = Signal.trap :SIGINT do
break if interrupted
interrupted = true
# Can't synchronize in a trap context, so read dirty
pids.each do |pid|
begin
Process.kill(:SIGKILL, pid) if pid
rescue Errno::ESRCH
end
end
puts yellow("\nshutting down...")
end
buffers = []
process_count.times do |thread_id|
worker_threads << Thread.new do
while !interrupted do
# Get the spec file for this rspec run
group = mutex.synchronize { if group_index < groups.length then groups[group_index += 1] else nil end }
break unless group && !interrupted
# Spawn the worker process with redirected output
io = IO.popen("ruby util/rspec_runner #{group}")
pids[thread_id] = io.pid
# TODO: make the buffer pluggable to handle other output formats like documentation
buffer = ProgressFormatBuffer.new(io, @color)
# Process the output
while !interrupted
output = buffer.read
break unless output && !interrupted
next if output.empty?
mutex.synchronize { print output }
end
# Kill the process if we were interrupted, just to be sure
if interrupted
begin
Process.kill(:SIGKILL, pids[thread_id])
rescue Errno::ESRCH
end
end
# Reap the process
result = Process.waitpid2(pids[thread_id])[1].success?
io.close
pids[thread_id] = nil
mutex.synchronize do
buffers << buffer
success &= result
end
end
end
end
# Join all worker threads
worker_threads.each do |thread|
thread.join
end
Signal.trap :SIGINT, original_handler
fail yellow('execution was interrupted') if interrupted
dump_summary buffers
success
end
def colorize(text, color_code)
if @color
"#{color_code}#{text}\e[0m"
else
text
end
end
def red(text)
colorize(text, "\e[31m")
end
def green(text)
colorize(text, "\e[32m")
end
def yellow(text)
colorize(text, "\e[33m")
end
def dump_summary(buffers)
puts
# Print out the pending tests
print_header = true
buffers.each do |buffer|
next if buffer.pending_lines.empty?
if print_header
puts "\nPending:"
print_header = false
end
puts buffer.pending_lines
end
# Print out the failures
print_header = true
buffers.each do |buffer|
next if buffer.failure_lines.empty?
if print_header
puts "\nFailures:"
print_header = false
end
puts
puts buffer.failure_lines
end
# Print out the run time
- puts "\nFinished in #{format_duration(Time.now - @start_time)}"
+ puts "\nFinished in #{::RSpec::Core::Formatters::Helpers.format_duration(Time.now - @start_time)}"
# Count all of the examples
examples = 0
failures = 0
pending = 0
buffers.each do |buffer|
examples += buffer.examples
failures += buffer.failures
pending += buffer.pending
end
if failures > 0
puts red(summary_count_line(examples, failures, pending))
elsif pending > 0
puts yellow(summary_count_line(examples, failures, pending))
else
puts green(summary_count_line(examples, failures, pending))
end
# Print out the failed examples
print_header = true
buffers.each do |buffer|
next if buffer.failed_example_lines.empty?
if print_header
puts "\nFailed examples:"
print_header = false
end
puts buffer.failed_example_lines
end
end
def summary_count_line(examples, failures, pending)
- summary = pluralize(examples, "example")
- summary << ", " << pluralize(failures, "failure")
+ summary = ::RSpec::Core::Formatters::Helpers.pluralize(examples, "example")
+ summary << ", " << ::RSpec::Core::Formatters::Helpers.pluralize(failures, "failure")
summary << ", #{pending} pending" if pending > 0
summary
end
end
end
end
namespace 'parallel' do
def color_output?
# Check with RSpec to see if color is enabled
config = ::RSpec::Core::Configuration.new
config.error_stream = $stderr
config.output_stream = $stdout
options = ::RSpec::Core::ConfigurationOptions.new []
- options.parse_options
options.configure config
config.color
end
desc 'Runs specs in parallel.'
task 'spec', :process_count, :group_size do |_, args|
# Default group size in rspec examples
DEFAULT_GROUP_SIZE = 1000
process_count = [(args[:process_count] || Facter.value("processorcount")).to_i, 1].max
group_size = [(args[:group_size] || DEFAULT_GROUP_SIZE).to_i, 1].max
abort unless Parallel::RSpec::Parallelizer.new(process_count, group_size, color_output?).run
end
end
end
diff --git a/util/rspec_grouper b/util/rspec_grouper
index f521dab57..46c44fea7 100755
--- a/util/rspec_grouper
+++ b/util/rspec_grouper
@@ -1,106 +1,105 @@
#!/usr/bin/env ruby
require 'rubygems'
require 'rspec'
# Disable ruby verbosity
# We need control over output so that the parallel task can parse it correctly
$VERBOSE = nil
module Parallel
module RSpec
#
# Responsible for grouping rspec examples into groups of a given size.
#
class Grouper
attr_reader :groups
attr_reader :files
attr_reader :total_examples
def initialize(group_size)
config = ::RSpec::Core::Configuration.new
options = ::RSpec::Core::ConfigurationOptions.new((ENV['TEST'] || ENV['TESTS'] || 'spec').split(';'))
- options.parse_options
options.configure config
# This will scan and load all spec examples
config.load_spec_files
@total_examples = 0
# Populate a map of spec file => example count, sorted ascending by count
# NOTE: this uses a private API of RSpec and is may break if the gem is updated
@files = ::RSpec::Core::ExampleGroup.children.inject({}) do |files, group|
file = group.metadata[:example_group_block].source_location[0]
count = count_examples(group)
files[file] = (files[file] || 0) + count
@total_examples += count
files
end.sort_by { |_, v| v}
# Group the spec files
@groups = []
group = nil
example_count = 0
@files.each do |file, count|
group = [] unless group
group << file
if (example_count += count) > group_size
example_count = 0
@groups << group
group = nil
end
end
@groups << group if group
end
private
def count_examples(group)
return 0 unless group
# Each group can have examples as well as child groups, so recursively traverse
group.children.inject(group.examples.count) { |count, g| count + count_examples(g) }
end
end
end
end
def print_usage
puts 'usage: rspec_grouper <group_size>'
end
if __FILE__ == $0
if ARGV.length != 1
print_usage
else
group_size = ARGV[0].to_i
abort 'error: group count must be greater than zero.' if group_size < 1
grouper = Parallel::RSpec::Grouper.new(group_size)
abort 'error: no rspec examples were found.' if grouper.total_examples == 0
groups = grouper.groups
puts "Grouped #{grouper.total_examples} rspec example(s) into #{groups.length} group(s) from #{grouper.files.count} file(s)."
puts
paths = []
begin
# Create a temp directory and write out group files
tmpdir = Dir.mktmpdir
groups.each_with_index do |group, index|
path = File.join(tmpdir, "group#{index+1}")
file = File.new(path, 'w')
paths << path
file.puts group
file.close
puts path
end
rescue Exception
# Delete all files on an exception
paths.each do |path|
begin
File.delete path
rescue Exception
end
end
raise
end
end
end
diff --git a/util/rspec_runner b/util/rspec_runner
index e4452a01c..77ce16f7d 100755
--- a/util/rspec_runner
+++ b/util/rspec_runner
@@ -1,53 +1,55 @@
#!/usr/bin/env ruby
require 'rubygems'
require 'rspec'
require 'rspec/core/formatters/progress_formatter'
-require 'rspec/core/command_line'
+require 'rspec/core/runner'
# Disable ruby verbosity
# We need control over output so that the parallel task can parse it correctly
$VERBOSE = nil
module Parallel
module RSpec
#
# Responsible for formatting output.
# This differs from the built-in progress formatter by not appending an index to failures.
#
class Formatter < ::RSpec::Core::Formatters::ProgressFormatter
+ ::RSpec::Core::Formatters.register self, :dump_failure
def dump_failure(example, _)
# Unlike the super class implementation, do not print the failure number
output.puts "#{short_padding}#{example.full_description}"
dump_failure_info(example)
end
end
#
# Responsible for running spec files given a spec file.
# We do it this way so that we can run very long spec file lists on Windows, since
# Windows has a limited argument length depending on method of invocation.
#
class Runner
def initialize(specs_file)
abort "error: spec list file '#{specs_file}' does not exist." unless File.exists? specs_file
@options = ['-fParallel::RSpec::Formatter']
File.readlines(specs_file).each { |line| @options << line.chomp }
end
def run
- ::RSpec::Core::CommandLine.new(@options).run($stderr, $stdout)
+ @options = ::RSpec::Core::ConfigurationOptions.new(@options)
+ ::RSpec::Core::Runner.new(@options).run($stderr, $stdout)
end
end
end
end
def print_usage
puts 'usage: rspec_runner <spec_list_file>'
end
if __FILE__ == $0
if ARGV.length != 1
print_usage
else
exit Parallel::RSpec::Runner.new(ARGV[0]).run
end
-end
\ No newline at end of file
+end

File Metadata

Mime Type
application/octet-stream
Expires
Mon, Oct 7, 5:20 PM (2 d)
Storage Engine
chunks
Storage Format
Chunks
Storage Handle
nAsHnWDbUeJ2
Default Alt Text
(4 MB)

Event Timeline