File: count_generic.rb

package info (click to toggle)
ruby-rspec-puppet 4.0.2%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,444 kB
  • sloc: ruby: 6,377; makefile: 6
file content (89 lines) | stat: -rw-r--r-- 2,320 bytes parent folder | download
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
81
82
83
84
85
86
87
88
89
# frozen_string_literal: true

module RSpec::Puppet
  module ManifestMatchers
    class CountGeneric
      DEFAULT_RESOURCES = [
        'Class[main]',
        'Class[Settings]',
        'Stage[main]'
      ].freeze

      attr_reader :resource_type

      def initialize(type, count, *method)
        @type = if type.nil?
                  method[0].to_s.gsub(/^have_(.+)_resource_count$/, '\1')
                else
                  type
                end
        @resource_type = referenced_type(@type)
        @expected_number = count.to_i
      end

      def matches?(catalogue)
        @catalogue = catalogue.call

        resources = @catalogue.resources.reject do |res|
          DEFAULT_RESOURCES.include?(res.ref)
        end

        @actual_number = if @type == 'resource'
                           resources.count do |res|
                             !%w[Class Node].include?(res.type)
                           end
                         else
                           resources.count do |res|
                             res.type == @resource_type
                           end
                         end

        @actual_number == @expected_number
      end

      def description
        desc = []

        desc << "contain exactly #{@expected_number}"
        if @type == 'class'
          desc << (@expected_number == 1 ? 'class' : 'classes').to_s
        else
          desc << @resource_type.to_s unless @type == 'resource'
          desc << (@expected_number == 1 ? 'resource' : 'resources').to_s
        end

        desc.join(' ')
      end

      def failure_message
        "expected that the catalogue would #{description} but it contains #{@actual_number}"
      end

      def failure_message_when_negated
        "expected that the catalogue would not #{description} but it does"
      end

      def supports_block_expectations
        true
      end

      def supports_value_expectations
        true
      end

      private

      def referenced_type(type)
        type.split('__').map(&:capitalize).join('::')
      end
    end

    def have_class_count(count)
      RSpec::Puppet::ManifestMatchers::CountGeneric.new('class', count)
    end

    def have_resource_count(count)
      RSpec::Puppet::ManifestMatchers::CountGeneric.new('resource', count)
    end
  end
end