rspec-puppet 2.3.2 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 320021848da7cb4b21717e49b02ce505a6d507a9
4
- data.tar.gz: 132dc40418a858f94d097a9342bfdfc108cb7976
3
+ metadata.gz: 1a4f52ea0428c49bc328570e7a71776b75b800b2
4
+ data.tar.gz: 461fadebe1cd4756715a99d54fefdf51c020a17b
5
5
  SHA512:
6
- metadata.gz: 3819322db7dbab18f6e943c21345aa26584bb7a2916aade4894b73af8e1a99a10cab204faf20ef6b31a26247845af3366872a4402d64acd89c3b3297f8ac0dac
7
- data.tar.gz: d564f7fc7f190f224f89a4ca4496e3892dc555dc067070a9f943bfa2601d78069979f05985b876eb94cf055125cb27bd75a6bb96cc849339c1787d9eff829cf0
6
+ metadata.gz: 8f79f8be40bf4e2c77e11ddf68130ea0fe97b8e629cf4768c2da1a15a096ed65fad3dff160208a36b9d221f652564956fc15113b56589562a8890c01a4678098
7
+ data.tar.gz: bc64b10392874054ebf8cfe7712abc25874bfa3d44ebd3c6dced81d3eae7c99b359754dd3d74481dfc1851264ce347f8f76990e0022f8e653b622a77ade449d5
data/CHANGELOG.md CHANGED
@@ -2,6 +2,44 @@
2
2
  All notable changes to this project will be documented in this file. This
3
3
  project adheres to [Semantic Versioning](http://semver.org/).
4
4
 
5
+ ## [2.5.0]
6
+
7
+ Headline features are app management, nested hashes in params, and testing for "internal" functions.
8
+
9
+ Thanks to everyone who contributed: Leo Arnold, Matt Schuchard, and Si Wilkins
10
+
11
+ ### Changed
12
+
13
+ * Updates to the README
14
+ * Improve Gemfile to work with older rubies
15
+
16
+ ### Added
17
+
18
+ * Add support for app management testing
19
+ * Enable nested hashes in params
20
+ * After refactoring the function test code, puppet 4 "internal" functions can now be tested too
21
+ * Link functions and types on setup
22
+ * Increased test coverage
23
+
24
+ ## [2.4.0]
25
+
26
+ This release now supports testing exported resources in the same way that normal resources in the catalog are tested. Access them in your examples using `exported_resources`. See "Testing Exported Resources" in the README for examples.
27
+
28
+ ### Changed
29
+
30
+ * This release pulls out much of the version-specific code into separate classes to reduce complexity and enable easier maintenance going forward.
31
+
32
+ ### Added
33
+
34
+ * Support colon-separated module_path and environmentpath values.
35
+ * Support a threshold for the code coverage test, that can fail the whole run.
36
+ * Ensure a consistent environment for all examples by adding a forced initialization of puppet before each.
37
+
38
+ ### Credits
39
+
40
+ Thanks to Adrien Thebo, Arthur Gautier, Brett Gray, and Nicholas Hinds, as well as all the folks helping out on github for their contributions to this release.
41
+
42
+
5
43
  ## [2.3.2]
6
44
 
7
45
  Properly fix yesterday's issue by unsharing the cache key before passing the data to puppet. This also contains a new test matrix to avoid missing a half-baked fix like yesterday.
@@ -95,7 +133,9 @@ Thanks to Adrien Thebo, Alex Harvey, Brian, Dan Bode, Dominic Cleal, Javier Pala
95
133
  ## 1.0.1 and earlier
96
134
  For changelog of versions 1.0.1 and earlier, see http://rspec-puppet.com/changelog/
97
135
 
98
- [2.x]: https://github.com/rodjek/rspec-puppet/compare/v2.3.0...master
136
+ [2.x]: https://github.com/rodjek/rspec-puppet/compare/v2.5.0...master
137
+ [2.5.0]: https://github.com/rodjek/rspec-puppet/compare/v2.4.0...v2.5.0
138
+ [2.4.0]: https://github.com/rodjek/rspec-puppet/compare/v2.3.2...v2.4.0
99
139
  [2.3.2]: https://github.com/rodjek/rspec-puppet/compare/v2.3.1...v2.3.2
100
140
  [2.3.1]: https://github.com/rodjek/rspec-puppet/compare/v2.3.0...v2.3.1
101
141
  [2.3.0]: https://github.com/rodjek/rspec-puppet/compare/v2.2.0...v2.3.0
data/README.md CHANGED
@@ -37,6 +37,10 @@ structure and naming convention.
37
37
  | |
38
38
  | +-- <define_name>_spec.rb
39
39
  |
40
+ +-- applications
41
+ | |
42
+ | +-- <application_name>_spec.rb
43
+ |
40
44
  +-- functions
41
45
  | |
42
46
  | +-- <function_name>_spec.rb
@@ -64,6 +68,10 @@ describe 'mydefine', :type => :define do
64
68
  ...
65
69
  end
66
70
 
71
+ describe 'myapplication', :type => :application do
72
+ ...
73
+ end
74
+
67
75
  describe 'myfunction', :type => :puppet_function do
68
76
  ...
69
77
  end
@@ -77,7 +85,7 @@ describe 'myhost.example.com', :type => :host do
77
85
  end
78
86
  ```
79
87
 
80
- ## Defined Types & Classes
88
+ ## Defined Types, Classes & Applications
81
89
 
82
90
  ### Matchers
83
91
 
@@ -354,16 +362,45 @@ let(:title) { 'foo' }
354
362
 
355
363
  #### Specifying the parameters to pass to a resources or parameterised class
356
364
 
365
+ Parameters of a defined type, class or application can be passed defining `:params` in a let,
366
+ and passing it a hash as seen below.
367
+
357
368
  ```ruby
358
369
  let(:params) { {:ensure => 'present', ...} }
359
370
  ```
360
371
 
361
- ##### Passing Puppet's `undef` as a parameter value
372
+ For passing Puppet's `undef` as a paremeter value, you can simply use `:undef` and it will
373
+ be translated to `undef` when compiling. For example:
362
374
 
363
375
  ```ruby
364
376
  let(:params) { {:user => :undef, ...} }
365
377
  ```
366
378
 
379
+ For references to nodes or resources as seen when using `require` or `before` properties,
380
+ or an `application` resource you can pass the string as an argument to the `ref` helper:
381
+
382
+ ```ruby
383
+ let(:params) { :require => ref('Package', 'sudoku') }
384
+ ```
385
+
386
+ Which translates to:
387
+
388
+ ```puppet
389
+ mydefine { 'mytitle': require => Package['sudoku'] }
390
+ ```
391
+
392
+ Another example, for an application setup (when using `app_management`):
393
+
394
+ ```ruby
395
+ let(:params) { { :nodes => { ref('Node', 'dbnode') => ref('Myapp::Mycomponent', 'myapp') } } }
396
+ ```
397
+
398
+ Will translate to:
399
+
400
+ ```puppet
401
+ site { myapp { 'myimpl': nodes => { Node['dbnode'] => Myapp::Mycomponent['myimpl'] } } }
402
+ ```
403
+
367
404
  #### Specifying the FQDN of the test node
368
405
 
369
406
  If the manifest you're testing expects to run on host with a particular name,
@@ -429,6 +466,67 @@ However, if you want to specify it in each example, you can do so
429
466
  let(:module_path) { '/path/to/your/module/dir' }
430
467
  ```
431
468
 
469
+ #### Testing Exported Resources
470
+
471
+ You can test if a resource was exported from the catalogue by using the
472
+ `exported_resources` accessor in combination with any of the standard matchers.
473
+
474
+ You can use `exported_resources` as the subject of a child context:
475
+
476
+ ```ruby
477
+ context 'exported resources' do
478
+ subject { exported_resources }
479
+
480
+ it { is_expected.to contain_file('foo') }
481
+ end
482
+ ```
483
+
484
+ You can also use `exported_resources` directly in a test:
485
+
486
+ ```ruby
487
+ it { expect(exported_resources).to contain_file('foo') }
488
+ ```
489
+
490
+ #### Testing applications
491
+
492
+ Applications in some ways behave as defined resources, but are more complex so
493
+ require a number of elements already documented above to be combined for testing.
494
+
495
+ A full example of the simplest rspec test for a single component application:
496
+
497
+ ```ruby
498
+ require 'spec_helper'
499
+
500
+ describe 'orch_app' do
501
+ let(:node) { 'my_node' }
502
+ let(:title) { 'my_awesome_app' }
503
+ let(:params) do
504
+ {
505
+ :nodes => {
506
+ ref('Node', node) => ref('Orch_app::Db', title),
507
+ }
508
+ }
509
+ end
510
+
511
+ it { should compile }
512
+ it { should contain_orch_app(title) }
513
+ end
514
+ ```
515
+
516
+ Each piece is required:
517
+
518
+ * You must turn on app_management during testing for the handling to work
519
+ * The `:node` definition is required to be set so later on you can reference it in the `:nodes` argument within `:params`
520
+ * Applications act like defined resources, and each require a `:title` to be defined
521
+ * The `:nodes` key in `:params` requires the use of node reference mappings to resource
522
+ mappings. The `ref` keyword allows you to provide these (a normal string will not work).
523
+
524
+ Beyond these requirements, the very basic `should compile` test and other matchers
525
+ as you would expect will work the same as classes and defined resources.
526
+
527
+ **Note:** for the moment, cross-node support is not available and will return an error.
528
+ Ensure you model your tests to be single-node for the time being.
529
+
432
530
  ## Functions
433
531
 
434
532
  ### Matchers
@@ -533,6 +631,20 @@ before(:each) { scope.expects(:lookupvar).with('some_variable').returns('some_va
533
631
  it { is_expected.to run.with_params('...').and_return('...') }
534
632
  ```
535
633
 
634
+ Note that this does not work when testing manifests which use custom functions. Instead,
635
+ you'll need to create a replacement function directly.
636
+
637
+ ```ruby
638
+ before(:each) do
639
+ Puppet::Parser::Functions.newfunction(:custom_function, :type => :rvalue) { |args|
640
+ raise ArgumentError, 'expected foobar' unless args[0] == 'foobar'
641
+ 'expected value'
642
+ }
643
+ end
644
+
645
+ ```
646
+
647
+
536
648
  ## Hiera integration
537
649
 
538
650
  ### Configuration
@@ -601,16 +713,30 @@ spec/fixtures/hiera/hiera.yaml
601
713
  ## Producing coverage reports
602
714
 
603
715
  You can output a basic resource coverage report with the following in
604
- you spec file.
716
+ your `spec_helper.rb`
605
717
 
606
718
  ```ruby
607
- at_exit { RSpec::Puppet::Coverage.report! }
719
+ RSpec.configure do |c|
720
+ c.after(:suite) do
721
+ RSpec::Puppet::Coverage.report!
722
+ end
723
+ end
608
724
  ```
609
725
 
610
726
  This checks which Puppet resources have been explicitly checked as part
611
727
  of the current test run and outputs both a coverage percentage and a
612
728
  list of untouched resources.
613
729
 
730
+ A desired code coverage level can be provided. If this level is not achieved, a test failure will be raised. This can be used with a CI service, such as Jenkins or Bamboo, to enforce code coverage. The following example requires the code coverage to be at least 95%.
731
+
732
+ ```ruby
733
+ RSpec.configure do |c|
734
+ c.after(:suite) do
735
+ RSpec::Puppet::Coverage.report!(95)
736
+ end
737
+ end
738
+ ```
739
+
614
740
  ## Related projects
615
741
 
616
742
  * [puppetlabs_spec_helper](https://github.com/puppetlabs/puppetlabs_spec_helper): shared spec helpers to setup puppet
@@ -0,0 +1,212 @@
1
+ module RSpec::Puppet
2
+ module Adapters
3
+
4
+ class Base
5
+ # Set up all Puppet settings applicable for this Puppet version
6
+ #
7
+ # @param example_group [RSpec::Core::ExampleGroup] The RSpec context to use for local settings
8
+ # @return [void]
9
+ def setup_puppet(example_group)
10
+ settings_map.each do |puppet_setting, rspec_setting|
11
+ set_setting(example_group, puppet_setting, rspec_setting)
12
+ end
13
+ @environment_name = example_group.environment
14
+ end
15
+
16
+ # Set up a specific Puppet setting.
17
+ # configuration setting.
18
+ #
19
+ # Puppet setting values can be taken from the global RSpec configuration, or from the currently
20
+ # executing RSpec context. When a setting is specified both in the global configuration and in
21
+ # the example group, the setting in the example group is preferred.
22
+ #
23
+ # @example Configuring a Puppet setting from a global RSpec configuration value
24
+ # RSpec.configure do |config|
25
+ # config.parser = "future"
26
+ # end
27
+ # # => Puppet[:parser] will be future
28
+ #
29
+ # @example Configuring a Puppet setting from within an RSpec example group
30
+ # RSpec.describe 'my_module::my_class', :type => :class do
31
+ # let(:module_path) { "/Users/luke/modules" }
32
+ # #=> Puppet[:modulepath] will be "/Users/luke/modules"
33
+ # end
34
+ #
35
+ # @example Configuring a Puppet setting with both a global RSpec configuration and local context
36
+ # RSpec.configure do |config|
37
+ # config.confdir = "/etc/puppet"
38
+ # end
39
+ # RSpec.describe 'my_module', :type => :class do
40
+ # # Puppet[:confdir] will be "/etc/puppet"
41
+ # end
42
+ # RSpec.describe 'my_module::my_class', :type => :class do
43
+ # let(:confdir) { "/etc/puppetlabs/puppet" }
44
+ # # => Puppet[:confdir] will be "/etc/puppetlabs/puppet" in this example group
45
+ # end
46
+ # RSpec.describe 'my_module::my_define', :type => :define do
47
+ # # Puppet[:confdir] will be "/etc/puppet" again
48
+ # end
49
+ #
50
+ # @param example_group [RSpec::Core::ExampleGroup] The RSpec context to use for local settings
51
+ # @param puppet_setting [Symbol] The name of the Puppet setting to configure
52
+ # @param rspec_setting [Symbol] The name of the RSpec context specific or global setting to use
53
+ # @return [void]
54
+ def set_setting(example_group, puppet_setting, rspec_setting)
55
+ if example_group.respond_to?(rspec_setting)
56
+ value = example_group.send(rspec_setting)
57
+ else
58
+ value = RSpec.configuration.send(rspec_setting)
59
+ end
60
+ begin
61
+ Puppet[puppet_setting] = value
62
+ rescue ArgumentError
63
+ # TODO: this silently swallows errors when applying settings that the current
64
+ # Puppet version does not accept, which means that user specified settings
65
+ # are ignored. This may lead to suprising behavior for users.
66
+ end
67
+ end
68
+
69
+ def catalog(node, exported)
70
+ if exported
71
+ # Use the compiler directly to skip the filtering done by the indirector
72
+ Puppet::Parser::Compiler.compile(node).filter { |r| !r.exported? }
73
+ else
74
+ Puppet::Resource::Catalog.indirection.find(node.name, :use_node => node)
75
+ end
76
+ end
77
+
78
+ def current_environment
79
+ Puppet::Node::Environment.new(@environment_name)
80
+ end
81
+
82
+ def settings_map
83
+ [
84
+ [:modulepath, :module_path],
85
+ [:config, :config],
86
+ [:confdir, :confdir],
87
+ ]
88
+ end
89
+
90
+ def modulepath
91
+ Puppet[:modulepath].split(File::PATH_SEPARATOR)
92
+ end
93
+
94
+ # @return [String, nil] The path to the Puppet manifest if it is present and set, nil otherwise.
95
+ def manifest
96
+ Puppet[:manifest]
97
+ end
98
+ end
99
+
100
+ class Adapter4X < Base
101
+ def setup_puppet(example_group)
102
+ super
103
+
104
+ if rspec_modulepath = RSpec.configuration.module_path
105
+ modulepath = rspec_modulepath.split(File::PATH_SEPARATOR)
106
+ else
107
+ modulepath = Puppet[:environmentpath].split(File::PATH_SEPARATOR).map do |path|
108
+ File.join(path, 'fixtures', 'modules')
109
+ end
110
+ end
111
+
112
+ if rspec_manifest = RSpec.configuration.manifest
113
+ manifest = rspec_manifest
114
+ else
115
+ manifest_paths = Puppet[:environmentpath].split(File::PATH_SEPARATOR).map do |path|
116
+ File.join(path, 'fixtures', 'manifests')
117
+ end
118
+
119
+ manifest = manifest_paths.find do |path|
120
+ File.exist?(path)
121
+ end
122
+
123
+ manifest ||= Puppet::Node::Environment::NO_MANIFEST
124
+ end
125
+
126
+ env = Puppet::Node::Environment.create(@environment_name, modulepath, manifest)
127
+ loader = Puppet::Environments::Static.new(env)
128
+
129
+ Puppet.push_context(
130
+ {
131
+ :environments => loader,
132
+ :current_environment => env
133
+ },
134
+ "Setup rspec-puppet environments"
135
+ )
136
+ end
137
+
138
+ def settings_map
139
+ super.concat([
140
+ [:environmentpath, :environmentpath],
141
+ [:hiera_config, :hiera_config],
142
+ [:strict_variables, :strict_variables],
143
+ ])
144
+ end
145
+
146
+ def catalog(node, exported)
147
+ node.environment = current_environment
148
+ super
149
+ end
150
+
151
+ def current_environment
152
+ Puppet.lookup(:current_environment)
153
+ end
154
+
155
+ def modulepath
156
+ current_environment.modulepath
157
+ end
158
+
159
+ # Puppet 4.0 specially handles environments that don't have a manifest set, so we check for the no manifest value
160
+ # and return nil when it is set.
161
+ #
162
+ # @return [String, nil] The path to the Puppet manifest if it is present and set, nil otherwise.
163
+ def manifest
164
+ m = current_environment.manifest
165
+ if m == Puppet::Node::Environment::NO_MANIFEST
166
+ nil
167
+ else
168
+ m
169
+ end
170
+ end
171
+ end
172
+
173
+ class Adapter3X < Base
174
+ def settings_map
175
+ super.concat([
176
+ [:manifestdir, :manifest_dir],
177
+ [:manifest, :manifest],
178
+ [:templatedir, :template_dir],
179
+ [:hiera_config, :hiera_config],
180
+ [:parser, :parser],
181
+ [:trusted_node_data, :trusted_node_data],
182
+ [:ordering, :ordering],
183
+ [:stringify_facts, :stringify_facts],
184
+ [:strict_variables, :strict_variables],
185
+ ])
186
+ end
187
+ end
188
+
189
+ class Adapter27 < Base
190
+ def settings_map
191
+ super.concat([
192
+ [:manifestdir, :manifest_dir],
193
+ [:manifest, :manifest],
194
+ [:templatedir, :template_dir],
195
+ ])
196
+ end
197
+ end
198
+
199
+ def self.get
200
+ [
201
+ [4.0, Adapter4X],
202
+ [3.0, Adapter3X],
203
+ [2.7, Adapter27]
204
+ ].each do |(version, klass)|
205
+ if Puppet.version.to_f >= version
206
+ return klass.new
207
+ end
208
+ end
209
+ raise "Puppet version #{Puppet.version.to_f} is not supported."
210
+ end
211
+ end
212
+ end
@@ -7,9 +7,13 @@ module RSpec::Puppet
7
7
  extend Forwardable
8
8
  def_delegators(:instance, :add, :cover!, :report!,
9
9
  :filters, :add_filter, :add_from_catalog)
10
- end
11
10
 
12
- include Singleton
11
+ attr_writer :instance
12
+
13
+ def instance
14
+ @instance ||= new
15
+ end
16
+ end
13
17
 
14
18
  def initialize
15
19
  @collection = {}
@@ -44,18 +48,8 @@ module RSpec::Puppet
44
48
  end
45
49
  end
46
50
 
47
- def report!
48
- report = {}
49
-
50
- report[:total] = @collection.size
51
- report[:touched] = @collection.count { |_, resource| resource.touched? }
52
- report[:untouched] = report[:total] - report[:touched]
53
- report[:coverage] = sprintf("%5.2f", ((report[:touched].to_f/report[:total].to_f)*100))
54
-
55
- report[:detailed] = Hash[*@collection.map do |name, wrapper|
56
- [name, wrapper.to_hash]
57
- end.flatten]
58
-
51
+ def report!(coverage_desired = nil)
52
+ report = results
59
53
  puts <<-EOH.gsub(/^ {8}/, '')
60
54
 
61
55
  Total resources: #{report[:total]}
@@ -68,16 +62,48 @@ module RSpec::Puppet
68
62
  Untouched resources:
69
63
 
70
64
  #{
71
- untouched_resources = report[:detailed].reject do |_,rsrc|
72
- rsrc["touched"]
65
+ untouched_resources = report[:resources].reject do |_,rsrc|
66
+ rsrc[:touched]
73
67
  end
74
68
  untouched_resources.inject([]) do |memo, (name,_)|
75
69
  memo << " #{name}"
76
70
  end.sort.join("\n")
77
71
  }
78
72
  EOH
73
+ if coverage_desired
74
+ coverage_test(coverage_desired, report[:coverage])
75
+ end
76
+ end
77
+ end
78
+
79
+ def coverage_test(coverage_desired, coverage_actual)
80
+ if coverage_desired.is_a?(Numeric) && coverage_desired.to_f <= 100.00 && coverage_desired.to_f >= 0.0
81
+ coverage_test = RSpec.describe("Code coverage.")
82
+ coverage_results = coverage_test.example("Must be at least #{coverage_desired}% of code coverage") {
83
+ expect( coverage_actual.to_f ).to be >= coverage_desired.to_f
84
+ }
85
+ coverage_test.run
86
+ passed = coverage_results.execution_result.status == :passed
87
+
88
+ RSpec.configuration.reporter.example_failed coverage_results unless passed
89
+ else
90
+ puts "The desired coverage must be 0 <= x <= 100, not '#{coverage_desired.inspect}'"
79
91
  end
92
+ end
93
+
94
+ def results
95
+ report = {}
96
+
97
+ report[:total] = @collection.size
98
+ report[:touched] = @collection.count { |_, resource| resource.touched? }
99
+ report[:untouched] = report[:total] - report[:touched]
100
+ report[:coverage] = "%5.2f" % ((report[:touched].to_f / report[:total].to_f) * 100)
101
+
102
+ report[:resources] = Hash[*@collection.map do |name, wrapper|
103
+ [name, wrapper.to_hash]
104
+ end.flatten]
80
105
 
106
+ report
81
107
  end
82
108
 
83
109
  private
@@ -122,16 +148,11 @@ module RSpec::Puppet
122
148
  #
123
149
  # @return [Array<String>]
124
150
  def module_paths(test_module)
125
- if Puppet.version.to_f >= 4.0
126
- modulepath = RSpec.configuration.module_path || File.join(Puppet[:environmentpath], 'fixtures', 'modules')
127
- manifest = RSpec.configuration.manifest || File.join(Puppet[:environmentpath], 'fixtures', 'manifests', 'site.pp')
128
- paths = [File.join(modulepath, test_module, 'manifests'), manifest]
129
- else
130
- paths = Puppet[:modulepath].split(File::PATH_SEPARATOR).map do |dir|
131
- File.join(dir, test_module, 'manifests')
132
- end
133
- paths << Puppet[:manifest]
151
+ adapter = RSpec.configuration.adapter
152
+ paths = adapter.modulepath.map do |dir|
153
+ File.join(dir, test_module, 'manifests')
134
154
  end
155
+ paths << adapter.manifest if adapter.manifest
135
156
  paths
136
157
  end
137
158
 
@@ -156,7 +177,7 @@ module RSpec::Puppet
156
177
 
157
178
  def to_hash
158
179
  {
159
- 'touched' => touched?,
180
+ :touched => touched?,
160
181
  }
161
182
  end
162
183
 
@@ -0,0 +1,19 @@
1
+ module RSpec::Puppet
2
+ # This module provides support for the application type
3
+ module ApplicationExampleGroup
4
+ include RSpec::Puppet::ManifestMatchers
5
+ include RSpec::Puppet::Support
6
+
7
+ def catalogue
8
+ @catalogue ||= load_catalogue(:application)
9
+ end
10
+
11
+ def exported_resources
12
+ lambda { load_catalogue(:application, true) }
13
+ end
14
+
15
+ def rspec_puppet_cleanup
16
+ @catalogue = nil
17
+ end
18
+ end
19
+ end
@@ -7,6 +7,10 @@ module RSpec::Puppet
7
7
  @catalogue ||= load_catalogue(:class)
8
8
  end
9
9
 
10
+ def exported_resources
11
+ lambda { load_catalogue(:class, true) }
12
+ end
13
+
10
14
  def rspec_puppet_cleanup
11
15
  @catalogue = nil
12
16
  end
@@ -7,6 +7,10 @@ module RSpec::Puppet
7
7
  @catalogue ||= load_catalogue(:define)
8
8
  end
9
9
 
10
+ def exported_resources
11
+ lambda { load_catalogue(:define, true) }
12
+ end
13
+
10
14
  def rspec_puppet_cleanup
11
15
  @catalogue = nil
12
16
  end
@@ -4,27 +4,87 @@ module RSpec::Puppet
4
4
  include RSpec::Puppet::ManifestMatchers
5
5
  include RSpec::Puppet::Support
6
6
 
7
- def subject
8
- function_name = self.class.top_level_description.downcase
7
+ class V4FunctionWrapper
8
+ attr_reader :func, :func_name
9
9
 
10
- vardir = setup_puppet
10
+ def initialize(name, func, overrides)
11
+ @func_name = name
12
+ @func = func
13
+ @overrides = overrides
14
+ end
11
15
 
12
- if Puppet.version.to_f >= 4.0
13
- env = build_4x_environment(environment)
14
- loader = Puppet::Pops::Loaders.new(env)
15
- func = loader.private_environment_loader.load(:function,function_name)
16
- return func if func
16
+ # This method is used by the `run` matcher to trigger the function execution, and provides a uniform interface across all puppet versions.
17
+ def execute(*args)
18
+ Puppet.override(@overrides, "rspec-test scope") do
19
+ @func.call(@overrides[:global_scope], *args)
20
+ end
17
21
  end
18
22
 
19
- # Return the method instance for the function. This can be used with
20
- # method.call
21
- if env
22
- return nil unless Puppet::Parser::Functions.function(function_name,env)
23
- else
24
- return nil unless Puppet::Parser::Functions.function(function_name)
23
+ # compatibility alias for existing tests
24
+ def call(scope, *args)
25
+ RSpec.deprecate("subject.call", :replacement => "is_expected.to run.with().and_raise_error(), or execute()")
26
+ execute(*args)
27
+ end
28
+ end
29
+
30
+ class V3FunctionWrapper
31
+ attr_accessor :func_name
32
+
33
+ def initialize(name, func)
34
+ @func_name = name
35
+ @func = func
36
+ end
37
+
38
+ # This method is used by the `run` matcher to trigger the function execution, and provides a uniform interface across all puppet versions.
39
+ def execute(*args)
40
+ if args.nil?
41
+ @func.call
42
+ else
43
+ @func.call(args)
44
+ end
45
+ end
46
+
47
+ # This method was formerly used by the `run` matcher to trigger the function execution, and provides puppet versions dependant interface.
48
+ def call(*args)
49
+ RSpec.deprecate("subject.call", :replacement => "is_expected.to run.with().and_raise_error(), or execute()")
50
+ if args.nil?
51
+ @func.call
52
+ else
53
+ @func.call(*args)
54
+ end
55
+ end
56
+ end
57
+
58
+ # (at least) rspec 3.5 doesn't seem to memoize `subject` when called from
59
+ # a before(:each) hook, so we need to memoize it ourselves.
60
+ def subject
61
+ @subject ||= find_function
62
+ end
63
+
64
+ def find_function
65
+ function_name = self.class.top_level_description.downcase
66
+
67
+ with_vardir do
68
+ env = adapter.current_environment
69
+
70
+ if Puppet.version.to_f >= 4.0
71
+ context_overrides = compiler.context_overrides
72
+ func = nil
73
+ Puppet.override(context_overrides, "rspec-test scope") do
74
+ loader = Puppet::Pops::Loaders.new(env)
75
+ func = V4FunctionWrapper.new(function_name, loader.private_environment_loader.load(:function, function_name), context_overrides)
76
+ @scope = context_overrides[:global_scope]
77
+ end
78
+
79
+ return func if func.func
80
+ end
81
+
82
+ if Puppet::Parser::Functions.function(function_name)
83
+ V3FunctionWrapper.new(function_name, scope.method("function_#{function_name}".intern))
84
+ else
85
+ nil
86
+ end
25
87
  end
26
- FileUtils.rm_rf(vardir) if File.directory?(vardir)
27
- scope.method("function_#{function_name}".intern)
28
88
  end
29
89
 
30
90
  def scope
@@ -36,6 +96,7 @@ module RSpec::Puppet
36
96
  end
37
97
 
38
98
  def rspec_puppet_cleanup
99
+ @subject = nil
39
100
  @catalogue = nil
40
101
  @compiler = nil
41
102
  @scope = nil
@@ -71,7 +132,9 @@ module RSpec::Puppet
71
132
  end
72
133
 
73
134
  def build_scope(compiler, node_name)
74
- if Puppet.version =~ /^2\.[67]/
135
+ if Puppet.version.to_f >= 4.0
136
+ return compiler.context_overrides[:global_scope]
137
+ elsif Puppet.version =~ /^2\.[67]/
75
138
  # loadall should only be necessary prior to 3.x
76
139
  # Please note, loadall needs to happen first when creating a scope, otherwise
77
140
  # you might receive undefined method `function_*' errors
@@ -87,11 +150,7 @@ module RSpec::Puppet
87
150
  end
88
151
 
89
152
  def build_node(name, opts = {})
90
- if Puppet.version.to_f >= 4.0
91
- node_environment = build_4x_environment(environment)
92
- else
93
- node_environment = Puppet::Node::Environment.new(environment)
94
- end
153
+ node_environment = adapter.current_environment
95
154
  opts.merge!({:environment => node_environment})
96
155
  Puppet::Node.new(name, opts)
97
156
  end
@@ -7,6 +7,10 @@ module RSpec::Puppet
7
7
  @catalogue ||= load_catalogue(:host)
8
8
  end
9
9
 
10
+ def exported_resources
11
+ lambda { load_catalogue(:host, true) }
12
+ end
13
+
10
14
  def rspec_puppet_cleanup
11
15
  @catalogue = nil
12
16
  end
@@ -5,6 +5,7 @@ require 'rspec-puppet/example/function_example_group'
5
5
  require 'rspec-puppet/example/host_example_group'
6
6
  require 'rspec-puppet/example/type_example_group'
7
7
  require 'rspec-puppet/example/provider_example_group'
8
+ require 'rspec-puppet/example/application_example_group'
8
9
 
9
10
  RSpec::configure do |c|
10
11
 
@@ -31,6 +32,9 @@ RSpec::configure do |c|
31
32
  c.include RSpec::Puppet::ProviderExampleGroup, :type => :provider, :example_group => {
32
33
  :file_path => c.escaped_path(%w[spec providers])
33
34
  }
35
+ c.include RSpec::Puppet::ApplicationExampleGroup, :type => :application, :example_group => {
36
+ :file_path => c.escaped_path(%w[spec applications])
37
+ }
34
38
  else
35
39
  c.include RSpec::Puppet::DefineExampleGroup, :type => :define, :file_path => c.escaped_path(%w[spec defines])
36
40
  c.include RSpec::Puppet::ClassExampleGroup, :type => :class, :file_path => c.escaped_path(%w[spec classes])
@@ -38,6 +42,7 @@ RSpec::configure do |c|
38
42
  c.include RSpec::Puppet::HostExampleGroup, :type => :host, :file_path => c.escaped_path(%w[spec hosts])
39
43
  c.include RSpec::Puppet::TypeExampleGroup, :type => :type, :file_path => c.escaped_path(%w[spec types])
40
44
  c.include RSpec::Puppet::ProviderExampleGroup, :type => :provider, :file_path => c.escaped_path(%w[spec providers])
45
+ c.include RSpec::Puppet::ApplicationExampleGroup, :type => :application, :file_path => c.escaped_path(%w[spec applications])
41
46
  end
42
47
 
43
48
  # Hook for each example group type to remove any caches or instance variables, since they will remain
@@ -3,23 +3,11 @@ module RSpec::Puppet
3
3
  class Run
4
4
  def matches?(func_obj)
5
5
  @func_obj = func_obj
6
- if @params
7
- if Puppet.version.to_f >= 4.0 and ! @func_obj.respond_to?(:receiver)
8
- @func = lambda { func_obj.call({}, *@params) }
9
- else
10
- @func = lambda { func_obj.call(@params) }
11
- end
12
- else
13
- if Puppet.version.to_f >= 4.0 and ! @func_obj.respond_to?(:receiver)
14
- @func = lambda { func_obj.call({}) }
15
- else
16
- @func = lambda { func_obj.call }
17
- end
18
- end
19
6
 
20
7
  @has_returned = false
21
8
  begin
22
- @actual_return = @func.call
9
+ # `*nil` does not evaluate to "no params" on ruby 1.8 :-(
10
+ @actual_return = @params.nil? ? @func_obj.execute : @func_obj.execute(*@params)
23
11
  @has_returned = true
24
12
  rescue Exception => e
25
13
  @actual_error = e
@@ -113,11 +101,7 @@ module RSpec::Puppet
113
101
 
114
102
  private
115
103
  def func_name
116
- if Puppet.version.to_f >= 4.0 and ! @func_ob and ! @func_obj.respond_to?(:receiver)
117
- @func_name ||= @func_obj.class.name
118
- else
119
- @func_name ||= @func_obj.name.to_s.gsub(/^function_/, '')
120
- end
104
+ @func_obj.func_name
121
105
  end
122
106
 
123
107
  def func_params
@@ -129,9 +113,9 @@ module RSpec::Puppet
129
113
  ''
130
114
  elsif @actual_error
131
115
  if @has_expected_return
132
- " instead of raising #{@actual_error.class.inspect}(#{@actual_error})"
116
+ " instead of raising #{@actual_error.class.inspect}(#{@actual_error})\n#{@actual_error.backtrace.join("\n")}"
133
117
  else
134
- " instead of #{@actual_error.class.inspect}(#{@actual_error})"
118
+ " instead of #{@actual_error.class.inspect}(#{@actual_error})\n#{@actual_error.backtrace.join("\n")}"
135
119
  end
136
120
  else # function has returned
137
121
  if @has_expected_error
@@ -0,0 +1,16 @@
1
+ module RSpec::Puppet
2
+ # A raw string object, that is used by helpers to allow consumers to return non-quoted strings
3
+ # as part of their params section.
4
+ class RawString
5
+ # Create a new RawString object
6
+ # @param [String] value string to wrap
7
+ def initialize(value)
8
+ @value = value
9
+ end
10
+
11
+ # @return [String] raw string
12
+ def inspect
13
+ @value
14
+ end
15
+ end
16
+ end
@@ -34,7 +34,7 @@ module RSpec::Puppet
34
34
 
35
35
  safe_touch('spec/fixtures/manifests/site.pp')
36
36
 
37
- %w(data manifests lib files templates).each do |dir|
37
+ %w(data manifests lib files templates functions types).each do |dir|
38
38
  if File.exist? dir
39
39
  safe_make_symlink("../../../../#{dir}", "spec/fixtures/modules/#{module_name}/#{dir}")
40
40
  end
@@ -1,4 +1,7 @@
1
1
  require 'rspec-puppet/cache'
2
+ require 'rspec-puppet/adapters'
3
+ require 'rspec-puppet/raw_string'
4
+
2
5
  module RSpec::Puppet
3
6
  module Support
4
7
 
@@ -12,32 +15,31 @@ module RSpec::Puppet
12
15
  'rp_env'
13
16
  end
14
17
 
15
- def load_catalogue(type)
16
- vardir = setup_puppet
17
-
18
- if Puppet.version.to_f >= 4.0 or Puppet[:parser] == 'future'
19
- code = [pre_cond, test_manifest(type)].compact.join("\n")
20
- else
21
- code = [import_str, pre_cond, test_manifest(type)].compact.join("\n")
22
- end
18
+ def load_catalogue(type, exported = false)
19
+ with_vardir do
20
+ if Puppet.version.to_f >= 4.0 or Puppet[:parser] == 'future'
21
+ code = [pre_cond, test_manifest(type)].compact.join("\n")
22
+ else
23
+ code = [import_str, pre_cond, test_manifest(type)].compact.join("\n")
24
+ end
23
25
 
24
- node_name = nodename(type)
26
+ node_name = nodename(type)
25
27
 
26
- hiera_config_value = self.respond_to?(:hiera_config) ? hiera_config : nil
28
+ hiera_config_value = self.respond_to?(:hiera_config) ? hiera_config : nil
27
29
 
28
- catalogue = build_catalog(node_name, facts_hash(node_name), hiera_config_value, code)
30
+ catalogue = build_catalog(node_name, facts_hash(node_name), hiera_config_value, code, exported)
29
31
 
30
- test_module = class_name.split('::').first
31
- RSpec::Puppet::Coverage.add_filter(type.to_s, self.class.description)
32
- RSpec::Puppet::Coverage.add_from_catalog(catalogue, test_module)
32
+ test_module = class_name.split('::').first
33
+ RSpec::Puppet::Coverage.add_filter(type.to_s, self.class.description)
34
+ RSpec::Puppet::Coverage.add_from_catalog(catalogue, test_module)
33
35
 
34
- FileUtils.rm_rf(vardir) if File.directory?(vardir)
35
- catalogue
36
+ catalogue
37
+ end
36
38
  end
37
39
 
38
40
  def import_str
39
41
  import_str = ""
40
- Puppet[:modulepath].split(File::PATH_SEPARATOR).each { |d|
42
+ adapter.modulepath.each { |d|
41
43
  if File.exists?(File.join(d, 'manifests', 'init.pp'))
42
44
  path_to_manifest = File.join([
43
45
  d,
@@ -51,7 +53,7 @@ module RSpec::Puppet
51
53
  ].join("\n")
52
54
  break
53
55
  elsif File.exists?(d)
54
- import_str = "import '#{Puppet[:manifest]}'\n"
56
+ import_str = "import '#{adapter.manifest}'\n"
55
57
  break
56
58
  end
57
59
  }
@@ -66,6 +68,12 @@ module RSpec::Puppet
66
68
  else
67
69
  "class { '#{class_name}': #{param_str} }"
68
70
  end
71
+ elsif type == :application
72
+ if self.respond_to? :params
73
+ "site { #{class_name} { '#{title}': #{param_str} } }"
74
+ else
75
+ raise ArgumentException, "You need to provide params for an application"
76
+ end
69
77
  elsif type == :define
70
78
  if self.respond_to? :params
71
79
  "#{class_name} { '#{title}': #{param_str} }"
@@ -79,7 +87,7 @@ module RSpec::Puppet
79
87
 
80
88
  def nodename(type)
81
89
  return node if self.respond_to?(:node)
82
- if [:class, :define, :function].include? type
90
+ if [:class, :define, :function, :application].include? type
83
91
  Puppet[:certname]
84
92
  else
85
93
  class_name
@@ -121,14 +129,28 @@ module RSpec::Puppet
121
129
  end
122
130
 
123
131
  def param_str
124
- params.keys.map do |r|
125
- param_val = params[r]
126
- param_val_str = if param_val == :undef
127
- 'undef' # verbatim undef keyword
128
- else
129
- escape_special_chars(param_val.inspect)
130
- end
131
- "#{r.to_s} => #{param_val_str}"
132
+ param_str_from_hash(params)
133
+ end
134
+
135
+ def str_from_value(value)
136
+ case value
137
+ when Hash
138
+ kvs = value.collect do |k,v|
139
+ "#{str_from_value(k)} => #{str_from_value(v)}"
140
+ end.join(", ")
141
+ "{ #{kvs} }"
142
+ when :undef
143
+ 'undef' # verbatim undef keyword
144
+ else
145
+ escape_special_chars(value.inspect)
146
+ end
147
+ end
148
+
149
+ def param_str_from_hash(params_hash)
150
+ # the param_str has special quoting rules, because the top-level keys are the Puppet
151
+ # params, which may not be quoted
152
+ params_hash.collect do |k,v|
153
+ "#{k.to_s} => #{str_from_value(v)}"
132
154
  end.join(', ')
133
155
  end
134
156
 
@@ -136,50 +158,12 @@ module RSpec::Puppet
136
158
  vardir = Dir.mktmpdir
137
159
  Puppet[:vardir] = vardir
138
160
 
139
- if Puppet.version.to_f >= 4.0
140
- settings = [
141
- [:modulepath, :module_path],
142
- [:environmentpath, :environmentpath],
143
- [:config, :config],
144
- [:confdir, :confdir],
145
- [:hiera_config, :hiera_config],
146
- [:strict_variables, :strict_variables],
147
- ]
148
- elsif Puppet.version.to_f >= 3.0
149
- settings = [
150
- [:modulepath, :module_path],
151
- [:manifestdir, :manifest_dir],
152
- [:manifest, :manifest],
153
- [:templatedir, :template_dir],
154
- [:config, :config],
155
- [:confdir, :confdir],
156
- [:hiera_config, :hiera_config],
157
- [:parser, :parser],
158
- [:trusted_node_data, :trusted_node_data],
159
- [:ordering, :ordering],
160
- [:stringify_facts, :stringify_facts],
161
- [:strict_variables, :strict_variables],
162
- ]
163
- else
164
- settings = [
165
- [:modulepath, :module_path],
166
- [:manifestdir, :manifest_dir],
167
- [:manifest, :manifest],
168
- [:templatedir, :template_dir],
169
- [:config, :config],
170
- [:confdir, :confdir],
171
- ]
172
- end
173
- settings.each do |a,b|
174
- value = self.respond_to?(b) ? self.send(b) : RSpec.configuration.send(b)
175
- begin
176
- Puppet[a] = value
177
- rescue ArgumentError
178
- Puppet.settings.setdefaults(:main, {a => {:default => value, :desc => a.to_s}})
179
- end
161
+ # Enable app_management by default for Puppet versions that support it
162
+ if Puppet.version.to_f >= 4.3
163
+ Puppet[:app_management] = true
180
164
  end
181
165
 
182
- Puppet[:modulepath].split(File::PATH_SEPARATOR).map do |d|
166
+ adapter.modulepath.map do |d|
183
167
  Dir["#{d}/*/lib"].entries
184
168
  end.flatten.each do |lib|
185
169
  $LOAD_PATH << lib
@@ -188,7 +172,16 @@ module RSpec::Puppet
188
172
  vardir
189
173
  end
190
174
 
191
- def build_catalog_without_cache(nodename, facts_val, hiera_config_val, code)
175
+ def with_vardir
176
+ begin
177
+ vardir = setup_puppet
178
+ return yield(vardir) if block_given?
179
+ ensure
180
+ FileUtils.rm_rf(vardir) if File.directory?(vardir)
181
+ end
182
+ end
183
+
184
+ def build_catalog_without_cache(nodename, facts_val, hiera_config_val, code, exported)
192
185
 
193
186
  # If we're going to rebuild the catalog, we should clear the cached instance
194
187
  # of Hiera that Puppet is using. This opens the possibility of the catalog
@@ -207,19 +200,7 @@ module RSpec::Puppet
207
200
 
208
201
  node_obj = Puppet::Node.new(nodename, { :parameters => facts_val, :facts => node_facts })
209
202
 
210
- # trying to be compatible with 2.7 as well as 2.6
211
- if Puppet::Resource::Catalog.respond_to? :find
212
- Puppet::Resource::Catalog.find(node_obj.name, :use_node => node_obj)
213
- elsif Puppet.version.to_f >= 4.0
214
- env = build_4x_environment(environment)
215
- loader = Puppet::Environments::Static.new(env)
216
- Puppet.override({:environments => loader}, 'Setup test environment') do
217
- node_obj.environment = env
218
- Puppet::Resource::Catalog.indirection.find(node_obj.name, :use_node => node_obj)
219
- end
220
- else
221
- Puppet::Resource::Catalog.indirection.find(node_obj.name, :use_node => node_obj)
222
- end
203
+ adapter.catalog(node_obj, exported)
223
204
  end
224
205
 
225
206
  def stub_facts!(facts)
@@ -259,10 +240,19 @@ module RSpec::Puppet
259
240
  end
260
241
  end
261
242
 
262
- def build_4x_environment(name)
263
- modulepath = RSpec.configuration.module_path || File.join(Puppet[:environmentpath], 'fixtures', 'modules')
264
- manifest = RSpec.configuration.manifest || File.join(Puppet[:environmentpath], 'fixtures', 'manifests')
265
- Puppet::Node::Environment.create(name, [modulepath], manifest)
243
+ # Helper to return a resource/node reference, so it gets translated in params to a raw string
244
+ # without quotes.
245
+ #
246
+ # @param [String] type reference type
247
+ # @param [String] title reference title
248
+ # @return [RSpec::Puppet::RawString] return a new RawString with the type/title populated correctly
249
+ def ref(type, title)
250
+ return RSpec::Puppet::RawString.new("#{type}['#{title}']")
266
251
  end
252
+
253
+ # @!attribute [r] adapter
254
+ # @api private
255
+ # @return [Class < RSpec::Puppet::Adapters::Base]
256
+ attr_accessor :adapter
267
257
  end
268
258
  end
data/lib/rspec-puppet.rb CHANGED
@@ -7,6 +7,7 @@ require 'rspec-puppet/matchers'
7
7
  require 'rspec-puppet/example'
8
8
  require 'rspec-puppet/setup'
9
9
  require 'rspec-puppet/coverage'
10
+ require 'rspec-puppet/adapters'
10
11
 
11
12
  begin
12
13
  require 'puppet/test/test_helper'
@@ -28,6 +29,7 @@ RSpec.configure do |c|
28
29
  c.add_setting :ordering, :default => 'title-hash'
29
30
  c.add_setting :stringify_facts, :default => true
30
31
  c.add_setting :strict_variables, :default => false
32
+ c.add_setting :adapter
31
33
 
32
34
  if defined?(Puppet::Test::TestHelper)
33
35
  begin
@@ -64,4 +66,12 @@ RSpec.configure do |c|
64
66
  end
65
67
  end
66
68
  end
69
+
70
+ c.before :each do
71
+ if self.class.ancestors.include? RSpec::Puppet::Support
72
+ @adapter = RSpec::Puppet::Adapters.get
73
+ @adapter.setup_puppet(self)
74
+ c.adapter = adapter
75
+ end
76
+ end
67
77
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rspec-puppet
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.3.2
4
+ version: 2.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tim Sharpe
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2016-01-26 00:00:00.000000000 Z
11
+ date: 2016-10-25 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rspec
@@ -35,10 +35,12 @@ files:
35
35
  - README.md
36
36
  - bin/rspec-puppet-init
37
37
  - lib/rspec-puppet.rb
38
+ - lib/rspec-puppet/adapters.rb
38
39
  - lib/rspec-puppet/cache.rb
39
40
  - lib/rspec-puppet/coverage.rb
40
41
  - lib/rspec-puppet/errors.rb
41
42
  - lib/rspec-puppet/example.rb
43
+ - lib/rspec-puppet/example/application_example_group.rb
42
44
  - lib/rspec-puppet/example/class_example_group.rb
43
45
  - lib/rspec-puppet/example/define_example_group.rb
44
46
  - lib/rspec-puppet/example/function_example_group.rb
@@ -55,6 +57,7 @@ files:
55
57
  - lib/rspec-puppet/matchers/run.rb
56
58
  - lib/rspec-puppet/matchers/type_matchers.rb
57
59
  - lib/rspec-puppet/rake_task.rb
60
+ - lib/rspec-puppet/raw_string.rb
58
61
  - lib/rspec-puppet/setup.rb
59
62
  - lib/rspec-puppet/spec_helper.rb
60
63
  - lib/rspec-puppet/support.rb
@@ -78,7 +81,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
78
81
  version: '0'
79
82
  requirements: []
80
83
  rubyforge_project:
81
- rubygems_version: 2.4.5.1
84
+ rubygems_version: 2.5.1
82
85
  signing_key:
83
86
  specification_version: 4
84
87
  summary: RSpec tests for your Puppet manifests