beaker-testmode_switcher 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: e6ae9b72921551c471f35351e450aef008b10f53
4
+ data.tar.gz: 825aa5ae1c2dd6decad2b64763149d2e1ac4c124
5
+ SHA512:
6
+ metadata.gz: f373d1afbf2f2e985bbf8df6ac7e3e1d1283c1d009bce8697e18bb2df1cd99f3ee2e2ec3d568c42a7227320ed202ea0f0df4d9f5bb2d8bd8bc5b12a61fd51e68
7
+ data.tar.gz: 4ccceec2ffa5f6de7992f6e601496cb82b7c4e234107df27f3a9237dded4a405b7f3cd8b8c61993bd458cb8a0e5ae24860773395bb88ffb1f4ab8f7de4c9d0bb
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.rubocop.yml ADDED
@@ -0,0 +1,27 @@
1
+ # increase the default metric limits to more realistic levels
2
+ Metrics/LineLength:
3
+ Max: 200
4
+
5
+ Metrics/MethodLength:
6
+ Max: 200
7
+
8
+ Metrics/AbcSize:
9
+ Max: 100
10
+
11
+ Metrics/ClassLength:
12
+ Max: 500
13
+
14
+ Metrics/CyclomaticComplexity:
15
+ Max: 20
16
+
17
+ Metrics/PerceivedComplexity:
18
+ Max: 20
19
+
20
+
21
+ # Don't be picky about string quoting
22
+ Style/PercentLiteralDelimiters:
23
+ Enabled: false
24
+
25
+ Style/StringLiterals:
26
+ Enabled: false
27
+
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ language: ruby
2
+ cache: bundler
3
+ bundler_args: --without development
4
+ rvm:
5
+ - 2.2.0
6
+ - 2.0.0
data/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ # Version 0.1.0
2
+
3
+ Initial release.
data/Gemfile ADDED
@@ -0,0 +1,14 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
4
+
5
+ group :test do
6
+ gem 'rubocop', require: false
7
+ end
8
+
9
+ group :development do
10
+ gem 'guard'
11
+ gem 'guard-rake'
12
+ gem 'guard-rspec'
13
+ gem 'pry-coolline'
14
+ end
data/Guardfile ADDED
@@ -0,0 +1,44 @@
1
+ # A sample Guardfile
2
+ # More info at https://github.com/guard/guard#readme
3
+
4
+ ## Uncomment and set this to only include directories you want to watch
5
+ directories %w(lib spec) \
6
+ .select { |d| Dir.exist?(d) ? d : UI.warning("Directory #{d} does not exist") }
7
+
8
+ ## Note: if you are using the `directories` clause above and you are not
9
+ ## watching the project directory ('.'), then you will want to move
10
+ ## the Guardfile to a watched dir and symlink it back, e.g.
11
+ #
12
+ # $ mkdir config
13
+ # $ mv Guardfile config/
14
+ # $ ln -s config/Guardfile .
15
+ #
16
+ # and, you'll have to watch "config/Guardfile" instead of "Guardfile"
17
+
18
+ # Note: The cmd option is now required due to the increasing number of ways
19
+ # rspec may be run, below are examples of the most common uses.
20
+ # * bundler: 'bundle exec rspec'
21
+ # * bundler binstubs: 'bin/rspec'
22
+ # * spring: 'bin/rspec' (This will use spring if running and you have
23
+ # installed the spring binstubs per the docs)
24
+ # * zeus: 'zeus rspec' (requires the server to be started separately)
25
+ # * 'just' rspec: 'rspec'
26
+
27
+ guard :rspec, cmd: "bundle exec rspec" do
28
+ require "guard/rspec/dsl"
29
+ dsl = Guard::RSpec::Dsl.new(self)
30
+
31
+ # RSpec files
32
+ rspec = dsl.rspec
33
+ watch(rspec.spec_helper) { rspec.spec_dir }
34
+ watch(rspec.spec_support) { rspec.spec_dir }
35
+ watch(rspec.spec_files)
36
+
37
+ # Ruby files
38
+ ruby = dsl.ruby
39
+ dsl.watch_spec_files_for(ruby.lib_files)
40
+ end
41
+
42
+ guard 'rake', task: 'default' do
43
+ watch(%r{^manifests\/(.+)\.pp$})
44
+ end
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
data/README.md ADDED
@@ -0,0 +1,72 @@
1
+ # Beaker::TestmodeSwitcher
2
+
3
+ When testing modules with beaker, you need to choose up-front whether to drive the tests using `puppet apply` or a master/agent setup. While choosing the apply approach is tempting due to the reduced resource usage, everyone is running master/agent setups, and those have subtle differences to `puppet apply` that might trip up your code. To solve this dilemma, use this gem to choose the test mode at runtime!
4
+
5
+ Beaker::TestmodeSwitcher supports running tests in master/agent mode, or using `puppet apply` or locally without any setup.
6
+
7
+ ## Usage
8
+
9
+ Set up you module for beaker testing as usual. Additionally add
10
+
11
+ ```ruby
12
+ gem 'beaker-testmode_switcher'
13
+ ```
14
+
15
+ to the `:system_tests` group in your module's Gemfile. Add
16
+
17
+ ```ruby
18
+ require 'beaker/testmode_switcher/dsl'
19
+ ```
20
+
21
+ to your `spec/spec_helper_acceptance.rb` to enable the DSL extensions. Instead of using `#apply_manifest_on` or `#run_agent_on` you can now use `#execute_manifest_on` and - depending on the test mode - will upload and execute the manifest on the right node(s).
22
+
23
+ The `BEAKER_TESTMODE` environment variable determines how the tests are run:
24
+
25
+ * `local`: No VMs are provisioned and tests are run with `puppet apply` using the context of your test runner. This mode uses the least resources and is great for development, but may require running the tests as root and could trash the system.
26
+ * `apply`: VMs are provisioned as normal (determined by the nodeset) and tests are run with `puppet apply` on the specified node. This mode only requires a single VM and is great for running the tests in an isolated environment. When the nodeset has more than one node, exactly one has to have the 'default' role assigned. This will be the node to execute the manifests.
27
+ * `agent`: VMs are provisioned as normal (determined by the nodeset). When running tests, the manifest is uploaded to the master and a full `puppet agent` run is kicked off on the specified node. This mode requires multiple VMs and a more involved provisioning step, but the tests run in a very production-like environment to ensure highest fidelity of the test results. The nodeset needs to contain one node with the 'master' role assigned. This will be the node to receive the manifest. When the nodeset has more than one node, exactly one has to have the 'default' role assigned. This will be the node to execute the puppet agent.
28
+
29
+ ## Reference
30
+
31
+ This experimental version supports only a minimal set of functionality from the beaker DSL:
32
+
33
+ * `create_remote_file_ex(file_path, file_content, opts = {})`: Creates a file at `file_path` with the content specified in `file_content` on the default node. `opts` can have the keys `:mode`, `:user`, and `:group` to specify the permissions, owner, and group respectively.
34
+
35
+ * `execute_manifest(manifest, opts = {})`: Execute the manifest on the default node. Depending on the `BEAKER_TESTMODE` environment variable, this may use `puppet agent` or `puppet apply`.
36
+ `opts` keys:
37
+ * `:debug`, `:trace`, `:noop`: set to true to enable the puppet option of the same name.
38
+ * `:dry_run`: set to true to skip executing the actual command.
39
+ * `:environment`: pass environment variables for the command as a hash.
40
+
41
+ * `resource(type, name, opts = {})`: Runs `puppet resource` with the specified `type` and `name` arguments.
42
+ `opts` keys:
43
+ * `:debug`, `:trace`, `:noop`: set to true to enable the puppet option of the same name.
44
+ * `:values`: pass a hash of key/value pairs which is passed on the commandline to `puppet resource` to influence the specified resource.
45
+ * `:dry_run`: set to true to skip executing the actual command.
46
+ * `:environment`: pass environment variables for the command as a hash.
47
+
48
+ * `scp_to_ex(from, to)`: Copies the file `from` to the location `to` on all nodes.
49
+
50
+ * `shell_ex(cmd, opts = {})`: Execute a shell command on the default node.
51
+ `opts` keys:
52
+ * `:dry_run`: set to true to skip executing the actual command.
53
+ * `:environment`: pass environment variables for the command as a hash.
54
+
55
+ Other helpful methods:
56
+
57
+ * `Beaker::TestmodeSwitcher.mode`: Returns the currently configured test mode.
58
+ * `Beaker::TestmodeSwitcher.runner`: Returns the currently configured runner.
59
+
60
+ ## Development
61
+
62
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.
63
+
64
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
65
+
66
+ ## Contributing
67
+
68
+ 1. Fork it
69
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
70
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
71
+ 4. Push to the branch (`git push origin my-new-feature`)
72
+ 5. Create a new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,13 @@
1
+ require "bundler/gem_tasks"
2
+
3
+ begin
4
+ require 'rspec/core/rake_task'
5
+ RSpec::Core::RakeTask.new(:spec)
6
+
7
+ require 'rubocop/rake_task'
8
+ RuboCop::RakeTask.new
9
+
10
+ task default: [:spec, :rubocop]
11
+ rescue LoadError # rubocop:disable Lint/HandleExceptions: rspec is optional
12
+ # no rspec available
13
+ end
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'beaker/testmode_switcher/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "beaker-testmode_switcher"
8
+ spec.version = Beaker::TestmodeSwitcher::VERSION
9
+ spec.authors = ["Puppet Labs", "David Schmitt", "Gareth Rushgrove", "Greg Hardy"]
10
+ spec.email = ["modules-team@puppetlabs.com"]
11
+
12
+ spec.summary = "Let's you run your puppet module tests in master/agent, apply or local mode."
13
+ spec.homepage = "https://github.com/puppetlabs/beaker-testmode_switcher"
14
+
15
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
16
+ spec.bindir = "exe"
17
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
18
+ spec.require_paths = ["lib"]
19
+
20
+ spec.add_dependency "beaker"
21
+ spec.add_dependency "master_manipulator"
22
+
23
+ spec.add_development_dependency "bundler", "~> 1.9"
24
+ spec.add_development_dependency "pry"
25
+ spec.add_development_dependency "rake", "~> 10.0"
26
+ spec.add_development_dependency "rspec", "~> 3"
27
+ end
data/bin/console ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "beaker/testmode_switcher"
5
+
6
+ # Add fixtures and/or initialization code here to make experimenting
7
+ # with the gem easier.
8
+
9
+ require "pry"
10
+ Pry.start
data/bin/setup ADDED
@@ -0,0 +1,5 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
@@ -0,0 +1,34 @@
1
+ require 'beaker/testmode_switcher/beaker_runners'
2
+ require 'beaker/testmode_switcher/local_runner'
3
+
4
+ module Beaker
5
+ # Contains the bulk of the code for switching the test mode.
6
+ module TestmodeSwitcher
7
+ # returns the current test mode
8
+ def self.testmode
9
+ mode = ENV['BEAKER_TESTMODE'] || 'apply'
10
+ if %w(apply agent local).include? mode
11
+ return mode.to_sym
12
+ else
13
+ fail ArgumentError, "Unknown BEAKER_TESTMODE supplied: '#{mode}'"
14
+ end
15
+ end
16
+
17
+ # creates a test runner implementing the specified mode
18
+ def self.create_runner(mode)
19
+ case mode
20
+ when :apply then
21
+ BeakerApplyRunner.new
22
+ when :agent then
23
+ BeakerAgentRunner.new
24
+ when :local
25
+ LocalRunner.new
26
+ end
27
+ end
28
+
29
+ # returns the current runner
30
+ def self.runner
31
+ @runner ||= create_runner(testmode)
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,106 @@
1
+ require 'beaker'
2
+ require 'shellwords'
3
+ require 'open3'
4
+
5
+ module Beaker
6
+ module TestmodeSwitcher
7
+ # Re-used functionality for all beaker runners
8
+ class BeakerRunnerBase
9
+ include Beaker::DSL
10
+
11
+ # create a remote file (using puppet apply) on the default host
12
+ def create_remote_file_ex(file_path, file_content, options = {})
13
+ mode = options[:mode] || '0644'
14
+ user = options[:user] || 'root'
15
+ group = options[:group] || 'root'
16
+ file_content.gsub!(/\\/, '\\')
17
+ file_content.gsub!(/'/, "\\'")
18
+ file_content.gsub!(/\n/, '\\n')
19
+ apply_manifest_on default, "file { '#{file_path}': ensure => present, content => '#{file_content}', mode => '#{mode}', user => '#{user}', group => '#{group}' }", catch_failures: true
20
+ end
21
+
22
+ # execute a puppet resource command on the default host
23
+ def resource(type, name, opts = {})
24
+ cmd = ["resource"]
25
+ cmd << "--debug" if opts[:debug]
26
+ cmd << "--noop" if opts[:noop]
27
+ cmd << "--trace" if opts[:trace]
28
+ cmd << type
29
+ cmd << name
30
+
31
+ if opts[:values]
32
+ opts[:values].each do |k, v|
33
+ cmd << "#{k}=#{v}"
34
+ end
35
+ end
36
+
37
+ on(default,
38
+ puppet(*cmd),
39
+ dry_run: opts[:dry_run],
40
+ environment: opts[:environment] || {},
41
+ acceptable_exit_codes: (0...256)
42
+ )
43
+ end
44
+
45
+ # copy a file using beaker's scp_to to all hosts
46
+ def scp_to_ex(from, to)
47
+ hosts.each do |host|
48
+ scp_to host, from, to
49
+ end
50
+ end
51
+
52
+ # execute an arbitrary command on the default host
53
+ def shell_ex(cmd)
54
+ shell(cmd)
55
+ end
56
+ end
57
+
58
+ # All functionality specific to running in 'agent' mode
59
+ class BeakerAgentRunner < BeakerRunnerBase
60
+ require 'master_manipulator'
61
+ include MasterManipulator::Site
62
+
63
+ # upload the manifest to the master and inject it into the site.pp
64
+ # then run a puppet agent on the default host
65
+ def execute_manifest(manifest, opts = {})
66
+ environment_base_path = on(master, puppet('config', 'print', 'environmentpath')).stdout.rstrip
67
+ prod_env_site_pp_path = File.join(environment_base_path, 'production', 'manifests', 'site.pp')
68
+ site_pp = create_site_pp(master, manifest: manifest)
69
+ inject_site_pp(master, prod_env_site_pp_path, site_pp)
70
+
71
+ cmd = ['agent', '--test', '--environment production']
72
+ cmd << "--debug" if opts[:debug]
73
+ cmd << "--noop" if opts[:noop]
74
+ cmd << "--trace" if opts[:trace]
75
+
76
+ # acceptable_exit_codes are passed because we want detailed-exit-codes but want to
77
+ # make our own assertions about the responses
78
+ on(default,
79
+ puppet(*cmd),
80
+ dry_run: opts[:dry_run],
81
+ environment: opts[:environment] || {},
82
+ acceptable_exit_codes: (0...256)
83
+ )
84
+ end
85
+ end
86
+
87
+ # All functionality specific to running in 'apply' mode
88
+ class BeakerApplyRunner < BeakerRunnerBase
89
+ # execute the manifest by running puppet apply on the default node
90
+ def execute_manifest(manifest, opts = {})
91
+ # acceptable_exit_codes and expect_changes are passed because we want detailed-exit-codes but want to
92
+ # make our own assertions about the responses
93
+ apply_manifest(
94
+ manifest,
95
+ expect_changes: true,
96
+ debug: opts[:debug],
97
+ dry_run: opts[:dry_run],
98
+ environment: opts[:environment] || {},
99
+ noop: opts[:noop],
100
+ trace: opts[:trace],
101
+ acceptable_exit_codes: (0...256)
102
+ )
103
+ end
104
+ end
105
+ end
106
+ end
@@ -0,0 +1,17 @@
1
+ require 'beaker/testmode_switcher'
2
+
3
+ module Beaker
4
+ module TestmodeSwitcher
5
+ # include this module into your namespace to access the DSL parts of TestmodeSwitcher
6
+ module DSL
7
+ # pass through methods to the runner
8
+ [:create_remote_file_ex, :scp_to_ex, :shell_ex, :resource, :execute_manifest].each do |name|
9
+ define_method(name) do |*args|
10
+ Beaker::TestmodeSwitcher.runner.send(name, *args)
11
+ end
12
+ end
13
+ end
14
+ end
15
+ end
16
+
17
+ include Beaker::TestmodeSwitcher::DSL
@@ -0,0 +1,156 @@
1
+ require 'shellwords'
2
+ require 'open3'
3
+
4
+ module Beaker
5
+ module TestmodeSwitcher
6
+ # All functionality specific to running in 'local' mode
7
+ class LocalRunner
8
+ # creates the file on the local machine and adjusts permissions
9
+ # the opts hash allows the following keys: :mode, :user, :group
10
+ def create_remote_file_ex(file_path, file_content, opts = {})
11
+ File.open(file_path, 'w') { |file| file.write(file_content) }
12
+
13
+ file_path_escaped = file_path.shellescape
14
+ commands = []
15
+ commands << "chmod #{opts[:mode].shellescape} #{file_path_escaped}" if opts[:mode]
16
+ commands << "chown #{opts[:user].shellescape} #{file_path_escaped}" if opts[:user]
17
+ commands << "chgrp #{opts[:group].shellescape} #{file_path_escaped}" if opts[:group]
18
+ if commands.empty?
19
+ success_result
20
+ else
21
+ use_local_shell(commands.join(' && '), opts)
22
+ end
23
+ end
24
+
25
+ # executes the supplied manifest using bundle and puppet apply
26
+ # the opts hash works like the opts of [apply_manifest_on](http://www.rubydoc.info/github/puppetlabs/beaker/Beaker/DSL/Helpers/PuppetHelpers#apply_manifest_on-instance_method) in the Beaker DSL.
27
+ # it accepts the following keys: :dry_run, :environment, :trace, :noop, and :debug
28
+ def execute_manifest(manifest, opts = {})
29
+ puts "Applied manifest [#{manifest}]" if ENV['DEBUG_MANIFEST']
30
+ cmd = ["bundle exec puppet apply -e #{manifest.delete("\n").shellescape} --detailed-exitcodes --modulepath spec/fixtures/modules --libdir lib"]
31
+ cmd << "--debug" if opts[:debug]
32
+ cmd << "--noop" if opts[:noop]
33
+ cmd << "--trace" if opts[:trace]
34
+ use_local_shell(cmd.join(' '), opts)
35
+ end
36
+
37
+ # build and execute complex puppet resource commands locally
38
+ # the type argument is the name of the resource type
39
+ # the name argument is the namevar of the resource
40
+ # the opts hash works like the opts of [apply_manifest_on](http://www.rubydoc.info/github/puppetlabs/beaker/Beaker/DSL/Helpers/PuppetHelpers#apply_manifest_on-instance_method) in the Beaker DSL.
41
+ # it accepts the following keys: :dry_run, :environment, :trace, :noop, and :debug
42
+ # additionally opts[:values] can be set to a hash of resource values to pass on the command line
43
+ def resource(type, name, opts = {})
44
+ cmd = ["bundle exec puppet resource --modulepath spec/fixtures/modules --libdir lib"]
45
+ cmd << "--debug" if opts[:debug]
46
+ cmd << "--noop" if opts[:noop]
47
+ cmd << "--trace" if opts[:trace]
48
+ cmd << type.shellescape
49
+ cmd << name.shellescape
50
+
51
+ if opts[:values]
52
+ opts[:values].each do |k, v|
53
+ cmd << "#{k.shellescape}=#{v.shellescape}"
54
+ end
55
+ end
56
+
57
+ # apply the command
58
+ use_local_shell(cmd.join(' '), opts)
59
+ end
60
+
61
+ # copies the file locally
62
+ def scp_to_ex(from, to)
63
+ FileUtils.cp(from, to)
64
+ success_result
65
+ end
66
+
67
+ # run a command through a local shell
68
+ # Pass options to alter execution through `opts`:
69
+ # * `:environment`: default: `{}`; these will be treated as extra environment variables that should be set before running the command
70
+ def shell_ex(cmd, opts = {})
71
+ use_local_shell(cmd, opts)
72
+ end
73
+
74
+ private
75
+
76
+ # build a Beaker::Result with a successful exit_code and no output
77
+ def success_result
78
+ result = Beaker::Result.new(:localhost, "")
79
+ result.exit_code = 0
80
+ result.finalize!
81
+ result
82
+ end
83
+
84
+ # fork/exec a process and collect its output
85
+ def use_local_shell(cmd, opts)
86
+ if opts[:dry_run]
87
+ puts "Would have run '#{cmd}'"
88
+ success_result
89
+ else
90
+ capture_command(cmd, opts[:environment] || {})
91
+ end
92
+ end
93
+
94
+ # runs a command and captures its output in a Beaker::Result
95
+ def capture_command(cmd, environment)
96
+ blocks = {
97
+ combined: [],
98
+ out: [],
99
+ err: []
100
+ }
101
+ exit_code = -1
102
+ Open3.popen3(environment, cmd) do |stdin, stdout, stderr, wait_thr|
103
+ # TODO: pass through $stdin/terminal to subprocess to allow interaction - e.g. pry - the subprocess
104
+ stdin.close_write
105
+
106
+ files = [stdout, stderr]
107
+
108
+ until files.all?(&:eof)
109
+ ready = IO.select(files)
110
+ next unless ready
111
+
112
+ ready[0].each do |f|
113
+ fileno = f.fileno
114
+ begin
115
+ data = f.read_nonblock(1024)
116
+ until data.empty?
117
+ $stdout.write(data)
118
+
119
+ # create a combined block list for better output interleaving
120
+ blocks[:combined] << data
121
+
122
+ # store each stream separately for the Beaker::Result API
123
+ if fileno == stdout.fileno
124
+ blocks[:out] << data
125
+ else
126
+ blocks[:err] << data
127
+ end
128
+
129
+ # try reading more data
130
+ # when the command writes more than 1k at a time, this is required to drain buffers
131
+ # and avoid stdout/stderr interleaving
132
+ begin
133
+ data = f.read_nonblock(1024)
134
+ rescue IO::EAGAINWaitReadable
135
+ data = ""
136
+ end
137
+ end
138
+ rescue EOFError # rubocop:disable Lint/HandleExceptions: expected exception
139
+ # pass on EOF
140
+ end
141
+ end
142
+ end
143
+
144
+ exit_code = wait_thr.value.exitstatus
145
+ end
146
+ result = Beaker::Result.new(:localhost, cmd)
147
+ result.stdout = blocks[:out].join
148
+ result.stderr = blocks[:err].join
149
+ result.output = blocks[:combined].join
150
+ result.exit_code = exit_code
151
+ result.finalize!
152
+ result
153
+ end
154
+ end
155
+ end
156
+ end
@@ -0,0 +1,6 @@
1
+ module Beaker
2
+ # central definition of this gem's version
3
+ module TestmodeSwitcher
4
+ VERSION = "0.1.0"
5
+ end
6
+ end
metadata ADDED
@@ -0,0 +1,148 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: beaker-testmode_switcher
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Puppet Labs
8
+ - David Schmitt
9
+ - Gareth Rushgrove
10
+ - Greg Hardy
11
+ autorequire:
12
+ bindir: exe
13
+ cert_chain: []
14
+ date: 2016-01-06 00:00:00.000000000 Z
15
+ dependencies:
16
+ - !ruby/object:Gem::Dependency
17
+ name: beaker
18
+ requirement: !ruby/object:Gem::Requirement
19
+ requirements:
20
+ - - '>='
21
+ - !ruby/object:Gem::Version
22
+ version: '0'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - '>='
28
+ - !ruby/object:Gem::Version
29
+ version: '0'
30
+ - !ruby/object:Gem::Dependency
31
+ name: master_manipulator
32
+ requirement: !ruby/object:Gem::Requirement
33
+ requirements:
34
+ - - '>='
35
+ - !ruby/object:Gem::Version
36
+ version: '0'
37
+ type: :runtime
38
+ prerelease: false
39
+ version_requirements: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - '>='
42
+ - !ruby/object:Gem::Version
43
+ version: '0'
44
+ - !ruby/object:Gem::Dependency
45
+ name: bundler
46
+ requirement: !ruby/object:Gem::Requirement
47
+ requirements:
48
+ - - ~>
49
+ - !ruby/object:Gem::Version
50
+ version: '1.9'
51
+ type: :development
52
+ prerelease: false
53
+ version_requirements: !ruby/object:Gem::Requirement
54
+ requirements:
55
+ - - ~>
56
+ - !ruby/object:Gem::Version
57
+ version: '1.9'
58
+ - !ruby/object:Gem::Dependency
59
+ name: pry
60
+ requirement: !ruby/object:Gem::Requirement
61
+ requirements:
62
+ - - '>='
63
+ - !ruby/object:Gem::Version
64
+ version: '0'
65
+ type: :development
66
+ prerelease: false
67
+ version_requirements: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - '>='
70
+ - !ruby/object:Gem::Version
71
+ version: '0'
72
+ - !ruby/object:Gem::Dependency
73
+ name: rake
74
+ requirement: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - ~>
77
+ - !ruby/object:Gem::Version
78
+ version: '10.0'
79
+ type: :development
80
+ prerelease: false
81
+ version_requirements: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ~>
84
+ - !ruby/object:Gem::Version
85
+ version: '10.0'
86
+ - !ruby/object:Gem::Dependency
87
+ name: rspec
88
+ requirement: !ruby/object:Gem::Requirement
89
+ requirements:
90
+ - - ~>
91
+ - !ruby/object:Gem::Version
92
+ version: '3'
93
+ type: :development
94
+ prerelease: false
95
+ version_requirements: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - ~>
98
+ - !ruby/object:Gem::Version
99
+ version: '3'
100
+ description:
101
+ email:
102
+ - modules-team@puppetlabs.com
103
+ executables: []
104
+ extensions: []
105
+ extra_rdoc_files: []
106
+ files:
107
+ - .gitignore
108
+ - .rspec
109
+ - .rubocop.yml
110
+ - .travis.yml
111
+ - CHANGELOG.md
112
+ - Gemfile
113
+ - Guardfile
114
+ - LICENSE
115
+ - README.md
116
+ - Rakefile
117
+ - beaker-testmode_switcher.gemspec
118
+ - bin/console
119
+ - bin/setup
120
+ - lib/beaker/testmode_switcher.rb
121
+ - lib/beaker/testmode_switcher/beaker_runners.rb
122
+ - lib/beaker/testmode_switcher/dsl.rb
123
+ - lib/beaker/testmode_switcher/local_runner.rb
124
+ - lib/beaker/testmode_switcher/version.rb
125
+ homepage: https://github.com/puppetlabs/beaker-testmode_switcher
126
+ licenses: []
127
+ metadata: {}
128
+ post_install_message:
129
+ rdoc_options: []
130
+ require_paths:
131
+ - lib
132
+ required_ruby_version: !ruby/object:Gem::Requirement
133
+ requirements:
134
+ - - '>='
135
+ - !ruby/object:Gem::Version
136
+ version: '0'
137
+ required_rubygems_version: !ruby/object:Gem::Requirement
138
+ requirements:
139
+ - - '>='
140
+ - !ruby/object:Gem::Version
141
+ version: '0'
142
+ requirements: []
143
+ rubyforge_project:
144
+ rubygems_version: 2.0.14
145
+ signing_key:
146
+ specification_version: 4
147
+ summary: Let's you run your puppet module tests in master/agent, apply or local mode.
148
+ test_files: []