summaryrefslogtreecommitdiff
path: root/spec/support/provider_example_group.rb
blob: 1431f78223faca44c466f3b785a54fea9ca9be20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class ProviderExampleGroup < Spec::Example::ExampleGroup

  # Allow access to the current resource
  attr_reader :resource

  # Build up the values for the resource in this scope
  before :each do
    resource_hash = example_group_hierarchy.inject({}) do |memo, klass|
      memo.merge(klass.options[:resource] || {})
    end
    full_hash = resource_hash.merge(:provider => described_class.name)
    @resource = described_class.resource_type.new(full_hash)
  end

  # Build the provider
  subject { described_class.new(@resource) }

  # Allow access to it via +provider+
  alias :provider :subject

  # Generate a context for a provider operating on a resource with:
  #
  # call-seq:
  #
  #   # A parameter/property set (when the value isn't important)
  #   resource_with :source do
  #     # ...
  #   end
  #
  #   # A parameter/property set to a specific value
  #   resource_with :source => 'a-specific-value' do
  #     # ...
  #   end
  #
  # Note: Choose one or the other (mixing will create two separate contexts)
  #
  def self.resource_with(*params, &block)
    params_with_values = params.last.is_a?(Hash) ? params.pop : {}
    build_value_context(params_with_values, &block)
    build_existence_context(*params, &block)
  end

  def self.build_existence_context(*params, &block) #:nodoc:
    unless params.empty?
      text = params.join(', ')
      placeholders = params.inject({}) { |memo, key| memo.merge(key => 'an-unimportant-value') }
      context("and with a #{text}", {:resource => placeholders}, &block)
    end
  end

  def self.build_value_context(params = {}, &block) #:nodoc:
    unless params.empty?
      text = params.map { |k, v| "#{k} => #{v.inspect}" }.join(' and with ')
      context("and with #{text}", {:resource => params}, &block)
    end
  end


  # Generate a context for a provider operating on a resource without
  # a given parameter/property.
  #
  # call-seq:
  #
  #   resource_without :source do
  #     # ...
  #   end
  #
  def self.resource_without(field, &block)
    context("and without a #{field}", &block)
  end

end

Spec::Example::ExampleGroupFactory.register(:provider, ProviderExampleGroup)

# Outside wrapper to lookup a provider and start the spec using ProviderExampleGroup
def describe_provider(type_name, provider_name, options = {}, &block)
  provider_class = Puppet::Type.type(type_name).provider(provider_name)
  describe(provider_class, options.merge(:type => :provider), &block)
end