diff --git a/.gitignore b/.gitignore index 090d8574..e19e7466 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ Gemfile.local TAGS terraform.tfstate.backup .terraform +.bundle +.gems diff --git a/.rubocop.yml b/.rubocop.yml deleted file mode 100644 index 44c9c826..00000000 --- a/.rubocop.yml +++ /dev/null @@ -1,77 +0,0 @@ ---- -AllCops: - Exclude: - - Gemfile - - Rakefile - - 'test/**/*' - - 'examples/plugins/train-*/test/**/*' - - 'vendor/**/*' -Documentation: - Enabled: false -AlignParameters: - Enabled: true -Encoding: - Enabled: false -HashSyntax: - Enabled: true -LineLength: - Enabled: false -EmptyLinesAroundBlockBody: - Enabled: false -MethodLength: - Max: 40 -NumericLiterals: - MinDigits: 10 -Metrics/CyclomaticComplexity: - Max: 10 -Metrics/PerceivedComplexity: - Max: 10 -Metrics/AbcSize: - Max: 33 -Metrics/ModuleLength: - Enabled: false -Style/PercentLiteralDelimiters: - PreferredDelimiters: - '%': '{}' - '%i': () - '%q': '{}' - '%Q': () - '%r': '{}' - '%s': () - '%w': '{}' - '%W': () - '%x': () -Style/AlignHash: - Enabled: false -Style/PredicateName: - Enabled: false -Style/ClassAndModuleChildren: - Enabled: false -Style/ConditionalAssignment: - Enabled: false -Style/BracesAroundHashParameters: - Enabled: false -Style/AndOr: - Enabled: false -Style/Not: - Enabled: false -Style/FileName: - Enabled: false -Style/TrailingCommaInLiteral: - EnforcedStyleForMultiline: comma -Style/TrailingCommaInArguments: - EnforcedStyleForMultiline: comma -Style/NegatedIf: - Enabled: false -Style/UnlessElse: - Enabled: false -BlockDelimiters: - Enabled: false -Style/SpaceAroundOperators: - Enabled: false -Style/IfUnlessModifier: - Enabled: false -Style/FrozenStringLiteralComment: - Enabled: false -SignalException: - Enabled: false diff --git a/Gemfile b/Gemfile index e4277d7d..cff13fb3 100644 --- a/Gemfile +++ b/Gemfile @@ -1,35 +1,35 @@ # encoding: utf-8 -source 'https://rubygems.org' -gemspec name: 'train' +source "https://rubygems.org" +gemspec name: "train" group :test do - gem 'coveralls', require: false - gem 'minitest', '~> 5.8' - gem 'rake', '~> 10' # @todo bump this when we bump rubocop - gem 'rubocop', '~> 0.36.0' - gem 'simplecov', '~> 0.10' - gem 'concurrent-ruby', '~> 1.0' - gem 'pry-byebug' - gem 'm' + gem "coveralls", require: false + gem "minitest", "~> 5.8" + gem "rake", "~> 10" + gem "chefstyle" + gem "simplecov", "~> 0.10" + gem "concurrent-ruby", "~> 1.0" + gem "pry-byebug" + gem "m" # This is not a true gem installation # (Gem::Specification.find_by_path('train-gem-fixture') will return nil) # but it's close enough to show the gempath handler can find a plugin # See test/unit/ - gem 'train-test-fixture', path: 'test/fixtures/plugins/train-test-fixture' + gem "train-test-fixture", path: "test/fixtures/plugins/train-test-fixture" end group :integration do - gem 'berkshelf', '>= 6.3.4' - gem 'test-kitchen', '>= 1.2.4' - gem 'kitchen-vagrant' - gem 'ed25519' # ed25519 ssh key support - gem 'bcrypt_pbkdf' # ed25519 ssh key support + gem "berkshelf", ">= 6.3.4" + gem "test-kitchen", ">= 1.2.4" + gem "kitchen-vagrant" + gem "ed25519" # ed25519 ssh key support + gem "bcrypt_pbkdf" # ed25519 ssh key support end group :tools do - gem 'pry', '~> 0.10' - gem 'rb-readline' - gem 'license_finder' + gem "pry", "~> 0.10" + gem "rb-readline" + gem "license_finder" end # add these additional dependencies into Gemfile.local diff --git a/Rakefile b/Rakefile index 35696e39..b722a940 100755 --- a/Rakefile +++ b/Rakefile @@ -1,50 +1,45 @@ #!/usr/bin/env rake # encoding: utf-8 -require 'bundler' -require 'bundler/gem_helper' -require 'rake/testtask' -require 'rubocop/rake_task' +require "bundler" +require "bundler/gem_helper" +require "rake/testtask" +require "chefstyle" +require "rubocop/rake_task" -Bundler::GemHelper.install_tasks name: 'train' +Bundler::GemHelper.install_tasks name: "train" -# Rubocop -desc 'Run Rubocop lint checks' -task :rubocop do - RuboCop::RakeTask.new +RuboCop::RakeTask.new(:lint) do |task| + task.options << "--display-cop-names" end - -# lint the project -desc 'Run robocop linter' -task lint: [:rubocop] - +# # run tests task default: [:test, :lint] Rake::TestTask.new do |t| - t.libs << 'test' - t.pattern = 'test/unit/**/*_test.rb' + t.libs << "test" + t.pattern = "test/unit/**/*_test.rb" t.warning = false t.verbose = true - t.ruby_opts = ['--dev'] if defined?(JRUBY_VERSION) + t.ruby_opts = ["--dev"] if defined?(JRUBY_VERSION) end namespace :test do task :docker do - path = File.join(File.dirname(__FILE__), 'test', 'integration') - sh('sh', '-c', "cd #{path} && ruby -I ../../lib docker_test.rb tests/*") + path = File.join(File.dirname(__FILE__), "test", "integration") + sh("sh", "-c", "cd #{path} && ruby -I ../../lib docker_test.rb tests/*") end task :windows do - Dir.glob('test/windows/*_test.rb').all? do |file| - sh(Gem.ruby, '-w', '-I .\test\windows', file) - end or fail 'Failures' + Dir.glob("test/windows/*_test.rb").all? do |file| + sh(Gem.ruby, "-w", '-I .\test\windows', file) + end || raise("Failures") end task :vm do - concurrency = ENV['CONCURRENCY'] || 4 - path = File.join(File.dirname(__FILE__), 'test', 'integration') - sh('sh', '-c', "cd #{path} && kitchen test -c #{concurrency}") + concurrency = ENV["CONCURRENCY"] || 4 + path = File.join(File.dirname(__FILE__), "test", "integration") + sh("sh", "-c", "cd #{path} && kitchen test -c #{concurrency}") end # Target required: @@ -59,15 +54,15 @@ namespace :test do # Run with a specific test: # test=path_block_device_test.rb rake "test:ssh[user@server]" task :ssh, [:target] do |t, args| - path = File.join(File.dirname(__FILE__), 'test', 'integration') - key_files = ENV['key_files'] || File.join(ENV['HOME'], '.ssh', 'id_rsa') + path = File.join(File.dirname(__FILE__), "test", "integration") + key_files = ENV["key_files"] || File.join(ENV["HOME"], ".ssh", "id_rsa") - sh_cmd = "cd #{path} && target=#{args[:target]} key_files=#{key_files}" + sh_cmd = "cd #{path} && target=#{args[:target]} key_files=#{key_files}" - sh_cmd += " debug=#{ENV['debug']}" if ENV['debug'] - sh_cmd += ' ruby -I ../../lib test_ssh.rb tests/' - sh_cmd += ENV['test'] || '*' + sh_cmd += " debug=#{ENV['debug']}" if ENV["debug"] + sh_cmd += " ruby -I ../../lib test_ssh.rb tests/" + sh_cmd += ENV["test"] || "*" - sh('sh', '-c', sh_cmd) + sh("sh", "-c", sh_cmd) end end diff --git a/contrib/fixup_requiretty.rb b/contrib/fixup_requiretty.rb index 1b8f2928..00dd8b8e 100644 --- a/contrib/fixup_requiretty.rb +++ b/contrib/fixup_requiretty.rb @@ -13,11 +13,11 @@ # (unless you set TRAIN_SUDO_VERY_MUCH=yes) # FIXME -user = ENV['TRAIN_SUDO_USER'] || 'todo-some-clever-default-maybe-current-user' +user = ENV["TRAIN_SUDO_USER"] || "todo-some-clever-default-maybe-current-user" sudoer = "/etc/sudoers.d/#{user}" log "Warning: a sudoers configuration for user #{user} already exists, "\ - 'doing nothing (override with TRAIN_SUDO_VERY_MUCH=yes)' do + "doing nothing (override with TRAIN_SUDO_VERY_MUCH=yes)" do only_if "test -f #{sudoer} || grep #{user} /etc/sudoers" end @@ -25,7 +25,7 @@ content "#{user} ALL=(root) NOPASSWD:ALL\n"\ "Defaults:#{user} !requiretty\n" mode 0600 - action ENV['TRAIN_SUDO_VERY_MUCH'] == 'yes' ? :create : :create_if_missing + action ENV["TRAIN_SUDO_VERY_MUCH"] == "yes" ? :create : :create_if_missing # Do not add something here if the user is mentioned explicitly in /etc/sudoers not_if "grep #{user} /etc/sudoers" diff --git a/examples/plugins/train-local-rot13/Gemfile b/examples/plugins/train-local-rot13/Gemfile index 4f5f2db3..0cc0b571 100644 --- a/examples/plugins/train-local-rot13/Gemfile +++ b/examples/plugins/train-local-rot13/Gemfile @@ -1,6 +1,6 @@ # encoding: utf-8 -source 'https://rubygems.org' +source "https://rubygems.org" # This is Gemfile, which is used by bundler # to ensure a coherent set of gems is installed. @@ -12,10 +12,10 @@ gemspec # Remaining group is only used for development. group :development do - gem 'bundler' - gem 'byebug' - gem 'inspec', '>= 2.2.112' # We need InSpec for the test harness while developing. - gem 'minitest' - gem 'rake' - gem 'rubocop', '= 0.49.1' # Need to keep in sync with main InSpec project, so config files will work + gem "bundler" + gem "byebug" + gem "inspec", ">= 2.2.112" # We need InSpec for the test harness while developing. + gem "minitest" + gem "rake" + gem "rubocop", "= 0.49.1" # Need to keep in sync with main InSpec project, so config files will work end diff --git a/examples/plugins/train-local-rot13/Rakefile b/examples/plugins/train-local-rot13/Rakefile index 00b06095..905f32c9 100644 --- a/examples/plugins/train-local-rot13/Rakefile +++ b/examples/plugins/train-local-rot13/Rakefile @@ -7,14 +7,14 @@ # This task template will make a task named 'test', and run # the tests that it finds. -require 'rake/testtask' +require "rake/testtask" Rake::TestTask.new do |t| - t.libs.push 'lib' + t.libs.push "lib" t.test_files = FileList[ - 'test/unit/*_test.rb', - 'test/integration/*_test.rb', - 'test/functional/*_test.rb', + "test/unit/*_test.rb", + "test/integration/*_test.rb", + "test/functional/*_test.rb", ] t.verbose = true # Ideally, we'd run tests with warnings enabled, @@ -27,15 +27,15 @@ end #------------------------------------------------------------------# # Code Style Tasks #------------------------------------------------------------------# -require 'rubocop/rake_task' +require "rubocop/rake_task" RuboCop::RakeTask.new(:lint) do |t| # Choices of rubocop rules to enforce are deeply personal. # Here, we set things up so that your plugin will use the Bundler-installed # train gem's copy of the Train project's rubocop.yml file (which # is indeed packaged with the train gem). - require 'train/globals' - train_rubocop_yml = File.join(Train.src_root, '.rubocop.yml') + require "train/globals" + train_rubocop_yml = File.join(Train.src_root, ".rubocop.yml") - t.options = ['--display-cop-names', '--config', train_rubocop_yml] + t.options = ["--display-cop-names", "--config", train_rubocop_yml] end diff --git a/examples/plugins/train-local-rot13/lib/train-local-rot13.rb b/examples/plugins/train-local-rot13/lib/train-local-rot13.rb index 7d441f01..21afa55c 100644 --- a/examples/plugins/train-local-rot13/lib/train-local-rot13.rb +++ b/examples/plugins/train-local-rot13/lib/train-local-rot13.rb @@ -12,10 +12,10 @@ $LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir) # It's traditional to keep your gem version in a separate file, so CI can find it easier. -require 'train-local-rot13/version' +require "train-local-rot13/version" # A train plugin has three components: Transport, Connection, and Platform. # Transport acts as the glue. -require 'train-local-rot13/transport' -require 'train-local-rot13/platform' -require 'train-local-rot13/connection' +require "train-local-rot13/transport" +require "train-local-rot13/platform" +require "train-local-rot13/connection" diff --git a/examples/plugins/train-local-rot13/lib/train-local-rot13/connection.rb b/examples/plugins/train-local-rot13/lib/train-local-rot13/connection.rb index 521349b6..26562ef8 100644 --- a/examples/plugins/train-local-rot13/lib/train-local-rot13/connection.rb +++ b/examples/plugins/train-local-rot13/lib/train-local-rot13/connection.rb @@ -15,18 +15,18 @@ # You don't have to worry about most of this. # This allow us to inherit from Train::Plugins::Transport::BaseConnection -require 'train' +require "train" # Push platform detection out to a mixin, as it tends # to develop at a different cadence than the rest -require 'train-local-rot13/platform' +require "train-local-rot13/platform" # This is a support library for our file content meddling -require 'train-local-rot13/file_content_rotator' +require "train-local-rot13/file_content_rotator" # This is a support library for our command meddling -require 'mixlib/shellout' -require 'ostruct' +require "mixlib/shellout" +require "ostruct" module TrainPlugins module LocalRot13 @@ -74,7 +74,7 @@ def run_command_via_connection(cmd) # And meddle with the stdout along the way. stdout: Rot13.rotate(run_result.stdout), stderr: run_result.stderr, - exit_status: run_result.exitstatus, + exit_status: run_result.exitstatus ) end end diff --git a/examples/plugins/train-local-rot13/lib/train-local-rot13/file_content_rotator.rb b/examples/plugins/train-local-rot13/lib/train-local-rot13/file_content_rotator.rb index e2c5817a..70dbadd5 100644 --- a/examples/plugins/train-local-rot13/lib/train-local-rot13/file_content_rotator.rb +++ b/examples/plugins/train-local-rot13/lib/train-local-rot13/file_content_rotator.rb @@ -1,7 +1,7 @@ # Here's our helper class for the file object. This is just some # silliness specific to the task of applying rot13 to the file content. -require 'rot13' +require "rot13" module TrainPlugins module LocalRot13 diff --git a/examples/plugins/train-local-rot13/lib/train-local-rot13/platform.rb b/examples/plugins/train-local-rot13/lib/train-local-rot13/platform.rb index 2419d726..38edc919 100644 --- a/examples/plugins/train-local-rot13/lib/train-local-rot13/platform.rb +++ b/examples/plugins/train-local-rot13/lib/train-local-rot13/platform.rb @@ -20,8 +20,8 @@ def platform # This plugin makes up a new platform. Train (or rather InSpec) only # know how to read files on Windows and Un*x (MacOS is a kind of Un*x), # so we'll say we're part of those families. - Train::Platforms.name('local-rot13').in_family('unix') - Train::Platforms.name('local-rot13').in_family('windows') + Train::Platforms.name("local-rot13").in_family("unix") + Train::Platforms.name("local-rot13").in_family("windows") # When you know you will only ever run on your dedicated platform # (for example, a plugin named train-aws would only run on the AWS @@ -32,7 +32,7 @@ def platform # Use release to report a version number. You might use the version # of the plugin, or a version of an important underlying SDK, or a # version of a remote API. - force_platform!('local-rot13', release: TrainPlugins::LocalRot13::VERSION) + force_platform!("local-rot13", release: TrainPlugins::LocalRot13::VERSION) end end end diff --git a/examples/plugins/train-local-rot13/lib/train-local-rot13/transport.rb b/examples/plugins/train-local-rot13/lib/train-local-rot13/transport.rb index a4c448f7..3ca67fa9 100644 --- a/examples/plugins/train-local-rot13/lib/train-local-rot13/transport.rb +++ b/examples/plugins/train-local-rot13/lib/train-local-rot13/transport.rb @@ -1,12 +1,12 @@ # Train Plugins v1 are usually declared under the TrainPlugins namespace. # Each plugin has three components: Transport, Connection, and Platform. # We'll only define the Transport here, but we'll refer to the others. -require 'train-local-rot13/connection' +require "train-local-rot13/connection" module TrainPlugins module LocalRot13 class Transport < Train.plugin(1) - name 'local-rot13' + name "local-rot13" # The only thing you MUST do in a transport is a define a # connection() method that returns a instance that is a diff --git a/examples/plugins/train-local-rot13/lib/train-local-rot13/version.rb b/examples/plugins/train-local-rot13/lib/train-local-rot13/version.rb index 65631df2..8cefeccf 100644 --- a/examples/plugins/train-local-rot13/lib/train-local-rot13/version.rb +++ b/examples/plugins/train-local-rot13/lib/train-local-rot13/version.rb @@ -5,6 +5,6 @@ module TrainPlugins module LocalRot13 - VERSION = '0.1.0'.freeze + VERSION = "0.1.0".freeze end end diff --git a/examples/plugins/train-local-rot13/test/functional/local-rot13_test.rb b/examples/plugins/train-local-rot13/test/functional/local-rot13_test.rb index c6d16e9c..b35f8a64 100644 --- a/examples/plugins/train-local-rot13/test/functional/local-rot13_test.rb +++ b/examples/plugins/train-local-rot13/test/functional/local-rot13_test.rb @@ -8,12 +8,12 @@ # works; we just know what it is supposed to do. # Include our test harness -require_relative '../helper' +require_relative "../helper" # Because InSpec is a Spec-style test suite, and Train has a close relationship # to InSpec, we're going to use MiniTest::Spec here, for familiar look and # feel. However, this isn't InSpec (or RSpec) code. -describe 'train-local-rot13' do +describe "train-local-rot13" do # Our helper.rb locates this library from the Train install that # Bundler installed for us. If we want its methods, we still must # import it. Including it here will make it available in all child @@ -44,39 +44,39 @@ it "should not explode on create" do # This checks for uncaught exceptions. - Train.create('local-rot13') + Train.create("local-rot13") # This checks for warnings (or any other output) to stdout/stderr - proc { Train.create('local-rot13') }.must_be_silent + proc { Train.create("local-rot13") }.must_be_silent end it "should not explode on connect" do # This checks for uncaught exceptions. - Train.create('local-rot13').connection + Train.create("local-rot13").connection # This checks for warnings (or any other output) to stdout/stderr - proc { Train.create('local-rot13').connection }.must_be_silent + proc { Train.create("local-rot13").connection }.must_be_silent end end describe "reading a file" do it "should rotate the text by 13 positions" do - conn = Train.create('local-rot13').connection + conn = Train.create("local-rot13").connection # Here, plugin_fixtures_path is provided by the TrainPluginFunctionalHelper, # and refers to the absolute path to the test fixtures directory. # The file 'hello' simply has the text 'hello' in it. - file_obj = conn.file(File.join(plugin_fixtures_path, 'hello')) - file_obj.content.wont_include('hello') - file_obj.content.must_include('uryyb') + file_obj = conn.file(File.join(plugin_fixtures_path, "hello")) + file_obj.content.wont_include("hello") + file_obj.content.must_include("uryyb") end end describe "running a command" do it "should rotate the stdout by 13 positions" do - conn = Train.create('local-rot13').connection - file_obj = conn.run_command('echo hello') - file_obj.stdout.wont_include('hello') - file_obj.stdout.must_include('uryyb') + conn = Train.create("local-rot13").connection + file_obj = conn.run_command("echo hello") + file_obj.stdout.wont_include("hello") + file_obj.stdout.must_include("uryyb") end end -end \ No newline at end of file +end diff --git a/examples/plugins/train-local-rot13/test/helper.rb b/examples/plugins/train-local-rot13/test/helper.rb index e80aa05d..430e5810 100644 --- a/examples/plugins/train-local-rot13/test/helper.rb +++ b/examples/plugins/train-local-rot13/test/helper.rb @@ -3,4 +3,4 @@ # This file's job is to collect any libraries needed for testing, as well as provide # any utilities to make testing a plugin easier. -require 'train/plugin_test_helper' \ No newline at end of file +require "train/plugin_test_helper" diff --git a/examples/plugins/train-local-rot13/test/unit/connection_test.rb b/examples/plugins/train-local-rot13/test/unit/connection_test.rb index f5759502..e1e8070e 100644 --- a/examples/plugins/train-local-rot13/test/unit/connection_test.rb +++ b/examples/plugins/train-local-rot13/test/unit/connection_test.rb @@ -2,10 +2,10 @@ # Its job is to verify that the Connection class is setup correctly. # Include our test harness -require_relative '../helper' +require_relative "../helper" # Load the class under test, the Connection definition. -require 'train-local-rot13/connection' +require "train-local-rot13/connection" # Because InSpec is a Spec-style test suite, we're going to use MiniTest::Spec # here, for familiar look and feel. However, this isn't InSpec (or RSpec) code. diff --git a/examples/plugins/train-local-rot13/test/unit/transport_test.rb b/examples/plugins/train-local-rot13/test/unit/transport_test.rb index be3879c6..0bbf1e79 100644 --- a/examples/plugins/train-local-rot13/test/unit/transport_test.rb +++ b/examples/plugins/train-local-rot13/test/unit/transport_test.rb @@ -2,10 +2,10 @@ # Its job is to verify that the Transport class is setup correctly. # Include our test harness -require_relative '../helper' +require_relative "../helper" # Load the class under test, the Plugin definition. -require 'train-local-rot13/transport' +require "train-local-rot13/transport" # Because InSpec is a Spec-style test suite, we're going to use MiniTest::Spec # here, for familiar look and feel. However, this isn't InSpec (or RSpec) code. @@ -23,8 +23,8 @@ it "should be registered with the plugin registry without the train- prtefix" do # Note that Train uses String keys here, not Symbols - Train::Plugins.registry.keys.wont_include('train-local-rot13') - Train::Plugins.registry.keys.must_include('local-rot13') + Train::Plugins.registry.keys.wont_include("train-local-rot13") + Train::Plugins.registry.keys.must_include("local-rot13") end it "should inherit from the Train plugin base" do diff --git a/examples/plugins/train-local-rot13/train-local-rot13.gemspec b/examples/plugins/train-local-rot13/train-local-rot13.gemspec index 765805bb..f579fe83 100644 --- a/examples/plugins/train-local-rot13/train-local-rot13.gemspec +++ b/examples/plugins/train-local-rot13/train-local-rot13.gemspec @@ -4,22 +4,22 @@ # It is traditional in a gemspec to dynamically load the current version # from a file in the source tree. The next three lines make that happen. -lib = File.expand_path('../lib', __FILE__) +lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require 'train-local-rot13/version' +require "train-local-rot13/version" Gem::Specification.new do |spec| # Importantly, all Train plugins must be prefixed with `train-` - spec.name = 'train-local-rot13' + spec.name = "train-local-rot13" # It is polite to namespace your plugin under TrainPlugins::YourPluginInCamelCase spec.version = TrainPlugins::LocalRot13::VERSION - spec.authors = ['Chef InSpec Team'] - spec.email = ['inspec@chef.io'] + spec.authors = ["Chef InSpec Team"] + spec.email = ["inspec@chef.io"] spec.summary = "Train Plugin example, rot13's file content and command output" - spec.description = 'Example for implementing a Train plugin. This simply performs the ROT13 substitution cipher on file content and command output.' - spec.homepage = 'https://github.com/inspec/train/tree/master/examples/plugin' - spec.license = 'Apache-2.0' + spec.description = "Example for implementing a Train plugin. This simply performs the ROT13 substitution cipher on file content and command output." + spec.homepage = "https://github.com/inspec/train/tree/master/examples/plugin" + spec.license = "Apache-2.0" # Though complicated-looking, this is pretty standard for a gemspec. # It just filters what will actually be packaged in the gem (leaving @@ -27,9 +27,9 @@ Gem::Specification.new do |spec| spec.files = %w{ README.md train-local-rot13.gemspec Gemfile } + Dir.glob( - 'lib/**/*', File::FNM_DOTMATCH + "lib/**/*", File::FNM_DOTMATCH ).reject { |f| File.directory?(f) } - spec.require_paths = ['lib'] + spec.require_paths = ["lib"] # If you rely on any other gems, list them here with any constraints. # This is how `inspec plugin install` is able to manage your dependencies. @@ -41,6 +41,6 @@ Gem::Specification.new do |spec| # Do not list inspec as a dependency of the train plugin. # All plugins should mention train, > 1.4 - spec.add_dependency 'train', '~> 1.4' - spec.add_dependency 'rot13', '~> 0.1' + spec.add_dependency "train", "~> 1.4" + spec.add_dependency "rot13", "~> 0.1" end diff --git a/lib/train.rb b/lib/train.rb index 80d4d157..3dd813e3 100644 --- a/lib/train.rb +++ b/lib/train.rb @@ -2,12 +2,12 @@ # # Author:: Dominik Richter () -require 'train/version' -require 'train/options' -require 'train/plugins' -require 'train/errors' -require 'train/platforms' -require 'uri' +require "train/version" +require "train/options" +require "train/plugins" +require "train/errors" +require "train/platforms" +require "uri" module Train # Create a new transport instance, with the plugin indicated by the @@ -42,12 +42,12 @@ def self.load_transport(transport_name) return transport_class unless transport_class.nil? # Try to load the transport name from the core transports... - require 'train/transports/' + transport_name - return Train::Plugins.registry[transport_name] + require "train/transports/" + transport_name + Train::Plugins.registry[transport_name] rescue LoadError => _ begin # If it's not in the core transports, try loading from a train plugin gem. - gem_name = 'train-' + transport_name + gem_name = "train-" + transport_name require gem_name return Train::Plugins.registry[transport_name] # rubocop: disable Lint/HandleExceptions @@ -92,7 +92,7 @@ def self.unpack_target_from_uri(uri_string, opts = {}) # rubocop: disable Metric # split up the target's host/scheme configuration uri = parse_uri(uri_string) - unless uri.host.nil? and uri.scheme.nil? + unless uri.host.nil? && uri.scheme.nil? creds[:backend] ||= uri.scheme creds[:host] ||= uri.hostname creds[:port] ||= uri.port @@ -128,9 +128,9 @@ def self.parse_uri(string) # e.g. mock://. To do this, we match it manually and fake the hostname case string when %r{^([a-z]+)://$} - string += 'dummy' + string += "dummy" when /^([a-z]+):$/ - string += '//dummy' + string += "//dummy" else raise Train::UserError, e end @@ -144,15 +144,15 @@ def self.parse_uri(string) # Examine the given credential information, and if all is well, # return the transport name. # TODO: this actually does no validation of the credential options whatsoever - def self.validate_backend(credentials, default_transport_name = 'local') + def self.validate_backend(credentials, default_transport_name = "local") return default_transport_name if credentials.nil? transport_name = credentials[:backend] # TODO: Determine if it is ever possible (or supported) for transport_name to be 'localhost' # TODO: After inspec/inspec/pull/3750 is merged, should be able to remove nil from the list - if credentials[:sudo] && [nil, 'local', 'localhost'].include?(transport_name) - fail Train::UserError, 'Sudo is only valid when running against a remote host. '\ - 'To run this locally with elevated privileges, run the command with `sudo ...`.' + if credentials[:sudo] && [nil, "local", "localhost"].include?(transport_name) + raise Train::UserError, "Sudo is only valid when running against a remote host. "\ + "To run this locally with elevated privileges, run the command with `sudo ...`." end return transport_name if !transport_name.nil? @@ -160,13 +160,13 @@ def self.validate_backend(credentials, default_transport_name = 'local') if !credentials[:target].nil? # We should not get here, because if target_uri unpacking was successful, # it would have set credentials[:backend] - fail Train::UserError, 'Cannot determine backend from target '\ + raise Train::UserError, "Cannot determine backend from target "\ "configuration #{credentials[:target]}. Valid example: ssh://192.168.0.1" end if !credentials[:host].nil? - fail Train::UserError, 'Host configured, but no backend was provided. Please '\ - 'specify how you want to connect. Valid example: ssh://192.168.0.1' + raise Train::UserError, "Host configured, but no backend was provided. Please "\ + "specify how you want to connect. Valid example: ssh://192.168.0.1" end credentials[:backend] = default_transport_name @@ -181,7 +181,7 @@ def self.group_keys_and_keyfiles(conf) conf[:key_files] = [] conf[:keys] = [] keys_mixed.each do |key| - if !key.nil? and File.file?(key) + if !key.nil? && File.file?(key) conf[:key_files].push(key) else conf[:keys].push(key) diff --git a/lib/train/errors.rb b/lib/train/errors.rb index 99030680..06104e40 100644 --- a/lib/train/errors.rb +++ b/lib/train/errors.rb @@ -13,7 +13,7 @@ module Train class Error < ::StandardError attr_reader :reason - def initialize(message = '', reason = :not_provided) + def initialize(message = "", reason = :not_provided) super(message) @reason = reason end diff --git a/lib/train/extras.rb b/lib/train/extras.rb index 89d5f62f..e3c2a819 100644 --- a/lib/train/extras.rb +++ b/lib/train/extras.rb @@ -3,8 +3,8 @@ # Author:: Dominik Richter () module Train::Extras - require 'train/extras/command_wrapper' - require 'train/extras/stat' + require "train/extras/command_wrapper" + require "train/extras/stat" CommandResult = Struct.new(:stdout, :stderr, :exit_status) LoginCommand = Struct.new(:command, :arguments) diff --git a/lib/train/extras/command_wrapper.rb b/lib/train/extras/command_wrapper.rb index de70b0d4..abda3845 100644 --- a/lib/train/extras/command_wrapper.rb +++ b/lib/train/extras/command_wrapper.rb @@ -2,8 +2,8 @@ # author: Dominik Richter # author: Christoph Hartmann -require 'base64' -require 'train/errors' +require "base64" +require "train/errors" module Train::Extras # Define the interface of all command wrappers. @@ -12,7 +12,7 @@ class CommandWrapperBase # # @return [Any] verification result, nil if all went well, otherwise a message def verify - fail Train::ClientError, "#{self.class} does not implement #verify()" + raise Train::ClientError, "#{self.class} does not implement #verify()" end # Wrap a command and return the augmented command which can be executed. @@ -20,7 +20,7 @@ def verify # @param [Strin] command that will be wrapper # @return [String] result of wrapping the command def run(_command) - fail Train::ClientError, "#{self.class} does not implement #run(command)" + raise Train::ClientError, "#{self.class} does not implement #run(command)" end end @@ -53,20 +53,20 @@ def initialize(backend, options) # (see CommandWrapperBase::verify) def verify - res = @backend.run_command(run('echo')) + res = @backend.run_command(run("echo")) return nil if res.exit_status == 0 - rawerr = res.stdout + ' ' + res.stderr + rawerr = res.stdout + " " + res.stderr { - 'Sorry, try again' => ['Wrong sudo password.', :bad_sudo_password], - 'sudo: no tty present and no askpass program specified' => - ['Sudo requires a password, please configure it.', :sudo_password_required], - 'sudo: command not found' => + "Sorry, try again" => ["Wrong sudo password.", :bad_sudo_password], + "sudo: no tty present and no askpass program specified" => + ["Sudo requires a password, please configure it.", :sudo_password_required], + "sudo: command not found" => ["Can't find sudo command. Please either install and "\ - 'configure it on the target or deactivate sudo.', :sudo_command_not_found], - 'sudo: sorry, you must have a tty to run sudo' => - ['Sudo requires a TTY. Please see the README on how to configure '\ - 'sudo to allow for non-interactive usage.', :sudo_no_tty], + "configure it on the target or deactivate sudo.", :sudo_command_not_found], + "sudo: sorry, you must have a tty to run sudo" => + ["Sudo requires a TTY. Please see the README on how to configure "\ + "sudo to allow for non-interactive usage.", :sudo_no_tty], }.each do |sudo, human| rawerr = human if rawerr.include? sudo end @@ -91,13 +91,13 @@ def self.active?(options) # wrap the cmd in a sudo command def sudo_wrap(cmd) return cmd unless @sudo - return cmd if @user == 'root' + return cmd if @user == "root" - res = (@sudo_command || 'sudo') + ' ' + res = (@sudo_command || "sudo") + " " res = "#{safe_string(@sudo_password + "\n")} | #{res}-S " unless @sudo_password.nil? - res << @sudo_options.to_s + ' ' unless @sudo_options.nil? + res << @sudo_options.to_s + " " unless @sudo_options.nil? res + cmd end @@ -107,8 +107,8 @@ def sudo_wrap(cmd) def shell_wrap(cmd) return cmd unless @shell - shell = @shell_command || '$SHELL' - options = ' ' + @shell_options.to_s unless @shell_options.nil? + shell = @shell_command || "$SHELL" + options = " " + @shell_options.to_s unless @shell_options.nil? "#{safe_string(cmd)} | #{shell}#{options}" end @@ -143,13 +143,13 @@ def run(command) # Wrap the cmd in an encoded command to allow pipes and quotes def powershell_wrap(cmd) - shell = @shell_command || 'powershell' + shell = @shell_command || "powershell" # Prevent progress stream from leaking into stderr script = "$ProgressPreference='SilentlyContinue';" + cmd # Encode script so PowerShell can use it - script = script.encode('UTF-16LE', 'UTF-8') + script = script.encode("UTF-16LE", "UTF-8") base64_script = Base64.strict_encode64(script) cmd = "#{shell} -NoProfile -EncodedCommand #{base64_script}" diff --git a/lib/train/extras/stat.rb b/lib/train/extras/stat.rb index f9cdaec0..518f52cc 100644 --- a/lib/train/extras/stat.rb +++ b/lib/train/extras/stat.rb @@ -4,13 +4,13 @@ module Train::Extras class Stat TYPES = { - socket: 00140000, - symlink: 00120000, - file: 00100000, - block_device: 00060000, - directory: 00040000, + socket: 00140000, + symlink: 00120000, + file: 00100000, + block_device: 00060000, + directory: 00040000, character_device: 00020000, - pipe: 00010000, + pipe: 00010000, }.freeze def self.find_type(mode) @@ -33,8 +33,8 @@ def self.stat(shell_escaped_path, backend, follow_symlink) end def self.linux_stat(shell_escaped_path, backend, follow_symlink) - lstat = follow_symlink ? ' -L' : '' - format = (backend.os.esx? || backend.os[:name] == 'alpine') ? '-c' : '--printf' + lstat = follow_symlink ? " -L" : "" + format = (backend.os.esx? || backend.os[:name] == "alpine") ? "-c" : "--printf" res = backend.run_command("stat#{lstat} #{shell_escaped_path} 2>/dev/null #{format} '%s\n%f\n%U\n%u\n%G\n%g\n%X\n%Y\n%C'") # ignore the exit_code: it is != 0 if selinux labels are not supported # on the system. @@ -45,16 +45,16 @@ def self.linux_stat(shell_escaped_path, backend, follow_symlink) tmask = fields[1].to_i(16) selinux = fields[8] ## selinux security context string not available on esxi - selinux = nil if selinux == '?' or selinux == '(null)' or selinux == 'C' + selinux = nil if (selinux == "?") || (selinux == "(null)") || (selinux == "C") { - type: find_type(tmask), - mode: tmask & 07777, + type: find_type(tmask), + mode: tmask & 07777, owner: fields[2], - uid: fields[3].to_i, + uid: fields[3].to_i, group: fields[4], - gid: fields[5].to_i, + gid: fields[5].to_i, mtime: fields[7].to_i, - size: fields[0].to_i, + size: fields[0].to_i, selinux_label: selinux, } end @@ -74,7 +74,7 @@ def self.bsd_stat(shell_escaped_path, backend, follow_symlink) # in combination with: # ... # gu Display group or user name. - lstat = follow_symlink ? ' -L' : '' + lstat = follow_symlink ? " -L" : "" res = backend.run_command( "stat#{lstat} -f '%z\n%p\n%Su\n%u\n%Sg\n%g\n%a\n%m' "\ "#{shell_escaped_path}") @@ -87,21 +87,21 @@ def self.bsd_stat(shell_escaped_path, backend, follow_symlink) tmask = fields[1].to_i(8) { - type: find_type(tmask), - mode: tmask & 07777, + type: find_type(tmask), + mode: tmask & 07777, owner: fields[2], - uid: fields[3].to_i, + uid: fields[3].to_i, group: fields[4], - gid: fields[5].to_i, + gid: fields[5].to_i, mtime: fields[7].to_i, - size: fields[0].to_i, + size: fields[0].to_i, selinux_label: fields[8], } end def self.aix_stat(shell_escaped_path, backend, follow_symlink) # Perl here b/c it is default on AIX - lstat = follow_symlink ? 'lstat' : 'stat' + lstat = follow_symlink ? "lstat" : "stat" stat_cmd = <<-EOP perl -e ' @a = #{lstat}(shift) or exit 2; @@ -115,16 +115,16 @@ def self.aix_stat(shell_escaped_path, backend, follow_symlink) return {} if res.exit_status != 0 fields = res.stdout.split("\n") return {} if fields.length != 7 - tmask = fields[0].to_i(8) + tmask = fields[0].to_i(8) { - type: find_type(tmask), - mode: tmask & 07777, + type: find_type(tmask), + mode: tmask & 07777, owner: fields[1], - uid: fields[2].to_i, + uid: fields[2].to_i, group: fields[3], - gid: fields[4].to_i, + gid: fields[4].to_i, mtime: fields[5].to_i, - size: fields[6].to_i, + size: fields[6].to_i, selinux_label: nil, } end diff --git a/lib/train/file.rb b/lib/train/file.rb index 5a54fb7f..d30b1819 100644 --- a/lib/train/file.rb +++ b/lib/train/file.rb @@ -3,15 +3,15 @@ # author: Christoph Hartmann # author: Dominik Richter -require 'train/file/local' -require 'train/file/remote' -require 'train/extras/stat' +require "train/file/local" +require "train/file/remote" +require "train/extras/stat" module Train class File # rubocop:disable Metrics/ClassLength def initialize(backend, path, follow_symlink = true) @backend = backend - @path = path || '' + @path = path || "" @follow_symlink = follow_symlink sanitize_filename(path) @@ -30,15 +30,15 @@ def sanitize_filename(_path) DATA_FIELDS.each do |m| define_method m.to_sym do - fail NotImplementedError, "File must implement the #{m}() method." + raise NotImplementedError, "File must implement the #{m}() method." end end def to_json res = Hash[DATA_FIELDS.map { |x| [x, method(x).call] }] # additional fields provided as input - res['type'] = type - res['follow_symlink'] = @follow_symlink + res["type"] = type + res["follow_symlink"] = @follow_symlink res end @@ -73,36 +73,36 @@ def file_version end def version?(version) - product_version == version or - file_version == version + (product_version == version) || + (file_version == version) end def block_device? - type.to_s == 'block_device' + type.to_s == "block_device" end def character_device? - type.to_s == 'character_device' + type.to_s == "character_device" end def pipe? - type.to_s == 'pipe' + type.to_s == "pipe" end def file? - type.to_s == 'file' + type.to_s == "file" end def socket? - type.to_s == 'socket' + type.to_s == "socket" end def directory? - type.to_s == 'directory' + type.to_s == "directory" end def symlink? - source.type.to_s == 'symlink' + source.type.to_s == "symlink" end def owned_by?(sth) @@ -134,16 +134,16 @@ def md5sum # Skip processing rest of method if fallback method is selected return perform_checksum_ruby(:md5) if defined?(@ruby_checksum_fallback) - checksum = if @backend.os.family == 'windows' + checksum = if @backend.os.family == "windows" perform_checksum_windows(:md5) else @md5_command ||= case @backend.os.family - when 'darwin' - 'md5 -r' - when 'solaris' - 'digest -a md5' + when "darwin" + "md5 -r" + when "solaris" + "digest -a md5" else - 'md5sum' + "md5sum" end perform_checksum_unix(@md5_command) @@ -156,16 +156,16 @@ def sha256sum # Skip processing rest of method if fallback method is selected return perform_checksum_ruby(:sha256) if defined?(@ruby_checksum_fallback) - checksum = if @backend.os.family == 'windows' + checksum = if @backend.os.family == "windows" perform_checksum_windows(:sha256) else @sha256_command ||= case @backend.os.family - when 'darwin', 'hpux', 'qnx' - 'shasum -a 256' - when 'solaris' - 'digest -a sha256' + when "darwin", "hpux", "qnx" + "shasum -a 256" + when "solaris" + "digest -a sha256" else - 'sha256sum' + "sha256sum" end perform_checksum_unix(@sha256_command) @@ -178,13 +178,13 @@ def sha256sum def perform_checksum_unix(cmd) res = @backend.run_command("#{cmd} #{@path}") - res.stdout.split(' ').first if res.exit_status == 0 + res.stdout.split(" ").first if res.exit_status == 0 end def perform_checksum_windows(method) cmd = "CertUtil -hashfile #{@path} #{method.to_s.upcase}" res = @backend.run_command(cmd) - res.stdout.split("\r\n")[1].tr(' ', '') if res.exit_status == 0 + res.stdout.split("\r\n")[1].tr(" ", "") if res.exit_status == 0 end # This pulls the content of the file to the machine running Train and uses diff --git a/lib/train/file/local.rb b/lib/train/file/local.rb index df85c329..d78c9d29 100644 --- a/lib/train/file/local.rb +++ b/lib/train/file/local.rb @@ -12,7 +12,7 @@ class Local < Train::File end def content - @content ||= ::File.read(@path, encoding: 'UTF-8') + @content ||= ::File.read(@path, encoding: "UTF-8") rescue StandardError => _ nil end @@ -23,7 +23,7 @@ def link_path @link_path ||= ::File.realpath(@path) rescue Errno::ELOOP => _ # Leave it blank on symbolic loop, same as readlink - @link_path = '' + @link_path = "" end end @@ -42,13 +42,13 @@ def character_device? def type case ::File.ftype(@path) - when 'blockSpecial' + when "blockSpecial" :block_device - when 'characterSpecial' + when "characterSpecial" :character_device - when 'link' + when "link" :symlink - when 'fifo' + when "fifo" :pipe else ::File.ftype(@path).to_sym @@ -76,5 +76,5 @@ def linked_to?(dst) # subclass requires are loaded after Train::File::Local is defined # to avoid superclass mismatch errors -require 'train/file/local/unix' -require 'train/file/local/windows' +require "train/file/local/unix" +require "train/file/local/windows" diff --git a/lib/train/file/local/unix.rb b/lib/train/file/local/unix.rb index 1949b6a1..d5c09d80 100644 --- a/lib/train/file/local/unix.rb +++ b/lib/train/file/local/unix.rb @@ -1,7 +1,7 @@ # encoding: utf-8 -require 'shellwords' -require 'train/extras/stat' +require "shellwords" +require "train/extras/stat" module Train class File @@ -36,9 +36,9 @@ def stat gid: file_stat.gid, } - lstat = @follow_symlink ? ' -L' : '' + lstat = @follow_symlink ? " -L" : "" res = @backend.run_command("stat#{lstat} #{@spath} 2>/dev/null --printf '%C'") - if res.exit_status == 0 && !res.stdout.empty? && res.stdout != '?' + if res.exit_status == 0 && !res.stdout.empty? && res.stdout != "?" @stat[:selinux_label] = res.stdout.strip end @@ -79,7 +79,7 @@ def pw_groupname(gid) end UNIX_MODE_OWNERS = { - all: 00777, + all: 00777, owner: 00700, group: 00070, other: 00007, diff --git a/lib/train/file/local/windows.rb b/lib/train/file/local/windows.rb index ef6c123b..3dd342e0 100644 --- a/lib/train/file/local/windows.rb +++ b/lib/train/file/local/windows.rb @@ -9,7 +9,7 @@ class Windows < Train::File::Local def sanitize_filename(path) return if path.nil? # we do not filter :, backslash and forward slash, since they are part of the path - @spath = path.gsub(/[<>"|?*]/, '') + @spath = path.gsub(/[<>"|?*]/, "") end def product_version diff --git a/lib/train/file/remote.rb b/lib/train/file/remote.rb index 6308c4aa..626cb6e1 100644 --- a/lib/train/file/remote.rb +++ b/lib/train/file/remote.rb @@ -3,9 +3,9 @@ module Train class File class Remote < Train::File - def basename(suffix = nil, sep = '/') - fail 'Not yet supported: Suffix in file.basename' unless suffix.nil? - @basename ||= detect_filename(path, sep || '/') + def basename(suffix = nil, sep = "/") + raise "Not yet supported: Suffix in file.basename" unless suffix.nil? + @basename ||= detect_filename(path, sep || "/") end def stat @@ -29,8 +29,8 @@ def detect_filename(path, sep) # subclass requires are loaded after Train::File::Remote is defined # to avoid superclass mismatch errors -require 'train/file/remote/aix' -require 'train/file/remote/linux' -require 'train/file/remote/qnx' -require 'train/file/remote/unix' -require 'train/file/remote/windows' +require "train/file/remote/aix" +require "train/file/remote/linux" +require "train/file/remote/qnx" +require "train/file/remote/unix" +require "train/file/remote/windows" diff --git a/lib/train/file/remote/aix.rb b/lib/train/file/remote/aix.rb index 652e2dab..c27541cb 100644 --- a/lib/train/file/remote/aix.rb +++ b/lib/train/file/remote/aix.rb @@ -1,6 +1,6 @@ # encoding: utf-8 -require 'train/file/remote/unix' +require "train/file/remote/unix" module Train class File diff --git a/lib/train/file/remote/linux.rb b/lib/train/file/remote/linux.rb index 2cf64cd4..b97ca15d 100644 --- a/lib/train/file/remote/linux.rb +++ b/lib/train/file/remote/linux.rb @@ -1,6 +1,6 @@ # encoding: utf-8 -require 'train/file/remote/unix' +require "train/file/remote/unix" module Train class File @@ -10,7 +10,7 @@ def content return @content if defined?(@content) @content = @backend.run_command("cat #{@spath} || echo -n").stdout return @content unless @content.empty? - @content = nil if directory? or size.nil? or size > 0 + @content = nil if directory? || size.nil? || (size > 0) @content end end diff --git a/lib/train/file/remote/qnx.rb b/lib/train/file/remote/qnx.rb index dabc68d1..388a99f1 100644 --- a/lib/train/file/remote/qnx.rb +++ b/lib/train/file/remote/qnx.rb @@ -3,28 +3,28 @@ # author: Christoph Hartmann # author: Dominik Richter -require 'train/file/remote/unix' +require "train/file/remote/unix" module Train class File class Remote class Qnx < Train::File::Remote::Unix def content - cat = 'cat' - cat = '/proc/boot/cat' if @backend.os[:release].to_i >= 7 + cat = "cat" + cat = "/proc/boot/cat" if @backend.os[:release].to_i >= 7 @content ||= case when !exist? nil else - @backend.run_command("#{cat} #{@spath}").stdout || '' + @backend.run_command("#{cat} #{@spath}").stdout || "" end end def type - if @backend.run_command("file #{@spath}").stdout.include?('directory') - return :directory + if @backend.run_command("file #{@spath}").stdout.include?("directory") + :directory else - return :file + :file end end @@ -32,7 +32,7 @@ def type mode owner group uid gid mtime size selinux_label link_path mounted stat }.each do |field| define_method field.to_sym do - fail NotImplementedError, "QNX does not implement the #{field}() method yet." + raise NotImplementedError, "QNX does not implement the #{field}() method yet." end end end diff --git a/lib/train/file/remote/unix.rb b/lib/train/file/remote/unix.rb index 833729fb..c5fe2928 100644 --- a/lib/train/file/remote/unix.rb +++ b/lib/train/file/remote/unix.rb @@ -1,13 +1,9 @@ -# encoding: utf-8 - -require 'shellwords' +require "shellwords" module Train class File class Remote class Unix < Train::File::Remote - attr_reader :path - def sanitize_filename(path) @spath = Shellwords.escape(path) || @path end @@ -16,19 +12,19 @@ def content @content ||= if !exist? || directory? nil - elsif size.nil? || size.zero? - '' + elsif size.nil? || size == 0 + "" else - @backend.run_command("cat #{@spath}").stdout || '' + @backend.run_command("cat #{@spath}").stdout || "" end end def exist? - @exist ||= ( - f = @follow_symlink ? '' : " || test -L #{@spath}" - @backend.run_command("test -e #{@spath}"+f) + @exist ||= begin + f = @follow_symlink ? "" : " || test -L #{@spath}" + @backend.run_command("test -e #{@spath}" + f) .exit_status == 0 - ) + end end def mounted @@ -88,14 +84,14 @@ def read_target_path full_path = @backend.run_command("readlink -n #{@spath} -f").stdout # Needed for some OSes like OSX that returns relative path # when the link and target are in the same directory - if !full_path.start_with?('/') && full_path != '' + if !full_path.start_with?("/") && full_path != "" full_path = ::File.expand_path("../#{full_path}", @spath) end full_path end UNIX_MODE_OWNERS = { - all: 00777, + all: 00777, owner: 00700, group: 00070, other: 00007, diff --git a/lib/train/file/remote/windows.rb b/lib/train/file/remote/windows.rb index e3129ef9..9110e038 100644 --- a/lib/train/file/remote/windows.rb +++ b/lib/train/file/remote/windows.rb @@ -10,7 +10,7 @@ class Windows < Train::File::Remote def sanitize_filename(path) return if path.nil? # we do not filter :, backslash and forward slash, since they are part of the path - @spath = path.gsub(/[<>"|?*]/, '') + @spath = path.gsub(/[<>"|?*]/, "") end def basename(suffix = nil, sep = '\\') @@ -28,7 +28,7 @@ def content def exist? return @exist if defined?(@exist) @exist = @backend.run_command( - "(Test-Path -Path \"#{@spath}\").ToString()").stdout.chomp == 'True' + "(Test-Path -Path \"#{@spath}\").ToString()").stdout.chomp == "True" end def owner @@ -39,11 +39,11 @@ def owner end def type - if attributes.include?('Archive') && !attributes.include?('Directory') + if attributes.include?("Archive") && !attributes.include?("Directory") return :file - elsif attributes.include?('ReparsePoint') + elsif attributes.include?("ReparsePoint") return :symlink - elsif attributes.include?('Directory') + elsif attributes.include?("Directory") return :directory end :unknown diff --git a/lib/train/globals.rb b/lib/train/globals.rb index 04e0a67a..2bc4188e 100644 --- a/lib/train/globals.rb +++ b/lib/train/globals.rb @@ -1,5 +1,5 @@ module Train def self.src_root - File.expand_path(File.join(__FILE__, '..', '..', '..')) + File.expand_path(File.join(__FILE__, "..", "..", "..")) end end diff --git a/lib/train/options.rb b/lib/train/options.rb index cda8c188..1c2e52c5 100644 --- a/lib/train/options.rb +++ b/lib/train/options.rb @@ -14,15 +14,15 @@ module ClassOptions def option(name, conf = nil, &block) d = conf || {} unless d.is_a? Hash - fail Train::ClientError, + raise Train::ClientError, "The transport plugin #{self} declared an option #{name} "\ "and didn't provide a valid configuration hash." end - if !conf.nil? and !conf[:default].nil? and block_given? - fail Train::ClientError, + if !conf.nil? && !conf[:default].nil? && block_given? + raise Train::ClientError, "The transport plugin #{self} declared an option #{name} "\ - 'with both a default value and block. Only use one of these.' + "with both a default value and block. Only use one of these." end d[:default] = block if block_given? @@ -37,7 +37,7 @@ def default_options def include_options(other) unless other.respond_to?(:default_options) - fail "Trying to include options from module #{other.inspect}, "\ + raise "Trying to include options from module #{other.inspect}, "\ "which doesn't seem to support options." end default_options.merge!(other.default_options) @@ -55,7 +55,7 @@ def default_options def merge_options(base, opts) res = base.merge(opts || {}) default_options.each do |field, hm| - next unless res[field].nil? and hm.key?(:default) + next unless res[field].nil? && hm.key?(:default) default = hm[:default] if default.is_a? Proc res[field] = default.call(res) @@ -68,8 +68,8 @@ def merge_options(base, opts) def validate_options(opts) default_options.each do |field, hm| - if opts[field].nil? and hm[:required] - fail Train::ClientError, + if opts[field].nil? && hm[:required] + raise Train::ClientError, "You must provide a value for #{field.to_s.inspect}." end end diff --git a/lib/train/platforms.rb b/lib/train/platforms.rb index 9f7d3243..117b37d7 100644 --- a/lib/train/platforms.rb +++ b/lib/train/platforms.rb @@ -1,13 +1,13 @@ # encoding: utf-8 -require 'train/platforms/common' -require 'train/platforms/detect' -require 'train/platforms/detect/scanner' -require 'train/platforms/detect/specifications/os' -require 'train/platforms/detect/specifications/api' -require 'train/platforms/detect/uuid' -require 'train/platforms/family' -require 'train/platforms/platform' +require "train/platforms/common" +require "train/platforms/detect" +require "train/platforms/detect/scanner" +require "train/platforms/detect/specifications/os" +require "train/platforms/detect/specifications/api" +require "train/platforms/detect/uuid" +require "train/platforms/family" +require "train/platforms/platform" module Train::Platforms class << self diff --git a/lib/train/platforms/common.rb b/lib/train/platforms/common.rb index 44326c68..03f6cc79 100644 --- a/lib/train/platforms/common.rb +++ b/lib/train/platforms/common.rb @@ -6,7 +6,7 @@ module Common # if it does not exist and add a child relationship. def in_family(family) if self.class == Train::Platforms::Family && @name == family - fail "Unable to add family #{@name} to itself: '#{@name}.in_family(#{family})'" + raise "Unable to add family #{@name} to itself: '#{@name}.in_family(#{family})'" end # add family to the family list diff --git a/lib/train/platforms/detect/helpers/os_common.rb b/lib/train/platforms/detect/helpers/os_common.rb index c097f3bf..88af6dad 100644 --- a/lib/train/platforms/detect/helpers/os_common.rb +++ b/lib/train/platforms/detect/helpers/os_common.rb @@ -1,8 +1,6 @@ -# encoding: utf-8 - -require 'train/platforms/detect/helpers/os_linux' -require 'train/platforms/detect/helpers/os_windows' -require 'rbconfig' +require "train/platforms/detect/helpers/os_linux" +require "train/platforms/detect/helpers/os_windows" +require "rbconfig" module Train::Platforms::Detect::Helpers module OSCommon @@ -10,11 +8,11 @@ module OSCommon include Train::Platforms::Detect::Helpers::Windows def ruby_host_os(regex) - ::RbConfig::CONFIG['host_os'] =~ regex + ::RbConfig::CONFIG["host_os"] =~ regex end def winrm? - @backend.class.to_s == 'Train::Transports::WinRM::Connection' + @backend.class.to_s == "Train::Transports::WinRM::Connection" end def unix_file_contents(path) @@ -23,12 +21,12 @@ def unix_file_contents(path) res = @backend.run_command("test -f #{path} && cat #{path}") # ignore files that can't be read - @files[path] = res.exit_status.zero? ? res.stdout : nil + @files[path] = res.exit_status == 0 ? res.stdout : nil @files[path] end def unix_file_exist?(path) - @backend.run_command("test -f #{path}").exit_status.zero? + @backend.run_command("test -f #{path}").exit_status == 0 end def command_output(cmd) @@ -39,26 +37,26 @@ def command_output(cmd) def unix_uname_s return @uname[:s] if @uname.key?(:s) - @uname[:s] = command_output('uname -s') + @uname[:s] = command_output("uname -s") end def unix_uname_r return @uname[:r] if @uname.key?(:r) - @uname[:r] = command_output('uname -r') + @uname[:r] = command_output("uname -r") end def unix_uname_m return @uname[:m] if @uname.key?(:m) - @uname[:m] = command_output('uname -m') + @uname[:m] = command_output("uname -m") end def brocade_version return @cache[:brocade] if @cache.key?(:brocade) - res = command_output('version') + res = command_output("version") m = res.match(/^Fabric OS:\s+v(\S+)$/) unless m.nil? - return @cache[:brocade] = { version: m[1], type: 'fos' } + return @cache[:brocade] = { version: m[1], type: "fos" } end @cache[:brocade] = nil @@ -66,22 +64,22 @@ def brocade_version def cisco_show_version return @cache[:cisco] if @cache.key?(:cisco) - res = command_output('show version') + res = command_output("show version") m = res.match(/Cisco IOS Software, [^,]+? \(([^,]+?)\), Version (\d+\.\d+)/) unless m.nil? - return @cache[:cisco] = { version: m[2], model: m[1], type: 'ios' } + return @cache[:cisco] = { version: m[2], model: m[1], type: "ios" } end m = res.match(/Cisco IOS Software, IOS-XE Software, [^,]+? \(([^,]+?)\), Version (\d+\.\d+\.\d+[A-Z]*)/) unless m.nil? - return @cache[:cisco] = { version: m[2], model: m[1], type: 'ios-xe' } + return @cache[:cisco] = { version: m[2], model: m[1], type: "ios-xe" } end m = res.match(/Cisco Nexus Operating System \(NX-OS\) Software/) unless m.nil? v = res[/^\s*system:\s+version (\d+\.\d+)/, 1] - return @cache[:cisco] = { version: v, type: 'nexus' } + return @cache[:cisco] = { version: v, type: "nexus" } end @cache[:cisco] = nil @@ -91,27 +89,28 @@ def unix_uuid (unix_uuid_from_chef || unix_uuid_from_machine_file || uuid_from_command || - raise(Train::TransportError, 'Cannot find a UUID for your node.')) + raise(Train::TransportError, "Cannot find a UUID for your node.")) end def unix_uuid_from_chef - file = @backend.file('/var/chef/cache/data_collector_metadata.json') - if file.exist? && !file.size.zero? + file = @backend.file("/var/chef/cache/data_collector_metadata.json") + if file.exist? && file.size != 0 json = ::JSON.parse(file.content) - return json['node_uuid'] if json['node_uuid'] + return json["node_uuid"] if json["node_uuid"] end end def unix_uuid_from_machine_file - %W( + # require 'pry';binding.pry + %W{ /etc/chef/chef_guid #{ENV['HOME']}/.chef/chef_guid /etc/machine-id /var/lib/dbus/machine-id /var/db/dbus/machine-id - ).each do |path| + }.each do |path| file = @backend.file(path) - next unless file.exist? && !file.size.zero? + next unless file.exist? && file.size != 0 return file.content.chomp if path =~ /guid/ return uuid_from_string(file.content.chomp) end @@ -124,7 +123,7 @@ def unix_uuid_from_machine_file def uuid_from_command return unless @platform[:uuid_command] result = @backend.run_command(@platform[:uuid_command]) - uuid_from_string(result.stdout.chomp) if result.exit_status.zero? && !result.stdout.empty? + uuid_from_string(result.stdout.chomp) if result.exit_status == 0 && !result.stdout.empty? end # This hashes the passed string into SHA1. @@ -133,11 +132,11 @@ def uuid_from_command def uuid_from_string(string) hash = Digest::SHA1.new hash.update(string) - ary = hash.digest.unpack('NnnnnN') + ary = hash.digest.unpack("NnnnnN") ary[2] = (ary[2] & 0x0FFF) | (5 << 12) ary[3] = (ary[3] & 0x3FFF) | 0x8000 # rubocop:disable Style/FormatString - '%08x-%04x-%04x-%04x-%04x%08x' % ary + "%08x-%04x-%04x-%04x-%04x%08x" % ary end end end diff --git a/lib/train/platforms/detect/helpers/os_linux.rb b/lib/train/platforms/detect/helpers/os_linux.rb index ba37fc06..2b6ae4ef 100644 --- a/lib/train/platforms/detect/helpers/os_linux.rb +++ b/lib/train/platforms/detect/helpers/os_linux.rb @@ -3,7 +3,7 @@ module Train::Platforms::Detect::Helpers module Linux def redhatish_platform(conf) - conf =~ /^red hat/i ? 'redhat' : /(\w+)/i.match(conf)[1].downcase + conf =~ /^red hat/i ? "redhat" : /(\w+)/i.match(conf)[1].downcase end def redhatish_version(conf) @@ -20,11 +20,11 @@ def redhatish_version(conf) end def linux_os_release - data = unix_file_contents('/etc/os-release') + data = unix_file_contents("/etc/os-release") return if data.nil? os_info = parse_os_release_info(data) - cisco_info_file = os_info['CISCO_RELEASE_INFO'] + cisco_info_file = os_info["CISCO_RELEASE_INFO"] if cisco_info_file os_info.merge!(parse_os_release_info(unix_file_contents(cisco_info_file))) end @@ -37,10 +37,10 @@ def parse_os_release_info(raw) raw.lines.each_with_object({}) do |line, memo| line.strip! - next if line.start_with?('#') + next if line.start_with?("#") next if line.empty? - key, value = line.split('=', 2) - memo[key] = value.gsub(/\A"|"\Z/, '') unless value.empty? + key, value = line.split("=", 2) + memo[key] = value.gsub(/\A"|"\Z/, "") unless value.empty? end end @@ -49,8 +49,8 @@ def lsb_config(content) release = /^DISTRIB_RELEASE=["']?(.+?)["']?$/.match(content) codename = /^DISTRIB_CODENAME=["']?(.+?)["']?$/.match(content) { - id: id.nil? ? nil : id[1], - release: release.nil? ? nil : release[1], + id: id.nil? ? nil : id[1], + release: release.nil? ? nil : release[1], codename: codename.nil? ? nil : codename[1], } end @@ -60,17 +60,17 @@ def lsb_release(content) release = /^Release:\s+(.+)$/.match(content) codename = /^Codename:\s+(.+)$/.match(content) { - id: id.nil? ? nil : id[1], - release: release.nil? ? nil : release[1], + id: id.nil? ? nil : id[1], + release: release.nil? ? nil : release[1], codename: codename.nil? ? nil : codename[1], } end def read_linux_lsb return @lsb unless @lsb.empty? - if !(raw = unix_file_contents('/etc/lsb-release')).nil? + if !(raw = unix_file_contents("/etc/lsb-release")).nil? @lsb = lsb_config(raw) - elsif !(raw = unix_file_contents('/usr/bin/lsb-release')).nil? + elsif !(raw = unix_file_contents("/usr/bin/lsb-release")).nil? @lsb = lsb_release(raw) end end diff --git a/lib/train/platforms/detect/helpers/os_windows.rb b/lib/train/platforms/detect/helpers/os_windows.rb index ded073e7..dd7f38b5 100644 --- a/lib/train/platforms/detect/helpers/os_windows.rb +++ b/lib/train/platforms/detect/helpers/os_windows.rb @@ -1,22 +1,20 @@ -# encoding: utf-8 - module Train::Platforms::Detect::Helpers module Windows def detect_windows # try to detect windows, use cmd.exe to also support Microsoft OpenSSH - res = @backend.run_command('cmd.exe /c ver') - return false if res.exit_status != 0 or res.stdout.empty? + res = @backend.run_command("cmd.exe /c ver") + return false if (res.exit_status != 0) || res.stdout.empty? # if the ver contains `Windows`, we know its a Windows system version = res.stdout.strip return false unless version.downcase =~ /windows/ - @platform[:family] = 'windows' + @platform[:family] = "windows" # try to extract release from eg. `Microsoft Windows [Version 6.3.9600]` release = /\[(?.*)\]/.match(version) unless release[:name].nil? # release is 6.3.9600 now - @platform[:release] = release[:name].downcase.gsub('version', '').strip + @platform[:release] = release[:name].downcase.gsub("version", "").strip # fallback, if we are not able to extract the name from wmic later @platform[:name] = "Windows #{@platform[:release]}" end @@ -31,19 +29,19 @@ def detect_windows # @see https://msdn.microsoft.com/en-us/library/bb742610.aspx#EEAA # Thanks to Matt Wrock (https://github.com/mwrock) for this hint def read_wmic - res = @backend.run_command('wmic os get * /format:list') + res = @backend.run_command("wmic os get * /format:list") if res.exit_status == 0 sys_info = {} - res.stdout.lines.each { |line| + res.stdout.lines.each do |line| m = /^\s*([^=]*?)\s*=\s*(.*?)\s*$/.match(line) sys_info[m[1].to_sym] = m[2] unless m.nil? || m[1].nil? - } + end @platform[:release] = sys_info[:Version] # additional info on windows @platform[:build] = sys_info[:BuildNumber] @platform[:name] = sys_info[:Caption] - @platform[:name] = @platform[:name].gsub('Microsoft', '').strip unless @platform[:name].empty? + @platform[:name] = @platform[:name].gsub("Microsoft", "").strip unless @platform[:name].empty? @platform[:arch] = read_wmic_cpu end end @@ -51,25 +49,25 @@ def read_wmic # `OSArchitecture` from `read_wmic` does not match a normal standard # For example, `x86_64` shows as `64-bit` def read_wmic_cpu - res = @backend.run_command('wmic cpu get architecture /format:list') + res = @backend.run_command("wmic cpu get architecture /format:list") if res.exit_status == 0 sys_info = {} - res.stdout.lines.each { |line| + res.stdout.lines.each do |line| m = /^\s*([^=]*?)\s*=\s*(.*?)\s*$/.match(line) sys_info[m[1].to_sym] = m[2] unless m.nil? || m[1].nil? - } + end end # This converts `wmic os get architecture` output to a normal standard # https://msdn.microsoft.com/en-us/library/aa394373(VS.85).aspx arch_map = { - 0 => 'i386', - 1 => 'mips', - 2 => 'alpha', - 3 => 'powerpc', - 5 => 'arm', - 6 => 'ia64', - 9 => 'x86_64', + 0 => "i386", + 1 => "mips", + 2 => "alpha", + 3 => "powerpc", + 5 => "arm", + 6 => "ia64", + 9 => "x86_64", } # The value of `wmic cpu get architecture` is always a number between 0-9 @@ -83,38 +81,38 @@ def windows_uuid uuid = windows_uuid_from_machine_file if uuid.nil? uuid = windows_uuid_from_wmic if uuid.nil? uuid = windows_uuid_from_registry if uuid.nil? - raise Train::TransportError, 'Cannot find a UUID for your node.' if uuid.nil? + raise Train::TransportError, "Cannot find a UUID for your node." if uuid.nil? uuid end def windows_uuid_from_machine_file - %W( + %W{ #{ENV['SYSTEMDRIVE']}\\chef\\chef_guid #{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}\\.chef\\chef_guid - ).each do |path| + }.each do |path| file = @backend.file(path) - return file.content.chomp if file.exist? && !file.size.zero? + return file.content.chomp if file.exist? && file.size != 0 end nil end def windows_uuid_from_chef file = @backend.file("#{ENV['SYSTEMDRIVE']}\\chef\\cache\\data_collector_metadata.json") - return if !file.exist? || file.size.zero? + return if !file.exist? || file.size == 0 json = JSON.parse(file.content) - json['node_uuid'] if json['node_uuid'] + json["node_uuid"] if json["node_uuid"] end def windows_uuid_from_wmic - result = @backend.run_command('wmic csproduct get UUID') - return unless result.exit_status.zero? + result = @backend.run_command("wmic csproduct get UUID") + return unless result.exit_status == 0 result.stdout.split("\r\n")[-1].strip end def windows_uuid_from_registry cmd = '(Get-ItemProperty "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography" -Name "MachineGuid")."MachineGuid"' result = @backend.run_command(cmd) - return unless result.exit_status.zero? + return unless result.exit_status == 0 result.stdout.chomp end end diff --git a/lib/train/platforms/detect/scanner.rb b/lib/train/platforms/detect/scanner.rb index 06b5e7e3..07b26a2d 100644 --- a/lib/train/platforms/detect/scanner.rb +++ b/lib/train/platforms/detect/scanner.rb @@ -1,6 +1,6 @@ # encoding: utf-8 -require 'train/platforms/detect/helpers/os_common' +require "train/platforms/detect/helpers/os_common" module Train::Platforms::Detect class Scanner @@ -38,7 +38,7 @@ def scan return get_platform(plat_result) end - fail Train::PlatformDetectionFailed, 'Sorry, we are unable to detect your platform' + raise Train::PlatformDetectionFailed, "Sorry, we are unable to detect your platform" end def scan_children(parent) @@ -65,8 +65,8 @@ def scan_family_children(plat) def check_condition(condition) condition.each do |k, v| - op, expected = v.strip.split(' ') - op = '==' if op == '=' + op, expected = v.strip.split(" ") + op = "==" if op == "=" return false if @platform[k].nil? || !instance_eval("'#{@platform[k]}' #{op} '#{expected}'") end diff --git a/lib/train/platforms/detect/specifications/api.rb b/lib/train/platforms/detect/specifications/api.rb index f69bfe49..1197f443 100644 --- a/lib/train/platforms/detect/specifications/api.rb +++ b/lib/train/platforms/detect/specifications/api.rb @@ -5,16 +5,16 @@ class Api def self.load plat = Train::Platforms - plat.family('api') + plat.family("api") - plat.family('cloud').in_family('api') - plat.name('aws').in_family('cloud') - plat.name('azure').in_family('cloud') - plat.name('gcp').in_family('cloud') - plat.name('vmware').in_family('cloud') + plat.family("cloud").in_family("api") + plat.name("aws").in_family("cloud") + plat.name("azure").in_family("cloud") + plat.name("gcp").in_family("cloud") + plat.name("vmware").in_family("cloud") - plat.family('iaas').in_family('api') - plat.name('oneview').in_family('iaas') + plat.family("iaas").in_family("api") + plat.name("oneview").in_family("iaas") end end end diff --git a/lib/train/platforms/detect/specifications/os.rb b/lib/train/platforms/detect/specifications/os.rb index 7dcbd14d..a7181cbb 100644 --- a/lib/train/platforms/detect/specifications/os.rb +++ b/lib/train/platforms/detect/specifications/os.rb @@ -13,15 +13,15 @@ def self.load plat = Train::Platforms # master family - plat.family('os').detect { true } + plat.family("os").detect { true } - plat.family('windows').in_family('os') - .detect { + plat.family("windows").in_family("os") + .detect do # Can't return from a `proc` thus the `is_windows` shenanigans is_windows = false is_windows = true if winrm? - if @backend.class.to_s == 'Train::Transports::Local::Connection' + if @backend.class.to_s == "Train::Transports::Local::Connection" is_windows = true if ruby_host_os(/mswin|mingw32|windows/) end @@ -31,61 +31,61 @@ def self.load end is_windows - } + end # windows platform - plat.name('windows').in_family('windows') - .detect { + plat.name("windows").in_family("windows") + .detect do true if detect_windows == true - } + end # unix master family - plat.family('unix').in_family('os') - .detect { + plat.family("unix").in_family("os") + .detect do # we want to catch a special case here where cisco commands # don't return an exit status and still print to stdout - if unix_uname_s =~ /./ && !unix_uname_s.start_with?('Line has invalid autocommand ') && !unix_uname_s.start_with?('The command you have entered') + if unix_uname_s =~ /./ && !unix_uname_s.start_with?("Line has invalid autocommand ") && !unix_uname_s.start_with?("The command you have entered") @platform[:arch] = unix_uname_m true end - } + end # linux master family - plat.family('linux').in_family('unix') - .detect { + plat.family("linux").in_family("unix") + .detect do true if unix_uname_s =~ /linux/i - } + end # debian family - plat.family('debian').in_family('linux') - .detect { - true unless unix_file_contents('/etc/debian_version').nil? - } - plat.name('ubuntu').title('Ubuntu Linux').in_family('debian') - .detect { + plat.family("debian").in_family("linux") + .detect do + true unless unix_file_contents("/etc/debian_version").nil? + end + plat.name("ubuntu").title("Ubuntu Linux").in_family("debian") + .detect do lsb = read_linux_lsb if lsb && lsb[:id] =~ /ubuntu/i @platform[:release] = lsb[:release] true end - } - plat.name('linuxmint').title('LinuxMint').in_family('debian') - .detect { + end + plat.name("linuxmint").title("LinuxMint").in_family("debian") + .detect do lsb = read_linux_lsb if lsb && lsb[:id] =~ /linuxmint/i @platform[:release] = lsb[:release] true end - } - plat.name('raspbian').title('Raspbian Linux').in_family('debian') - .detect { - if (linux_os_release && linux_os_release['NAME'] =~ /raspbian/i) || \ - unix_file_exist?('/usr/bin/raspi-config') - @platform[:release] = unix_file_contents('/etc/debian_version').chomp + end + plat.name("raspbian").title("Raspbian Linux").in_family("debian") + .detect do + if (linux_os_release && linux_os_release["NAME"] =~ /raspbian/i) || \ + unix_file_exist?("/usr/bin/raspi-config") + @platform[:release] = unix_file_contents("/etc/debian_version").chomp true end - } - plat.name('debian').title('Debian Linux').in_family('debian') - .detect { + end + plat.name("debian").title("Debian Linux").in_family("debian") + .detect do lsb = read_linux_lsb if lsb && lsb[:id] =~ /debian/i @platform[:release] = lsb[:release] @@ -93,247 +93,247 @@ def self.load end # if we get this far we have to be some type of debian - @platform[:release] = unix_file_contents('/etc/debian_version').chomp + @platform[:release] = unix_file_contents("/etc/debian_version").chomp true - } + end # fedora family - plat.family('fedora').in_family('linux') - .detect { - true if linux_os_release && linux_os_release['NAME'] =~ /fedora/i - } - plat.name('fedora').title('Fedora').in_family('fedora') - .detect { - @platform[:release] = linux_os_release['VERSION_ID'] + plat.family("fedora").in_family("linux") + .detect do + true if linux_os_release && linux_os_release["NAME"] =~ /fedora/i + end + plat.name("fedora").title("Fedora").in_family("fedora") + .detect do + @platform[:release] = linux_os_release["VERSION_ID"] true - } + end # arista_eos family # this checks for the arista bash shell # must come before redhat as it uses fedora under the hood - plat.family('arista_eos').title('Arista EOS Family').in_family('linux') - .detect { + plat.family("arista_eos").title("Arista EOS Family").in_family("linux") + .detect do true - } - plat.name('arista_eos_bash').title('Arista EOS Bash Shell').in_family('arista_eos') - .detect { - if unix_file_exist?('/usr/bin/FastCli') + end + plat.name("arista_eos_bash").title("Arista EOS Bash Shell").in_family("arista_eos") + .detect do + if unix_file_exist?("/usr/bin/FastCli") cmd = @backend.run_command('FastCli -p 15 -c "show version | json"') if cmd.exit_status == 0 && !cmd.stdout.empty? - require 'json' + require "json" begin eos_ver = JSON.parse(cmd.stdout) - @platform[:release] = eos_ver['version'] - @platform[:arch] = eos_ver['architecture'] + @platform[:release] = eos_ver["version"] + @platform[:arch] = eos_ver["architecture"] true rescue JSON::ParserError nil end end end - } + end # redhat family - plat.family('redhat').in_family('linux') - .detect { + plat.family("redhat").in_family("linux") + .detect do # I am not sure this returns true for all redhats in this family # for now we are going to just try each platform # return true unless unix_file_contents('/etc/redhat-release').nil? true - } - plat.name('centos').title('Centos Linux').in_family('redhat') - .detect { + end + plat.name("centos").title("Centos Linux").in_family("redhat") + .detect do lsb = read_linux_lsb if lsb && lsb[:id] =~ /centos/i @platform[:release] = lsb[:release] true - elsif linux_os_release && linux_os_release['NAME'] =~ /centos/i - @platform[:release] = redhatish_version(unix_file_contents('/etc/redhat-release')) + elsif linux_os_release && linux_os_release["NAME"] =~ /centos/i + @platform[:release] = redhatish_version(unix_file_contents("/etc/redhat-release")) true end - } - plat.name('oracle').title('Oracle Linux').in_family('redhat') - .detect { - if !(raw = unix_file_contents('/etc/oracle-release')).nil? + end + plat.name("oracle").title("Oracle Linux").in_family("redhat") + .detect do + if !(raw = unix_file_contents("/etc/oracle-release")).nil? @platform[:release] = redhatish_version(raw) true - elsif !(raw = unix_file_contents('/etc/enterprise-release')).nil? + elsif !(raw = unix_file_contents("/etc/enterprise-release")).nil? @platform[:release] = redhatish_version(raw) true end - } - plat.name('scientific').title('Scientific Linux').in_family('redhat') - .detect { + end + plat.name("scientific").title("Scientific Linux").in_family("redhat") + .detect do lsb = read_linux_lsb if lsb && lsb[:id] =~ /scientific/i @platform[:release] = lsb[:release] true end - } - plat.name('xenserver').title('Xenserer Linux').in_family('redhat') - .detect { + end + plat.name("xenserver").title("Xenserer Linux").in_family("redhat") + .detect do lsb = read_linux_lsb if lsb && lsb[:id] =~ /xenserver/i @platform[:release] = lsb[:release] true end - } - plat.name('parallels-release').title('Parallels Linux').in_family('redhat') - .detect { - if !(raw = unix_file_contents('/etc/parallels-release')).nil? + end + plat.name("parallels-release").title("Parallels Linux").in_family("redhat") + .detect do + if !(raw = unix_file_contents("/etc/parallels-release")).nil? @platform[:name] = redhatish_platform(raw) @platform[:release] = raw[/(\d\.\d\.\d)/, 1] true end - } - plat.name('wrlinux').title('Wind River Linux').in_family('redhat') - .detect { - if linux_os_release && linux_os_release['ID_LIKE'] =~ /wrlinux/i - @platform[:release] = linux_os_release['VERSION'] + end + plat.name("wrlinux").title("Wind River Linux").in_family("redhat") + .detect do + if linux_os_release && linux_os_release["ID_LIKE"] =~ /wrlinux/i + @platform[:release] = linux_os_release["VERSION"] true end - } - plat.name('amazon').title('Amazon Linux').in_family('redhat') - .detect { + end + plat.name("amazon").title("Amazon Linux").in_family("redhat") + .detect do lsb = read_linux_lsb if lsb && lsb[:id] =~ /amazon/i @platform[:release] = lsb[:release] true - elsif (raw = unix_file_contents('/etc/system-release')) =~ /amazon/i + elsif (raw = unix_file_contents("/etc/system-release")) =~ /amazon/i @platform[:name] = redhatish_platform(raw) @platform[:release] = redhatish_version(raw) true end - } - plat.name('cloudlinux').title('CloudLinux').in_family('redhat') - .detect { + end + plat.name("cloudlinux").title("CloudLinux").in_family("redhat") + .detect do lsb = read_linux_lsb if lsb && lsb[:id] =~ /cloudlinux/i @platform[:release] = lsb[:release] true - elsif (raw = unix_file_contents('/etc/redhat-release')) =~ /cloudlinux/i + elsif (raw = unix_file_contents("/etc/redhat-release")) =~ /cloudlinux/i @platform[:name] = redhatish_platform(raw) @platform[:release] = redhatish_version(raw) true end - } + end # keep redhat at the end as a fallback for anything with a redhat-release - plat.name('redhat').title('Red Hat Linux').in_family('redhat') - .detect { + plat.name("redhat").title("Red Hat Linux").in_family("redhat") + .detect do lsb = read_linux_lsb if lsb && lsb[:id] =~ /redhat/i @platform[:release] = lsb[:release] true - elsif !(raw = unix_file_contents('/etc/redhat-release')).nil? + elsif !(raw = unix_file_contents("/etc/redhat-release")).nil? # must be some type of redhat @platform[:name] = redhatish_platform(raw) @platform[:release] = redhatish_version(raw) true end - } + end # suse family - plat.family('suse').in_family('linux') - .detect { - if !(suse = unix_file_contents('/etc/SuSE-release')).nil? + plat.family("suse").in_family("linux") + .detect do + if !(suse = unix_file_contents("/etc/SuSE-release")).nil? # https://rubular.com/r/UKaYWolCYFMfp1 - version = suse.scan(/VERSION = (\d+)\nPATCHLEVEL = (\d+)/).flatten.join('.') + version = suse.scan(/VERSION = (\d+)\nPATCHLEVEL = (\d+)/).flatten.join(".") # https://rubular.com/r/b5PN3hZDxa5amV - version = suse[/VERSION\s?=\s?"?([\d\.]{2,})"?/, 1] if version == '' + version = suse[/VERSION\s?=\s?"?([\d\.]{2,})"?/, 1] if version == "" @platform[:release] = version true end - } - plat.name('opensuse').title('OpenSUSE Linux').in_family('suse') - .detect { - true if unix_file_contents('/etc/SuSE-release') =~ /^opensuse/i - } - plat.name('suse').title('Suse Linux').in_family('suse') - .detect { - true if unix_file_contents('/etc/SuSE-release') =~ /suse/i - } + end + plat.name("opensuse").title("OpenSUSE Linux").in_family("suse") + .detect do + true if unix_file_contents("/etc/SuSE-release") =~ /^opensuse/i + end + plat.name("suse").title("Suse Linux").in_family("suse") + .detect do + true if unix_file_contents("/etc/SuSE-release") =~ /suse/i + end # arch - plat.name('arch').title('Arch Linux').in_family('linux') - .detect { - if !unix_file_contents('/etc/arch-release').nil? + plat.name("arch").title("Arch Linux").in_family("linux") + .detect do + if !unix_file_contents("/etc/arch-release").nil? # Because this is a rolling release distribution, # use the kernel release, ex. 4.1.6-1-ARCH @platform[:release] = unix_uname_r true end - } + end # slackware - plat.name('slackware').title('Slackware Linux').in_family('linux') - .detect { - if !(raw = unix_file_contents('/etc/slackware-version')).nil? + plat.name("slackware").title("Slackware Linux").in_family("linux") + .detect do + if !(raw = unix_file_contents("/etc/slackware-version")).nil? @platform[:release] = raw.scan(/(\d+|\.+)/).join true end - } + end # gentoo - plat.name('gentoo').title('Gentoo Linux').in_family('linux') - .detect { - if !(raw = unix_file_contents('/etc/gentoo-release')).nil? + plat.name("gentoo").title("Gentoo Linux").in_family("linux") + .detect do + if !(raw = unix_file_contents("/etc/gentoo-release")).nil? @platform[:release] = raw.scan(/(\d+|\.+)/).join true end - } + end # exherbo - plat.name('exherbo').title('Exherbo Linux').in_family('linux') - .detect { - unless unix_file_contents('/etc/exherbo-release').nil? + plat.name("exherbo").title("Exherbo Linux").in_family("linux") + .detect do + unless unix_file_contents("/etc/exherbo-release").nil? # Because this is a rolling release distribution, # use the kernel release, ex. 4.1.6 @platform[:release] = unix_uname_r true end - } + end # alpine - plat.name('alpine').title('Alpine Linux').in_family('linux') - .detect { - if !(raw = unix_file_contents('/etc/alpine-release')).nil? + plat.name("alpine").title("Alpine Linux").in_family("linux") + .detect do + if !(raw = unix_file_contents("/etc/alpine-release")).nil? @platform[:release] = raw.strip true end - } + end # coreos - plat.name('coreos').title('CoreOS Linux').in_family('linux') - .detect { - unless unix_file_contents('/etc/coreos/update.conf').nil? + plat.name("coreos").title("CoreOS Linux").in_family("linux") + .detect do + unless unix_file_contents("/etc/coreos/update.conf").nil? lsb = read_linux_lsb @platform[:release] = lsb[:release] true end - } + end # brocade family detected here if device responds to 'uname' command, # happens when logging in as root - plat.family('brocade').title('Brocade Family').in_family('linux') - .detect { + plat.family("brocade").title("Brocade Family").in_family("linux") + .detect do !brocade_version.nil? - } + end # genaric linux # this should always be last in the linux family list - plat.name('linux').title('Genaric Linux').in_family('linux') - .detect { + plat.name("linux").title("Genaric Linux").in_family("linux") + .detect do true - } + end # openvms - plat.name('openvms').title('OpenVMS').in_family('unix') - .detect { + plat.name("openvms").title("OpenVMS").in_family("unix") + .detect do if unix_uname_s =~ /unrecognized command verb/i - cmd = @backend.run_command('show system/noprocess') + cmd = @backend.run_command("show system/noprocess") unless cmd.exit_status != 0 || cmd.stdout.empty? - @platform[:name] = cmd.stdout.downcase.split(' ')[0] + @platform[:name] = cmd.stdout.downcase.split(" ")[0] cmd = @backend.run_command('write sys$output f$getsyi("VERSION")') @platform[:release] = cmd.stdout.downcase.split("\n")[1][1..-1] cmd = @backend.run_command('write sys$output f$getsyi("ARCH_NAME")') @@ -341,78 +341,78 @@ def self.load true end end - } + end # aix - plat.family('aix').in_family('unix') - .detect { + plat.family("aix").in_family("unix") + .detect do true if unix_uname_s =~ /aix/i - } - plat.name('aix').title('Aix').in_family('aix') - .detect { - out = @backend.run_command('uname -rvp').stdout + end + plat.name("aix").title("Aix").in_family("aix") + .detect do + out = @backend.run_command("uname -rvp").stdout m = out.match(/(\d+)\s+(\d+)\s+(.*)/) unless m.nil? @platform[:release] = "#{m[2]}.#{m[1]}" @platform[:arch] = m[3].to_s end true - } + end # solaris family - plat.family('solaris').in_family('unix') - .detect { + plat.family("solaris").in_family("unix") + .detect do if unix_uname_s =~ /sunos/i unless (version = /^5\.(?\d+)$/.match(unix_uname_r)).nil? - @platform[:release] = version['release'] + @platform[:release] = version["release"] end - arch = @backend.run_command('uname -p') + arch = @backend.run_command("uname -p") @platform[:arch] = arch.stdout.chomp if arch.exit_status == 0 true end - } - plat.name('smartos').title('SmartOS').in_family('solaris') - .detect { - rel = unix_file_contents('/etc/release') + end + plat.name("smartos").title("SmartOS").in_family("solaris") + .detect do + rel = unix_file_contents("/etc/release") if /^.*(SmartOS).*$/ =~ rel true end - } - plat.name('omnios').title('Omnios').in_family('solaris') - .detect { - rel = unix_file_contents('/etc/release') + end + plat.name("omnios").title("Omnios").in_family("solaris") + .detect do + rel = unix_file_contents("/etc/release") if !(m = /^\s*(OmniOS).*r(\d+).*$/.match(rel)).nil? @platform[:release] = m[2] true end - } - plat.name('openindiana').title('Openindiana').in_family('solaris') - .detect { - rel = unix_file_contents('/etc/release') + end + plat.name("openindiana").title("Openindiana").in_family("solaris") + .detect do + rel = unix_file_contents("/etc/release") if !(m = /^\s*(OpenIndiana).*oi_(\d+).*$/.match(rel)).nil? @platform[:release] = m[2] true end - } - plat.name('opensolaris').title('Open Solaris').in_family('solaris') - .detect { - rel = unix_file_contents('/etc/release') + end + plat.name("opensolaris").title("Open Solaris").in_family("solaris") + .detect do + rel = unix_file_contents("/etc/release") if !(m = /^\s*(OpenSolaris).*snv_(\d+).*$/.match(rel)).nil? @platform[:release] = m[2] true end - } - plat.name('nexentacore').title('Nexentacore').in_family('solaris') - .detect { - rel = unix_file_contents('/etc/release') + end + plat.name("nexentacore").title("Nexentacore").in_family("solaris") + .detect do + rel = unix_file_contents("/etc/release") if /^\s*(NexentaCore)\s.*$/ =~ rel true end - } - plat.name('solaris').title('Solaris').in_family('solaris') - .detect { - rel = unix_file_contents('/etc/release') + end + plat.name("solaris").title("Solaris").in_family("solaris") + .detect do + rel = unix_file_contents("/etc/release") if !(m = /Oracle Solaris (\d+)/.match(rel)).nil? # TODO: should be string! @platform[:release] = m[1] @@ -423,43 +423,43 @@ def self.load # must be some unknown solaris true - } + end # hpux - plat.family('hpux').in_family('unix') - .detect { + plat.family("hpux").in_family("unix") + .detect do true if unix_uname_s =~ /hp-ux/i - } - plat.name('hpux').title('Hpux').in_family('hpux') - .detect { + end + plat.name("hpux").title("Hpux").in_family("hpux") + .detect do @platform[:release] = unix_uname_r.lines[0].chomp true - } + end # qnx - plat.family('qnx').in_family('unix') - .detect { + plat.family("qnx").in_family("unix") + .detect do true if unix_uname_s =~ /qnx/i - } - plat.name('qnx').title('QNX').in_family('qnx') - .detect { + end + plat.name("qnx").title("QNX").in_family("qnx") + .detect do @platform[:name] = unix_uname_s.lines[0].chomp.downcase @platform[:release] = unix_uname_r.lines[0].chomp @platform[:arch] = unix_uname_m true - } + end # bsd family - plat.family('bsd').in_family('unix') - .detect { + plat.family("bsd").in_family("unix") + .detect do # we need a better way to determin this family # for now we are going to just try each platform true - } - plat.family('darwin').in_family('bsd') - .detect { + end + plat.family("darwin").in_family("bsd") + .detect do if unix_uname_s =~ /darwin/i - cmd = unix_file_contents('/usr/bin/sw_vers') + cmd = unix_file_contents("/usr/bin/sw_vers") unless cmd.nil? m = cmd.match(/^ProductVersion:\s+(.+)$/) @platform[:release] = m.nil? ? nil : m[1] @@ -470,122 +470,122 @@ def self.load @platform[:arch] = unix_uname_m true end - } - plat.name('mac_os_x').title('macOS X').in_family('darwin') - .detect { - cmd = unix_file_contents('/System/Library/CoreServices/SystemVersion.plist') + end + plat.name("mac_os_x").title("macOS X").in_family("darwin") + .detect do + cmd = unix_file_contents("/System/Library/CoreServices/SystemVersion.plist") @platform[:uuid_command] = "system_profiler SPHardwareDataType | awk '/UUID/ { print $3; }'" true if cmd =~ /Mac OS X/i - } - plat.name('darwin').title('Darwin').in_family('darwin') - .detect { + end + plat.name("darwin").title("Darwin").in_family("darwin") + .detect do # must be some other type of darwin @platform[:name] = unix_uname_s.lines[0].chomp true - } - plat.name('freebsd').title('Freebsd').in_family('bsd') - .detect { + end + plat.name("freebsd").title("Freebsd").in_family("bsd") + .detect do if unix_uname_s =~ /freebsd/i @platform[:name] = unix_uname_s.lines[0].chomp @platform[:release] = unix_uname_r.lines[0].chomp true end - } - plat.name('openbsd').title('Openbsd').in_family('bsd') - .detect { + end + plat.name("openbsd").title("Openbsd").in_family("bsd") + .detect do if unix_uname_s =~ /openbsd/i @platform[:name] = unix_uname_s.lines[0].chomp @platform[:release] = unix_uname_r.lines[0].chomp true end - } - plat.name('netbsd').title('Netbsd').in_family('bsd') - .detect { + end + plat.name("netbsd").title("Netbsd").in_family("bsd") + .detect do if unix_uname_s =~ /netbsd/i @platform[:name] = unix_uname_s.lines[0].chomp @platform[:release] = unix_uname_r.lines[0].chomp true end - } + end # arista_eos family - plat.family('arista_eos').title('Arista EOS Family').in_family('os') - .detect { + plat.family("arista_eos").title("Arista EOS Family").in_family("os") + .detect do true - } - plat.name('arista_eos').title('Arista EOS').in_family('arista_eos') - .detect { - cmd = @backend.run_command('show version | json') + end + plat.name("arista_eos").title("Arista EOS").in_family("arista_eos") + .detect do + cmd = @backend.run_command("show version | json") if cmd.exit_status == 0 && !cmd.stdout.empty? - require 'json' + require "json" begin eos_ver = JSON.parse(cmd.stdout) - @platform[:release] = eos_ver['version'] - @platform[:arch] = eos_ver['architecture'] + @platform[:release] = eos_ver["version"] + @platform[:arch] = eos_ver["architecture"] true rescue JSON::ParserError nil end end - } + end # esx - plat.family('esx').title('ESXi Family').in_family('os') - .detect { + plat.family("esx").title("ESXi Family").in_family("os") + .detect do true if unix_uname_s =~ /vmkernel/i - } - plat.name('vmkernel').in_family('esx') - .detect { + end + plat.name("vmkernel").in_family("esx") + .detect do @platform[:name] = unix_uname_s.lines[0].chomp @platform[:release] = unix_uname_r.lines[0].chomp true - } + end # cisco_ios family - plat.family('cisco').title('Cisco Family').in_family('os') - .detect { + plat.family("cisco").title("Cisco Family").in_family("os") + .detect do !cisco_show_version.nil? - } - plat.name('cisco_ios').title('Cisco IOS').in_family('cisco') - .detect { + end + plat.name("cisco_ios").title("Cisco IOS").in_family("cisco") + .detect do v = cisco_show_version - next unless v[:type] == 'ios' + next unless v[:type] == "ios" @platform[:release] = v[:version] @platform[:arch] = nil true - } - plat.name('cisco_ios_xe').title('Cisco IOS XE').in_family('cisco') - .detect { + end + plat.name("cisco_ios_xe").title("Cisco IOS XE").in_family("cisco") + .detect do v = cisco_show_version - next unless v[:type] == 'ios-xe' + next unless v[:type] == "ios-xe" @platform[:release] = v[:version] @platform[:arch] = nil true - } - plat.name('cisco_nexus').title('Cisco Nexus').in_family('cisco') - .detect { + end + plat.name("cisco_nexus").title("Cisco Nexus").in_family("cisco") + .detect do v = cisco_show_version - next unless v[:type] == 'nexus' + next unless v[:type] == "nexus" @platform[:release] = v[:version] @platform[:arch] = nil - @platform[:uuid_command] = 'show version | include Processor' + @platform[:uuid_command] = "show version | include Processor" true - } + end # brocade family - plat.family('brocade').title('Brocade Family').in_family('os') - .detect { + plat.family("brocade").title("Brocade Family").in_family("os") + .detect do !brocade_version.nil? - } + end - plat.name('brocade_fos').title('Brocade FOS').in_family('brocade') - .detect { + plat.name("brocade_fos").title("Brocade FOS").in_family("brocade") + .detect do v = brocade_version - next unless v[:type] == 'fos' + next unless v[:type] == "fos" @platform[:release] = v[:version] @platform[:arch] = nil true - } + end end end end diff --git a/lib/train/platforms/detect/uuid.rb b/lib/train/platforms/detect/uuid.rb index bf54865f..7e298a5e 100644 --- a/lib/train/platforms/detect/uuid.rb +++ b/lib/train/platforms/detect/uuid.rb @@ -1,8 +1,6 @@ -# encoding: utf-8 - -require 'digest/sha1' -require 'securerandom' -require 'json' +require "digest/sha1" +require "securerandom" +require "json" module Train::Platforms::Detect class UUID @@ -24,10 +22,10 @@ def find_or_create_uuid else if @platform[:uuid_command] result = @backend.run_command(@platform[:uuid_command]) - return uuid_from_string(result.stdout.chomp) if result.exit_status.zero? && !result.stdout.empty? + return uuid_from_string(result.stdout.chomp) if result.exit_status == 0 && !result.stdout.empty? end - raise 'Could not find platform uuid! Please set a uuid_command for your platform.' + raise "Could not find platform uuid! Please set a uuid_command for your platform." end end end diff --git a/lib/train/platforms/platform.rb b/lib/train/platforms/platform.rb index 3cc95128..9e313f51 100644 --- a/lib/train/platforms/platform.rb +++ b/lib/train/platforms/platform.rb @@ -44,7 +44,7 @@ def clean_name(force: false) @cleaned_name = nil if force @cleaned_name ||= begin name = (@platform[:name] || @name) - name.downcase!.tr!(' ', '_') if name =~ /[A-Z ]/ + name.downcase!.tr!(" ", "_") if name =~ /[A-Z ]/ name end end @@ -59,7 +59,7 @@ def uuid if respond_to?(name) send(name) else - 'unknown' + "unknown" end end @@ -88,8 +88,8 @@ def add_platform_methods # Add in family methods family_list = Train::Platforms.families family_list.each_value do |k| - next if respond_to?(k.name + '?') - define_singleton_method(k.name + '?') do + next if respond_to?(k.name + "?") + define_singleton_method(k.name + "?") do family_hierarchy.include?(k.name) end end @@ -103,7 +103,7 @@ def add_platform_methods end # Create method for name if its not already true - m = name + '?' + m = name + "?" return if respond_to?(m) define_singleton_method(m) do true diff --git a/lib/train/plugin_test_helper.rb b/lib/train/plugin_test_helper.rb index 0a7540f4..8c24edb1 100644 --- a/lib/train/plugin_test_helper.rb +++ b/lib/train/plugin_test_helper.rb @@ -3,27 +3,27 @@ # Load Train. We certainly need the plugin system, and also several other parts # that are tightly coupled. Train itself is fairly light, and non-invasive. -require 'train' +require "train" # You can select from a number of test harnesses. Since Train is closely related # to InSpec, and InSpec uses Spec-style controls in profile code, you will # probably want to use something like minitest/spec, which provides Spec-style # tests. -require 'minitest/spec' -require 'minitest/autorun' +require "minitest/spec" +require "minitest/autorun" # Data formats commonly used in testing -require 'json' -require 'ostruct' +require "json" +require "ostruct" # Utilities often needed -require 'fileutils' -require 'tmpdir' -require 'pathname' +require "fileutils" +require "tmpdir" +require "pathname" # You might want to put some debugging tools here. We run tests to find bugs, # after all. -require 'byebug' +require "byebug" # Configure MiniTest to expose things like `let` class Module @@ -38,11 +38,11 @@ def self.included(base) plugin_test_helper_path = Pathname.new(caller_locations(4, 1).first.absolute_path) plugin_src_root = plugin_test_helper_path.parent.parent base.let(:plugin_src_path) { plugin_src_root } - base.let(:plugin_fixtures_path) { File.join(plugin_src_root, 'test', 'fixtures') } + base.let(:plugin_fixtures_path) { File.join(plugin_src_root, "test", "fixtures") } end - let(:train_src_path) { File.expand_path(File.join(__FILE__, '..', '..')) } - let(:train_fixtures_path) { File.join(train_src_path, 'test', 'fixtures') } + let(:train_src_path) { File.expand_path(File.join(__FILE__, "..", "..")) } + let(:train_fixtures_path) { File.join(train_src_path, "test", "fixtures") } let(:registry) { Train::Plugins.registry } end diff --git a/lib/train/plugins.rb b/lib/train/plugins.rb index 85fb9ae2..ca4c1fe7 100644 --- a/lib/train/plugins.rb +++ b/lib/train/plugins.rb @@ -3,11 +3,11 @@ # Author:: Dominik Richter () # Author:: Christoph Hartmann () -require 'train/errors' +require "train/errors" module Train class Plugins - require 'train/plugins/transport' + require "train/plugins/transport" class << self # Retrieve the current plugin registry, containing all plugin names @@ -30,10 +30,10 @@ def registry # @return [Transport] the versioned transport base class def self.plugin(version = 1) if version != 1 - fail ClientError, - 'Only understand train plugin version 1. You are trying to '\ + raise ClientError, + "Only understand train plugin version 1. You are trying to "\ "initialize a train plugin #{version}, which is not supported "\ - 'in the current release of train.' + "in the current release of train." end ::Train::Plugins::Transport end diff --git a/lib/train/plugins/base_connection.rb b/lib/train/plugins/base_connection.rb index f6df6efb..739b6a5c 100644 --- a/lib/train/plugins/base_connection.rb +++ b/lib/train/plugins/base_connection.rb @@ -1,9 +1,9 @@ # encoding: utf-8 -require 'train/errors' -require 'train/extras' -require 'train/file' -require 'logger' +require "train/errors" +require "train/extras" +require "train/file" +require "logger" class Train::Plugins::Transport # A Connection instance can be generated and re-generated, given new @@ -64,12 +64,12 @@ def cache_enabled?(type) # Enable caching types for Train. Currently we support # :api_call, :file and :command types def enable_cache(type) - fail Train::UnknownCacheType, "#{type} is not a valid cache type" unless @cache_enabled.keys.include?(type.to_sym) + raise Train::UnknownCacheType, "#{type} is not a valid cache type" unless @cache_enabled.keys.include?(type.to_sym) @cache_enabled[type.to_sym] = true end def disable_cache(type) - fail Train::UnknownCacheType, "#{type} is not a valid cache type" unless @cache_enabled.keys.include?(type.to_sym) + raise Train::UnknownCacheType, "#{type} is not a valid cache type" unless @cache_enabled.keys.include?(type.to_sym) @cache_enabled[type.to_sym] = false clear_cache(type.to_sym) end @@ -81,13 +81,13 @@ def close def to_json { - 'files' => Hash[@cache[:file].map { |x, y| [x, y.to_json] }], + "files" => Hash[@cache[:file].map { |x, y| [x, y.to_json] }], } end def load_json(j) - require 'train/transports/mock' - j['files'].each do |path, jf| + require "train/transports/mock" + j["files"].each do |path, jf| @cache[:file][path] = Train::Transports::Mock::Connection::File.from_json(jf) end end @@ -137,7 +137,7 @@ def file(path, *args) # # @return [LoginCommand] array of command line tokens def login_command - fail NotImplementedError, "#{self.class} does not implement #login_command()" + raise NotImplementedError, "#{self.class} does not implement #login_command()" end # Block and return only when the remote host is prepared and ready to @@ -161,7 +161,7 @@ def wait_until_ready # # @return [CommandResult] contains the result of running the command def run_command_via_connection(_command, &_data_handler) - fail NotImplementedError, "#{self.class} does not implement #run_command_via_connection()" + raise NotImplementedError, "#{self.class} does not implement #run_command_via_connection()" end # Interact with files on the target. Read, write, and get metadata @@ -170,7 +170,7 @@ def run_command_via_connection(_command, &_data_handler) # @param [String] path which is being inspected # @return [FileCommon] file object that allows for interaction def file_via_connection(_path, *_args) - fail NotImplementedError, "#{self.class} does not implement #file_via_connection(...)" + raise NotImplementedError, "#{self.class} does not implement #file_via_connection(...)" end def clear_cache(type) diff --git a/lib/train/plugins/transport.rb b/lib/train/plugins/transport.rb index abadb9f0..c17efd70 100644 --- a/lib/train/plugins/transport.rb +++ b/lib/train/plugins/transport.rb @@ -3,17 +3,17 @@ # Author:: Dominik Richter () # Author:: Christoph Hartmann () -require 'logger' -require 'train/errors' -require 'train/extras' -require 'train/options' +require "logger" +require "train/errors" +require "train/extras" +require "train/options" class Train::Plugins class Transport include Train::Extras Train::Options.attach(self) - require 'train/plugins/base_connection' + require "train/plugins/base_connection" # Initialize a new Transport object # @@ -30,7 +30,7 @@ def initialize(options = {}) # @param [Hash] _options = nil provide optional configuration params # @return [Connection] the connection for this configuration def connection(_options = nil) - fail Train::ClientError, "#{self.class} does not implement #connection()" + raise Train::ClientError, "#{self.class} does not implement #connection()" end # Register the inheriting class with as a train plugin using the diff --git a/lib/train/transports/azure.rb b/lib/train/transports/azure.rb index 2f414515..a51d24e1 100644 --- a/lib/train/transports/azure.rb +++ b/lib/train/transports/azure.rb @@ -1,27 +1,27 @@ # encoding: utf-8 -require 'train/plugins' -require 'ms_rest_azure' -require 'azure_mgmt_resources' -require 'azure_graph_rbac' -require 'azure_mgmt_key_vault' -require 'socket' -require 'timeout' -require 'train/transports/helpers/azure/file_credentials' -require 'train/transports/clients/azure/graph_rbac' -require 'train/transports/clients/azure/vault' +require "train/plugins" +require "ms_rest_azure" +require "azure_mgmt_resources" +require "azure_graph_rbac" +require "azure_mgmt_key_vault" +require "socket" +require "timeout" +require "train/transports/helpers/azure/file_credentials" +require "train/transports/clients/azure/graph_rbac" +require "train/transports/clients/azure/vault" module Train::Transports class Azure < Train.plugin(1) - name 'azure' - option :tenant_id, default: ENV['AZURE_TENANT_ID'] - option :client_id, default: ENV['AZURE_CLIENT_ID'] - option :client_secret, default: ENV['AZURE_CLIENT_SECRET'] - option :subscription_id, default: ENV['AZURE_SUBSCRIPTION_ID'] - option :msi_port, default: ENV['AZURE_MSI_PORT'] || '50342' + name "azure" + option :tenant_id, default: ENV["AZURE_TENANT_ID"] + option :client_id, default: ENV["AZURE_CLIENT_ID"] + option :client_secret, default: ENV["AZURE_CLIENT_SECRET"] + option :subscription_id, default: ENV["AZURE_SUBSCRIPTION_ID"] + option :msi_port, default: ENV["AZURE_MSI_PORT"] || "50342" # This can provide the client id and secret - option :credentials_file, default: ENV['AZURE_CRED_FILE'] + option :credentials_file, default: ENV["AZURE_CRED_FILE"] def connection(_ = nil) @connection ||= Connection.new(@options) @@ -30,7 +30,7 @@ def connection(_ = nil) class Connection < BaseConnection attr_reader :options - DEFAULT_FILE = ::File.join(Dir.home, '.azure', 'credentials') + DEFAULT_FILE = ::File.join(Dir.home, ".azure", "credentials") def initialize(options) @apis = {} @@ -51,14 +51,14 @@ def initialize(options) @options[:msi_port] = @options[:msi_port].to_i unless @options[:msi_port].nil? # additional platform details - release = Gem.loaded_specs['azure_mgmt_resources'].version + release = Gem.loaded_specs["azure_mgmt_resources"].version @platform_details = { release: "azure_mgmt_resources-v#{release}" } connect end def platform - force_platform!('azure', @platform_details) + force_platform!("azure", @platform_details) end def azure_client(klass = ::Azure::Resources::Profiles::Latest::Mgmt::Client, opts = {}) @@ -85,13 +85,13 @@ def azure_client(klass = ::Azure::Resources::Profiles::Latest::Mgmt::Client, opt def connect if msi_auth? # this needs set for azure cloud to authenticate - ENV['MSI_VM'] = 'true' + ENV["MSI_VM"] = "true" provider = ::MsRestAzure::MSITokenProvider.new(@options[:msi_port]) else provider = ::MsRestAzure::ApplicationTokenProvider.new( @options[:tenant_id], @options[:client_id], - @options[:client_secret], + @options[:client_secret] ) end @@ -166,7 +166,7 @@ def msi_auth? def port_open?(port, seconds = 3) Timeout.timeout(seconds) do begin - TCPSocket.new('localhost', port).close + TCPSocket.new("localhost", port).close true rescue SystemCallError false diff --git a/lib/train/transports/cisco_ios_connection.rb b/lib/train/transports/cisco_ios_connection.rb index f0d55a7b..f549fba3 100644 --- a/lib/train/transports/cisco_ios_connection.rb +++ b/lib/train/transports/cisco_ios_connection.rb @@ -24,8 +24,8 @@ def uri end def unique_identifier - result = run_command_via_connection('show version | include Processor') - result.stdout.split(' ')[-1] + result = run_command_via_connection("show version | include Processor") + result.stdout.split(" ")[-1] end private @@ -45,26 +45,26 @@ def session if @enable_password # This verifies we are not in privileged exec mode before running the # enable command. Otherwise, the password will be in history. - if run_command_via_connection('show privilege').stdout.split[-1] != '15' + if run_command_via_connection("show privilege").stdout.split[-1] != "15" # Extra newlines to get back to prompt if incorrect password is used run_command_via_connection("enable\n#{@enable_password}\n\n\n") end end # Prevent `--MORE--` by removing terminal length limit - run_command_via_connection('terminal length 0') + run_command_via_connection("terminal length 0") @session end def run_command_via_connection(cmd, &_data_handler) # Ensure buffer is empty before sending data - @buf = '' + @buf = "" logger.debug("[SSH] Running `#{cmd}` on #{self}") session.send_data(cmd + "\r\n") - logger.debug('[SSH] waiting for prompt') + logger.debug("[SSH] waiting for prompt") until @buf =~ @prompt if @buf =~ /Bad (secrets|password)|Access denied/ raise BadEnablePassword @@ -74,16 +74,16 @@ def run_command_via_connection(cmd, &_data_handler) # Save the buffer and clear it for the next command output = @buf.dup - @buf = '' + @buf = "" format_result(format_output(output, cmd)) end ERROR_MATCHERS = [ - 'Bad IP address', - 'Incomplete command', - 'Invalid input detected', - 'Unrecognized host', + "Bad IP address", + "Incomplete command", + "Invalid input detected", + "Unrecognized host", ].freeze # IOS commands do not have an exit code so we must compare the command @@ -92,9 +92,9 @@ def run_command_via_connection(cmd, &_data_handler) # result. def format_result(result) if ERROR_MATCHERS.none? { |e| result.include?(e) } - CommandResult.new(result, '', 0) + CommandResult.new(result, "", 0) else - CommandResult.new('', result, 1) + CommandResult.new("", result, 1) end end @@ -107,10 +107,10 @@ def format_output(output, cmd) trailing_line_endings = /(\r\n)+$/ output - .sub(leading_prompt, '') - .sub(command_string, '') - .gsub(trailing_prompt, '') - .gsub(trailing_line_endings, '') + .sub(leading_prompt, "") + .sub(command_string, "") + .gsub(trailing_prompt, "") + .gsub(trailing_line_endings, "") end # Create an SSH channel that writes to @buf when data is received @@ -121,9 +121,9 @@ def open_channel(ssh) @buf += data end - ch.send_channel_request('shell') do |_, success| - raise 'Failed to open SSH shell' unless success - logger.debug('[SSH] shell opened') + ch.send_channel_request("shell") do |_, success| + raise "Failed to open SSH shell" unless success + logger.debug("[SSH] shell opened") end end end diff --git a/lib/train/transports/clients/azure/graph_rbac.rb b/lib/train/transports/clients/azure/graph_rbac.rb index 2922a3b1..273a5181 100644 --- a/lib/train/transports/clients/azure/graph_rbac.rb +++ b/lib/train/transports/clients/azure/graph_rbac.rb @@ -1,6 +1,6 @@ # encoding: utf-8 -require 'azure_graph_rbac' +require "azure_graph_rbac" # Wrapper class for ::Azure::GraphRbac::Profiles::Latest::Client allowing custom configuration, # for example, defining additional settings for the ::MsRestAzure::ApplicationTokenProvider. @@ -20,7 +20,7 @@ def self.provider(credentials) credentials[:tenant_id], credentials[:client_id], credentials[:client_secret], - settings, + settings ) end diff --git a/lib/train/transports/clients/azure/vault.rb b/lib/train/transports/clients/azure/vault.rb index 00b59425..b46f88c3 100644 --- a/lib/train/transports/clients/azure/vault.rb +++ b/lib/train/transports/clients/azure/vault.rb @@ -1,15 +1,15 @@ # encoding: utf-8 -require 'azure_mgmt_key_vault' +require "azure_mgmt_key_vault" # Wrapper class for ::Azure::KeyVault::Profiles::Latest::Mgmt::Client allowing custom configuration, # for example, defining additional settings for the ::MsRestAzure::ApplicationTokenProvider. class Vault AUTH_ENDPOINT = MsRestAzure::AzureEnvironments::AzureCloud.active_directory_endpoint_url - RESOURCE_ENDPOINT = 'https://vault.azure.net'.freeze + RESOURCE_ENDPOINT = "https://vault.azure.net".freeze def self.client(vault_name, credentials) - raise ::Train::UserError, 'Vault Name cannot be nil' if vault_name.nil? + raise ::Train::UserError, "Vault Name cannot be nil" if vault_name.nil? credentials[:credentials] = ::MsRest::TokenCredentials.new(provider(credentials)) credentials[:base_url] = api_endpoint(vault_name) @@ -22,7 +22,7 @@ def self.provider(credentials) credentials[:tenant_id], credentials[:client_id], credentials[:client_secret], - settings, + settings ) end diff --git a/lib/train/transports/docker.rb b/lib/train/transports/docker.rb index 6b97fa25..9c077724 100644 --- a/lib/train/transports/docker.rb +++ b/lib/train/transports/docker.rb @@ -1,13 +1,8 @@ -# encoding: utf-8 -# -# Author:: Dominik Richter -# Author:: Christoph Hartmann - -require 'docker' +require "docker" module Train::Transports class Docker < Train.plugin(1) - name 'docker' + name "docker" include_options Train::Extras::CommandWrapper option :host, required: true @@ -59,10 +54,9 @@ def initialize(conf) super(conf) @id = options[:host] @container = ::Docker::Container.get(@id) || - fail("Can't find Docker container #{@id}") + raise("Can't find Docker container #{@id}") @cmd_wrapper = nil @cmd_wrapper = CommandWrapper.load(self, @options) - self end def close @@ -93,7 +87,7 @@ def run_command_via_connection(cmd, &_data_handler) cmd = @cmd_wrapper.run(cmd) unless @cmd_wrapper.nil? stdout, stderr, exit_status = @container.exec( [ - '/bin/sh', '-c', cmd + "/bin/sh", "-c", cmd ]) CommandResult.new(stdout.join, stderr.join, exit_status) rescue ::Docker::Error::DockerError => _ diff --git a/lib/train/transports/gcp.rb b/lib/train/transports/gcp.rb index 5e366671..a0cc281f 100644 --- a/lib/train/transports/gcp.rb +++ b/lib/train/transports/gcp.rb @@ -1,21 +1,21 @@ # encoding: utf-8 -require 'train/plugins' -require 'google/apis' -require 'google/apis/cloudresourcemanager_v1' -require 'google/apis/compute_v1' -require 'google/apis/storage_v1' -require 'google/apis/iam_v1' -require 'google/apis/admin_directory_v1' -require 'googleauth' +require "train/plugins" +require "google/apis" +require "google/apis/cloudresourcemanager_v1" +require "google/apis/compute_v1" +require "google/apis/storage_v1" +require "google/apis/iam_v1" +require "google/apis/admin_directory_v1" +require "googleauth" module Train::Transports class Gcp < Train.plugin(1) - name 'gcp' + name "gcp" # GCP will look automatically for the below env var for service accounts etc. : option :google_application_credentials, required: false do - ENV['GOOGLE_APPLICATION_CREDENTIALS'] + ENV["GOOGLE_APPLICATION_CREDENTIALS"] end # see https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application # In the absence of this, the client is expected to have already set up local credentials via: @@ -25,10 +25,10 @@ class Gcp < Train.plugin(1) # https://cloud.google.com/compute/docs/regions-zones/changing-default-zone-region # can also specify project via env var: option :google_cloud_project, required: false do - ENV['GOOGLE_CLOUD_PROJECT'] + ENV["GOOGLE_CLOUD_PROJECT"] end option :google_super_admin_email, required: false do - ENV['GOOGLE_SUPER_ADMIN_EMAIL'] + ENV["GOOGLE_SUPER_ADMIN_EMAIL"] end def connection(_ = nil) @@ -40,7 +40,7 @@ def initialize(options) super(options) # additional GCP platform metadata - release = Gem.loaded_specs['google-api-client'].version + release = Gem.loaded_specs["google-api-client"].version @platform_details = { release: "google-api-client-v#{release}" } # Initialize the client object cache @@ -51,7 +51,7 @@ def initialize(options) end def platform - force_platform!('gcp', @platform_details) + force_platform!("gcp", @platform_details) end # Instantiate some named classes for ease of use @@ -72,7 +72,7 @@ def gcp_storage_client end def gcp_admin_client - scopes = ['https://www.googleapis.com/auth/admin.directory.user.readonly'] + scopes = ["https://www.googleapis.com/auth/admin.directory.user.readonly"] authorization = Google::Auth.get_application_default(scopes).dup # Use of the Admin API requires delegation (impersonation). An email address of a Super Admin in # the G Suite account may be required. @@ -88,13 +88,13 @@ def gcp_client(klass) end def connect - ENV['GOOGLE_APPLICATION_CREDENTIALS'] = @options[:google_application_credentials] if @options[:google_application_credentials] - ENV['GOOGLE_CLOUD_PROJECT'] = @options[:google_cloud_project] if @options[:google_cloud_project] + ENV["GOOGLE_APPLICATION_CREDENTIALS"] = @options[:google_application_credentials] if @options[:google_application_credentials] + ENV["GOOGLE_CLOUD_PROJECT"] = @options[:google_cloud_project] if @options[:google_cloud_project] # GCP initialization - scopes = ['https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/compute'] + scopes = ["https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute"] authorization = Google::Auth.get_application_default(scopes) - Google::Apis::ClientOptions.default.application_name = 'chef-inspec-train' + Google::Apis::ClientOptions.default.application_name = "chef-inspec-train" Google::Apis::ClientOptions.default.application_version = Train::VERSION Google::Apis::RequestOptions.default.authorization = authorization end @@ -104,11 +104,11 @@ def uri end def unique_identifier - unique_id = 'default' + unique_id = "default" # use auth client_id for users (issuer is nil) - unique_id=gcp_iam_client.request_options.authorization.client_id unless gcp_iam_client.request_options.authorization.client_id.nil? + unique_id = gcp_iam_client.request_options.authorization.client_id unless gcp_iam_client.request_options.authorization.client_id.nil? # for service account credentials (client_id is nil) - unique_id=gcp_iam_client.request_options.authorization.issuer unless gcp_iam_client.request_options.authorization.issuer.nil? + unique_id = gcp_iam_client.request_options.authorization.issuer unless gcp_iam_client.request_options.authorization.issuer.nil? unique_id end end diff --git a/lib/train/transports/helpers/azure/file_credentials.rb b/lib/train/transports/helpers/azure/file_credentials.rb index b89168d8..854ca698 100644 --- a/lib/train/transports/helpers/azure/file_credentials.rb +++ b/lib/train/transports/helpers/azure/file_credentials.rb @@ -1,9 +1,9 @@ # encoding: utf-8 -require 'inifile' -require 'train/transports/helpers/azure/file_parser' -require 'train/transports/helpers/azure/subscription_number_file_parser' -require 'train/transports/helpers/azure/subscription_id_file_parser' +require "inifile" +require "train/transports/helpers/azure/file_parser" +require "train/transports/helpers/azure/subscription_number_file_parser" +require "train/transports/helpers/azure/subscription_id_file_parser" module Train::Transports module Helpers @@ -13,7 +13,7 @@ def self.parse(subscription_id: nil, credentials_file: nil, **_) return {} if credentials_file.nil? return {} unless ::File.readable?(credentials_file) credentials = IniFile.load(::File.expand_path(credentials_file)) - subscription_id = parser(subscription_id, ENV['AZURE_SUBSCRIPTION_NUMBER'], credentials).subscription_id + subscription_id = parser(subscription_id, ENV["AZURE_SUBSCRIPTION_NUMBER"], credentials).subscription_id creds(subscription_id, credentials) end @@ -30,9 +30,9 @@ def self.parser(subscription_id, subscription_number, credentials) def self.creds(subscription_id, credentials) { subscription_id: subscription_id, - tenant_id: credentials[subscription_id]['tenant_id'], - client_id: credentials[subscription_id]['client_id'], - client_secret: credentials[subscription_id]['client_secret'], + tenant_id: credentials[subscription_id]["tenant_id"], + client_id: credentials[subscription_id]["client_id"], + client_secret: credentials[subscription_id]["client_secret"], } end end diff --git a/lib/train/transports/helpers/azure/file_parser.rb b/lib/train/transports/helpers/azure/file_parser.rb index 33a87fb8..0d325137 100644 --- a/lib/train/transports/helpers/azure/file_parser.rb +++ b/lib/train/transports/helpers/azure/file_parser.rb @@ -13,7 +13,7 @@ def initialize(credentials) def validate! return if @credentials.sections.count == 1 - raise 'Credentials file must have one entry. Check your credentials file. If you have more than one entry set AZURE_SUBSCRIPTION_ID environment variable.' + raise "Credentials file must have one entry. Check your credentials file. If you have more than one entry set AZURE_SUBSCRIPTION_ID environment variable." end def subscription_id diff --git a/lib/train/transports/helpers/azure/subscription_number_file_parser.rb b/lib/train/transports/helpers/azure/subscription_number_file_parser.rb index cbc102ea..8c43de76 100644 --- a/lib/train/transports/helpers/azure/subscription_number_file_parser.rb +++ b/lib/train/transports/helpers/azure/subscription_number_file_parser.rb @@ -13,7 +13,7 @@ def initialize(index, credentials) def validate! if @index == 0 - raise 'Index must be greater than 0.' + raise "Index must be greater than 0." end if @index > @credentials.sections.length diff --git a/lib/train/transports/local.rb b/lib/train/transports/local.rb index c0488a12..877bf3a7 100644 --- a/lib/train/transports/local.rb +++ b/lib/train/transports/local.rb @@ -3,13 +3,13 @@ # author: Dominik Richter # author: Christoph Hartmann -require 'train/plugins' -require 'train/errors' -require 'mixlib/shellout' +require "train/plugins" +require "train/errors" +require "mixlib/shellout" module Train::Transports class Local < Train.plugin(1) - name 'local' + name "local" class PipeError < Train::TransportError; end @@ -33,7 +33,7 @@ def login_command end def uri - 'local://' + "local://" end private @@ -41,10 +41,10 @@ def uri def select_runner(options) if os.windows? # Force a 64 bit poweshell if needed - if RUBY_PLATFORM == 'i386-mingw32' && os.arch == 'x86_64' + if RUBY_PLATFORM == "i386-mingw32" && os.arch == "x86_64" powershell_cmd = "#{ENV['SystemRoot']}\\sysnative\\WindowsPowerShell\\v1.0\\powershell.exe" else - powershell_cmd = 'powershell' + powershell_cmd = "powershell" end # Attempt to use a named pipe but fallback to ShellOut if that fails @@ -67,7 +67,7 @@ def force_runner(command_runner) when :windows_shell WindowsShellRunner.new else - fail "Runner type `#{command_runner}` not supported" + raise "Runner type `#{command_runner}` not supported" end end @@ -82,7 +82,7 @@ def run_command_via_connection(cmd, &_data_handler) res.run_command Local::CommandResult.new(res.stdout, res.stderr, res.exitstatus) rescue Errno::ENOENT => _ - CommandResult.new('', '', 1) + CommandResult.new("", "", 1) end def file_via_connection(path) @@ -112,10 +112,10 @@ def run_command(cmd) end class WindowsShellRunner - require 'json' - require 'base64' + require "json" + require "base64" - def initialize(powershell_cmd = 'powershell') + def initialize(powershell_cmd = "powershell") @powershell_cmd = powershell_cmd end @@ -124,7 +124,7 @@ def run_command(script) script = "$ProgressPreference='SilentlyContinue';" + script # Encode script so PowerShell can use it - script = script.encode('UTF-16LE', 'UTF-8') + script = script.encode("UTF-16LE", "UTF-8") base64_script = Base64.strict_encode64(script) cmd = "#{@powershell_cmd} -NoProfile -EncodedCommand #{base64_script}" @@ -136,14 +136,14 @@ def run_command(script) end class WindowsPipeRunner - require 'json' - require 'base64' - require 'securerandom' + require "json" + require "base64" + require "securerandom" - def initialize(powershell_cmd = 'powershell') + def initialize(powershell_cmd = "powershell") @powershell_cmd = powershell_cmd @pipe = acquire_pipe - fail PipeError if @pipe.nil? + raise PipeError if @pipe.nil? end def run_command(cmd) @@ -167,7 +167,7 @@ def acquire_pipe # PowerShell needs time to create pipe. 100.times do begin - pipe = open("//./pipe/#{pipe_name}", 'r+') + pipe = open("//./pipe/#{pipe_name}", "r+") break rescue sleep 0.1 @@ -178,7 +178,7 @@ def acquire_pipe end def start_pipe_server(pipe_name) - require 'win32/process' + require "win32/process" script = <<-EOF $ErrorActionPreference = 'Stop' @@ -213,14 +213,14 @@ def start_pipe_server(pipe_name) } EOF - utf8_script = script.encode('UTF-16LE', 'UTF-8') + utf8_script = script.encode("UTF-16LE", "UTF-8") base64_script = Base64.strict_encode64(utf8_script) cmd = "#{@powershell_cmd} -NoProfile -ExecutionPolicy bypass -NonInteractive -EncodedCommand #{base64_script}" server_pid = Process.create(command_line: cmd).process_id # Ensure process is killed when the Train process exits - at_exit { Process.kill('KILL', server_pid) } + at_exit { Process.kill("KILL", server_pid) } end end end diff --git a/lib/train/transports/mock.rb b/lib/train/transports/mock.rb index 69753344..e4c02900 100644 --- a/lib/train/transports/mock.rb +++ b/lib/train/transports/mock.rb @@ -1,11 +1,9 @@ -# encoding: utf-8 - -require 'train/plugins' -require 'digest' +require "train/plugins" +require "digest" module Train::Transports class Mock < Train.plugin(1) - name 'mock' + name "mock" def initialize(conf = nil) @conf = conf || {} @@ -17,39 +15,39 @@ def connection end def to_s - 'Mock Transport' + "Mock Transport" end private def trace_calls interface_methods = { - 'Train::Transports::Mock' => + "Train::Transports::Mock" => Train::Transports::Mock.instance_methods(false), - 'Train::Transports::Mock::Connection' => + "Train::Transports::Mock::Connection" => Connection.instance_methods(false), - 'Train::Transports::Mock::Connection::File' => + "Train::Transports::Mock::Connection::File" => Connection::FileCommon.instance_methods(false), - 'Train::Transports::Mock::Connection::OS' => + "Train::Transports::Mock::Connection::OS" => Train::Platform.instance_methods(false), } # rubocop:disable Metrics/ParameterLists # rubocop:disable Lint/Eval - set_trace_func proc { |event, _file, _line, id, binding, classname| - unless classname.to_s.start_with?('Train::Transports::Mock') and - event == 'call' and - interface_methods[classname.to_s].include?(id) + set_trace_func(proc { |event, _file, _line, id, binding, classname| + unless classname.to_s.start_with?("Train::Transports::Mock") && + (event == "call") && + interface_methods[classname.to_s].include?(id) next end # kindly borrowed from the wonderful simple-tracer by matugm arg_names = eval( - 'method(__method__).parameters.map { |arg| arg[1].to_s }', + "method(__method__).parameters.map { |arg| arg[1].to_s }", binding) - args = eval("#{arg_names}.map { |arg| eval(arg) }", binding).join(', ') - prefix = '-' * (classname.to_s.count(':') - 2) + '> ' + args = eval("#{arg_names}.map { |arg| eval(arg) }", binding).join(", ") + prefix = "-" * (classname.to_s.count(":") - 2) + "> " puts("#{prefix}#{id} #{args}") - } + }) # rubocop:enable all end end @@ -67,14 +65,14 @@ def initialize(conf = nil) end def uri - 'mock://' + "mock://" end def mock_os(value = {}) # if a user passes a nil value, set to an empty hash so the merge still succeeds value ||= {} - value.each { |k, v| value[k] = 'unknown' if v.nil? } - value = { name: 'mock', family: 'mock', release: 'unknown', arch: 'unknown' }.merge(value) + value.each { |k, v| value[k] = "unknown" if v.nil? } + value = { name: "mock", family: "mock", release: "unknown", arch: "unknown" }.merge(value) platform = Train::Platforms.name(value[:name]) platform.find_family_hierarchy @@ -100,26 +98,26 @@ def files end def mock_command(cmd, stdout = nil, stderr = nil, exit_status = 0) - @cache[:command][cmd] = Command.new(stdout || '', stderr || '', exit_status) + @cache[:command][cmd] = Command.new(stdout || "", stderr || "", exit_status) end def command_not_found(cmd) if @options[:verbose] - $stderr.puts('Command not mocked:') - $stderr.puts(' '+cmd.to_s.split("\n").join("\n ")) - $stderr.puts(' SHA: ' + Digest::SHA256.hexdigest(cmd.to_s)) + $stderr.puts("Command not mocked:") + $stderr.puts(" " + cmd.to_s.split("\n").join("\n ")) + $stderr.puts(" SHA: " + Digest::SHA256.hexdigest(cmd.to_s)) end # return a non-zero exit code mock_command(cmd, nil, nil, 1) end def file_not_found(path) - $stderr.puts('File not mocked: '+path.to_s) if @options[:verbose] + $stderr.puts("File not mocked: " + path.to_s) if @options[:verbose] File.new(self, path) end def to_s - 'Mock Connection' + "Mock Connection" end private @@ -142,23 +140,23 @@ class Train::Transports::Mock::Connection class Train::Transports::Mock::Connection class File < Train::File def self.from_json(json) - res = new(json['backend'], - json['path'], - json['follow_symlink']) - res.type = json['type'] + res = new(json["backend"], + json["path"], + json["follow_symlink"]) + res.type = json["type"] Train::File::DATA_FIELDS.each do |f| - m = (f.tr('?', '') + '=').to_sym + m = (f.tr("?", "") + "=").to_sym res.method(m).call(json[f]) end res end Train::File::DATA_FIELDS.each do |m| - attr_accessor m.tr('?', '').to_sym - next unless m.include?('?') + attr_accessor m.tr("?", "").to_sym + next unless m.include?("?") define_method m.to_sym do - method(m.tr('?', '').to_sym).call + method(m.tr("?", "").to_sym).call end end attr_accessor :type diff --git a/lib/train/transports/ssh.rb b/lib/train/transports/ssh.rb index 4d18af9a..cac2d7fb 100644 --- a/lib/train/transports/ssh.rb +++ b/lib/train/transports/ssh.rb @@ -18,9 +18,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -require 'net/ssh' -require 'net/scp' -require 'train/errors' +require "net/ssh" +require "net/scp" +require "train/errors" module Train::Transports # Wrapped exception for any internally raised SSH-related errors. @@ -34,10 +34,10 @@ class SSHPTYFailed < Train::TransportError; end # # @author Fletcher Nichol class SSH < Train.plugin(1) # rubocop:disable Metrics/ClassLength - name 'ssh' + name "ssh" - require 'train/transports/ssh_connection' - require 'train/transports/cisco_ios_connection' + require "train/transports/ssh_connection" + require "train/transports/cisco_ios_connection" # add options for submodules include_options Train::Extras::CommandWrapper @@ -45,7 +45,7 @@ class SSH < Train.plugin(1) # rubocop:disable Metrics/ClassLength # common target configuration option :host, required: true option :port, default: 22, required: true - option :user, default: 'root', required: true + option :user, default: "root", required: true option :key_files, default: nil option :password, default: nil @@ -60,7 +60,7 @@ class SSH < Train.plugin(1) # rubocop:disable Metrics/ClassLength option :pty, default: false option :proxy_command, default: nil option :bastion_host, default: nil - option :bastion_user, default: 'root' + option :bastion_user, default: "root" option :bastion_port, default: 22 option :non_interactive, default: false option :verify_host_key, default: false @@ -89,34 +89,34 @@ def validate_options(options) super(options) key_files = Array(options[:key_files]) - options[:auth_methods] ||= ['none'] + options[:auth_methods] ||= ["none"] unless key_files.empty? - options[:auth_methods].push('publickey') + options[:auth_methods].push("publickey") options[:keys_only] = true if options[:password].nil? options[:key_files] = key_files end unless options[:password].nil? - options[:auth_methods].push('password', 'keyboard-interactive') + options[:auth_methods].push("password", "keyboard-interactive") end - if options[:auth_methods] == ['none'] + if options[:auth_methods] == ["none"] if ssh_known_identities.empty? - fail Train::ClientError, - 'Your SSH Agent has no keys added, and you have not specified a password or a key file' + raise Train::ClientError, + "Your SSH Agent has no keys added, and you have not specified a password or a key file" else - logger.debug('[SSH] Using Agent keys as no password or key file have been specified') - options[:auth_methods].push('publickey') + logger.debug("[SSH] Using Agent keys as no password or key file have been specified") + options[:auth_methods].push("publickey") end end if options[:pty] - logger.warn('[SSH] PTY requested: stderr will be merged into stdout') + logger.warn("[SSH] PTY requested: stderr will be merged into stdout") end if [options[:proxy_command], options[:bastion_host]].all? { |type| !type.nil? } - fail Train::ClientError, 'Only one of proxy_command or bastion_host needs to be specified' + raise Train::ClientError, "Only one of proxy_command or bastion_host needs to be specified" end super @@ -142,30 +142,30 @@ def ssh_known_identities # @api private def connection_options(opts) connection_options = { - logger: logger, - user_known_hosts_file: '/dev/null', - hostname: opts[:host], - port: opts[:port], - username: opts[:user], - compression: opts[:compression], - compression_level: opts[:compression_level], - keepalive: opts[:keepalive], - keepalive_interval: opts[:keepalive_interval], - timeout: opts[:connection_timeout], - connection_retries: opts[:connection_retries], + logger: logger, + user_known_hosts_file: "/dev/null", + hostname: opts[:host], + port: opts[:port], + username: opts[:user], + compression: opts[:compression], + compression_level: opts[:compression_level], + keepalive: opts[:keepalive], + keepalive_interval: opts[:keepalive_interval], + timeout: opts[:connection_timeout], + connection_retries: opts[:connection_retries], connection_retry_sleep: opts[:connection_retry_sleep], - max_wait_until_ready: opts[:max_wait_until_ready], - auth_methods: opts[:auth_methods], - keys_only: opts[:keys_only], - keys: opts[:key_files], - password: opts[:password], - forward_agent: opts[:forward_agent], - proxy_command: opts[:proxy_command], - bastion_host: opts[:bastion_host], - bastion_user: opts[:bastion_user], - bastion_port: opts[:bastion_port], - non_interactive: opts[:non_interactive], - transport_options: opts, + max_wait_until_ready: opts[:max_wait_until_ready], + auth_methods: opts[:auth_methods], + keys_only: opts[:keys_only], + keys: opts[:key_files], + password: opts[:password], + forward_agent: opts[:forward_agent], + proxy_command: opts[:proxy_command], + bastion_host: opts[:bastion_host], + bastion_user: opts[:bastion_user], + bastion_port: opts[:bastion_port], + non_interactive: opts[:non_interactive], + transport_options: opts, } # disable host key verification. The hash key and value to use # depends on the version of net-ssh in use. @@ -203,20 +203,20 @@ def verify_host_key_value(given) # 5.0+ style { # It's not a boolean anymore. - 'true' => :always, - 'false' => :never, + "true" => :always, + "false" => :never, true => :always, false => :never, # May be correct value, but strings from JSON config - 'always' => :always, - 'never' => :never, + "always" => :always, + "never" => :never, nil => :never, }.fetch(given, given) else # up to 4.2 style { - 'true' => true, - 'false' => false, + "true" => true, + "false" => false, nil => false, }.fetch(given, given) end diff --git a/lib/train/transports/ssh_connection.rb b/lib/train/transports/ssh_connection.rb index 14294e61..112c7f63 100644 --- a/lib/train/transports/ssh_connection.rb +++ b/lib/train/transports/ssh_connection.rb @@ -18,9 +18,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -require 'net/ssh' -require 'net/scp' -require 'timeout' +require "net/ssh" +require "net/scp" +require "timeout" class Train::Transports::SSH # A Connection instance can be generated and re-generated, given new @@ -63,17 +63,17 @@ def close end def ssh_opts - level = logger.debug? ? 'VERBOSE' : 'ERROR' - fwd_agent = options[:forward_agent] ? 'yes' : 'no' + level = logger.debug? ? "VERBOSE" : "ERROR" + fwd_agent = options[:forward_agent] ? "yes" : "no" args = %w{ -o UserKnownHostsFile=/dev/null } args += %w{ -o StrictHostKeyChecking=no } args += %w{ -o IdentitiesOnly=yes } if options[:keys] args += %w{ -o BatchMode=yes } if options[:non_interactive] - args += %W( -o LogLevel=#{level} ) - args += %W( -o ForwardAgent=#{fwd_agent} ) if options.key?(:forward_agent) + args += %W{ -o LogLevel=#{level} } + args += %W{ -o ForwardAgent=#{fwd_agent} } if options.key?(:forward_agent) Array(options[:keys]).each do |ssh_key| - args += %W( -i #{ssh_key} ) + args += %W{ -i #{ssh_key} } end args end @@ -86,19 +86,19 @@ def generate_proxy_command return @proxy_command unless @proxy_command.nil? args = %w{ ssh } args += ssh_opts - args += %W( #{@bastion_user}@#{@bastion_host} ) - args += %W( -p #{@bastion_port} ) + args += %W{ #{@bastion_user}@#{@bastion_host} } + args += %W{ -p #{@bastion_port} } args += %w{ -W %h:%p } - args.join(' ') + args.join(" ") end # (see Base::Connection#login_command) def login_command args = ssh_opts - args += %W( -o ProxyCommand='#{generate_proxy_command}' ) if check_proxy - args += %W( -p #{@port} ) - args += %W( #{@username}@#{@hostname} ) - LoginCommand.new('ssh', args) + args += %W{ -o ProxyCommand='#{generate_proxy_command}' } if check_proxy + args += %W{ -p #{@port} } + args += %W{ #{@username}@#{@hostname} } + LoginCommand.new("ssh", args) end # (see Base::Connection#upload) @@ -138,7 +138,7 @@ def wait_until_ready retries: @max_wait_until_ready / delay, delay: delay, message: "Waiting for SSH service on #{@hostname}:#{@port}, " \ - "retrying in #{delay} seconds", + "retrying in #{delay} seconds" ) run_command(PING_COMMAND.dup) end @@ -172,14 +172,14 @@ def uri def establish_connection(opts) logger.debug("[SSH] opening connection to #{self}") if check_proxy - require 'net/ssh/proxy/command' + require "net/ssh/proxy/command" @options[:proxy] = Net::SSH::Proxy::Command.new(generate_proxy_command) end Net::SSH.start(@hostname, @username, @options.clone.delete_if { |_key, value| value.nil? }) rescue *RESCUE_EXCEPTIONS_ON_ESTABLISH => e if (opts[:retries] -= 1) <= 0 logger.warn("[SSH] connection failed, terminating (#{e.inspect})") - raise Train::Transports::SSHFailed, 'SSH session could not be established' + raise Train::Transports::SSHFailed, "SSH session could not be established" end if opts[:message] @@ -200,7 +200,7 @@ def file_via_connection(path) Train::File::Remote::Aix.new(self, path) elsif os.solaris? Train::File::Remote::Unix.new(self, path) - elsif os[:name] == 'qnx' + elsif os[:name] == "qnx" Train::File::Remote::Qnx.new(self, path) elsif os.windows? Train::File::Remote::Windows.new(self, path) @@ -210,7 +210,7 @@ def file_via_connection(path) end def run_command_via_connection(cmd, &data_handler) - cmd.dup.force_encoding('binary') if cmd.respond_to?(:force_encoding) + cmd.dup.force_encoding("binary") if cmd.respond_to?(:force_encoding) logger.debug("[SSH] #{self} (#{cmd})") reset_session if session.closed? @@ -228,7 +228,7 @@ def run_command_via_connection(cmd, &data_handler) # transport. This retries the command if this is the case. # See: # https://github.com/inspec/train/pull/271 - logger.debug('[SSH] Possible Cisco IOS race condition, retrying command') + logger.debug("[SSH] Possible Cisco IOS race condition, retrying command") # Only attempt retry up to 5 times to avoid infinite loop @ios_cmd_retries += 1 @@ -246,7 +246,7 @@ def run_command_via_connection(cmd, &data_handler) def session(retry_options = {}) @session ||= establish_connection({ retries: @connection_retries.to_i, - delay: @connection_retry_sleep.to_i, + delay: @connection_retry_sleep.to_i, }.merge(retry_options)) end @@ -260,7 +260,7 @@ def reset_session # @api private def to_s options_to_print = @options.clone - options_to_print[:password] = '' if options_to_print.key?(:password) + options_to_print[:password] = "" if options_to_print.key?(:password) "#{@username}@#{@hostname}<#{options_to_print.inspect}>" end @@ -274,7 +274,7 @@ def to_s # # @api private def execute_on_channel(cmd, &data_handler) - stdout = stderr = '' + stdout = stderr = "" exit_status = nil session.open_channel do |channel| # wrap commands if that is configured @@ -282,11 +282,11 @@ def execute_on_channel(cmd, &data_handler) if @transport_options[:pty] channel.request_pty do |_ch, success| - fail Train::Transports::SSHPTYFailed, 'Requesting PTY failed' unless success + raise Train::Transports::SSHPTYFailed, "Requesting PTY failed" unless success end end channel.exec(cmd) do |_, success| - abort 'Couldn\'t execute command on SSH.' unless success + abort "Couldn't execute command on SSH." unless success channel.on_data do |_, data| yield(data) unless data_handler.nil? stdout += data @@ -297,11 +297,11 @@ def execute_on_channel(cmd, &data_handler) stderr += data end - channel.on_request('exit-status') do |_, data| + channel.on_request("exit-status") do |_, data| exit_status = data.read_long end - channel.on_request('exit-signal') do |_, data| + channel.on_request("exit-signal") do |_, data| exit_status = data.read_long end end diff --git a/lib/train/transports/vmware.rb b/lib/train/transports/vmware.rb index 0379f43b..ea93de96 100644 --- a/lib/train/transports/vmware.rb +++ b/lib/train/transports/vmware.rb @@ -1,16 +1,16 @@ # encoding: utf-8 -require 'train/plugins' -require 'open3' -require 'ostruct' -require 'json' -require 'mkmf' +require "train/plugins" +require "open3" +require "ostruct" +require "json" +require "mkmf" module Train::Transports class VMware < Train.plugin(1) - name 'vmware' - option :viserver, default: proc { ENV['VISERVER'] } - option :username, default: proc { ENV['VISERVER_USERNAME'] } - option :password, default: proc { ENV['VISERVER_PASSWORD'] } + name "vmware" + option :viserver, default: proc { ENV["VISERVER"] } + option :username, default: proc { ENV["VISERVER_USERNAME"] } + option :password, default: proc { ENV["VISERVER_PASSWORD"] } option :insecure, default: false def connection(_ = nil) @@ -18,7 +18,7 @@ def connection(_ = nil) end class Connection < BaseConnection # rubocop:disable ClassLength - POWERSHELL_PROMPT_REGEX = /PS\s.*> $/ + POWERSHELL_PROMPT_REGEX = /PS\s.*> $/.freeze def initialize(options) super(options) @@ -29,18 +29,18 @@ def initialize(options) @username = options[:username] @viserver = options[:viserver] @session = nil - @stdout_buffer = '' - @stderr_buffer = '' + @stdout_buffer = "" + @stderr_buffer = "" @powershell_binary = detect_powershell_binary if @powershell_binary == :powershell - require 'train/transports/local' + require "train/transports/local" @powershell = Train::Transports::Local::Connection.new(options) end if options[:insecure] == true - run_command_via_connection('Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Scope Session -Confirm:$False') + run_command_via_connection("Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Scope Session -Confirm:$False") end @platform_details = { @@ -58,11 +58,11 @@ def connect message = "Unable to connect to VIServer at #{options[:viserver]}. " case result.stderr when /Invalid server certificate/ - message += 'Certification verification failed. Please use `--insecure` or set `Set-PowerCLIConfiguration -InvalidCertificateAction Ignore` in PowerShell' + message += "Certification verification failed. Please use `--insecure` or set `Set-PowerCLIConfiguration -InvalidCertificateAction Ignore` in PowerShell" when /incorrect user name or password/ - message += 'Incorrect username or password' + message += "Incorrect username or password" else - message += result.stderr.gsub(/-Password .*\s/, '-Password REDACTED') + message += result.stderr.gsub(/-Password .*\s/, "-Password REDACTED") end raise message @@ -70,7 +70,7 @@ def connect end def platform - force_platform!('vmware', @platform_details) + force_platform!("vmware", @platform_details) end def run_command_via_connection(cmd, &_data_handler) @@ -78,8 +78,8 @@ def run_command_via_connection(cmd, &_data_handler) result = parse_pwsh_output(cmd) # Attach exit status to result - exit_status = parse_pwsh_output('echo $?').stdout.chomp - result.exit_status = exit_status == 'True' ? 0 : 1 + exit_status = parse_pwsh_output("echo $?").stdout.chomp + result.exit_status = exit_status == "True" ? 0 : 1 result else @@ -88,7 +88,7 @@ def run_command_via_connection(cmd, &_data_handler) end def unique_identifier - uuid_command = '(Get-VMHost | Get-View).hardware.systeminfo.uuid' + uuid_command = "(Get-VMHost | Get-View).hardware.systeminfo.uuid" run_command_via_connection(uuid_command).stdout.chomp end @@ -99,26 +99,24 @@ def uri private def detect_powershell_binary - if find_executable0('pwsh') + if find_executable0("pwsh") :pwsh - elsif find_executable0('powershell') + elsif find_executable0("powershell") :powershell else - raise 'Cannot find PowerShell binary, is `pwsh` installed?' + raise "Cannot find PowerShell binary, is `pwsh` installed?" end end # Read from stdout pipe until prompt is received def flush_stdout(pipe) - while @stdout_buffer !~ POWERSHELL_PROMPT_REGEX - @stdout_buffer += pipe.read_nonblock(1) - end + @stdout_buffer += pipe.read_nonblock(1) while @stdout_buffer !~ POWERSHELL_PROMPT_REGEX @stdout_buffer rescue IO::EAGAINWaitReadable # We cannot know when the stdout pipe is finished so we keep reading retry ensure - @stdout_buffer = '' + @stdout_buffer = "" end # This must be called after `flush_stdout` to ensure buffer is full @@ -132,7 +130,7 @@ def flush_stderr(pipe) # is unreadable. @stderr_buffer ensure - @stderr_buffer = '' + @stderr_buffer = "" end def parse_pwsh_output(cmd) @@ -141,10 +139,10 @@ def parse_pwsh_output(cmd) stdout = flush_stdout(session.stdout) # Remove stdin from stdout (including trailing newline) - stdout.slice!(0, cmd.length+1) + stdout.slice!(0, cmd.length + 1) # Remove prompt from stdout - stdout.gsub!(POWERSHELL_PROMPT_REGEX, '') + stdout.gsub!(POWERSHELL_PROMPT_REGEX, "") # Grab stderr stderr = flush_stderr(session.stderr) @@ -157,10 +155,10 @@ def parse_pwsh_output(cmd) end def powercli_version - version_command = '[string](Get-Module -Name VMware.PowerCLI -ListAvailable | Select -ExpandProperty Version)' + version_command = "[string](Get-Module -Name VMware.PowerCLI -ListAvailable | Select -ExpandProperty Version)" result = run_command_via_connection(version_command) if result.stdout.empty? || result.exit_status != 0 - raise 'Unable to determine PowerCLI Module version, is it installed?' + raise "Unable to determine PowerCLI Module version, is it installed?" end result.stdout.chomp @@ -169,7 +167,7 @@ def powercli_version def session return @session unless @session.nil? - stdin, stdout, stderr = Open3.popen3('pwsh') + stdin, stdout, stderr = Open3.popen3("pwsh") # Remove leading prompt and intro text flush_stdout(stdout) diff --git a/lib/train/transports/winrm.rb b/lib/train/transports/winrm.rb index 06769f4e..0ef9d1b0 100644 --- a/lib/train/transports/winrm.rb +++ b/lib/train/transports/winrm.rb @@ -20,9 +20,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -require 'rbconfig' -require 'uri' -require 'train/errors' +require "rbconfig" +require "uri" +require "train/errors" module Train::Transports # Wrapped exception for any internally raised WinRM-related errors. @@ -36,22 +36,22 @@ class WinRMFailed < Train::TransportError; end # @author Salim Afiune # @author Fletcher Nichol class WinRM < Train.plugin(1) # rubocop:disable ClassLength - name 'winrm' + name "winrm" - require 'train/transports/winrm_connection' + require "train/transports/winrm_connection" # ref: https://github.com/winrb/winrm#transports - SUPPORTED_WINRM_TRANSPORTS = %i(negotiate ssl plaintext kerberos).freeze + SUPPORTED_WINRM_TRANSPORTS = %i{negotiate ssl plaintext kerberos}.freeze # common target configuration option :host, required: true option :port - option :user, default: 'administrator', required: true + option :user, default: "administrator", required: true option :password, nil option :winrm_transport, default: :negotiate option :winrm_disable_sspi, default: false option :winrm_basic_auth_only, default: false - option :path, default: '/wsman' + option :path, default: "/wsman" option :ssl, default: false option :self_signed, default: false @@ -93,21 +93,21 @@ def validate_options(opts) super(opts) # set scheme and port based on ssl activation - scheme = opts[:ssl] ? 'https' : 'http' + scheme = opts[:ssl] ? "https" : "http" port = opts[:port] port = (opts[:ssl] ? 5986 : 5985) if port.nil? winrm_transport = opts[:winrm_transport].to_sym unless SUPPORTED_WINRM_TRANSPORTS.include?(winrm_transport) - fail Train::ClientError, "Unsupported transport type: #{winrm_transport.inspect}" + raise Train::ClientError, "Unsupported transport type: #{winrm_transport.inspect}" end # remove leading '/' - path = (opts[:path] || '').sub(%r{^/+}, '') + path = (opts[:path] || "").sub(%r{^/+}, "") opts[:endpoint] = "#{scheme}://#{opts[:host]}:#{port}/#{path}" end - WINRM_FS_SPEC_VERSION = '~> 1.0'.freeze + WINRM_FS_SPEC_VERSION = "~> 1.0".freeze # Builds the hash of options needed by the Connection object on # construction. @@ -117,23 +117,23 @@ def validate_options(opts) # @api private def connection_options(opts) { - logger: logger, - transport: opts[:winrm_transport].to_sym, - disable_sspi: opts[:winrm_disable_sspi], - basic_auth_only: opts[:winrm_basic_auth_only], - hostname: opts[:host], - endpoint: opts[:endpoint], - user: opts[:user], - password: opts[:password], - rdp_port: opts[:rdp_port], - connection_retries: opts[:connection_retries], - connection_retry_sleep: opts[:connection_retry_sleep], - max_wait_until_ready: opts[:max_wait_until_ready], + logger: logger, + transport: opts[:winrm_transport].to_sym, + disable_sspi: opts[:winrm_disable_sspi], + basic_auth_only: opts[:winrm_basic_auth_only], + hostname: opts[:host], + endpoint: opts[:endpoint], + user: opts[:user], + password: opts[:password], + rdp_port: opts[:rdp_port], + connection_retries: opts[:connection_retries], + connection_retry_sleep: opts[:connection_retry_sleep], + max_wait_until_ready: opts[:max_wait_until_ready], no_ssl_peer_verification: opts[:self_signed], - realm: opts[:kerberos_realm], - service: opts[:kerberos_service], - ca_trust_path: opts[:ca_trust_path], - ssl_peer_fingerprint: opts[:ssl_peer_fingerprint], + realm: opts[:kerberos_realm], + service: opts[:kerberos_service], + ca_trust_path: opts[:ca_trust_path], + ssl_peer_fingerprint: opts[:ssl_peer_fingerprint], } end @@ -156,24 +156,24 @@ def create_new_connection(options, &block) # (see Base#load_needed_dependencies!) def load_needed_dependencies! spec_version = WINRM_FS_SPEC_VERSION.dup - logger.debug('winrm-fs requested,' \ + logger.debug("winrm-fs requested," \ " loading WinRM::FS gem (#{spec_version})") - gem 'winrm-fs', spec_version - first_load = require 'winrm-fs' + gem "winrm-fs", spec_version + first_load = require "winrm-fs" load_winrm_transport! if first_load - logger.debug('WinRM::FS library loaded') + logger.debug("WinRM::FS library loaded") else - logger.debug('WinRM::FS previously loaded') + logger.debug("WinRM::FS previously loaded") end rescue LoadError => e logger.fatal( "The `winrm-fs' gem is missing and must" \ - ' be installed or cannot be properly activated. Run' \ + " be installed or cannot be properly activated. Run" \ " `gem install winrm-fs --version '#{spec_version}'`" \ - ' or add the following to your Gemfile if you are using Bundler:' \ - " `gem 'winrm-fs', '#{spec_version}'`.", + " or add the following to your Gemfile if you are using Bundler:" \ + " `gem 'winrm-fs', '#{spec_version}'`." ) raise Train::UserError, "Could not load or activate WinRM::FS (#{e.message})" @@ -183,7 +183,7 @@ def load_needed_dependencies! # # @api private def load_winrm_transport! - silence_warnings { require 'winrm-fs' } + silence_warnings { require "winrm-fs" } end # Return the last saved WinRM connection instance. diff --git a/lib/train/transports/winrm_connection.rb b/lib/train/transports/winrm_connection.rb index 1f52d4d7..4dfbe1b3 100644 --- a/lib/train/transports/winrm_connection.rb +++ b/lib/train/transports/winrm_connection.rb @@ -49,7 +49,7 @@ def close # (see Base::Connection#login_command) def login_command - case RbConfig::CONFIG['host_os'] + case RbConfig::CONFIG["host_os"] when /darwin/ login_command_for_mac when /mswin|msys|mingw|cygwin|bccwin|wince|emc/ @@ -57,7 +57,7 @@ def login_command when /linux/ login_command_for_linux else - fail ActionFailed, + raise ActionFailed, "Remote login not supported in #{self.class} " \ "from host OS '#{RbConfig::CONFIG['host_os']}'." end @@ -79,7 +79,7 @@ def wait_until_ready delay = 3 session( retry_limit: @max_wait_until_ready / delay, - retry_delay: delay, + retry_delay: delay ) run_command_via_connection(PING_COMMAND.dup) end @@ -99,7 +99,7 @@ def file_via_connection(path) def run_command_via_connection(command, &data_handler) return if command.nil? logger.debug("[WinRM] #{self} (#{command})") - out = '' + out = "" response = session.run(command) do |stdout, _| yield(stdout) if data_handler && stdout @@ -119,7 +119,7 @@ def rdp_doc(opts = {}) host = URI.parse(options[:endpoint]).host content = [ "full address:s:#{host}:#{@rdp_port}", - 'prompt for credentials:i:1', + "prompt for credentials:i:1", "username:s:#{options[:user]}", ].join("\n") @@ -145,10 +145,10 @@ def file_manager # @return [LoginCommand] a login command # @api private def login_command_for_linux - args = %W( -u #{options[:user]} ) - args += %W( -p #{options[:pass]} ) if options.key?(:pass) - args += %W( #{URI.parse(options[:endpoint]).host}:#{@rdp_port} ) - LoginCommand.new('rdesktop', args) + args = %W{ -u #{options[:user]} } + args += %W{ -p #{options[:pass]} } if options.key?(:pass) + args += %W{ #{URI.parse(options[:endpoint]).host}:#{@rdp_port} } + LoginCommand.new("rdesktop", args) end # Builds a `LoginCommand` for use by Mac-based platforms. @@ -156,7 +156,7 @@ def login_command_for_linux # @return [LoginCommand] a login command # @api private def login_command_for_mac - LoginCommand.new('open', rdp_doc(mac: true)) + LoginCommand.new("open", rdp_doc(mac: true)) end # Builds a `LoginCommand` for use by Windows-based platforms. @@ -164,7 +164,7 @@ def login_command_for_mac # @return [LoginCommand] a login command # @api private def login_command_for_windows - LoginCommand.new('mstsc', rdp_doc) + LoginCommand.new("mstsc", rdp_doc) end # Establishes a remote shell session, or establishes one when invoked @@ -193,7 +193,7 @@ def session(retry_options = {}) # @api private def to_s options_to_print = @options.clone - options_to_print[:password] = '' if options_to_print.key?(:password) + options_to_print[:password] = "" if options_to_print.key?(:password) "#{@username}@#{@hostname}<#{options_to_print.inspect}>" end end diff --git a/lib/train/version.rb b/lib/train/version.rb index 7d41e44b..a67dc97e 100644 --- a/lib/train/version.rb +++ b/lib/train/version.rb @@ -3,5 +3,5 @@ # Author:: Dominik Richter () module Train - VERSION = '2.1.10'.freeze + VERSION = "2.1.10".freeze end diff --git a/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture.rb b/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture.rb index b5f5ed68..26477679 100644 --- a/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture.rb +++ b/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture.rb @@ -1,4 +1,4 @@ lib = File.expand_path("../../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require 'train-test-fixture/transport' \ No newline at end of file +require "train-test-fixture/transport" diff --git a/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/connection.rb b/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/connection.rb index 0b85cd9a..f4eb7a84 100644 --- a/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/connection.rb +++ b/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/connection.rb @@ -1,5 +1,5 @@ -require 'train-test-fixture/platform' -require 'train/transports/local' +require "train-test-fixture/platform" +require "train/transports/local" module TrainPlugins module TestFixture @@ -14,8 +14,8 @@ def initialize(options) def run_command_via_connection(cmd) Train::Transports::Local::CommandResult.new( - 'Mock Command Result stdout', - 'Mock Command Result stderr', + "Mock Command Result stdout", + "Mock Command Result stderr", 17 ) end @@ -27,7 +27,7 @@ def file_via_connection(path, *args) class MockFile < Train::File def content # Remarkably, the content is always the same. - 'Lorem Ipsum' + "Lorem Ipsum" end end end diff --git a/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/platform.rb b/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/platform.rb index fe2171c8..e8687af6 100644 --- a/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/platform.rb +++ b/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/platform.rb @@ -1,4 +1,4 @@ -require 'train-test-fixture/version' +require "train-test-fixture/version" module TrainPlugins module TestFixture @@ -6,11 +6,11 @@ module Platform def platform # Build this platform's family declarations. # You'll need at least unix and windows to make the file() resource work. - Train::Platforms.name('test-fixture').in_family('unix') - Train::Platforms.name('test-fixture').in_family('windows') - force_platform!('test-fixture', + Train::Platforms.name("test-fixture").in_family("unix") + Train::Platforms.name("test-fixture").in_family("windows") + force_platform!("test-fixture", release: TrainPlugins::TestFixture::VERSION, - arch: 'mock', + arch: "mock" ) end end diff --git a/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/transport.rb b/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/transport.rb index c811209e..e7284fc8 100644 --- a/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/transport.rb +++ b/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/transport.rb @@ -1,9 +1,9 @@ -require 'train-test-fixture/connection' +require "train-test-fixture/connection" module TrainPlugins module TestFixture class Transport < Train.plugin(1) - name 'test-fixture' + name "test-fixture" def connection(_ = nil) @connection ||= TrainPlugins::TestFixture::Connection.new(@options) diff --git a/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/version.rb b/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/version.rb index b68f3d9b..1a416acf 100644 --- a/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/version.rb +++ b/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/version.rb @@ -1,5 +1,5 @@ module TrainPlugins module TestFixture - VERSION = '0.1.0' + VERSION = "0.1.0".freeze end end diff --git a/test/fixtures/plugins/train-test-fixture/train-test-fixture.gemspec b/test/fixtures/plugins/train-test-fixture/train-test-fixture.gemspec index 4b8a9b7d..6da1a066 100644 --- a/test/fixtures/plugins/train-test-fixture/train-test-fixture.gemspec +++ b/test/fixtures/plugins/train-test-fixture/train-test-fixture.gemspec @@ -4,10 +4,10 @@ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = "train-test-fixture" - spec.version = '0.1.0' + spec.version = "0.1.0" spec.authors = ["Inspec core engineering team"] spec.email = ["hello@chef.io"] - spec.license = 'Apache-2.0' + spec.license = "Apache-2.0" spec.summary = %q{Test train plugin. Not intended for use as an example.} spec.description = <<-EOD diff --git a/test/helper.rb b/test/helper.rb index 5615b63f..ec77c33a 100644 --- a/test/helper.rb +++ b/test/helper.rb @@ -1,14 +1,14 @@ # encoding: utf-8 -require 'coveralls' +require "coveralls" Coveralls.wear! -require 'minitest/autorun' -require 'minitest/spec' -require 'mocha/minitest' -require 'mocha/setup' -require 'byebug' +require "minitest/autorun" +require "minitest/spec" +require "mocha/minitest" +require "mocha/setup" +require "byebug" -require 'train' +require "train" # needed to force unix? and others to be created Train::Platforms::Detect::Specifications::OS.load diff --git a/test/integration/Berksfile b/test/integration/Berksfile index 7ad64b06..637f362c 100644 --- a/test/integration/Berksfile +++ b/test/integration/Berksfile @@ -1,3 +1,3 @@ -source 'https://supermarket.chef.io' -cookbook 'sudo', '~> 2.7.2' -cookbook 'test', path: 'cookbooks/test' +source "https://supermarket.chef.io" +cookbook "sudo", "~> 2.7.2" +cookbook "test", path: "cookbooks/test" diff --git a/test/integration/cookbooks/test/metadata.rb b/test/integration/cookbooks/test/metadata.rb index e7a82d6d..ea5f21d9 100644 --- a/test/integration/cookbooks/test/metadata.rb +++ b/test/integration/cookbooks/test/metadata.rb @@ -1 +1 @@ -name 'test' +name "test" diff --git a/test/integration/cookbooks/test/recipes/default.rb b/test/integration/cookbooks/test/recipes/default.rb index 170d20ba..8b11de84 100644 --- a/test/integration/cookbooks/test/recipes/default.rb +++ b/test/integration/cookbooks/test/recipes/default.rb @@ -9,92 +9,92 @@ # Finally (for now), it actually executes the all tests with # the local execution backend -include_recipe('test::prep_files') +include_recipe("test::prep_files") # prepare ssh for backend -execute 'create ssh key' do +execute "create ssh key" do command 'ssh-keygen -t rsa -b 2048 -f /root/.ssh/id_rsa -N ""' - not_if 'test -e /root/.ssh/id_rsa' + not_if "test -e /root/.ssh/id_rsa" end -execute 'add ssh key to vagrant user' do - command 'cat /root/.ssh/id_rsa.pub >> /home/vagrant/.ssh/authorized_keys' +execute "add ssh key to vagrant user" do + command "cat /root/.ssh/id_rsa.pub >> /home/vagrant/.ssh/authorized_keys" end -execute 'test ssh connection' do +execute "test ssh connection" do command 'ssh -o StrictHostKeyChecking=no -i /root/.ssh/id_rsa vagrant@localhost "echo 1"' end # prepare a few users %w{ nopasswd passwd nosudo reqtty customcommand }.each do |name| user name do - password '$1$7MCNTXPI$r./jqCEoVlLlByYKSL3sZ.' + password "$1$7MCNTXPI$r./jqCEoVlLlByYKSL3sZ." manage_home true end end %w{nopasswd vagrant}.each do |name| sudo name do - user '%'+name + user "%" + name nopasswd true - defaults ['!requiretty'] + defaults ["!requiretty"] end end -sudo 'passwd' do - user 'passwd' +sudo "passwd" do + user "passwd" nopasswd false - defaults ['!requiretty'] + defaults ["!requiretty"] end -sudo 'reqtty' do - user 'reqtty' +sudo "reqtty" do + user "reqtty" nopasswd true - defaults ['requiretty'] + defaults ["requiretty"] end -sudo 'customcommand' do - user 'customcommand' +sudo "customcommand" do + user "customcommand" nopasswd true - defaults ['!requiretty'] + defaults ["!requiretty"] end # execute tests -execute 'bundle install' do - command '/opt/chef/embedded/bin/bundle install --without integration tools' - cwd '/tmp/kitchen/data' +execute "bundle install" do + command "/opt/chef/embedded/bin/bundle install --without integration tools" + cwd "/tmp/kitchen/data" end -execute 'run local tests' do - command '/opt/chef/embedded/bin/ruby -I lib test/integration/test_local.rb test/integration/tests/*_test.rb' - cwd '/tmp/kitchen/data' +execute "run local tests" do + command "/opt/chef/embedded/bin/ruby -I lib test/integration/test_local.rb test/integration/tests/*_test.rb" + cwd "/tmp/kitchen/data" end -execute 'run ssh tests' do - command '/opt/chef/embedded/bin/ruby -I lib test/integration/test_ssh.rb test/integration/tests/*_test.rb' - cwd '/tmp/kitchen/data' +execute "run ssh tests" do + command "/opt/chef/embedded/bin/ruby -I lib test/integration/test_ssh.rb test/integration/tests/*_test.rb" + cwd "/tmp/kitchen/data" end %w{passwd nopasswd reqtty customcommand}.each do |name| execute "run local sudo tests as #{name}" do command "/opt/chef/embedded/bin/ruby -I lib test/integration/sudo/#{name}.rb" - cwd '/tmp/kitchen/data' + cwd "/tmp/kitchen/data" user name end end -execute 'fix sudoers for reqtty' do - command 'chef-apply contrib/fixup_requiretty.rb' - cwd '/tmp/kitchen/data' +execute "fix sudoers for reqtty" do + command "chef-apply contrib/fixup_requiretty.rb" + cwd "/tmp/kitchen/data" environment( - 'TRAIN_SUDO_USER' => 'reqtty', - 'TRAIN_SUDO_VERY_MUCH' => 'yes', + "TRAIN_SUDO_USER" => "reqtty", + "TRAIN_SUDO_VERY_MUCH" => "yes" ) end # if it's fixed, it should behave like user 'nopasswd' -execute 'run local sudo tests as reqtty, no longer requiring a tty' do +execute "run local sudo tests as reqtty, no longer requiring a tty" do command "/opt/chef/embedded/bin/ruby -I lib test/integration/sudo/nopasswd.rb" - cwd '/tmp/kitchen/data' - user 'reqtty' + cwd "/tmp/kitchen/data" + user "reqtty" end diff --git a/test/integration/cookbooks/test/recipes/prep_files.rb b/test/integration/cookbooks/test/recipes/prep_files.rb index 69298917..b88212c6 100644 --- a/test/integration/cookbooks/test/recipes/prep_files.rb +++ b/test/integration/cookbooks/test/recipes/prep_files.rb @@ -5,52 +5,52 @@ # Helper recipe to create create a few files in the operating # systems, which the runner will test against. -gid = node['platform_family'] == 'aix' ? 'system' : node['root_group'] +gid = node["platform_family"] == "aix" ? "system" : node["root_group"] -file '/tmp/file' do - mode '0765' - owner 'root' +file "/tmp/file" do + mode "0765" + owner "root" group gid - content 'hello world' + content "hello world" end -file '/tmp/sfile' do - mode '7765' - owner 'root' +file "/tmp/sfile" do + mode "7765" + owner "root" group gid - content 'hello suid/sgid/sticky' + content "hello suid/sgid/sticky" end -file '/tmp/spaced file' do - content 'hello space' +file "/tmp/spaced file" do + content "hello space" end -directory '/tmp/folder' do - mode '0567' - owner 'root' +directory "/tmp/folder" do + mode "0567" + owner "root" group gid end -link '/tmp/symlink' do - to '/tmp/file' - owner 'root' +link "/tmp/symlink" do + to "/tmp/file" + owner "root" group gid - mode '0777' + mode "0777" end -link '/usr/bin/allyourbase' do - to '/usr/bin/sudo' - owner 'root' +link "/usr/bin/allyourbase" do + to "/usr/bin/sudo" + owner "root" group gid - mode '0777' + mode "0777" end -execute 'create pipe/fifo' do - command 'mkfifo /tmp/pipe' - not_if 'test -e /tmp/pipe' +execute "create pipe/fifo" do + command "mkfifo /tmp/pipe" + not_if "test -e /tmp/pipe" end -execute 'create block_device' do +execute "create block_device" do command "mknod /tmp/block_device b 7 7 && chmod 0666 /tmp/block_device && chown root:#{gid} /tmp/block_device" - not_if 'test -e /tmp/block_device' + not_if "test -e /tmp/block_device" end diff --git a/test/integration/docker_run.rb b/test/integration/docker_run.rb index eac7bcae..2bb3e929 100644 --- a/test/integration/docker_run.rb +++ b/test/integration/docker_run.rb @@ -1,23 +1,20 @@ -# encoding: utf-8 -# author: Dominik Richter - -require 'docker' -require 'yaml' -require 'concurrent' +require "docker" +require "yaml" +require "concurrent" class DockerRunner def initialize(conf_path = nil) - @conf_path = conf_path || ENV['config'] + @conf_path = conf_path || ENV["config"] unless File.file?(@conf_path) - fail "Can't find configuration in #{@conf_path}" + raise "Can't find configuration in #{@conf_path}" end @conf = YAML.load_file(@conf_path) - if @conf.nil? or @conf.empty? - fail "Can't read coniguration in #{@conf_path}" + if @conf.nil? || @conf.empty? + raise "Can't read coniguration in #{@conf_path}" end - if @conf['images'].nil? - fail "You must configure test images in your #{@conf_path}" + if @conf["images"].nil? + raise "You must configure test images in your #{@conf_path}" end @images = docker_images_by_tag @@ -26,9 +23,9 @@ def initialize(conf_path = nil) end def run_all(&block) - fail 'You must provide a block for run_all' unless block_given? + raise "You must provide a block for run_all" unless block_given? - promises = @conf['images'].map do |id| + promises = @conf["images"].map do |id| run_on_target(id, &block) end @@ -40,10 +37,10 @@ def run_all(&block) end def run_on_target(name, &block) - pr = Concurrent::Promise.new { + pr = Concurrent::Promise.new do begin container = start_container(name) - res = block.call(name, container) + res = yield(name, container) # special rescue block to handle not implemented error rescue NotImplementedError => err raise err.message @@ -51,7 +48,7 @@ def run_on_target(name, &block) # always stop the container stop_container(container) res - }.execute + end.execute # failure handling pr.rescue do |err| @@ -63,8 +60,8 @@ def run_on_target(name, &block) def provision_image(image, prov, files) tries ||= 3 - return image if prov['script'].nil? - path = File.join(File.dirname(@conf_path), prov['script']) + return image if prov["script"].nil? + path = File.join(File.dirname(@conf_path), prov["script"]) unless File.file?(path) puts "Can't find script file #{path}" return image @@ -72,14 +69,14 @@ def provision_image(image, prov, files) puts " script #{path}" dst = "/bootstrap#{files.length}.sh" files.push(dst) - image.insert_local('localPath' => path, 'outputPath' => dst) + image.insert_local("localPath" => path, "outputPath" => dst) rescue StandardError => _ - retry unless (tries -= 1).zero? + retry unless (tries -= 1) == 0 end def bootstrap_image(name, image) files = [] - provisions = Array(@conf['provision']) + provisions = Array(@conf["provision"]) puts "--> provision docker #{name}" unless provisions.empty? provisions.each do |prov| image = provision_image(image, prov, files) @@ -88,8 +85,8 @@ def bootstrap_image(name, image) end def start_container(name, version = nil) - unless name.include?(':') - version ||= 'latest' + unless name.include?(":") + version ||= "latest" name = "#{name}:#{version}" end puts "--> schedule docker #{name}" @@ -101,7 +98,7 @@ def start_container(name, version = nil) @image_pull_tickets.acquire(1) puts "... start pull image #{name}" - image = Docker::Image.create('fromImage' => name) + image = Docker::Image.create("fromImage" => name) @image_pull_tickets.release(1) unless image.nil? @@ -109,7 +106,7 @@ def start_container(name, version = nil) end end - fail "Can't find nor pull docker image #{name}" if image.nil? + raise "Can't find nor pull docker image #{name}" if image.nil? @docker_run_tickets.acquire(1) @@ -117,9 +114,9 @@ def start_container(name, version = nil) puts "--> start docker #{name}" container = Docker::Container.create( - 'Cmd' => %w{sleep 3600}, - 'Image' => image.id, - 'OpenStdin' => true, + "Cmd" => %w{sleep 3600}, + "Image" => image.id, + "OpenStdin" => true ) container.start @@ -144,7 +141,7 @@ def stop_container(container) def docker_images_by_tag images = {} Docker::Image.all.map do |img| - Array(img.info['RepoTags']).each do |tag| + Array(img.info["RepoTags"]).each do |tag| images[tag] = img end end diff --git a/test/integration/docker_test.rb b/test/integration/docker_test.rb index 2d2af101..30eb4dd9 100644 --- a/test/integration/docker_test.rb +++ b/test/integration/docker_test.rb @@ -1,12 +1,12 @@ # encoding: utf-8 -require_relative 'docker_run' +require_relative "docker_run" tests = ARGV def test_container(container, tests) puts "--> run test on docker #{container.id}" pid = Process.fork do - ENV['CONTAINER'] = container.id - require_relative 'docker_test_container.rb' + ENV["CONTAINER"] = container.id + require_relative "docker_test_container.rb" Process.exit end @@ -21,4 +21,4 @@ def test_container(container, tests) failures = results.compact failures.each { |f| puts "\033[31;1m#{f}\033[0m\n\n" } -failures.empty? or fail 'Test failures' +failures.empty? || raise("Test failures") diff --git a/test/integration/docker_test_container.rb b/test/integration/docker_test_container.rb index 85cde8f4..b0eaa97f 100644 --- a/test/integration/docker_test_container.rb +++ b/test/integration/docker_test_container.rb @@ -1,20 +1,20 @@ # encoding: utf-8 # author: Dominik Richter -require 'train' -require_relative 'helper' +require "train" +require_relative "helper" -container_id = ENV['CONTAINER'] or - fail 'You must provide a container ID via CONTAINER env' +(container_id = ENV["CONTAINER"]) || + raise("You must provide a container ID via CONTAINER env") tests = ARGV -puts ['Running tests:', tests].flatten.join("\n- ") -puts '' +puts ["Running tests:", tests].flatten.join("\n- ") +puts "" backends = {} backends[:docker] = proc { |*args| opt = Train.target_config({ host: container_id }) - Train.create('docker', opt).connection(args[0]) + Train.create("docker", opt).connection(args[0]) } backends.each do |type, get_backend| diff --git a/test/integration/helper.rb b/test/integration/helper.rb index 3551b737..26f478e8 100644 --- a/test/integration/helper.rb +++ b/test/integration/helper.rb @@ -1,10 +1,10 @@ # encoding: utf-8 -require 'coveralls' +require "coveralls" Coveralls.wear! -require 'minitest/autorun' -require 'minitest/spec' +require "minitest/autorun" +require "minitest/spec" # Tests configuration: module Test @@ -23,12 +23,12 @@ def dup(o) def root_group(os) case os[:family] - when 'freebsd' - 'wheel' - when 'aix' - 'system' + when "freebsd" + "wheel" + when "aix" + "system" else - 'root' + "root" end end @@ -40,22 +40,22 @@ def selinux_label(backend, path = nil) h = {} h.default = Hash.new(nil) - h['redhat'] = {} - h['redhat'].default = 'unconfined_u:object_r:user_tmp_t:s0' - h['redhat']['5.11'] = 'user_u:object_r:tmp_t' - h['centos'] = h['fedora'] = h['redhat'] + h["redhat"] = {} + h["redhat"].default = "unconfined_u:object_r:user_tmp_t:s0" + h["redhat"]["5.11"] = "user_u:object_r:tmp_t" + h["centos"] = h["fedora"] = h["redhat"] labels.default = dup(h) - h['redhat'].default = 'unconfined_u:object_r:tmp_t:s0' - labels['/tmp/block_device'] = dup(h) + h["redhat"].default = "unconfined_u:object_r:tmp_t:s0" + labels["/tmp/block_device"] = dup(h) h = {} h.default = Hash.new(nil) - h['redhat'] = {} - h['redhat'].default = 'system_u:object_r:null_device_t:s0' - h['redhat']['5.11'] = 'system_u:object_r:null_device_t' - h['centos'] = h['fedora'] = h['redhat'] - labels['/dev/null'] = dup(h) + h["redhat"] = {} + h["redhat"].default = "system_u:object_r:null_device_t:s0" + h["redhat"]["5.11"] = "system_u:object_r:null_device_t" + h["centos"] = h["fedora"] = h["redhat"] + labels["/dev/null"] = dup(h) labels[path][os[:family]][os[:release]] end diff --git a/test/integration/sudo/customcommand.rb b/test/integration/sudo/customcommand.rb index ef732d50..cd3072fc 100644 --- a/test/integration/sudo/customcommand.rb +++ b/test/integration/sudo/customcommand.rb @@ -1,15 +1,15 @@ # encoding: utf-8 # author: Jeremy Miller -require_relative 'run_as' +require_relative "run_as" -describe 'run custom sudo command' do - it 'is running as non-root without sudo' do - run_as('whoami').stdout.wont_match(/root/i) +describe "run custom sudo command" do + it "is running as non-root without sudo" do + run_as("whoami").stdout.wont_match(/root/i) end - it 'is running nopasswd custom sudo command' do - run_as('whoami', { sudo: true, sudo_command: 'allyourbase' }) + it "is running nopasswd custom sudo command" do + run_as("whoami", { sudo: true, sudo_command: "allyourbase" }) .stdout.must_match(/root/i) end end diff --git a/test/integration/sudo/nopasswd.rb b/test/integration/sudo/nopasswd.rb index 12e9df5e..1bea022e 100644 --- a/test/integration/sudo/nopasswd.rb +++ b/test/integration/sudo/nopasswd.rb @@ -1,16 +1,12 @@ -# encoding: utf-8 -# author: Dominik Richter -# author: Christoph Hartmann +require_relative "run_as" -require_relative 'run_as' - -describe 'run_command' do - it 'is running as non-root without sudo' do - run_as('whoami').stdout.wont_match /root/i +describe "run_command" do + it "is running as non-root without sudo" do + run_as("whoami").stdout.wont_match(/root/i) end - it 'is running nopasswd sudo' do - run_as('whoami', { sudo: true }) - .stdout.must_match /root/i + it "is running nopasswd sudo" do + run_as("whoami", { sudo: true }) + .stdout.must_match(/root/i) end end diff --git a/test/integration/sudo/passwd.rb b/test/integration/sudo/passwd.rb index 9ec495a2..cca48a9e 100644 --- a/test/integration/sudo/passwd.rb +++ b/test/integration/sudo/passwd.rb @@ -1,21 +1,17 @@ -# encoding: utf-8 -# author: Dominik Richter -# author: Christoph Hartmann +require_relative "run_as" -require_relative 'run_as' - -describe 'run_command' do - it 'is running as non-root without sudo' do - run_as('whoami').stdout.wont_match /root/i +describe "run_command" do + it "is running as non-root without sudo" do + run_as("whoami").stdout.wont_match(/root/i) end - it 'is not running sudo without password' do - err = ->{Train.create('local', { sudo: true }).connection}.must_raise Train::UserError - err.message.must_match /Sudo requires a password/ + it "is not running sudo without password" do + err = -> { Train.create("local", { sudo: true }).connection }.must_raise Train::UserError + err.message.must_match(/Sudo requires a password/) end - it 'is running passwd sudo' do - run_as('whoami', { sudo: true, sudo_password: 'password' }) - .stdout.must_match /root/i + it "is running passwd sudo" do + run_as("whoami", { sudo: true, sudo_password: "password" }) + .stdout.must_match(/root/i) end end diff --git a/test/integration/sudo/reqtty.rb b/test/integration/sudo/reqtty.rb index 2664e0aa..75ef109c 100644 --- a/test/integration/sudo/reqtty.rb +++ b/test/integration/sudo/reqtty.rb @@ -1,17 +1,12 @@ -# encoding: utf-8 -# author: Dominik Richter -# author: Christoph Hartmann -# author: Stephan Renatus +require_relative "run_as" -require_relative 'run_as' - -describe 'run_command' do - it 'is running as non-root without sudo' do - run_as('whoami').stdout.wont_match /root/i +describe "run_command" do + it "is running as non-root without sudo" do + run_as("whoami").stdout.wont_match(/root/i) end - it 'is throwing an error trying to use sudo' do - err = ->{ run_as('whoami', { sudo: true }) }.must_raise Train::UserError - err.message.must_match /Sudo failed: Sudo requires a TTY. Please see the README/i + it "is throwing an error trying to use sudo" do + err = -> { run_as("whoami", { sudo: true }) }.must_raise Train::UserError + err.message.must_match(/Sudo failed: Sudo requires a TTY. Please see the README/i) end end diff --git a/test/integration/sudo/run_as.rb b/test/integration/sudo/run_as.rb index ec7554fa..faa77bcb 100644 --- a/test/integration/sudo/run_as.rb +++ b/test/integration/sudo/run_as.rb @@ -2,11 +2,11 @@ # author: Dominik Richter # author: Christoph Hartmann -require_relative '../helper' -require 'train' +require_relative "../helper" +require "train" def run_as(cmd, opts = {}) - Train.create('local', opts) + Train.create("local", opts) .connection .run_command(cmd) end diff --git a/test/integration/test_local.rb b/test/integration/test_local.rb index 01e40937..eb37d739 100644 --- a/test/integration/test_local.rb +++ b/test/integration/test_local.rb @@ -1,13 +1,13 @@ # encoding: utf-8 # author: Dominik Richter -require_relative 'helper' -require 'train' +require_relative "helper" +require "train" backends = {} backends[:local] = proc { |*opts| - Train.create('local', {}).connection(opts[0]) + Train.create("local", {}).connection(opts[0]) } tests = ARGV diff --git a/test/integration/test_ssh.rb b/test/integration/test_ssh.rb index c7a4918e..e460fc8d 100644 --- a/test/integration/test_ssh.rb +++ b/test/integration/test_ssh.rb @@ -1,21 +1,21 @@ # encoding: utf-8 # author: Dominik Richter -require_relative 'helper' -require 'train' -require 'logger' +require_relative "helper" +require "train" +require "logger" backends = {} backend_conf = { - 'target' => ENV['target'] || 'vagrant@localhost', - 'key_files' => ENV['key_files'] || '/root/.ssh/id_rsa', - 'logger' => Logger.new($stdout), + "target" => ENV["target"] || "vagrant@localhost", + "key_files" => ENV["key_files"] || "/root/.ssh/id_rsa", + "logger" => Logger.new($stdout), } -backend_conf['target'] = 'ssh://' + backend_conf['target'] -backend_conf['logger'].level = \ - if ENV.key?('debug') - case ENV['debug'].to_s +backend_conf["target"] = "ssh://" + backend_conf["target"] +backend_conf["logger"].level = \ + if ENV.key?("debug") + case ENV["debug"].to_s when /^false$/i, /^0$/i Logger::INFO else @@ -27,7 +27,7 @@ backends[:ssh] = proc { |*args| conf = Train.target_config(backend_conf) - Train.create('ssh', conf).connection(args[0]) + Train.create("ssh", conf).connection(args[0]) } tests = ARGV diff --git a/test/integration/tests/path_block_device_test.rb b/test/integration/tests/path_block_device_test.rb index 22d70847..4040eb77 100644 --- a/test/integration/tests/path_block_device_test.rb +++ b/test/integration/tests/path_block_device_test.rb @@ -1,73 +1,73 @@ # encoding: utf-8 -describe 'file interface' do +describe "file interface" do let(:backend) { get_backend.call } - describe 'block device' do - let(:file) { backend.file('/tmp/block_device') } + describe "block device" do + let(:file) { backend.file("/tmp/block_device") } - it 'exists' do + it "exists" do file.exist?.must_equal(true) end - it 'is a block device' do + it "is a block device" do file.block_device?.must_equal(true) end - it 'has type :block_device' do + it "has type :block_device" do file.type.must_equal(:block_device) end - it 'has no content' do - file.content.must_equal('') + it "has no content" do + file.content.must_equal("") end - it 'has owner name root' do - file.owner.must_equal('root') + it "has owner name root" do + file.owner.must_equal("root") end - it 'has group name' do + it "has group name" do file.group.must_equal(Test.root_group(backend.os)) end - it 'has mode 0666' do + it "has mode 0666" do file.mode.must_equal(00666) end - it 'checks mode? 0666' do + it "checks mode? 0666" do file.mode?(00666).must_equal(true) end - it 'has no link_path' do + it "has no link_path" do file.link_path.must_be_nil end - it 'has the correct md5sum' do - file.md5sum.must_equal('d41d8cd98f00b204e9800998ecf8427e') + it "has the correct md5sum" do + file.md5sum.must_equal("d41d8cd98f00b204e9800998ecf8427e") end - it 'has the correct sha256sum' do - file.sha256sum.must_equal('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855') + it "has the correct sha256sum" do + file.sha256sum.must_equal("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") end - it 'has a modified time' do - file.mtime.must_be_close_to(Time.now.to_i - Test.mtime/2, Test.mtime) + it "has a modified time" do + file.mtime.must_be_close_to(Time.now.to_i - Test.mtime / 2, Test.mtime) end - it 'has inode size of 0' do + it "has inode size of 0" do file.size.must_equal(0) end - it 'has selinux label handling' do + it "has selinux label handling" do res = Test.selinux_label(backend, file.path) file.selinux_label.must_equal(res) end - it 'has no product_version' do + it "has no product_version" do file.product_version.must_be_nil end - it 'has no file_version' do + it "has no file_version" do file.file_version.must_be_nil end end diff --git a/test/integration/tests/path_character_device_test.rb b/test/integration/tests/path_character_device_test.rb index fa3aea77..52d7ac7b 100644 --- a/test/integration/tests/path_character_device_test.rb +++ b/test/integration/tests/path_character_device_test.rb @@ -1,73 +1,73 @@ # encoding: utf-8 -describe 'file interface' do +describe "file interface" do let(:backend) { get_backend.call } - describe 'character device' do - let(:file) { backend.file('/dev/null') } + describe "character device" do + let(:file) { backend.file("/dev/null") } - it 'exists' do + it "exists" do file.exist?.must_equal(true) end - it 'is a character device' do + it "is a character device" do file.character_device?.must_equal(true) end - it 'has type :character_device' do + it "has type :character_device" do file.type.must_equal(:character_device) end - it 'has empty content' do - file.content.must_equal('') + it "has empty content" do + file.content.must_equal("") end - it 'has owner name root' do - file.owner.must_equal('root') + it "has owner name root" do + file.owner.must_equal("root") end - it 'has group name' do + it "has group name" do file.group.must_equal(Test.root_group(backend.os)) end - it 'has mode 0666' do + it "has mode 0666" do file.mode.must_equal(00666) end - it 'checks mode? 0666' do + it "checks mode? 0666" do file.mode?(00666).must_equal(true) end - it 'has no link_path' do + it "has no link_path" do file.link_path.must_be_nil end - it 'has an md5sum' do - file.md5sum.must_equal('d41d8cd98f00b204e9800998ecf8427e') + it "has an md5sum" do + file.md5sum.must_equal("d41d8cd98f00b204e9800998ecf8427e") end - it 'has an sha256sum' do - file.sha256sum.must_equal('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855') + it "has an sha256sum" do + file.sha256sum.must_equal("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") end - it 'has a modified time' do - file.mtime.must_be_close_to(Time.now.to_i - Test.mtime/2, Test.mtime) + it "has a modified time" do + file.mtime.must_be_close_to(Time.now.to_i - Test.mtime / 2, Test.mtime) end - it 'has inode size of 0' do + it "has inode size of 0" do file.size.must_equal(0) end - it 'has selinux label handling' do + it "has selinux label handling" do res = Test.selinux_label(backend, file.path) file.selinux_label.must_equal(res) end - it 'has no product_version' do + it "has no product_version" do file.product_version.must_be_nil end - it 'has no file_version' do + it "has no file_version" do file.file_version.must_be_nil end end diff --git a/test/integration/tests/path_file_test.rb b/test/integration/tests/path_file_test.rb index 8a578f3e..a8c0c33c 100644 --- a/test/integration/tests/path_file_test.rb +++ b/test/integration/tests/path_file_test.rb @@ -1,99 +1,99 @@ # encoding: utf-8 -describe 'file interface' do +describe "file interface" do let(:backend) { get_backend.call } - describe 'regular file' do - let(:file) { backend.file('/tmp/file') } + describe "regular file" do + let(:file) { backend.file("/tmp/file") } - it 'exists' do + it "exists" do file.exist?.must_equal(true) end - it 'is a file' do + it "is a file" do file.file?.must_equal(true) end - it 'has type :file' do + it "has type :file" do file.type.must_equal(:file) end - it 'has content' do - file.content.must_equal('hello world') + it "has content" do + file.content.must_equal("hello world") end - it 'has owner name root' do - file.owner.must_equal('root') + it "has owner name root" do + file.owner.must_equal("root") end - it 'has group name' do + it "has group name" do file.group.must_equal(Test.root_group(backend.os)) end - it 'has mode 0765' do + it "has mode 0765" do file.mode.must_equal(00765) end - it 'checks mode? 0765' do + it "checks mode? 0765" do file.mode?(00765).must_equal(true) end - it 'doesnt check mode? 0764' do + it "doesnt check mode? 0764" do file.mode?(00764).must_equal(false) end - it 'has no link_path' do + it "has no link_path" do file.link_path.must_be_nil end - it 'has an md5sum' do - file.md5sum.must_equal('5eb63bbbe01eeed093cb22bb8f5acdc3') + it "has an md5sum" do + file.md5sum.must_equal("5eb63bbbe01eeed093cb22bb8f5acdc3") end - it 'has an sha256sum' do - file.sha256sum.must_equal('b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9') + it "has an sha256sum" do + file.sha256sum.must_equal("b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9") end - it 'has a modified time' do - file.mtime.must_be_close_to(Time.now.to_i - Test.mtime/2, Test.mtime) + it "has a modified time" do + file.mtime.must_be_close_to(Time.now.to_i - Test.mtime / 2, Test.mtime) end - it 'has size' do + it "has size" do # Must be around 11 Bytes, +- 4 file.size.must_be_close_to(11, 4) end - it 'has selinux label handling' do + it "has selinux label handling" do res = Test.selinux_label(backend, file.path) file.selinux_label.must_equal(res) end - it 'has no product_version' do + it "has no product_version" do file.product_version.must_be_nil end - it 'has no file_version' do + it "has no file_version" do file.file_version.must_be_nil end - it 'provides a json representation' do + it "provides a json representation" do j = file.to_json j.must_be_kind_of Hash - j['type'].must_equal :file + j["type"].must_equal :file end end - describe 'regular file' do - let(:file) { backend.file('/tmp/sfile') } - it 'has mode 7765' do + describe "regular file" do + let(:file) { backend.file("/tmp/sfile") } + it "has mode 7765" do file.mode.must_equal(07765) end end - describe 'regular file' do - let(:file) { backend.file('/tmp/spaced file') } - it 'has content' do - file.content.must_equal('hello space') + describe "regular file" do + let(:file) { backend.file("/tmp/spaced file") } + it "has content" do + file.content.must_equal("hello space") end end end diff --git a/test/integration/tests/path_folder_test.rb b/test/integration/tests/path_folder_test.rb index 0f2eaa43..df92ded7 100644 --- a/test/integration/tests/path_folder_test.rb +++ b/test/integration/tests/path_folder_test.rb @@ -1,89 +1,89 @@ # encoding: utf-8 -describe 'file interface' do +describe "file interface" do let(:backend) { get_backend.call } - describe 'a folder' do - let(:file) { backend.file('/tmp/folder') } + describe "a folder" do + let(:file) { backend.file("/tmp/folder") } - it 'exists' do + it "exists" do file.exist?.must_equal(true) end - it 'is a directory' do + it "is a directory" do file.directory?.must_equal(true) end - it 'has type :directory' do + it "has type :directory" do file.type.must_equal(:directory) end case get_backend.call.os[:family] - when 'freebsd' - it 'has freebsd folder content behavior' do + when "freebsd" + it "has freebsd folder content behavior" do file.content.must_equal("\u0003\u0000") end - it 'has an md5sum' do - file.md5sum.must_equal('598f4fe64aefab8f00bcbea4c9239abf') + it "has an md5sum" do + file.md5sum.must_equal("598f4fe64aefab8f00bcbea4c9239abf") end - it 'has an sha256sum' do - file.sha256sum.must_equal('9b4fb24edd6d1d8830e272398263cdbf026b97392cc35387b991dc0248a628f9') + it "has an sha256sum" do + file.sha256sum.must_equal("9b4fb24edd6d1d8830e272398263cdbf026b97392cc35387b991dc0248a628f9") end else - it 'has no content' do + it "has no content" do file.content.must_be_nil end - it 'raises an error if md5sum is attempted' do + it "raises an error if md5sum is attempted" do proc { file.md5sum }.must_raise RuntimeError end - it 'raises an error if sha256sum is attempted' do + it "raises an error if sha256sum is attempted" do proc { file.sha256sum }.must_raise RuntimeError end end - it 'has owner name root' do - file.owner.must_equal('root') + it "has owner name root" do + file.owner.must_equal("root") end - it 'has group name' do + it "has group name" do file.group.must_equal(Test.root_group(backend.os)) end - it 'has mode 0567' do + it "has mode 0567" do file.mode.must_equal(00567) end - it 'checks mode? 0567' do + it "checks mode? 0567" do file.mode?(00567).must_equal(true) end - it 'has no link_path' do + it "has no link_path" do file.link_path.must_be_nil end - it 'has a modified time' do - file.mtime.must_be_close_to(Time.now.to_i - Test.mtime/2, Test.mtime) + it "has a modified time" do + file.mtime.must_be_close_to(Time.now.to_i - Test.mtime / 2, Test.mtime) end - it 'has inode size' do + it "has inode size" do file.size.must_be_close_to(4096, 4096) end - it 'has selinux label handling' do + it "has selinux label handling" do res = Test.selinux_label(backend, file.path) file.selinux_label.must_equal(res) end - it 'has no product_version' do + it "has no product_version" do file.product_version.must_be_nil end - it 'has no file_version' do + it "has no file_version" do file.file_version.must_be_nil end end diff --git a/test/integration/tests/path_missing_test.rb b/test/integration/tests/path_missing_test.rb index 7e584d7d..d779b3bb 100644 --- a/test/integration/tests/path_missing_test.rb +++ b/test/integration/tests/path_missing_test.rb @@ -1,75 +1,75 @@ # encoding: utf-8 -describe 'file interface' do +describe "file interface" do let(:backend) { get_backend.call } - describe 'a path that doesnt exist' do - let(:file) { - backend.file('/do_not_create_this_path_please_or_my_tests_will_fail') - } + describe "a path that doesnt exist" do + let(:file) do + backend.file("/do_not_create_this_path_please_or_my_tests_will_fail") + end - it 'does not exist' do + it "does not exist" do file.exist?.must_equal(false) end - it 'is not a file' do + it "is not a file" do file.file?.must_equal(false) end - it 'has type nil' do + it "has type nil" do file.type.must_be_nil end - it 'has no content' do + it "has no content" do file.content.must_be_nil end - it 'has no owner' do + it "has no owner" do file.owner.must_be_nil end - it 'has no group' do + it "has no group" do file.group.must_be_nil end - it 'has mode nil' do + it "has mode nil" do file.mode.must_be_nil end - it 'checks mode? nil' do + it "checks mode? nil" do file.mode?(nil).must_equal(true) end - it 'has no link_path' do + it "has no link_path" do file.link_path.must_be_nil end - it 'raises an error if md5sum is attempted' do + it "raises an error if md5sum is attempted" do proc { file.md5sum }.must_raise RuntimeError end - it 'raises an error if sha256sum is attempted' do + it "raises an error if sha256sum is attempted" do proc { file.sha256sum }.must_raise RuntimeError end - it 'has a modified time' do + it "has a modified time" do file.mtime.must_be_nil end - it 'has inode size' do + it "has inode size" do # Must be around 11 Bytes, +- 4 file.size.must_be_nil end - it 'has no selinux_label' do + it "has no selinux_label" do file.selinux_label.must_be_nil end - it 'has no product_version' do + it "has no product_version" do file.product_version.must_be_nil end - it 'has no file_version' do + it "has no file_version" do file.file_version.must_be_nil end end diff --git a/test/integration/tests/path_pipe_test.rb b/test/integration/tests/path_pipe_test.rb index 4c25511a..9895e8a9 100644 --- a/test/integration/tests/path_pipe_test.rb +++ b/test/integration/tests/path_pipe_test.rb @@ -1,61 +1,61 @@ # encoding: utf-8 -describe 'file interface' do +describe "file interface" do let(:backend) { get_backend.call } - describe 'pipe / fifo' do - let(:file) { backend.file('/tmp/pipe') } + describe "pipe / fifo" do + let(:file) { backend.file("/tmp/pipe") } - it 'exists' do + it "exists" do file.exist?.must_equal(true) end - it 'is a pipe' do + it "is a pipe" do file.pipe?.must_equal(true) end - it 'has type :pipe' do + it "has type :pipe" do file.type.must_equal(:pipe) end - it 'has owner name root' do - file.owner.must_equal('root') + it "has owner name root" do + file.owner.must_equal("root") end - it 'has group name' do + it "has group name" do file.group.must_equal(Test.root_group(backend.os)) end - it 'has mode 0644' do + it "has mode 0644" do file.mode.must_equal(00644) end - it 'checks mode? 0644' do + it "checks mode? 0644" do file.mode?(00644).must_equal(true) end - it 'has no link_path' do + it "has no link_path" do file.link_path.must_be_nil end - it 'has a modified time' do - file.mtime.must_be_close_to(Time.now.to_i - Test.mtime/2, Test.mtime) + it "has a modified time" do + file.mtime.must_be_close_to(Time.now.to_i - Test.mtime / 2, Test.mtime) end - it 'has inode size of 0' do + it "has inode size of 0" do file.size.must_equal(0) end - it 'has selinux label handling' do + it "has selinux label handling" do res = Test.selinux_label(backend, file.path) file.selinux_label.must_equal(res) end - it 'has no product_version' do + it "has no product_version" do file.product_version.must_be_nil end - it 'has no file_version' do + it "has no file_version" do file.file_version.must_be_nil end end diff --git a/test/integration/tests/path_symlink_test.rb b/test/integration/tests/path_symlink_test.rb index 0cae34c3..e50c457f 100644 --- a/test/integration/tests/path_symlink_test.rb +++ b/test/integration/tests/path_symlink_test.rb @@ -1,94 +1,94 @@ # encoding: utf-8 -describe 'file interface' do +describe "file interface" do let(:backend) { get_backend.call } - describe 'symlink file' do - let(:file) { backend.file('/tmp/symlink') } + describe "symlink file" do + let(:file) { backend.file("/tmp/symlink") } - it 'exists' do + it "exists" do file.exist?.must_equal(true) end - it 'is a symlink' do + it "is a symlink" do file.symlink?.must_equal(true) end - it 'is pointing to a file' do + it "is pointing to a file" do file.file?.must_equal(true) end - it 'is not pointing to a folder' do + it "is not pointing to a folder" do file.directory?.must_equal(false) end - it 'has type :file' do + it "has type :file" do file.type.must_equal(:file) end - it 'has content' do - file.content.must_equal('hello world') + it "has content" do + file.content.must_equal("hello world") end - it 'has owner name root' do - file.owner.must_equal('root') + it "has owner name root" do + file.owner.must_equal("root") end - it 'has uid 0' do + it "has uid 0" do file.uid.must_equal(0) end - it 'has group name' do + it "has group name" do file.group.must_equal(Test.root_group(backend.os)) end - it 'has gid 0' do + it "has gid 0" do file.gid.must_equal(0) end - it 'has mode 0777' do + it "has mode 0777" do file.source.mode.must_equal(00777) end - it 'has mode 0765' do + it "has mode 0765" do file.mode.must_equal(00765) end - it 'checks mode? 0765' do + it "checks mode? 0765" do file.mode?(00765).must_equal(true) end - it 'has link_path' do - file.link_path.must_equal('/tmp/file') + it "has link_path" do + file.link_path.must_equal("/tmp/file") end - it 'has an md5sum' do - file.md5sum.must_equal('5eb63bbbe01eeed093cb22bb8f5acdc3') + it "has an md5sum" do + file.md5sum.must_equal("5eb63bbbe01eeed093cb22bb8f5acdc3") end - it 'has an sha256sum' do - file.sha256sum.must_equal('b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9') + it "has an sha256sum" do + file.sha256sum.must_equal("b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9") end - it 'has a modified time' do - file.mtime.must_be_close_to(Time.now.to_i - Test.mtime/2, Test.mtime) + it "has a modified time" do + file.mtime.must_be_close_to(Time.now.to_i - Test.mtime / 2, Test.mtime) end - it 'has size' do + it "has size" do # Must be around 11 Bytes, +- 4 file.size.must_be_close_to(11, 4) end - it 'has selinux label handling' do + it "has selinux label handling" do res = Test.selinux_label(backend, file.path) file.selinux_label.must_equal(res) end - it 'has no product_version' do + it "has no product_version" do file.product_version.must_be_nil end - it 'has no file_version' do + it "has no file_version" do file.file_version.must_be_nil end end diff --git a/test/integration/tests/run_command_test.rb b/test/integration/tests/run_command_test.rb index 124c4894..0f8b1eea 100644 --- a/test/integration/tests/run_command_test.rb +++ b/test/integration/tests/run_command_test.rb @@ -1,35 +1,35 @@ # encoding: utf-8 -describe 'run_command' do +describe "run_command" do let(:backend) { get_backend.call() } - it 'can echo commands' do - res = backend.run_command('echo hello world') + it "can echo commands" do + res = backend.run_command("echo hello world") res.stdout.must_equal("hello world\n") - res.stderr.must_equal('') + res.stderr.must_equal("") res.exit_status.must_equal(0) end - it 'can run frozen commands' do - res = backend.run_command('echo hello world'.freeze) + it "can run frozen commands" do + res = backend.run_command("echo hello world".freeze) res.stdout.must_equal("hello world\n") - res.stderr.must_equal('') + res.stderr.must_equal("") res.exit_status.must_equal(0) end - it 'can echo commands to stderr' do + it "can echo commands to stderr" do # TODO: Specinfra often fails on this test. # Fix and re-enable it. - res = backend.run_command('>&2 echo hello world') - res.stdout.must_equal('') + res = backend.run_command(">&2 echo hello world") + res.stdout.must_equal("") res.stderr.must_equal("hello world\n") res.exit_status.must_equal(0) end - it 'prints a correct exit status' do - res = backend.run_command('exit 123') - res.stdout.must_equal('') - res.stderr.must_equal('') + it "prints a correct exit status" do + res = backend.run_command("exit 123") + res.stdout.must_equal("") + res.stderr.must_equal("") res.exit_status.must_equal(123) end end diff --git a/test/unit/extras/command_wrapper_test.rb b/test/unit/extras/command_wrapper_test.rb index 5ad58f27..877e30bb 100644 --- a/test/unit/extras/command_wrapper_test.rb +++ b/test/unit/extras/command_wrapper_test.rb @@ -2,58 +2,58 @@ # author: Dominik Richter # author: Christoph Hartmann -require 'helper' -require 'train/transports/mock' -require 'train/extras' -require 'base64' +require "helper" +require "train/transports/mock" +require "train/extras" +require "base64" -describe 'linux command' do +describe "linux command" do let(:cls) { Train::Extras::LinuxCommand } let(:cmd) { rand.to_s } - let(:backend) { + let(:backend) do backend = Train::Transports::Mock.new.connection - backend.mock_os({ family: 'linux' }) + backend.mock_os({ family: "linux" }) backend - } + end - describe 'sudo wrapping' do - it 'wraps commands in sudo' do + describe "sudo wrapping" do + it "wraps commands in sudo" do lc = cls.new(backend, { sudo: true }) lc.run(cmd).must_equal "sudo #{cmd}" end - it 'doesnt wrap commands in sudo if user == root' do - lc = cls.new(backend, { sudo: true, user: 'root' }) + it "doesnt wrap commands in sudo if user == root" do + lc = cls.new(backend, { sudo: true, user: "root" }) lc.run(cmd).must_equal cmd end - it 'wraps commands in sudo with all options' do + it "wraps commands in sudo with all options" do opts = rand.to_s lc = cls.new(backend, { sudo: true, sudo_options: opts }) lc.run(cmd).must_equal "sudo #{opts} #{cmd}" end - it 'runs commands in sudo with password' do + it "runs commands in sudo with password" do pw = rand.to_s lc = cls.new(backend, { sudo: true, sudo_password: pw }) bpw = Base64.strict_encode64(pw + "\n") lc.run(cmd).must_equal "echo #{bpw} | base64 --decode | sudo -S #{cmd}" end - it 'wraps commands in sudo_command instead of sudo' do + it "wraps commands in sudo_command instead of sudo" do sudo_command = rand.to_s lc = cls.new(backend, { sudo: true, sudo_command: sudo_command }) lc.run(cmd).must_equal "#{sudo_command} #{cmd}" end - it 'wraps commands in sudo_command with all options' do + it "wraps commands in sudo_command with all options" do opts = rand.to_s sudo_command = rand.to_s lc = cls.new(backend, { sudo: true, sudo_command: sudo_command, sudo_options: opts }) lc.run(cmd).must_equal "#{sudo_command} #{opts} #{cmd}" end - it 'runs commands in sudo_command with password' do + it "runs commands in sudo_command with password" do pw = rand.to_s sudo_command = rand.to_s lc = cls.new(backend, { sudo: true, sudo_command: sudo_command, sudo_password: pw }) @@ -62,66 +62,66 @@ end end - describe 'shell wrapping' do - it 'wraps commands in a default shell with login' do - lc = cls.new(backend, { shell: true, shell_options: '--login' }) + describe "shell wrapping" do + it "wraps commands in a default shell with login" do + lc = cls.new(backend, { shell: true, shell_options: "--login" }) bcmd = Base64.strict_encode64(cmd) lc.run(cmd).must_equal "echo #{bcmd} | base64 --decode | $SHELL --login" end - it 'wraps sudo commands in a default shell with login' do - lc = cls.new(backend, { sudo: true, shell: true, shell_options: '--login' }) + it "wraps sudo commands in a default shell with login" do + lc = cls.new(backend, { sudo: true, shell: true, shell_options: "--login" }) bcmd = Base64.strict_encode64("sudo #{cmd}") lc.run(cmd).must_equal "echo #{bcmd} | base64 --decode | $SHELL --login" end - it 'wraps sudo commands and sudo passwords in a default shell with login' do + it "wraps sudo commands and sudo passwords in a default shell with login" do pw = rand.to_s - lc = cls.new(backend, { sudo: true, sudo_password: pw, shell: true, shell_options: '--login' }) + lc = cls.new(backend, { sudo: true, sudo_password: pw, shell: true, shell_options: "--login" }) bpw = Base64.strict_encode64(pw + "\n") bcmd = Base64.strict_encode64("echo #{bpw} | base64 --decode | sudo -S #{cmd}") lc.run(cmd).must_equal "echo #{bcmd} | base64 --decode | $SHELL --login" end - it 'wraps commands in a default shell when shell is true' do + it "wraps commands in a default shell when shell is true" do lc = cls.new(backend, { shell: true }) bcmd = Base64.strict_encode64(cmd) lc.run(cmd).must_equal "echo #{bcmd} | base64 --decode | $SHELL" end - it 'doesnt wrap commands in a shell when shell is false' do + it "doesnt wrap commands in a shell when shell is false" do lc = cls.new(backend, { shell: false }) lc.run(cmd).must_equal cmd end - it 'wraps commands in a `shell` instead of default shell' do - lc = cls.new(backend, { shell: true, shell_command: '/bin/bash' }) + it "wraps commands in a `shell` instead of default shell" do + lc = cls.new(backend, { shell: true, shell_command: "/bin/bash" }) bcmd = Base64.strict_encode64(cmd) lc.run(cmd).must_equal "echo #{bcmd} | base64 --decode | /bin/bash" end - it 'wraps commands in a default shell with login' do - lc = cls.new(backend, { shell: true, shell_command: '/bin/bash', shell_options: '--login' }) + it "wraps commands in a default shell with login" do + lc = cls.new(backend, { shell: true, shell_command: "/bin/bash", shell_options: "--login" }) bcmd = Base64.strict_encode64(cmd) lc.run(cmd).must_equal "echo #{bcmd} | base64 --decode | /bin/bash --login" end end end -describe 'windows command' do +describe "windows command" do let(:cls) { Train::Extras::WindowsCommand } let(:cmd) { rand.to_s } - let(:backend) { + let(:backend) do backend = Train::Transports::Mock.new.connection - backend.mock_os({ family: 'windows' }) + backend.mock_os({ family: "windows" }) backend - } + end - describe 'shell wrapping' do - it 'wraps commands in a default powershell' do + describe "shell wrapping" do + it "wraps commands in a default powershell" do lc = cls.new(backend, { shell: true }) wcmd = "$ProgressPreference='SilentlyContinue';" + cmd - bcmd = Base64.strict_encode64(wcmd.encode('UTF-16LE', 'UTF-8')) + bcmd = Base64.strict_encode64(wcmd.encode("UTF-16LE", "UTF-8")) lc.run(cmd).must_equal "powershell -NoProfile -EncodedCommand #{bcmd}" end end diff --git a/test/unit/extras/stat_test.rb b/test/unit/extras/stat_test.rb index a0e3bf07..dc0d73d1 100644 --- a/test/unit/extras/stat_test.rb +++ b/test/unit/extras/stat_test.rb @@ -1,69 +1,68 @@ -# encoding: utf-8 -require 'helper' -require 'train/extras' -require 'train/transports/mock' +require "helper" +require "train/extras" +require "train/transports/mock" -describe 'stat' do +describe "stat" do let(:cls) { Train::Extras::Stat } - describe 'find_type' do - let (:random_mode) { (rand * 1000).to_i } + describe "find_type" do + let(:random_mode) { (rand * 1000).to_i } - it 'detects :unknown types' do + it "detects :unknown types" do cls.find_type(random_mode).must_equal :unknown end - it 'detects sockets' do + it "detects sockets" do cls.find_type(00140755).must_equal :socket end - it 'detects symlinks' do + it "detects symlinks" do cls.find_type(00120755).must_equal :symlink end - it 'detects files' do + it "detects files" do cls.find_type(00100755).must_equal :file end - it 'detects block devices' do + it "detects block devices" do cls.find_type(00060755).must_equal :block_device end - it 'detects directories' do + it "detects directories" do cls.find_type(00040755).must_equal :directory end - it 'detects character devices' do + it "detects character devices" do cls.find_type(00020755).must_equal :character_device end - it 'detects pipes' do + it "detects pipes" do cls.find_type(00010755).must_equal :pipe end end - describe 'linux stat' do - let(:backend) { + describe "linux stat" do + let(:backend) do mock = Train::Transports::Mock.new(verbose: true).connection - mock.mock_os({ name: 'ubuntu', family: 'debian', release: '15.04', arch: 'x86_64' }) + mock.mock_os({ name: "ubuntu", family: "debian", release: "15.04", arch: "x86_64" }) mock.commands = { - "stat /path 2>/dev/null --printf '%s\n%f\n%U\n%u\n%G\n%g\n%X\n%Y\n%C'" => mock.mock_command('', '', '', 0), - "stat /path-stat 2>/dev/null --printf '%s\n%f\n%U\n%u\n%G\n%g\n%X\n%Y\n%C'" => mock.mock_command('', "360\n43ff\nroot\n0\nrootz\n1\n1444520846\n1444522445\n?", '', 0), + "stat /path 2>/dev/null --printf '%s\n%f\n%U\n%u\n%G\n%g\n%X\n%Y\n%C'" => mock.mock_command("", "", "", 0), + "stat /path-stat 2>/dev/null --printf '%s\n%f\n%U\n%u\n%G\n%g\n%X\n%Y\n%C'" => mock.mock_command("", "360\n43ff\nroot\n0\nrootz\n1\n1444520846\n1444522445\n?", "", 0), } mock - } + end - it 'ignores wrong stat results' do - cls.linux_stat('/path', backend, false).must_equal({}) + it "ignores wrong stat results" do + cls.linux_stat("/path", backend, false).must_equal({}) end - it 'reads correct stat results' do - cls.linux_stat('/path-stat', backend, false).must_equal({ + it "reads correct stat results" do + cls.linux_stat("/path-stat", backend, false).must_equal({ type: :directory, mode: 01777, - owner: 'root', + owner: "root", uid: 0, - group: 'rootz', + group: "rootz", gid: 1, mtime: 1444522445, size: 360, @@ -72,28 +71,28 @@ end end - describe 'esx stat' do - let(:backend) { + describe "esx stat" do + let(:backend) do mock = Train::Transports::Mock.new(verbose: true).connection - mock.mock_os({ name: 'vmkernel', family: 'esx', release: '5' }) + mock.mock_os({ name: "vmkernel", family: "esx", release: "5" }) mock.commands = { - "stat /path 2>/dev/null -c '%s\n%f\n%U\n%u\n%G\n%g\n%X\n%Y\n%C'" => mock.mock_command('', '', '', 0), - "stat /path-stat 2>/dev/null -c '%s\n%f\n%U\n%u\n%G\n%g\n%X\n%Y\n%C'" => mock.mock_command('', "360\n43ff\nroot\n0\nrootz\n1\n1444520846\n1444522445\n?", '', 0), + "stat /path 2>/dev/null -c '%s\n%f\n%U\n%u\n%G\n%g\n%X\n%Y\n%C'" => mock.mock_command("", "", "", 0), + "stat /path-stat 2>/dev/null -c '%s\n%f\n%U\n%u\n%G\n%g\n%X\n%Y\n%C'" => mock.mock_command("", "360\n43ff\nroot\n0\nrootz\n1\n1444520846\n1444522445\n?", "", 0), } mock - } + end - it 'ignores wrong stat results' do - cls.linux_stat('/path', backend, false).must_equal({}) + it "ignores wrong stat results" do + cls.linux_stat("/path", backend, false).must_equal({}) end - it 'reads correct stat results' do - cls.linux_stat('/path-stat', backend, false).must_equal({ + it "reads correct stat results" do + cls.linux_stat("/path-stat", backend, false).must_equal({ type: :directory, mode: 01777, - owner: 'root', + owner: "root", uid: 0, - group: 'rootz', + group: "rootz", gid: 1, mtime: 1444522445, size: 360, @@ -102,28 +101,28 @@ end end - describe 'alpine stat' do - let(:backend) { + describe "alpine stat" do + let(:backend) do mock = Train::Transports::Mock.new(verbose: true).connection - mock.mock_os({ name: 'alpine', family: 'alpine', release: nil }) + mock.mock_os({ name: "alpine", family: "alpine", release: nil }) mock.commands = { - "stat /path 2>/dev/null -c '%s\n%f\n%U\n%u\n%G\n%g\n%X\n%Y\n%C'" => mock.mock_command('', '', '', 0), - "stat /path-stat 2>/dev/null -c '%s\n%f\n%U\n%u\n%G\n%g\n%X\n%Y\n%C'" => mock.mock_command('', "360\n43ff\nroot\n0\nrootz\n1\n1444520846\n1444522445\n?", '', 0), + "stat /path 2>/dev/null -c '%s\n%f\n%U\n%u\n%G\n%g\n%X\n%Y\n%C'" => mock.mock_command("", "", "", 0), + "stat /path-stat 2>/dev/null -c '%s\n%f\n%U\n%u\n%G\n%g\n%X\n%Y\n%C'" => mock.mock_command("", "360\n43ff\nroot\n0\nrootz\n1\n1444520846\n1444522445\n?", "", 0), } mock - } + end - it 'ignores wrong stat results' do - cls.linux_stat('/path', backend, false).must_equal({}) + it "ignores wrong stat results" do + cls.linux_stat("/path", backend, false).must_equal({}) end - it 'reads correct stat results' do - cls.linux_stat('/path-stat', backend, false).must_equal({ + it "reads correct stat results" do + cls.linux_stat("/path-stat", backend, false).must_equal({ type: :directory, mode: 01777, - owner: 'root', + owner: "root", uid: 0, - group: 'rootz', + group: "rootz", gid: 1, mtime: 1444522445, size: 360, @@ -132,36 +131,36 @@ end end - describe 'bsd stat' do + describe "bsd stat" do let(:backend) { Minitest::Mock.new } - it 'ignores failed stat results' do + it "ignores failed stat results" do res = Minitest::Mock.new - res.expect :stdout, '.....' + res.expect :stdout, "....." res.expect :exit_status, 1 backend.expect :run_command, res, [String] - cls.bsd_stat('/path', backend, false).must_equal({}) + cls.bsd_stat("/path", backend, false).must_equal({}) end - it 'ignores wrong stat results' do + it "ignores wrong stat results" do res = Minitest::Mock.new - res.expect :stdout, '' + res.expect :stdout, "" res.expect :exit_status, 0 backend.expect :run_command, res, [String] - cls.bsd_stat('/path', backend, false).must_equal({}) + cls.bsd_stat("/path", backend, false).must_equal({}) end - it 'reads correct stat results' do + it "reads correct stat results" do res = Minitest::Mock.new res.expect :stdout, "360\n41777\nroot\n0\nrootz\n1\n1444520846\n1444522445" res.expect :exit_status, 0 backend.expect :run_command, res, [String] - cls.bsd_stat('/path', backend, false).must_equal({ + cls.bsd_stat("/path", backend, false).must_equal({ type: :directory, mode: 01777, - owner: 'root', + owner: "root", uid: 0, - group: 'rootz', + group: "rootz", gid: 1, mtime: 1444522445, size: 360, @@ -170,36 +169,36 @@ end end - describe 'aix stat' do + describe "aix stat" do let(:backend) { Minitest::Mock.new } - it 'ignores failed stat results' do + it "ignores failed stat results" do res = Minitest::Mock.new - res.expect :stdout, '.....' + res.expect :stdout, "....." res.expect :exit_status, 1 backend.expect :run_command, res, [String] - cls.aix_stat('/path', backend, false).must_equal({}) + cls.aix_stat("/path", backend, false).must_equal({}) end - it 'ignores wrong stat results' do + it "ignores wrong stat results" do res = Minitest::Mock.new - res.expect :stdout, '' + res.expect :stdout, "" res.expect :exit_status, 0 backend.expect :run_command, res, [String] - cls.aix_stat('/path', backend, false).must_equal({}) + cls.aix_stat("/path", backend, false).must_equal({}) end - it 'reads correct stat results' do + it "reads correct stat results" do res = Minitest::Mock.new res.expect :stdout, "41777\nroot\n0\nrootz\n1\n1444522445\n360\n" res.expect :exit_status, 0 backend.expect :run_command, res, [String] - cls.aix_stat('/path', backend, false).must_equal({ + cls.aix_stat("/path", backend, false).must_equal({ type: :directory, mode: 01777, - owner: 'root', + owner: "root", uid: 0, - group: 'rootz', + group: "rootz", gid: 1, mtime: 1444522445, size: 360, diff --git a/test/unit/file/local/unix_test.rb b/test/unit/file/local/unix_test.rb index 781df6ad..a845ffef 100644 --- a/test/unit/file/local/unix_test.rb +++ b/test/unit/file/local/unix_test.rb @@ -1,95 +1,97 @@ -require 'helper' -require 'train/file/local/unix' -require 'train/transports/mock' -require 'train/transports/local' +require "helper" +require "train/file/local/unix" +require "train/transports/mock" +require "train/transports/local" describe Train::File::Local::Unix do let(:cls) { Train::File::Local::Unix } - let(:backend) { + let(:backend) do backend = Train::Transports::Mock.new.connection - backend.mock_os({ family: 'linux' }) + backend.mock_os({ family: "linux" }) backend - } + end - it 'checks a mounted path' do + it "checks a mounted path" do backend.mock_command("mount | grep -- ' on /mount/path '", rand.to_s) - cls.new(backend, '/mount/path').mounted?.must_equal true + cls.new(backend, "/mount/path").mounted?.must_equal true end - describe 'file metadata' do + describe "file metadata" do let(:transport) { Train::Transports::Local.new } let(:connection) { transport.connection } let(:stat) { Struct.new(:mode, :size, :mtime, :uid, :gid) } let(:uid) { rand } let(:gid) { rand } - let(:statres) { stat.new(00140755, rand, (rand*100).to_i, uid, gid) } + let(:statres) { stat.new(00140755, rand, (rand * 100).to_i, uid, gid) } def meta_stub(method, param, &block) pwres = Struct.new(:name) - Etc.stub :getpwuid, pwres.new('owner') do - Etc.stub :getgrgid, pwres.new('group') do - File.stub method, param do; yield; end + Etc.stub :getpwuid, pwres.new("owner") do + Etc.stub :getgrgid, pwres.new("group") do + File.stub method, param do + yield + end end end end - it 'recognizes type' do + it "recognizes type" do meta_stub :stat, statres do connection.file(rand.to_s).stat[:type].must_equal :socket end end - it 'recognizes mode' do + it "recognizes mode" do meta_stub :stat, statres do connection.file(rand.to_s).stat[:mode].must_equal 00755 end end - it 'recognizes mtime' do + it "recognizes mtime" do meta_stub :stat, statres do connection.file(rand.to_s).stat[:mtime].must_equal statres.mtime end end - it 'recognizes size' do + it "recognizes size" do meta_stub :stat, statres do connection.file(rand.to_s).stat[:size].must_equal statres.size end end - it 'recognizes uid' do + it "recognizes uid" do meta_stub :stat, statres do connection.file(rand.to_s).stat[:uid].must_equal uid end end - it 'recognizes gid' do + it "recognizes gid" do meta_stub :stat, statres do connection.file(rand.to_s).stat[:gid].must_equal gid end end - it 'recognizes owner' do + it "recognizes owner" do meta_stub :stat, statres do - connection.file(rand.to_s).owner.must_equal 'owner' + connection.file(rand.to_s).owner.must_equal "owner" end end - it 'recognizes group' do + it "recognizes group" do meta_stub :stat, statres do - connection.file(rand.to_s).group.must_equal 'group' + connection.file(rand.to_s).group.must_equal "group" end end - it 'grouped_into' do + it "grouped_into" do meta_stub :stat, statres do - connection.file(rand.to_s).grouped_into?('group').must_equal true + connection.file(rand.to_s).grouped_into?("group").must_equal true end end - it 'recognizes selinux label' do + it "recognizes selinux label" do meta_stub :stat, statres do label = rand.to_s res = Train::Extras::CommandResult.new(label, nil, 0) @@ -99,7 +101,7 @@ def meta_stub(method, param, &block) end end - it 'recognizes source selinux label' do + it "recognizes source selinux label" do meta_stub :lstat, statres do label = rand.to_s res = Train::Extras::CommandResult.new(label, nil, 0) @@ -110,7 +112,7 @@ def meta_stub(method, param, &block) end end - describe '#unix_mode_mask' do + describe "#unix_mode_mask" do let(:file_tester) do Class.new(cls) do define_method :type do @@ -119,106 +121,106 @@ def meta_stub(method, param, &block) end.new(nil, nil, false) end - it 'check owner mode calculation' do - file_tester.unix_mode_mask('owner', 'x').must_equal 0100 - file_tester.unix_mode_mask('owner', 'w').must_equal 0200 - file_tester.unix_mode_mask('owner', 'r').must_equal 0400 + it "check owner mode calculation" do + file_tester.unix_mode_mask("owner", "x").must_equal 0100 + file_tester.unix_mode_mask("owner", "w").must_equal 0200 + file_tester.unix_mode_mask("owner", "r").must_equal 0400 end - it 'check group mode calculation' do - file_tester.unix_mode_mask('group', 'x').must_equal 0010 - file_tester.unix_mode_mask('group', 'w').must_equal 0020 - file_tester.unix_mode_mask('group', 'r').must_equal 0040 + it "check group mode calculation" do + file_tester.unix_mode_mask("group", "x").must_equal 0010 + file_tester.unix_mode_mask("group", "w").must_equal 0020 + file_tester.unix_mode_mask("group", "r").must_equal 0040 end - it 'check other mode calculation' do - file_tester.unix_mode_mask('other', 'x').must_equal 0001 - file_tester.unix_mode_mask('other', 'w').must_equal 0002 - file_tester.unix_mode_mask('other', 'r').must_equal 0004 + it "check other mode calculation" do + file_tester.unix_mode_mask("other", "x").must_equal 0001 + file_tester.unix_mode_mask("other", "w").must_equal 0002 + file_tester.unix_mode_mask("other", "r").must_equal 0004 end - it 'check all mode calculation' do - file_tester.unix_mode_mask('all', 'x').must_equal 0111 - file_tester.unix_mode_mask('all', 'w').must_equal 0222 - file_tester.unix_mode_mask('all', 'r').must_equal 0444 + it "check all mode calculation" do + file_tester.unix_mode_mask("all", "x").must_equal 0111 + file_tester.unix_mode_mask("all", "w").must_equal 0222 + file_tester.unix_mode_mask("all", "r").must_equal 0444 end end - describe '#md5sum' do - let(:md5_checksum) { '57d4c6f9d15313fd5651317e588c035d' } + describe "#md5sum" do + let(:md5_checksum) { "57d4c6f9d15313fd5651317e588c035d" } let(:ruby_md5_mock) do checksum_mock = mock - checksum_mock.expects(:update).returns('') + checksum_mock.expects(:update).returns("") checksum_mock.expects(:hexdigest).returns(md5_checksum) checksum_mock end - it 'defaults to a Ruby based checksum if other methods fail' do - backend.mock_command('md5sum /tmp/testfile', '', '', 1) + it "defaults to a Ruby based checksum if other methods fail" do + backend.mock_command("md5sum /tmp/testfile", "", "", 1) Digest::MD5.expects(:new).returns(ruby_md5_mock) - cls.new(backend, '/tmp/testfile').md5sum.must_equal md5_checksum + cls.new(backend, "/tmp/testfile").md5sum.must_equal md5_checksum end - it 'calculates the correct md5sum on the `linux` platform family' do + it "calculates the correct md5sum on the `linux` platform family" do output = "#{md5_checksum} /tmp/testfile" - backend.mock_command('md5sum /tmp/testfile', output) - cls.new(backend, '/tmp/testfile').md5sum.must_equal md5_checksum + backend.mock_command("md5sum /tmp/testfile", output) + cls.new(backend, "/tmp/testfile").md5sum.must_equal md5_checksum end - it 'calculates the correct md5sum on the `darwin` platform family' do + it "calculates the correct md5sum on the `darwin` platform family" do output = "#{md5_checksum} /tmp/testfile" - backend.mock_os(family: 'darwin') - backend.mock_command('md5 -r /tmp/testfile', output) - cls.new(backend, '/tmp/testfile').md5sum.must_equal md5_checksum + backend.mock_os(family: "darwin") + backend.mock_command("md5 -r /tmp/testfile", output) + cls.new(backend, "/tmp/testfile").md5sum.must_equal md5_checksum end - it 'calculates the correct md5sum on the `solaris` platform family' do + it "calculates the correct md5sum on the `solaris` platform family" do # The `digest` command doesn't output the filename by default output = "#{md5_checksum}" - backend.mock_os(family: 'solaris') - backend.mock_command('digest -a md5 /tmp/testfile', output) - cls.new(backend, '/tmp/testfile').md5sum.must_equal md5_checksum + backend.mock_os(family: "solaris") + backend.mock_command("digest -a md5 /tmp/testfile", output) + cls.new(backend, "/tmp/testfile").md5sum.must_equal md5_checksum end end - describe '#sha256sum' do - let(:sha256_checksum) { - '491260aaa6638d4a64c714a17828c3d82bad6ca600c9149b3b3350e91bcd283d' - } + describe "#sha256sum" do + let(:sha256_checksum) do + "491260aaa6638d4a64c714a17828c3d82bad6ca600c9149b3b3350e91bcd283d" + end let(:ruby_sha256_mock) do checksum_mock = mock - checksum_mock.expects(:update).returns('') + checksum_mock.expects(:update).returns("") checksum_mock.expects(:hexdigest).returns(sha256_checksum) checksum_mock end - it 'defaults to a Ruby based checksum if other methods fail' do - backend.mock_command('sha256sum /tmp/testfile', '', '', 1) + it "defaults to a Ruby based checksum if other methods fail" do + backend.mock_command("sha256sum /tmp/testfile", "", "", 1) Digest::SHA256.expects(:new).returns(ruby_sha256_mock) - cls.new(backend, '/tmp/testfile').sha256sum.must_equal sha256_checksum + cls.new(backend, "/tmp/testfile").sha256sum.must_equal sha256_checksum end - it 'calculates the correct sha256sum on the `linux` platform family' do + it "calculates the correct sha256sum on the `linux` platform family" do output = "#{sha256_checksum} /tmp/testfile" - backend.mock_command('sha256sum /tmp/testfile', output) - cls.new(backend, '/tmp/testfile').sha256sum.must_equal sha256_checksum + backend.mock_command("sha256sum /tmp/testfile", output) + cls.new(backend, "/tmp/testfile").sha256sum.must_equal sha256_checksum end - it 'calculates the correct sha256sum on the `darwin` platform family' do + it "calculates the correct sha256sum on the `darwin` platform family" do output = "#{sha256_checksum} /tmp/testfile" - backend.mock_os(family: 'darwin') - backend.mock_command('shasum -a 256 /tmp/testfile', output) - cls.new(backend, '/tmp/testfile').sha256sum.must_equal sha256_checksum + backend.mock_os(family: "darwin") + backend.mock_command("shasum -a 256 /tmp/testfile", output) + cls.new(backend, "/tmp/testfile").sha256sum.must_equal sha256_checksum end - it 'calculates the correct sha256sum on the `solaris` platform family' do + it "calculates the correct sha256sum on the `solaris` platform family" do # The `digest` command doesn't output the filename by default output = "#{sha256_checksum}" - backend.mock_os(family: 'solaris') - backend.mock_command('digest -a sha256 /tmp/testfile', output) - cls.new(backend, '/tmp/testfile').sha256sum.must_equal sha256_checksum + backend.mock_os(family: "solaris") + backend.mock_command("digest -a sha256 /tmp/testfile", output) + cls.new(backend, "/tmp/testfile").sha256sum.must_equal sha256_checksum end end end diff --git a/test/unit/file/local/windows_test.rb b/test/unit/file/local/windows_test.rb index 322062f2..61f9ab81 100644 --- a/test/unit/file/local/windows_test.rb +++ b/test/unit/file/local/windows_test.rb @@ -1,62 +1,62 @@ # encoding: utf-8 -require 'helper' -require 'train/transports/mock' -require 'train/file/local/windows' +require "helper" +require "train/transports/mock" +require "train/file/local/windows" -describe 'file common' do +describe "file common" do let(:cls) { Train::File::Local::Windows } - let(:backend) { + let(:backend) do backend = Train::Transports::Mock.new.connection - backend.mock_os({ family: 'windows' }) + backend.mock_os({ family: "windows" }) backend - } + end - it 'check escaping of invalid chars in path' do + it "check escaping of invalid chars in path" do wf = cls.new(nil, nil) - wf.sanitize_filename('c:/test') .must_equal 'c:/test' - wf.sanitize_filename('c:/test directory') .must_equal 'c:/test directory' + wf.sanitize_filename("c:/test") .must_equal "c:/test" + wf.sanitize_filename("c:/test directory") .must_equal "c:/test directory" %w{ < > " * ?}.each do |char| - wf.sanitize_filename("c:/test#{char}directory") .must_equal 'c:/testdirectory' + wf.sanitize_filename("c:/test#{char}directory") .must_equal "c:/testdirectory" end end - it 'returns file version' do + it "returns file version" do out = rand.to_s backend.mock_command('[System.Diagnostics.FileVersionInfo]::GetVersionInfo("path").FileVersion', out) - cls.new(backend, 'path').file_version.must_equal out + cls.new(backend, "path").file_version.must_equal out end - it 'returns product version' do + it "returns product version" do out = rand.to_s backend.mock_command('[System.Diagnostics.FileVersionInfo]::GetVersionInfo("path").FileVersion', out) - cls.new(backend, 'path').file_version.must_equal out + cls.new(backend, "path").file_version.must_equal out end - it 'returns owner of file' do + it "returns owner of file" do out = rand.to_s backend.mock_command('Get-Acl "path" | select -expand Owner', out) - cls.new(backend, 'path').owner.must_equal out + cls.new(backend, "path").owner.must_equal out end - describe '#md5sum' do - let(:md5_checksum) { '4ce0c733cdcf1d2f78532bbd9ce3441d' } + describe "#md5sum" do + let(:md5_checksum) { "4ce0c733cdcf1d2f78532bbd9ce3441d" } let(:filepath) { 'C:\Windows\explorer.exe' } let(:ruby_md5_mock) do checksum_mock = mock - checksum_mock.expects(:update).returns('') + checksum_mock.expects(:update).returns("") checksum_mock.expects(:hexdigest).returns(md5_checksum) checksum_mock end - it 'defaults to a Ruby based checksum if other methods fail' do - backend.mock_command("CertUtil -hashfile #{filepath} MD5", '', '', 1) + it "defaults to a Ruby based checksum if other methods fail" do + backend.mock_command("CertUtil -hashfile #{filepath} MD5", "", "", 1) Digest::MD5.expects(:new).returns(ruby_md5_mock) - cls.new(backend, '/tmp/testfile').md5sum.must_equal md5_checksum + cls.new(backend, "/tmp/testfile").md5sum.must_equal md5_checksum end - it 'calculates the correct md5sum on the `windows` platform family' do + it "calculates the correct md5sum on the `windows` platform family" do output = <<-EOC MD5 hash of file C:\\Windows\\explorer.exe:\r 4c e0 c7 33 cd cf 1d 2f 78 53 2b bd 9c e3 44 1d\r @@ -68,26 +68,26 @@ end end - describe '#sha256sum' do - let(:sha256_checksum) { - '85270240a5fd51934f0627c92b2282749d071fdc9ac351b81039ced5b10f798b' - } + describe "#sha256sum" do + let(:sha256_checksum) do + "85270240a5fd51934f0627c92b2282749d071fdc9ac351b81039ced5b10f798b" + end let(:filepath) { 'C:\Windows\explorer.exe' } let(:ruby_sha256_mock) do checksum_mock = mock - checksum_mock.expects(:update).returns('') + checksum_mock.expects(:update).returns("") checksum_mock.expects(:hexdigest).returns(sha256_checksum) checksum_mock end - it 'defaults to a Ruby based checksum if other methods fail' do - backend.mock_command('CertUtil -hashfile #{filepath} SHA256', '', '', 1) + it "defaults to a Ruby based checksum if other methods fail" do + backend.mock_command('CertUtil -hashfile #{filepath} SHA256', "", "", 1) Digest::SHA256.expects(:new).returns(ruby_sha256_mock) - cls.new(backend, '/tmp/testfile').sha256sum.must_equal sha256_checksum + cls.new(backend, "/tmp/testfile").sha256sum.must_equal sha256_checksum end - it 'calculates the correct sha256sum on the `windows` platform family' do + it "calculates the correct sha256sum on the `windows` platform family" do output = <<-EOC SHA256 hash of file C:\\Windows\\explorer.exe:\r 85 27 02 40 a5 fd 51 93 4f 06 27 c9 2b 22 82 74 9d 07 1f dc 9a c3 51 b8 10 39 ce d5 b1 0f 79 8b\r diff --git a/test/unit/file/local_test.rb b/test/unit/file/local_test.rb index a25e85e7..2f032d98 100644 --- a/test/unit/file/local_test.rb +++ b/test/unit/file/local_test.rb @@ -1,11 +1,11 @@ -require 'helper' -require 'train/transports/local' +require "helper" +require "train/transports/local" describe Train::File::Local do let(:transport) { Train::Transports::Local.new } let(:connection) { transport.connection } - it 'gets file contents' do + it "gets file contents" do res = rand.to_s File.stub :read, res do connection.file(rand.to_s).content.must_equal(res) @@ -13,14 +13,14 @@ end { - exist?: :exist?, - file?: :file?, - socket?: :socket?, - directory?: :directory?, - symlink?: :symlink?, - pipe?: :pipe?, + exist?: :exist?, + file?: :file?, + socket?: :socket?, + directory?: :directory?, + symlink?: :symlink?, + pipe?: :pipe?, character_device?: :chardev?, - block_device?: :blockdev?, + block_device?: :blockdev?, }.each do |method, file_method| it "checks if file is a #{method}" do File.stub file_method.to_sym, true do @@ -29,76 +29,76 @@ end end - describe '#type' do - it 'returns the type block_device if it is block device' do + describe "#type" do + it "returns the type block_device if it is block device" do File.stub :ftype, "blockSpecial" do connection.file(rand.to_s).type.must_equal :block_device end end - it 'returns the type character_device if it is character device' do + it "returns the type character_device if it is character device" do File.stub :ftype, "characterSpecial" do connection.file(rand.to_s).type.must_equal :character_device end end - it 'returns the type symlink if it is symlink' do + it "returns the type symlink if it is symlink" do File.stub :ftype, "link" do connection.file(rand.to_s).type.must_equal :symlink end end - it 'returns the type file if it is file' do + it "returns the type file if it is file" do File.stub :ftype, "file" do connection.file(rand.to_s).type.must_equal :file end end - it 'returns the type directory if it is block directory' do + it "returns the type directory if it is block directory" do File.stub :ftype, "directory" do connection.file(rand.to_s).type.must_equal :directory end end - it 'returns the type pipe if it is pipe' do + it "returns the type pipe if it is pipe" do File.stub :ftype, "fifo" do connection.file(rand.to_s).type.must_equal :pipe end end - it 'returns the type socket if it is socket' do + it "returns the type socket if it is socket" do File.stub :ftype, "socket" do connection.file(rand.to_s).type.must_equal :socket end end - it 'returns the unknown if not known' do + it "returns the unknown if not known" do File.stub :ftype, "unknown" do connection.file(rand.to_s).type.must_equal :unknown end end end - describe '#path' do - it 'returns the path if it is not a symlink' do + describe "#path" do + it "returns the path if it is not a symlink" do File.stub :symlink?, false do filename = rand.to_s connection.file(filename).path.must_equal filename end end - it 'returns the link_path if it is a symlink' do + it "returns the link_path if it is a symlink" do File.stub :symlink?, true do file_obj = connection.file(rand.to_s) - file_obj.stub :link_path, '/path/to/resolved_link' do - file_obj.path.must_equal '/path/to/resolved_link' + file_obj.stub :link_path, "/path/to/resolved_link" do + file_obj.path.must_equal "/path/to/resolved_link" end end end end - describe '#link_path' do - it 'returns file\'s link path' do + describe "#link_path" do + it "returns file's link path" do out = rand.to_s File.stub :realpath, out do File.stub :symlink?, true do @@ -108,8 +108,8 @@ end end - describe '#shallow_shlink_path' do - it 'returns file\'s direct link path' do + describe "#shallow_shlink_path" do + it "returns file's direct link path" do out = rand.to_s File.stub :readlink, out do File.stub :symlink?, true do diff --git a/test/unit/file/remote/aix_test.rb b/test/unit/file/remote/aix_test.rb index 246e0701..46a655dc 100644 --- a/test/unit/file/remote/aix_test.rb +++ b/test/unit/file/remote/aix_test.rb @@ -1,81 +1,81 @@ -require 'helper' -require 'train/transports/local' -require 'train/file/remote/aix' -require 'train/transports/mock' +require "helper" +require "train/transports/local" +require "train/file/remote/aix" +require "train/transports/mock" describe Train::File::Remote::Aix do let(:cls) { Train::File::Remote::Aix } - let(:backend) { + let(:backend) do backend = Train::Transports::Mock.new.connection - backend.mock_os({ name: 'aix', family: 'unix' }) + backend.mock_os({ name: "aix", family: "unix" }) backend - } + end - it 'returns a nil link_path if the object is not a symlink' do - file = cls.new(backend, 'path') + it "returns a nil link_path if the object is not a symlink" do + file = cls.new(backend, "path") file.stubs(:symlink?).returns(false) file.link_path.must_be_nil end - it 'returns a correct link_path' do - file = cls.new(backend, 'path') + it "returns a correct link_path" do + file = cls.new(backend, "path") file.stubs(:symlink?).returns(true) - backend.mock_command("perl -e 'print readlink shift' path", 'our_link_path') - file.link_path.must_equal 'our_link_path' + backend.mock_command("perl -e 'print readlink shift' path", "our_link_path") + file.link_path.must_equal "our_link_path" end - it 'returns a correct shallow_link_path' do - file = cls.new(backend, 'path') + it "returns a correct shallow_link_path" do + file = cls.new(backend, "path") file.stubs(:symlink?).returns(true) - backend.mock_command("perl -e 'print readlink shift' path", 'our_link_path') - file.link_path.must_equal 'our_link_path' + backend.mock_command("perl -e 'print readlink shift' path", "our_link_path") + file.link_path.must_equal "our_link_path" end - describe '#md5sum' do - let(:md5_checksum) { '57d4c6f9d15313fd5651317e588c035d' } + describe "#md5sum" do + let(:md5_checksum) { "57d4c6f9d15313fd5651317e588c035d" } let(:ruby_md5_mock) do checksum_mock = mock - checksum_mock.expects(:update).returns('') + checksum_mock.expects(:update).returns("") checksum_mock.expects(:hexdigest).returns(md5_checksum) checksum_mock end - it 'defaults to a Ruby based checksum if other methods fail' do - backend.mock_command('md5sum /tmp/testfile', '', '', 1) + it "defaults to a Ruby based checksum if other methods fail" do + backend.mock_command("md5sum /tmp/testfile", "", "", 1) Digest::MD5.expects(:new).returns(ruby_md5_mock) - cls.new(backend, '/tmp/testfile').md5sum.must_equal md5_checksum + cls.new(backend, "/tmp/testfile").md5sum.must_equal md5_checksum end - it 'calculates the correct md5sum on the `aix` platform family' do + it "calculates the correct md5sum on the `aix` platform family" do output = "#{md5_checksum} /tmp/testfile" - backend.mock_command('md5sum /tmp/testfile', output) - cls.new(backend, '/tmp/testfile').md5sum.must_equal md5_checksum + backend.mock_command("md5sum /tmp/testfile", output) + cls.new(backend, "/tmp/testfile").md5sum.must_equal md5_checksum end end - describe '#sha256sum' do - let(:sha256_checksum) { - '491260aaa6638d4a64c714a17828c3d82bad6ca600c9149b3b3350e91bcd283d' - } + describe "#sha256sum" do + let(:sha256_checksum) do + "491260aaa6638d4a64c714a17828c3d82bad6ca600c9149b3b3350e91bcd283d" + end let(:ruby_sha256_mock) do checksum_mock = mock - checksum_mock.expects(:update).returns('') + checksum_mock.expects(:update).returns("") checksum_mock.expects(:hexdigest).returns(sha256_checksum) checksum_mock end - it 'defaults to a Ruby based checksum if other methods fail' do - backend.mock_command('sha256sum /tmp/testfile', '', '', 1) + it "defaults to a Ruby based checksum if other methods fail" do + backend.mock_command("sha256sum /tmp/testfile", "", "", 1) Digest::SHA256.expects(:new).returns(ruby_sha256_mock) - cls.new(backend, '/tmp/testfile').sha256sum.must_equal sha256_checksum + cls.new(backend, "/tmp/testfile").sha256sum.must_equal sha256_checksum end - it 'calculates the correct sha256sum on the `aix` platform family' do + it "calculates the correct sha256sum on the `aix` platform family" do output = "#{sha256_checksum} /tmp/testfile" - backend.mock_command('sha256sum /tmp/testfile', output) - cls.new(backend, '/tmp/testfile').sha256sum.must_equal sha256_checksum + backend.mock_command("sha256sum /tmp/testfile", output) + cls.new(backend, "/tmp/testfile").sha256sum.must_equal sha256_checksum end end end diff --git a/test/unit/file/remote/linux_test.rb b/test/unit/file/remote/linux_test.rb index d2d65587..5b9057ce 100644 --- a/test/unit/file/remote/linux_test.rb +++ b/test/unit/file/remote/linux_test.rb @@ -1,221 +1,221 @@ -require 'helper' -require 'train/transports/local' -require 'train/file/remote/linux' -require 'train/transports/mock' +require "helper" +require "train/transports/local" +require "train/file/remote/linux" +require "train/transports/mock" describe Train::File::Remote::Linux do let(:cls) { Train::File::Remote::Linux } - let(:backend) { + let(:backend) do backend = Train::Transports::Mock.new.connection - backend.mock_os({ name: 'linux', family: 'unix' }) + backend.mock_os({ name: "linux", family: "unix" }) backend - } + end - def mock_stat(args, out, err = '', code = 0) + def mock_stat(args, out, err = "", code = 0) backend.mock_command( "stat #{args} 2>/dev/null --printf '%s\n%f\n%U\n%u\n%G\n%g\n%X\n%Y\n%C'", out, err, code ) end - it 'works on nil path' do - cls.new(backend, nil).path.must_equal '' + it "works on nil path" do + cls.new(backend, nil).path.must_equal "" end - it 'provides the full path' do - cls.new(backend, '/dir/file').path.must_equal '/dir/file' + it "provides the full path" do + cls.new(backend, "/dir/file").path.must_equal "/dir/file" end - it 'provides the basename to a unix path' do - cls.new(backend, '/dir/file').basename.must_equal 'file' + it "provides the basename to a unix path" do + cls.new(backend, "/dir/file").basename.must_equal "file" end - it 'reads file contents' do + it "reads file contents" do out = rand.to_s - backend.mock_command('cat path || echo -n', out) - cls.new(backend, 'path').content.must_equal out + backend.mock_command("cat path || echo -n", out) + cls.new(backend, "path").content.must_equal out end - it 'reads file contents' do - backend.mock_command('cat path || echo -n', '') - mock_stat('-L path', '', 'some error...', 1) - cls.new(backend, 'path').content.must_be_nil + it "reads file contents" do + backend.mock_command("cat path || echo -n", "") + mock_stat("-L path", "", "some error...", 1) + cls.new(backend, "path").content.must_be_nil end - it 'reads file contents' do + it "reads file contents" do out = rand.to_s backend.mock_command('cat /spaced\\ path || echo -n', out) - cls.new(backend, '/spaced path').content.must_equal out + cls.new(backend, "/spaced path").content.must_equal out end - it 'checks for file existance' do - backend.mock_command('test -e path', true) - cls.new(backend, 'path').exist?.must_equal true + it "checks for file existance" do + backend.mock_command("test -e path", true) + cls.new(backend, "path").exist?.must_equal true end - it 'checks for file existance' do - backend.mock_command('test -e path', nil, nil, 1) - cls.new(backend, 'path').exist?.must_equal false + it "checks for file existance" do + backend.mock_command("test -e path", nil, nil, 1) + cls.new(backend, "path").exist?.must_equal false end - it 'retrieves the link path via #path()' do + it "retrieves the link path via #path()" do out = rand.to_s - mock_stat('path', "13\na1ff\nz\n1001\nz\n1001\n1444573475\n1444573475\n?") - backend.mock_command('readlink -n path -f', out) - cls.new(backend, 'path').path.must_equal File.join(Dir.pwd, out) + mock_stat("path", "13\na1ff\nz\n1001\nz\n1001\n1444573475\n1444573475\n?") + backend.mock_command("readlink -n path -f", out) + cls.new(backend, "path").path.must_equal File.join(Dir.pwd, out) end - it 'retrieves the link path' do + it "retrieves the link path" do out = rand.to_s - mock_stat('path', "13\na1ff\nz\n1001\nz\n1001\n1444573475\n1444573475\n?") - backend.mock_command('readlink -n path -f', out) - cls.new(backend, 'path').link_path.must_equal File.join(Dir.pwd, out) + mock_stat("path", "13\na1ff\nz\n1001\nz\n1001\n1444573475\n1444573475\n?") + backend.mock_command("readlink -n path -f", out) + cls.new(backend, "path").link_path.must_equal File.join(Dir.pwd, out) end - it 'provide the source path' do - cls.new(backend, 'path').source_path.must_equal 'path' + it "provide the source path" do + cls.new(backend, "path").source_path.must_equal "path" end - it 'checks a mounted path' do + it "checks a mounted path" do backend.mock_command("mount | grep -- ' on /mount/path '", rand.to_s) - cls.new(backend, '/mount/path').mounted?.must_equal true + cls.new(backend, "/mount/path").mounted?.must_equal true end - it 'has nil product version' do - cls.new(backend, 'path').product_version.must_be_nil + it "has nil product version" do + cls.new(backend, "path").product_version.must_be_nil end - it 'has nil file version' do - cls.new(backend, 'path').file_version.must_be_nil + it "has nil file version" do + cls.new(backend, "path").file_version.must_be_nil end - describe 'stat on a file' do - before { mock_stat('-L path', "13\na1ff\nz\n1001\nz2\n1002\n1444573475\n1444573475\nlabels") } - let(:f) { cls.new(backend, 'path') } + describe "stat on a file" do + before { mock_stat("-L path", "13\na1ff\nz\n1001\nz2\n1002\n1444573475\n1444573475\nlabels") } + let(:f) { cls.new(backend, "path") } - it 'retrieves the file type' do + it "retrieves the file type" do f.type.must_equal :symlink end - it 'retrieves the file mode' do + it "retrieves the file mode" do f.mode.must_equal 00777 end - it 'retrieves the file owner' do - f.owner.must_equal 'z' + it "retrieves the file owner" do + f.owner.must_equal "z" end - it 'retrieves the file uid' do + it "retrieves the file uid" do f.uid.must_equal 1001 end - it 'retrieves the file group' do - f.group.must_equal 'z2' + it "retrieves the file group" do + f.group.must_equal "z2" end - it 'retrieves the file gid' do + it "retrieves the file gid" do f.gid.must_equal 1002 end - it 'retrieves the file mtime' do + it "retrieves the file mtime" do f.mtime.must_equal 1444573475 end - it 'retrieves the file size' do + it "retrieves the file size" do f.size.must_equal 13 end - it 'retrieves the file selinux_label' do - f.selinux_label.must_equal 'labels' + it "retrieves the file selinux_label" do + f.selinux_label.must_equal "labels" end end - describe 'stat on the source file' do - before { mock_stat('path', "13\na1ff\nz\n1001\nz2\n1002\n1444573475\n1444573475\nlabels") } - let(:f) { cls.new(backend, 'path').source } + describe "stat on the source file" do + before { mock_stat("path", "13\na1ff\nz\n1001\nz2\n1002\n1444573475\n1444573475\nlabels") } + let(:f) { cls.new(backend, "path").source } - it 'retrieves the file type' do + it "retrieves the file type" do f.type.must_equal :symlink end - it 'retrieves the file mode' do + it "retrieves the file mode" do f.mode.must_equal 00777 end - it 'retrieves the file owner' do - f.owner.must_equal 'z' + it "retrieves the file owner" do + f.owner.must_equal "z" end - it 'retrieves the file uid' do + it "retrieves the file uid" do f.uid.must_equal 1001 end - it 'retrieves the file group' do - f.group.must_equal 'z2' + it "retrieves the file group" do + f.group.must_equal "z2" end - it 'retrieves the file gid' do + it "retrieves the file gid" do f.gid.must_equal 1002 end - it 'retrieves the file mtime' do + it "retrieves the file mtime" do f.mtime.must_equal 1444573475 end - it 'retrieves the file size' do + it "retrieves the file size" do f.size.must_equal 13 end - it 'retrieves the file selinux_label' do - f.selinux_label.must_equal 'labels' + it "retrieves the file selinux_label" do + f.selinux_label.must_equal "labels" end end - describe '#md5sum' do - let(:md5_checksum) { '57d4c6f9d15313fd5651317e588c035d' } + describe "#md5sum" do + let(:md5_checksum) { "57d4c6f9d15313fd5651317e588c035d" } let(:ruby_md5_mock) do checksum_mock = mock - checksum_mock.expects(:update).returns('') + checksum_mock.expects(:update).returns("") checksum_mock.expects(:hexdigest).returns(md5_checksum) checksum_mock end - it 'defaults to a Ruby based checksum if other methods fail' do - backend.mock_command('md5sum /tmp/testfile', '', '', 1) + it "defaults to a Ruby based checksum if other methods fail" do + backend.mock_command("md5sum /tmp/testfile", "", "", 1) Digest::MD5.expects(:new).returns(ruby_md5_mock) - cls.new(backend, '/tmp/testfile').md5sum.must_equal md5_checksum + cls.new(backend, "/tmp/testfile").md5sum.must_equal md5_checksum end - it 'calculates the correct md5sum on the `linux` platform family' do + it "calculates the correct md5sum on the `linux` platform family" do output = "#{md5_checksum} /tmp/testfile" - backend.mock_command('md5sum /tmp/testfile', output) - cls.new(backend, '/tmp/testfile').md5sum.must_equal md5_checksum + backend.mock_command("md5sum /tmp/testfile", output) + cls.new(backend, "/tmp/testfile").md5sum.must_equal md5_checksum end end - describe '#sha256sum' do - let(:sha256_checksum) { - '491260aaa6638d4a64c714a17828c3d82bad6ca600c9149b3b3350e91bcd283d' - } + describe "#sha256sum" do + let(:sha256_checksum) do + "491260aaa6638d4a64c714a17828c3d82bad6ca600c9149b3b3350e91bcd283d" + end let(:ruby_sha256_mock) do checksum_mock = mock - checksum_mock.expects(:update).returns('') + checksum_mock.expects(:update).returns("") checksum_mock.expects(:hexdigest).returns(sha256_checksum) checksum_mock end - it 'defaults to a Ruby based checksum if other methods fail' do - backend.mock_command('sha256sum /tmp/testfile', '', '', 1) + it "defaults to a Ruby based checksum if other methods fail" do + backend.mock_command("sha256sum /tmp/testfile", "", "", 1) Digest::SHA256.expects(:new).returns(ruby_sha256_mock) - cls.new(backend, '/tmp/testfile').sha256sum.must_equal sha256_checksum + cls.new(backend, "/tmp/testfile").sha256sum.must_equal sha256_checksum end - it 'calculates the correct sha256sum on the `linux` platform family' do + it "calculates the correct sha256sum on the `linux` platform family" do output = "#{sha256_checksum} /tmp/testfile" - backend.mock_command('sha256sum /tmp/testfile', output) - cls.new(backend, '/tmp/testfile').sha256sum.must_equal sha256_checksum + backend.mock_command("sha256sum /tmp/testfile", output) + cls.new(backend, "/tmp/testfile").sha256sum.must_equal sha256_checksum end end end diff --git a/test/unit/file/remote/qnx_test.rb b/test/unit/file/remote/qnx_test.rb index 10846f0e..bf3c242c 100644 --- a/test/unit/file/remote/qnx_test.rb +++ b/test/unit/file/remote/qnx_test.rb @@ -1,80 +1,80 @@ -require 'helper' -require 'train/transports/local' -require 'train/file/remote/qnx' -require 'train/transports/mock' +require "helper" +require "train/transports/local" +require "train/file/remote/qnx" +require "train/transports/mock" describe Train::File::Remote::Qnx do let(:cls) { Train::File::Remote::Qnx } - let(:backend) { + let(:backend) do backend = Train::Transports::Mock.new.connection - backend.mock_os({ family: 'qnx' }) + backend.mock_os({ family: "qnx" }) backend - } + end - it 'returns file contents when the file exists' do + it "returns file contents when the file exists" do out = rand.to_s - backend.mock_command('cat path', out) - file = cls.new(backend, 'path') + backend.mock_command("cat path", out) + file = cls.new(backend, "path") file.stubs(:exist?).returns(true) file.content.must_equal out end - it 'returns nil contents when the file does not exist' do - file = cls.new(backend, 'path') + it "returns nil contents when the file does not exist" do + file = cls.new(backend, "path") file.stubs(:exist?).returns(false) file.content.must_be_nil end - it 'returns a file type' do - backend.mock_command('file path', 'blah directory blah') - cls.new(backend, 'path').type.must_equal :directory + it "returns a file type" do + backend.mock_command("file path", "blah directory blah") + cls.new(backend, "path").type.must_equal :directory end - it 'returns a directory type' do - backend.mock_command('file path', 'blah regular file blah') - cls.new(backend, 'path').type.must_equal :file + it "returns a directory type" do + backend.mock_command("file path", "blah regular file blah") + cls.new(backend, "path").type.must_equal :file end - it 'raises exception for unimplemented methods' do - file = cls.new(backend, 'path') + it "raises exception for unimplemented methods" do + file = cls.new(backend, "path") %w{mode owner group uid gid mtime size selinux_label link_path mounted stat}.each do |m| proc { file.send(m) }.must_raise NotImplementedError end end - describe '#md5sum' do - let(:md5_checksum) { '17404a596cbd0d1e6c7d23fcd845ab82' } + describe "#md5sum" do + let(:md5_checksum) { "17404a596cbd0d1e6c7d23fcd845ab82" } let(:ruby_md5_mock) do checksum_mock = mock - checksum_mock.expects(:update).returns('') + checksum_mock.expects(:update).returns("") checksum_mock.expects(:hexdigest).returns(md5_checksum) checksum_mock end - it 'defaults to a Ruby based checksum if other methods fail' do - backend.mock_command('md5sum /tmp/testfile', '', '', 1) + it "defaults to a Ruby based checksum if other methods fail" do + backend.mock_command("md5sum /tmp/testfile", "", "", 1) Digest::MD5.expects(:new).returns(ruby_md5_mock) - cls.new(backend, '/tmp/testfile').md5sum.must_equal md5_checksum + cls.new(backend, "/tmp/testfile").md5sum.must_equal md5_checksum end end - describe '#sha256sum' do - let(:sha256_checksum) { - 'ec864fe99b539704b8872ac591067ef22d836a8d942087f2dba274b301ebe6e5' - } + describe "#sha256sum" do + let(:sha256_checksum) do + "ec864fe99b539704b8872ac591067ef22d836a8d942087f2dba274b301ebe6e5" + end let(:ruby_sha256_mock) do checksum_mock = mock - checksum_mock.expects(:update).returns('') + checksum_mock.expects(:update).returns("") checksum_mock.expects(:hexdigest).returns(sha256_checksum) checksum_mock end - it 'defaults to a Ruby based checksum if other methods fail' do - backend.mock_command('sha256sum /tmp/testfile', '', '', 1) + it "defaults to a Ruby based checksum if other methods fail" do + backend.mock_command("sha256sum /tmp/testfile", "", "", 1) Digest::SHA256.expects(:new).returns(ruby_sha256_mock) - cls.new(backend, '/tmp/testfile').sha256sum.must_equal sha256_checksum + cls.new(backend, "/tmp/testfile").sha256sum.must_equal sha256_checksum end end end diff --git a/test/unit/file/remote/unix_test.rb b/test/unit/file/remote/unix_test.rb index cd1cb45e..609fc908 100644 --- a/test/unit/file/remote/unix_test.rb +++ b/test/unit/file/remote/unix_test.rb @@ -1,19 +1,19 @@ -require 'helper' -require 'train/transports/mock' -require 'train/file/remote/unix' +require "helper" +require "train/transports/mock" +require "train/file/remote/unix" describe Train::File::Remote::Unix do let(:cls) { Train::File::Remote::Unix } - let(:backend) { + let(:backend) do backend = Train::Transports::Mock.new.connection - backend.mock_os({ family: 'linux' }) + backend.mock_os({ family: "linux" }) backend - } + end def mockup(stubs) Class.new(cls) do - stubs.each do |k,v| + stubs.each do |k, v| define_method k.to_sym do v end @@ -21,99 +21,97 @@ def mockup(stubs) end.new(nil, nil, false) end - describe 'unix_mode_mask' do + describe "unix_mode_mask" do let(:fc) { mockup(type: :file) } - it 'check owner mode calculation' do - fc.unix_mode_mask('owner', 'x').must_equal 0100 - fc.unix_mode_mask('owner', 'w').must_equal 0200 - fc.unix_mode_mask('owner', 'r').must_equal 0400 + it "check owner mode calculation" do + fc.unix_mode_mask("owner", "x").must_equal 0100 + fc.unix_mode_mask("owner", "w").must_equal 0200 + fc.unix_mode_mask("owner", "r").must_equal 0400 end - it 'check group mode calculation' do - fc.unix_mode_mask('group', 'x').must_equal 0010 - fc.unix_mode_mask('group', 'w').must_equal 0020 - fc.unix_mode_mask('group', 'r').must_equal 0040 + it "check group mode calculation" do + fc.unix_mode_mask("group", "x").must_equal 0010 + fc.unix_mode_mask("group", "w").must_equal 0020 + fc.unix_mode_mask("group", "r").must_equal 0040 end - it 'check other mode calculation' do - fc.unix_mode_mask('other', 'x').must_equal 0001 - fc.unix_mode_mask('other', 'w').must_equal 0002 - fc.unix_mode_mask('other', 'r').must_equal 0004 + it "check other mode calculation" do + fc.unix_mode_mask("other", "x").must_equal 0001 + fc.unix_mode_mask("other", "w").must_equal 0002 + fc.unix_mode_mask("other", "r").must_equal 0004 end - it 'check all mode calculation' do - fc.unix_mode_mask('all', 'x').must_equal 0111 - fc.unix_mode_mask('all', 'w').must_equal 0222 - fc.unix_mode_mask('all', 'r').must_equal 0444 + it "check all mode calculation" do + fc.unix_mode_mask("all", "x").must_equal 0111 + fc.unix_mode_mask("all", "w").must_equal 0222 + fc.unix_mode_mask("all", "r").must_equal 0444 end end - describe '#md5sum' do - let(:md5_checksum) { '57d4c6f9d15313fd5651317e588c035d' } + describe "#md5sum" do + let(:md5_checksum) { "57d4c6f9d15313fd5651317e588c035d" } let(:ruby_md5_mock) do checksum_mock = mock - checksum_mock.expects(:update).returns('') + checksum_mock.expects(:update).returns("") checksum_mock.expects(:hexdigest).returns(md5_checksum) checksum_mock end - it 'defaults to a Ruby based checksum if other methods fail' do - backend.mock_command('md5 -r /tmp/testfile', '', '', 1) + it "defaults to a Ruby based checksum if other methods fail" do + backend.mock_command("md5 -r /tmp/testfile", "", "", 1) Digest::MD5.expects(:new).returns(ruby_md5_mock) - cls.new(backend, '/tmp/testfile').md5sum.must_equal md5_checksum + cls.new(backend, "/tmp/testfile").md5sum.must_equal md5_checksum end - - it 'calculates the correct md5sum on the `darwin` platform family' do + it "calculates the correct md5sum on the `darwin` platform family" do output = "#{md5_checksum} /tmp/testfile" - backend.mock_os(family: 'darwin') - backend.mock_command('md5 -r /tmp/testfile', output) - cls.new(backend, '/tmp/testfile').md5sum.must_equal md5_checksum + backend.mock_os(family: "darwin") + backend.mock_command("md5 -r /tmp/testfile", output) + cls.new(backend, "/tmp/testfile").md5sum.must_equal md5_checksum end - it 'calculates the correct md5sum on the `solaris` platform family' do + it "calculates the correct md5sum on the `solaris` platform family" do # The `digest` command doesn't output the filename by default output = "#{md5_checksum}" - backend.mock_os(family: 'solaris') - backend.mock_command('digest -a md5 /tmp/testfile', output) - cls.new(backend, '/tmp/testfile').md5sum.must_equal md5_checksum + backend.mock_os(family: "solaris") + backend.mock_command("digest -a md5 /tmp/testfile", output) + cls.new(backend, "/tmp/testfile").md5sum.must_equal md5_checksum end end - describe '#sha256sum' do - let(:sha256_checksum) { - '491260aaa6638d4a64c714a17828c3d82bad6ca600c9149b3b3350e91bcd283d' - } + describe "#sha256sum" do + let(:sha256_checksum) do + "491260aaa6638d4a64c714a17828c3d82bad6ca600c9149b3b3350e91bcd283d" + end let(:ruby_sha256_mock) do checksum_mock = mock - checksum_mock.expects(:update).returns('') + checksum_mock.expects(:update).returns("") checksum_mock.expects(:hexdigest).returns(sha256_checksum) checksum_mock end - it 'defaults to a Ruby based checksum if other methods fail' do - backend.mock_command('shasum -a 256 /tmp/testfile', '', '', 1) + it "defaults to a Ruby based checksum if other methods fail" do + backend.mock_command("shasum -a 256 /tmp/testfile", "", "", 1) Digest::SHA256.expects(:new).returns(ruby_sha256_mock) - cls.new(backend, '/tmp/testfile').sha256sum.must_equal sha256_checksum + cls.new(backend, "/tmp/testfile").sha256sum.must_equal sha256_checksum end - - it 'calculates the correct sha256sum on the `darwin` platform family' do + it "calculates the correct sha256sum on the `darwin` platform family" do output = "#{sha256_checksum} /tmp/testfile" - backend.mock_os(family: 'darwin') - backend.mock_command('shasum -a 256 /tmp/testfile', output) - cls.new(backend, '/tmp/testfile').sha256sum.must_equal sha256_checksum + backend.mock_os(family: "darwin") + backend.mock_command("shasum -a 256 /tmp/testfile", output) + cls.new(backend, "/tmp/testfile").sha256sum.must_equal sha256_checksum end - it 'calculates the correct sha256sum on the `solaris` platform family' do + it "calculates the correct sha256sum on the `solaris` platform family" do # The `digest` command doesn't output the filename by default output = "#{sha256_checksum}" - backend.mock_os(family: 'solaris') - backend.mock_command('digest -a sha256 /tmp/testfile', output) - cls.new(backend, '/tmp/testfile').sha256sum.must_equal sha256_checksum + backend.mock_os(family: "solaris") + backend.mock_command("digest -a sha256 /tmp/testfile", output) + cls.new(backend, "/tmp/testfile").sha256sum.must_equal sha256_checksum end end end diff --git a/test/unit/file/remote/windows_test.rb b/test/unit/file/remote/windows_test.rb index f0a0374d..a549326b 100644 --- a/test/unit/file/remote/windows_test.rb +++ b/test/unit/file/remote/windows_test.rb @@ -1,33 +1,33 @@ -require 'helper' -require 'train/transports/mock' -require 'train/file/remote/windows' +require "helper" +require "train/transports/mock" +require "train/file/remote/windows" describe Train::File::Remote::Windows do let(:cls) { Train::File::Remote::Windows } - let(:backend) { + let(:backend) do backend = Train::Transports::Mock.new.connection - backend.mock_os({ family: 'windows' }) + backend.mock_os({ family: "windows" }) backend - } + end - describe '#md5sum' do - let(:md5_checksum) { '4ce0c733cdcf1d2f78532bbd9ce3441d' } + describe "#md5sum" do + let(:md5_checksum) { "4ce0c733cdcf1d2f78532bbd9ce3441d" } let(:filepath) { 'C:\Windows\explorer.exe' } let(:ruby_md5_mock) do checksum_mock = mock - checksum_mock.expects(:update).returns('') + checksum_mock.expects(:update).returns("") checksum_mock.expects(:hexdigest).returns(md5_checksum) checksum_mock end - it 'defaults to a Ruby based checksum if other methods fail' do - backend.mock_command("CertUtil -hashfile #{filepath} MD5", '', '', 1) + it "defaults to a Ruby based checksum if other methods fail" do + backend.mock_command("CertUtil -hashfile #{filepath} MD5", "", "", 1) Digest::MD5.expects(:new).returns(ruby_md5_mock) - cls.new(backend, '/tmp/testfile').md5sum.must_equal md5_checksum + cls.new(backend, "/tmp/testfile").md5sum.must_equal md5_checksum end - it 'calculates the correct md5sum on the `windows` platform family' do + it "calculates the correct md5sum on the `windows` platform family" do output = <<-EOC MD5 hash of file C:\\Windows\\explorer.exe:\r 4c e0 c7 33 cd cf 1d 2f 78 53 2b bd 9c e3 44 1d\r @@ -39,26 +39,26 @@ end end - describe '#sha256sum' do - let(:sha256_checksum) { - '85270240a5fd51934f0627c92b2282749d071fdc9ac351b81039ced5b10f798b' - } + describe "#sha256sum" do + let(:sha256_checksum) do + "85270240a5fd51934f0627c92b2282749d071fdc9ac351b81039ced5b10f798b" + end let(:filepath) { 'C:\Windows\explorer.exe' } let(:ruby_sha256_mock) do checksum_mock = mock - checksum_mock.expects(:update).returns('') + checksum_mock.expects(:update).returns("") checksum_mock.expects(:hexdigest).returns(sha256_checksum) checksum_mock end - it 'defaults to a Ruby based checksum if other methods fail' do - backend.mock_command("CertUtil -hashfile #{filepath} SHA256", '', '', 1) + it "defaults to a Ruby based checksum if other methods fail" do + backend.mock_command("CertUtil -hashfile #{filepath} SHA256", "", "", 1) Digest::SHA256.expects(:new).returns(ruby_sha256_mock) - cls.new(backend, '/tmp/testfile').sha256sum.must_equal sha256_checksum + cls.new(backend, "/tmp/testfile").sha256sum.must_equal sha256_checksum end - it 'calculates the correct sha256sum on the `windows` platform family' do + it "calculates the correct sha256sum on the `windows` platform family" do output = <<-EOC SHA256 hash of file C:\\Windows\\explorer.exe:\r 85 27 02 40 a5 fd 51 93 4f 06 27 c9 2b 22 82 74 9d 07 1f dc 9a c3 51 b8 10 39 ce d5 b1 0f 79 8b\r diff --git a/test/unit/file/remote_test.rb b/test/unit/file/remote_test.rb index 32fed0f3..281aa3b2 100644 --- a/test/unit/file/remote_test.rb +++ b/test/unit/file/remote_test.rb @@ -1,62 +1,62 @@ -require 'helper' -require 'train/file/remote' +require "helper" +require "train/file/remote" describe Train::File::Remote do - let(:cls) { Train::File::Remote } + let(:cls) { Train::File::Remote } def mockup(stubs) Class.new(cls) do - stubs.each do |k,v| + stubs.each do |k, v| define_method k.to_sym do v end end end.new(nil, nil, false) - end + end - describe 'basename helper' do + describe "basename helper" do def fc(path) mockup(type: :file, path: path) end - it 'works with an empty path' do - fc('').basename.must_equal '' + it "works with an empty path" do + fc("").basename.must_equal "" end - it 'separates a simple path (defaults to unix mode)' do - fc('/dir/file').basename.must_equal 'file' + it "separates a simple path (defaults to unix mode)" do + fc("/dir/file").basename.must_equal "file" end - it 'separates a simple path (Unix mode)' do - fc('/dir/file').basename(nil, '/').must_equal 'file' + it "separates a simple path (Unix mode)" do + fc("/dir/file").basename(nil, "/").must_equal "file" end - it 'separates a simple path (Windows mode)' do - fc('C:\dir\file').basename(nil, '\\').must_equal 'file' + it "separates a simple path (Windows mode)" do + fc('C:\dir\file').basename(nil, '\\').must_equal "file" end - it 'identifies a folder name (Unix mode)' do - fc('/dir/file/').basename(nil, '/').must_equal 'file' + it "identifies a folder name (Unix mode)" do + fc("/dir/file/").basename(nil, "/").must_equal "file" end - it 'identifies a folder name (Windows mode)' do - fc('C:\dir\file\\').basename(nil, '\\').must_equal 'file' + it "identifies a folder name (Windows mode)" do + fc('C:\dir\file\\').basename(nil, '\\').must_equal "file" end - it 'ignores tailing separators (Unix mode)' do - fc('/dir/file///').basename(nil, '/').must_equal 'file' + it "ignores tailing separators (Unix mode)" do + fc("/dir/file///").basename(nil, "/").must_equal "file" end - it 'ignores tailing separators (Windows mode)' do - fc('C:\dir\file\\\\\\').basename(nil, '\\').must_equal 'file' + it "ignores tailing separators (Windows mode)" do + fc('C:\dir\file\\\\\\').basename(nil, '\\').must_equal "file" end - it 'doesnt work with backward slashes (Unix mode)' do - fc('C:\dir\file').basename(nil, '/').must_equal 'C:\\dir\file' + it "doesnt work with backward slashes (Unix mode)" do + fc('C:\dir\file').basename(nil, "/").must_equal 'C:\\dir\file' end - it 'doesnt work with forward slashes (Windows mode)' do - fc('/dir/file').basename(nil, '\\').must_equal '/dir/file' + it "doesnt work with forward slashes (Windows mode)" do + fc("/dir/file").basename(nil, '\\').must_equal "/dir/file" end end -end \ No newline at end of file +end diff --git a/test/unit/file_test.rb b/test/unit/file_test.rb index a9a5e990..4f845aeb 100644 --- a/test/unit/file_test.rb +++ b/test/unit/file_test.rb @@ -1,12 +1,12 @@ -require 'helper' +require "helper" describe Train::File do let(:cls) { Train::File } - let(:new_cls) { cls.new(nil, '/temp/file', false) } + let(:new_cls) { cls.new(nil, "/temp/file", false) } def mockup(stubs) Class.new(cls) do - stubs.each do |k,v| + stubs.each do |k, v| define_method k.to_sym do v end @@ -14,113 +14,113 @@ def mockup(stubs) end.new(nil, nil, false) end - it 'has the default type of unknown' do + it "has the default type of unknown" do new_cls.type.must_equal :unknown end - it 'throws Not implemented error for exist?' do + it "throws Not implemented error for exist?" do # proc { Train.validate_backend({ host: rand }) }.must_raise Train::UserError - proc { new_cls.exist?}.must_raise NotImplementedError + proc { new_cls.exist? }.must_raise NotImplementedError end - it 'throws Not implemented error for mode' do + it "throws Not implemented error for mode" do proc { new_cls.mode }.must_raise NotImplementedError end - it 'throws Not implemented error for owner' do + it "throws Not implemented error for owner" do proc { new_cls.owner }.must_raise NotImplementedError end - it 'throws Not implemented error for group' do + it "throws Not implemented error for group" do proc { new_cls.group }.must_raise NotImplementedError end - it 'throws Not implemented error for uid' do + it "throws Not implemented error for uid" do proc { new_cls.uid }.must_raise NotImplementedError end - it 'throws Not implemented error for gid' do + it "throws Not implemented error for gid" do proc { new_cls.gid }.must_raise NotImplementedError end - it 'throws Not implemented error for content' do + it "throws Not implemented error for content" do proc { new_cls.content }.must_raise NotImplementedError end - it 'throws Not implemented error for mtime' do + it "throws Not implemented error for mtime" do proc { new_cls.mtime }.must_raise NotImplementedError end - it 'throws Not implemented error for size' do + it "throws Not implemented error for size" do proc { new_cls.size }.must_raise NotImplementedError end - it 'throws Not implemented error for selinux_label' do + it "throws Not implemented error for selinux_label" do proc { new_cls.selinux_label }.must_raise NotImplementedError end - it 'return path of file' do - new_cls.path.must_equal('/temp/file') + it "return path of file" do + new_cls.path.must_equal("/temp/file") end - it 'set product_version to nil' do + it "set product_version to nil" do new_cls.product_version.must_be_nil end - it 'set product_version to nil' do + it "set product_version to nil" do new_cls.file_version.must_be_nil end - describe 'type' do - it 'recognized type == file' do + describe "type" do + it "recognized type == file" do fc = mockup(type: :file) fc.file?.must_equal true end - it 'recognized type == block_device' do + it "recognized type == block_device" do fc = mockup(type: :block_device) fc.block_device?.must_equal true end - it 'recognized type == character_device' do + it "recognized type == character_device" do fc = mockup(type: :character_device) fc.character_device?.must_equal true end - it 'recognized type == socket' do + it "recognized type == socket" do fc = mockup(type: :socket) fc.socket?.must_equal true end - it 'recognized type == directory' do + it "recognized type == directory" do fc = mockup(type: :directory) fc.directory?.must_equal true end - it 'recognized type == pipe' do + it "recognized type == pipe" do fc = mockup(type: :pipe) fc.pipe?.must_equal true end - it 'recognized type == symlink' do + it "recognized type == symlink" do fc = mockup(type: :symlink) fc.symlink?.must_equal true end end - describe 'version' do - it 'recognized wrong version' do + describe "version" do + it "recognized wrong version" do fc = mockup(product_version: rand, file_version: rand) fc.version?(rand).must_equal false end - it 'recognized product_version' do + it "recognized product_version" do x = rand fc = mockup(product_version: x, file_version: rand) fc.version?(x).must_equal true end - it 'recognized file_version' do + it "recognized file_version" do x = rand fc = mockup(product_version: rand, file_version: x) fc.version?(x).must_equal true diff --git a/test/unit/platforms/detect/os_common_test.rb b/test/unit/platforms/detect/os_common_test.rb index 11c81c00..1300c3b8 100644 --- a/test/unit/platforms/detect/os_common_test.rb +++ b/test/unit/platforms/detect/os_common_test.rb @@ -1,6 +1,6 @@ # encoding: utf-8 -require 'helper' +require "helper" class OsDetectLinuxTester attr_reader :platform @@ -11,85 +11,85 @@ def initialize end end -describe 'os_common' do +describe "os_common" do let(:detector) { OsDetectLinuxTester.new } - describe 'winrm? check' do - it 'return winrm? true' do - require 'train/transports/winrm' + describe "winrm? check" do + it "return winrm? true" do + require "train/transports/winrm" be = Train::Transports::WinRM::Connection.new(nil) detector.instance_variable_set(:@backend, be) detector.winrm?.must_equal(true) end - it 'return winrm? false when winrm is loaded' do - require 'train/transports/winrm' - be = mock('Backend') + it "return winrm? false when winrm is loaded" do + require "train/transports/winrm" + be = mock("Backend") detector.instance_variable_set(:@backend, be) detector.winrm?.must_equal(false) end - it 'return winrm? false when winrm is not loaded' do - require 'train/transports/winrm' - winrm = Train::Transports.send(:remove_const, 'WinRM') - be = mock('Backend') + it "return winrm? false when winrm is not loaded" do + require "train/transports/winrm" + winrm = Train::Transports.send(:remove_const, "WinRM") + be = mock("Backend") detector.instance_variable_set(:@backend, be) detector.winrm?.must_equal(false) - Train::Transports.const_set('WinRM', winrm) + Train::Transports.const_set("WinRM", winrm) end end - describe 'unix file contents' do - it 'return new file contents' do - be = mock('Backend') - output = mock('Output', exit_status: 0) - output.expects(:stdout).returns('test') - be.stubs(:run_command).with('test -f /etc/fstab && cat /etc/fstab').returns(output) + describe "unix file contents" do + it "return new file contents" do + be = mock("Backend") + output = mock("Output", exit_status: 0) + output.expects(:stdout).returns("test") + be.stubs(:run_command).with("test -f /etc/fstab && cat /etc/fstab").returns(output) detector.instance_variable_set(:@backend, be) detector.instance_variable_set(:@files, {}) - detector.unix_file_contents('/etc/fstab').must_equal('test') + detector.unix_file_contents("/etc/fstab").must_equal("test") end - it 'return new file contents cached' do - be = mock('Backend') + it "return new file contents cached" do + be = mock("Backend") detector.instance_variable_set(:@backend, be) - detector.instance_variable_set(:@files, { '/etc/profile' => 'test' }) - detector.unix_file_contents('/etc/profile').must_equal('test') + detector.instance_variable_set(:@files, { "/etc/profile" => "test" }) + detector.unix_file_contents("/etc/profile").must_equal("test") end end - describe 'unix file exist?' do - it 'file does exist' do - be = mock('Backend') - be.stubs(:run_command).with('test -f /etc/test').returns(mock('Output', exit_status: 0)) + describe "unix file exist?" do + it "file does exist" do + be = mock("Backend") + be.stubs(:run_command).with("test -f /etc/test").returns(mock("Output", exit_status: 0)) detector.instance_variable_set(:@backend, be) - detector.unix_file_exist?('/etc/test').must_equal(true) + detector.unix_file_exist?("/etc/test").must_equal(true) end end - describe '#detect_linux_arch' do - it 'uname m call' do - be = mock('Backend') - be.stubs(:run_command).with('uname -m').returns(mock('Output', stdout: "x86_64\n")) + describe "#detect_linux_arch" do + it "uname m call" do + be = mock("Backend") + be.stubs(:run_command).with("uname -m").returns(mock("Output", stdout: "x86_64\n")) detector.instance_variable_set(:@backend, be) detector.instance_variable_set(:@uname, {}) - detector.unix_uname_m.must_equal('x86_64') + detector.unix_uname_m.must_equal("x86_64") end - it 'uname s call' do - be = mock('Backend') - be.stubs(:run_command).with('uname -s').returns(mock('Output', stdout: "linux")) + it "uname s call" do + be = mock("Backend") + be.stubs(:run_command).with("uname -s").returns(mock("Output", stdout: "linux")) detector.instance_variable_set(:@backend, be) detector.instance_variable_set(:@uname, {}) - detector.unix_uname_s.must_equal('linux') + detector.unix_uname_s.must_equal("linux") end - it 'uname r call' do - be = mock('Backend') - be.stubs(:run_command).with('uname -r').returns(mock('Output', stdout: "17.0.0\n")) + it "uname r call" do + be = mock("Backend") + be.stubs(:run_command).with("uname -r").returns(mock("Output", stdout: "17.0.0\n")) detector.instance_variable_set(:@backend, be) detector.instance_variable_set(:@uname, {}) - detector.unix_uname_r.must_equal('17.0.0') + detector.unix_uname_r.must_equal("17.0.0") end end end diff --git a/test/unit/platforms/detect/os_linux_test.rb b/test/unit/platforms/detect/os_linux_test.rb index 4b358612..490ed492 100644 --- a/test/unit/platforms/detect/os_linux_test.rb +++ b/test/unit/platforms/detect/os_linux_test.rb @@ -1,131 +1,131 @@ # encoding: utf-8 -require 'helper' -require 'train/transports/mock' +require "helper" +require "train/transports/mock" class OsDetectLinuxTester include Train::Platforms::Detect::Helpers::OSCommon end -describe 'os_linux' do +describe "os_linux" do let(:detector) { OsDetectLinuxTester.new } - describe 'redhatish_platform cleaner' do - it 'normal redhat' do - detector.redhatish_platform('Red Hattter').must_equal('redhat') + describe "redhatish_platform cleaner" do + it "normal redhat" do + detector.redhatish_platform("Red Hattter").must_equal("redhat") end - it 'custom redhat' do - detector.redhatish_platform('Centos Pro 11').must_equal('centos') + it "custom redhat" do + detector.redhatish_platform("Centos Pro 11").must_equal("centos") end end - describe 'redhatish_version cleaner' do - it 'normal rawhide' do - detector.redhatish_version('18 (Rawhide) Pro').must_equal('18 (rawhide)') + describe "redhatish_version cleaner" do + it "normal rawhide" do + detector.redhatish_version("18 (Rawhide) Pro").must_equal("18 (rawhide)") end - it 'normal linux' do - detector.redhatish_version('derived from Ubuntu Linux 11').must_equal('11') + it "normal linux" do + detector.redhatish_version("derived from Ubuntu Linux 11").must_equal("11") end - it 'amazon linux 2 new release naming schema' do - detector.redhatish_version('Amazon Linux release 2 (Karoo)').must_equal('2') + it "amazon linux 2 new release naming schema" do + detector.redhatish_version("Amazon Linux release 2 (Karoo)").must_equal("2") end - it 'amazon linux 2 old release naming schema' do - detector.redhatish_version('Amazon Linux 2').must_equal('2') + it "amazon linux 2 old release naming schema" do + detector.redhatish_version("Amazon Linux 2").must_equal("2") end end - describe 'lsb parse' do - it 'lsb config' do + describe "lsb parse" do + it "lsb config" do lsb = "DISTRIB_ID=Ubuntu\nDISTRIB_RELEASE=14.06\nDISTRIB_CODENAME=xenial" - expect = { :id=>'Ubuntu', :release=>'14.06', :codename=>'xenial' } + expect = { id: "Ubuntu", release: "14.06", codename: "xenial" } detector.lsb_config(lsb).must_equal(expect) end - it 'lsb releasel' do + it "lsb releasel" do lsb = "Distributor ID: Ubuntu\nRelease: 14.06\nCodename: xenial" - expect = { :id=>'Ubuntu', :release=>'14.06', :codename=>'xenial' } + expect = { id: "Ubuntu", release: "14.06", codename: "xenial" } detector.lsb_release(lsb).must_equal(expect) end end - describe '#linux_os_release' do - describe 'when no os-release data is available' do - it 'returns nil' do - detector.expects(:unix_file_contents).with('/etc/os-release').returns(nil) + describe "#linux_os_release" do + describe "when no os-release data is available" do + it "returns nil" do + detector.expects(:unix_file_contents).with("/etc/os-release").returns(nil) detector.linux_os_release.must_be_nil end end end - describe 'when os-release data exists with no CISCO_RELEASE_INFO' do - let(:os_release) { { 'KEY1' => 'VALUE1' } } + describe "when os-release data exists with no CISCO_RELEASE_INFO" do + let(:os_release) { { "KEY1" => "VALUE1" } } - it 'returns a correct hash' do - detector.expects(:unix_file_contents).with('/etc/os-release').returns('os-release data') - detector.expects(:parse_os_release_info).with('os-release data').returns(os_release) - detector.linux_os_release['KEY1'].must_equal('VALUE1') + it "returns a correct hash" do + detector.expects(:unix_file_contents).with("/etc/os-release").returns("os-release data") + detector.expects(:parse_os_release_info).with("os-release data").returns(os_release) + detector.linux_os_release["KEY1"].must_equal("VALUE1") end end - describe 'when os-release data exists with CISCO_RELEASE_INFO' do - let(:os_release) { { 'KEY1' => 'VALUE1', 'CISCO_RELEASE_INFO' => 'cisco_file' } } - let(:cisco_release) { { 'KEY1' => 'NEWVALUE1', 'KEY2' => 'VALUE2' } } + describe "when os-release data exists with CISCO_RELEASE_INFO" do + let(:os_release) { { "KEY1" => "VALUE1", "CISCO_RELEASE_INFO" => "cisco_file" } } + let(:cisco_release) { { "KEY1" => "NEWVALUE1", "KEY2" => "VALUE2" } } - it 'returns a correct hash' do - detector.expects(:unix_file_contents).with('/etc/os-release').returns('os-release data') - detector.expects(:unix_file_contents).with('cisco_file').returns('cisco data') - detector.expects(:parse_os_release_info).with('os-release data').returns(os_release) - detector.expects(:parse_os_release_info).with('cisco data').returns(cisco_release) + it "returns a correct hash" do + detector.expects(:unix_file_contents).with("/etc/os-release").returns("os-release data") + detector.expects(:unix_file_contents).with("cisco_file").returns("cisco data") + detector.expects(:parse_os_release_info).with("os-release data").returns(os_release) + detector.expects(:parse_os_release_info).with("cisco data").returns(cisco_release) os_info = detector.linux_os_release - os_info['KEY1'].must_equal('NEWVALUE1') - os_info['KEY2'].must_equal('VALUE2') + os_info["KEY1"].must_equal("NEWVALUE1") + os_info["KEY2"].must_equal("VALUE2") end end - describe '#parse_os_release_info' do - describe 'when nil is supplied' do - it 'returns an empty hash' do + describe "#parse_os_release_info" do + describe "when nil is supplied" do + it "returns an empty hash" do detector.parse_os_release_info(nil).must_equal({}) end end - describe 'when unexpectedly-formatted data is supplied' do + describe "when unexpectedly-formatted data is supplied" do let(:data) do - <<-EOL -blah blah -no good data here + <<~EOL + blah blah + no good data here EOL end - it 'returns an empty hash' do + it "returns an empty hash" do detector.parse_os_release_info(nil).must_equal({}) end end - describe 'when properly-formatted data is supplied' do + describe "when properly-formatted data is supplied" do let(:data) do - <<-EOL -KEY1=value1 -KEY2= -KEY3=value3 -KEY4="value4 with spaces" -KEY5="value5 with a = sign" + <<~EOL + KEY1=value1 + KEY2= + KEY3=value3 + KEY4="value4 with spaces" + KEY5="value5 with a = sign" EOL end - it 'parses the data correctly' do + it "parses the data correctly" do parsed_data = detector.parse_os_release_info(data) - parsed_data['KEY1'].must_equal('value1') - parsed_data.key?('KEY2').must_equal(false) - parsed_data['KEY3'].must_equal('value3') - parsed_data['KEY4'].must_equal('value4 with spaces') - parsed_data['KEY5'].must_equal('value5 with a = sign') + parsed_data["KEY1"].must_equal("value1") + parsed_data.key?("KEY2").must_equal(false) + parsed_data["KEY3"].must_equal("value3") + parsed_data["KEY4"].must_equal("value4 with spaces") + parsed_data["KEY5"].must_equal("value5 with a = sign") end end end diff --git a/test/unit/platforms/detect/os_windows_test.rb b/test/unit/platforms/detect/os_windows_test.rb index f182b0b4..7d237ab3 100644 --- a/test/unit/platforms/detect/os_windows_test.rb +++ b/test/unit/platforms/detect/os_windows_test.rb @@ -1,7 +1,7 @@ # encoding: utf-8 -require 'helper' -require 'train/transports/mock' +require "helper" +require "train/transports/mock" class OsDetectWindowsTester attr_reader :platform, :backend @@ -10,98 +10,98 @@ class OsDetectWindowsTester def initialize @platform = {} @backend = Train::Transports::Mock.new.connection - @backend.mock_os({ family: 'windows' }) + @backend.mock_os({ family: "windows" }) end end -describe 'os_detect_windows' do - describe 'windows 2012' do - let(:detector) { +describe "os_detect_windows" do + describe "windows 2012" do + let(:detector) do detector = OsDetectWindowsTester.new - detector.backend.mock_command('cmd.exe /c ver', "\r\nMicrosoft Windows [Version 6.3.9600]\r\n", '', 0) - detector.backend.mock_command('wmic os get * /format:list',"\r\r\nBuildNumber=9600\r\r\nCaption=Microsoft Windows Server 2012 R2 Standard\r\r\nOSArchitecture=64-bit\r\r\nVersion=6.3.9600\r\r\n" , '', 0) - detector.backend.mock_command('wmic cpu get architecture /format:list',"\r\r\nArchitecture=9\r\r\n" , '', 0) + detector.backend.mock_command("cmd.exe /c ver", "\r\nMicrosoft Windows [Version 6.3.9600]\r\n", "", 0) + detector.backend.mock_command("wmic os get * /format:list", "\r\r\nBuildNumber=9600\r\r\nCaption=Microsoft Windows Server 2012 R2 Standard\r\r\nOSArchitecture=64-bit\r\r\nVersion=6.3.9600\r\r\n" , "", 0) + detector.backend.mock_command("wmic cpu get architecture /format:list", "\r\r\nArchitecture=9\r\r\n" , "", 0) detector - } + end - it 'sets the correct family/release for windows' do + it "sets the correct family/release for windows" do detector.detect_windows - detector.platform[:family].must_equal('windows') - detector.platform[:name].must_equal('Windows Server 2012 R2 Standard') - detector.platform[:arch].must_equal('x86_64') - detector.platform[:release].must_equal('6.3.9600') + detector.platform[:family].must_equal("windows") + detector.platform[:name].must_equal("Windows Server 2012 R2 Standard") + detector.platform[:arch].must_equal("x86_64") + detector.platform[:release].must_equal("6.3.9600") end end - describe 'windows 2008' do - let(:detector) { + describe "windows 2008" do + let(:detector) do detector = OsDetectWindowsTester.new - detector.backend.mock_command('cmd.exe /c ver', "\r\nMicrosoft Windows [Version 6.1.7601]\r\n", '', 0) - detector.backend.mock_command('wmic os get * /format:list',"\r\r\nBuildNumber=7601\r\r\nCaption=Microsoft Windows Server 2008 R2 Standard \r\r\nOSArchitecture=64-bit\r\r\nVersion=6.1.7601\r\r\n" , '', 0) - detector.backend.mock_command('wmic cpu get architecture /format:list',"\r\r\nArchitecture=9\r\r\n" , '', 0) + detector.backend.mock_command("cmd.exe /c ver", "\r\nMicrosoft Windows [Version 6.1.7601]\r\n", "", 0) + detector.backend.mock_command("wmic os get * /format:list", "\r\r\nBuildNumber=7601\r\r\nCaption=Microsoft Windows Server 2008 R2 Standard \r\r\nOSArchitecture=64-bit\r\r\nVersion=6.1.7601\r\r\n" , "", 0) + detector.backend.mock_command("wmic cpu get architecture /format:list", "\r\r\nArchitecture=9\r\r\n" , "", 0) detector - } + end - it 'sets the correct family/release for windows' do + it "sets the correct family/release for windows" do detector.detect_windows - detector.platform[:family].must_equal('windows') - detector.platform[:name].must_equal('Windows Server 2008 R2 Standard') - detector.platform[:arch].must_equal('x86_64') - detector.platform[:release].must_equal('6.1.7601') + detector.platform[:family].must_equal("windows") + detector.platform[:name].must_equal("Windows Server 2008 R2 Standard") + detector.platform[:arch].must_equal("x86_64") + detector.platform[:release].must_equal("6.1.7601") end end - describe 'windows 7' do - let(:detector) { + describe "windows 7" do + let(:detector) do detector = OsDetectWindowsTester.new - detector.backend.mock_command('cmd.exe /c ver', "\r\nMicrosoft Windows [Version 6.1.7601]\r\n", '', 0) - detector.backend.mock_command('wmic os get * /format:list',"\r\r\nBuildNumber=7601\r\r\nCaption=Microsoft Windows 7 Enterprise \r\r\nOSArchitecture=32-bit\r\r\nVersion=6.1.7601\r\r\n\r\r\n" , '', 0) - detector.backend.mock_command('wmic cpu get architecture /format:list',"\r\r\nArchitecture=0\r\r\n" , '', 0) + detector.backend.mock_command("cmd.exe /c ver", "\r\nMicrosoft Windows [Version 6.1.7601]\r\n", "", 0) + detector.backend.mock_command("wmic os get * /format:list", "\r\r\nBuildNumber=7601\r\r\nCaption=Microsoft Windows 7 Enterprise \r\r\nOSArchitecture=32-bit\r\r\nVersion=6.1.7601\r\r\n\r\r\n" , "", 0) + detector.backend.mock_command("wmic cpu get architecture /format:list", "\r\r\nArchitecture=0\r\r\n" , "", 0) detector - } + end - it 'sets the correct family/release for windows' do + it "sets the correct family/release for windows" do detector.detect_windows - detector.platform[:family].must_equal('windows') - detector.platform[:name].must_equal('Windows 7 Enterprise') - detector.platform[:arch].must_equal('i386') - detector.platform[:release].must_equal('6.1.7601') + detector.platform[:family].must_equal("windows") + detector.platform[:name].must_equal("Windows 7 Enterprise") + detector.platform[:arch].must_equal("i386") + detector.platform[:release].must_equal("6.1.7601") end end - describe 'windows 10' do - let(:detector) { + describe "windows 10" do + let(:detector) do detector = OsDetectWindowsTester.new - detector.backend.mock_command('cmd.exe /c ver', "\r\nMicrosoft Windows [Version 10.0.10240]\r\n", '', 0) - detector.backend.mock_command('wmic os get * /format:list',"\r\r\nBuildNumber=10240\r\r\nCaption=Microsoft Windows 10 Pro\r\r\nOSArchitecture=64-bit\r\r\nVersion=10.0.10240\r\r\n\r\r\n" , '', 0) - detector.backend.mock_command('wmic cpu get architecture /format:list',"\r\r\nArchitecture=9\r\r\n" , '', 0) + detector.backend.mock_command("cmd.exe /c ver", "\r\nMicrosoft Windows [Version 10.0.10240]\r\n", "", 0) + detector.backend.mock_command("wmic os get * /format:list", "\r\r\nBuildNumber=10240\r\r\nCaption=Microsoft Windows 10 Pro\r\r\nOSArchitecture=64-bit\r\r\nVersion=10.0.10240\r\r\n\r\r\n" , "", 0) + detector.backend.mock_command("wmic cpu get architecture /format:list", "\r\r\nArchitecture=9\r\r\n" , "", 0) detector - } + end - it 'sets the correct family/release for windows' do + it "sets the correct family/release for windows" do detector.detect_windows - detector.platform[:family].must_equal('windows') - detector.platform[:name].must_equal('Windows 10 Pro') - detector.platform[:arch].must_equal('x86_64') - detector.platform[:release].must_equal('10.0.10240') + detector.platform[:family].must_equal("windows") + detector.platform[:name].must_equal("Windows 10 Pro") + detector.platform[:arch].must_equal("x86_64") + detector.platform[:release].must_equal("10.0.10240") end end - describe 'windows 98' do - let(:detector) { + describe "windows 98" do + let(:detector) do detector = OsDetectWindowsTester.new - detector.backend.mock_command('cmd.exe /c ver', "\r\nMicrosoft Windows [Version 4.10.1998]\r\n", '', 0) - detector.backend.mock_command('wmic os get * /format:list', nil, '', 1) - detector.backend.mock_command('wmic cpu get architecture /format:list', nil, '', 1) + detector.backend.mock_command("cmd.exe /c ver", "\r\nMicrosoft Windows [Version 4.10.1998]\r\n", "", 0) + detector.backend.mock_command("wmic os get * /format:list", nil, "", 1) + detector.backend.mock_command("wmic cpu get architecture /format:list", nil, "", 1) detector - } + end - it 'fallback to version number if wmic is not available' do + it "fallback to version number if wmic is not available" do detector.detect_windows - detector.platform[:family].must_equal('windows') - detector.platform[:name].must_equal('Windows 4.10.1998') + detector.platform[:family].must_equal("windows") + detector.platform[:name].must_equal("Windows 4.10.1998") detector.platform[:arch].must_be_nil - detector.platform[:release].must_equal('4.10.1998') + detector.platform[:release].must_equal("4.10.1998") end end end diff --git a/test/unit/platforms/detect/scanner_test.rb b/test/unit/platforms/detect/scanner_test.rb index 6c6b29bc..7a593843 100644 --- a/test/unit/platforms/detect/scanner_test.rb +++ b/test/unit/platforms/detect/scanner_test.rb @@ -1,61 +1,61 @@ # encoding: utf-8 -require 'helper' -require 'train/platforms/detect/scanner' -require 'train/transports/mock' +require "helper" +require "train/platforms/detect/scanner" +require "train/transports/mock" -describe 'scanner' do +describe "scanner" do let(:backend) { Train::Transports::Mock::Connection.new } let(:scanner) { Train::Platforms::Detect::Scanner.new(backend) } - describe 'scan family children' do - it 'return child' do - family = Train::Platforms.family('linux') - scanner.scan_family_children(family).name.must_equal('linux') - scanner.instance_variable_get(:@family_hierarchy).must_equal(['linux']) + describe "scan family children" do + it "return child" do + family = Train::Platforms.family("linux") + scanner.scan_family_children(family).name.must_equal("linux") + scanner.instance_variable_get(:@family_hierarchy).must_equal(["linux"]) end - it 'return nil' do - family = Train::Platforms.family('fake-fam') + it "return nil" do + family = Train::Platforms.family("fake-fam") scanner.scan_family_children(family).must_be_nil scanner.instance_variable_get(:@family_hierarchy).must_be_empty end end - describe 'check condition' do - it 'return true equal' do - scanner.instance_variable_set(:@platform, { arch: 'x86_64' }) - scanner.check_condition({ arch: '= x86_64' }).must_equal(true) + describe "check condition" do + it "return true equal" do + scanner.instance_variable_set(:@platform, { arch: "x86_64" }) + scanner.check_condition({ arch: "= x86_64" }).must_equal(true) end - it 'return true greater then' do - scanner.instance_variable_set(:@platform, { release: '8.2' }) - scanner.check_condition({ release: '>= 7' }).must_equal(true) + it "return true greater then" do + scanner.instance_variable_set(:@platform, { release: "8.2" }) + scanner.check_condition({ release: ">= 7" }).must_equal(true) end - it 'return false greater then' do - scanner.instance_variable_set(:@platform, { release: '2.2' }) - scanner.check_condition({ release: '> 7' }).must_equal(false) + it "return false greater then" do + scanner.instance_variable_set(:@platform, { release: "2.2" }) + scanner.check_condition({ release: "> 7" }).must_equal(false) end end - describe 'get platform' do - it 'return empty platform' do - plat = Train::Platforms.name('linux') + describe "get platform" do + it "return empty platform" do + plat = Train::Platforms.name("linux") plat = scanner.get_platform(plat) plat.platform.must_equal({}) plat.backend.must_equal(backend) plat.family_hierarchy.must_equal([]) end - it 'return full platform' do - scanner.instance_variable_set(:@platform, { family: 'linux' }) - scanner.instance_variable_set(:@family_hierarchy, [ 'linux', 'unix' ]) - plat = Train::Platforms.name('linux') + it "return full platform" do + scanner.instance_variable_set(:@platform, { family: "linux" }) + scanner.instance_variable_set(:@family_hierarchy, %w{linux unix}) + plat = Train::Platforms.name("linux") plat = scanner.get_platform(plat) - plat.platform.must_equal({ family: 'linux' }) + plat.platform.must_equal({ family: "linux" }) plat.backend.must_equal(backend) - plat.family_hierarchy.must_equal([ 'linux', 'unix' ]) + plat.family_hierarchy.must_equal(%w{linux unix}) end end end diff --git a/test/unit/platforms/detect/uuid_test.rb b/test/unit/platforms/detect/uuid_test.rb index 432a60f0..51490ad8 100644 --- a/test/unit/platforms/detect/uuid_test.rb +++ b/test/unit/platforms/detect/uuid_test.rb @@ -1,8 +1,8 @@ # encoding: utf-8 -require 'helper' -require 'train/transports/mock' -require 'securerandom' +require "helper" +require "train/transports/mock" +require "securerandom" class TestFile def initialize(string) @@ -22,7 +22,7 @@ def content end end -describe 'uuid' do +describe "uuid" do def mock_platform(name, commands = {}, files = {}, plat_options = {}) Train::Platforms.list[name] = nil mock = Train::Transports::Mock::Connection.new @@ -39,95 +39,95 @@ def mock_platform(name, commands = {}, files = {}, plat_options = {}) mock.force_platform!(name, plat_options) end - it 'finds a linux uuid from chef entity_uuid' do - files = { '/var/chef/cache/data_collector_metadata.json' => '{"node_uuid":"d400073f-0920-41aa-8dd3-2ea59b18f5ce"}' } - plat = mock_platform('linux', {}, files) - plat.uuid.must_equal 'd400073f-0920-41aa-8dd3-2ea59b18f5ce' + it "finds a linux uuid from chef entity_uuid" do + files = { "/var/chef/cache/data_collector_metadata.json" => '{"node_uuid":"d400073f-0920-41aa-8dd3-2ea59b18f5ce"}' } + plat = mock_platform("linux", {}, files) + plat.uuid.must_equal "d400073f-0920-41aa-8dd3-2ea59b18f5ce" end - it 'finds a windows uuid from chef entity_uuid' do - ENV['SYSTEMDRIVE'] = 'C:' + it "finds a windows uuid from chef entity_uuid" do + ENV["SYSTEMDRIVE"] = "C:" files = { 'C:\chef\cache\data_collector_metadata.json' => '{"node_uuid":"d400073f-0920-41aa-8dd3-2ea59b18f5ce"}' } - plat = mock_platform('windows', {}, files) - plat.uuid.must_equal 'd400073f-0920-41aa-8dd3-2ea59b18f5ce' + plat = mock_platform("windows", {}, files) + plat.uuid.must_equal "d400073f-0920-41aa-8dd3-2ea59b18f5ce" end - it 'finds a linux uuid from /etc/chef/chef_guid' do - files = { '/etc/chef/chef_guid' => '5e430326-b5aa-56f8-975f-c3ca1c21df91' } - plat = mock_platform('linux', {}, files) - plat.uuid.must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91' + it "finds a linux uuid from /etc/chef/chef_guid" do + files = { "/etc/chef/chef_guid" => "5e430326-b5aa-56f8-975f-c3ca1c21df91" } + plat = mock_platform("linux", {}, files) + plat.uuid.must_equal "5e430326-b5aa-56f8-975f-c3ca1c21df91" end - it 'finds a linux uuid from /home/testuser/.chef/chef_guid' do - ENV['HOME'] = '/home/testuser' - files = { '/home/testuser/.chef/chef_guid' => '5e430326-b5aa-56f8-975f-c3ca1c21df91' } - plat = mock_platform('linux', {}, files) - plat.uuid.must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91' + it "finds a linux uuid from /home/testuser/.chef/chef_guid" do + ENV["HOME"] = "/home/testuser" + files = { "/home/testuser/.chef/chef_guid" => "5e430326-b5aa-56f8-975f-c3ca1c21df91" } + plat = mock_platform("linux", {}, files) + plat.uuid.must_equal "5e430326-b5aa-56f8-975f-c3ca1c21df91" end - it 'finds a linux uuid from /etc/machine-id' do - files = { '/etc/machine-id' => '123141dsfadf' } - plat = mock_platform('linux', {}, files) - plat.uuid.must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91' + it "finds a linux uuid from /etc/machine-id" do + files = { "/etc/machine-id" => "123141dsfadf" } + plat = mock_platform("linux", {}, files) + plat.uuid.must_equal "5e430326-b5aa-56f8-975f-c3ca1c21df91" end - it 'finds a linux uuid from /var/lib/dbus/machine-id' do + it "finds a linux uuid from /var/lib/dbus/machine-id" do files = { - '/etc/machine-id' => '', - '/var/lib/dbus/machine-id' => '123141dsfadf', + "/etc/machine-id" => "", + "/var/lib/dbus/machine-id" => "123141dsfadf", } - plat = mock_platform('linux', {}, files) - plat.uuid.must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91' + plat = mock_platform("linux", {}, files) + plat.uuid.must_equal "5e430326-b5aa-56f8-975f-c3ca1c21df91" end - it 'finds a linux uuid from /etc/machine-id' do - files = { '/etc/machine-id' => '123141dsfadf' } - plat = mock_platform('linux', {}, files) - plat.uuid.must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91' + it "finds a linux uuid from /etc/machine-id" do + files = { "/etc/machine-id" => "123141dsfadf" } + plat = mock_platform("linux", {}, files) + plat.uuid.must_equal "5e430326-b5aa-56f8-975f-c3ca1c21df91" end - it 'finds a windows uuid from wmic' do - commands = { 'wmic csproduct get UUID' => "UUID\r\nd400073f-0920-41aa-8dd3-2ea59b18f5ce\r\n" } - plat = mock_platform('windows', commands) - plat.uuid.must_equal 'd400073f-0920-41aa-8dd3-2ea59b18f5ce' + it "finds a windows uuid from wmic" do + commands = { "wmic csproduct get UUID" => "UUID\r\nd400073f-0920-41aa-8dd3-2ea59b18f5ce\r\n" } + plat = mock_platform("windows", commands) + plat.uuid.must_equal "d400073f-0920-41aa-8dd3-2ea59b18f5ce" end - it 'finds a windows uuid from registry' do + it "finds a windows uuid from registry" do commands = { '(Get-ItemProperty "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography" -Name "MachineGuid")."MachineGuid"' => "d400073f-0920-41aa-8dd3-2ea59b18f5ce\r\n" } - plat = mock_platform('windows', commands) - plat.uuid.must_equal 'd400073f-0920-41aa-8dd3-2ea59b18f5ce' + plat = mock_platform("windows", commands) + plat.uuid.must_equal "d400073f-0920-41aa-8dd3-2ea59b18f5ce" end it 'finds a windows uuid from C:\chef\chef_guid' do - ENV['SYSTEMDRIVE'] = 'C:' - files = { 'C:\chef\chef_guid' => '5e430326-b5aa-56f8-975f-c3ca1c21df91' } - plat = mock_platform('windows', {}, files) - plat.uuid.must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91' + ENV["SYSTEMDRIVE"] = "C:" + files = { 'C:\chef\chef_guid' => "5e430326-b5aa-56f8-975f-c3ca1c21df91" } + plat = mock_platform("windows", {}, files) + plat.uuid.must_equal "5e430326-b5aa-56f8-975f-c3ca1c21df91" end it 'finds a windows uuid from C:\Users\test\.chef\chef_guid' do - ENV['HOMEDRIVE'] = 'C:\\' - ENV['HOMEPATH'] = 'Users\test' - files = { 'C:\Users\test\.chef\chef_guid' => '5e430326-b5aa-56f8-975f-c3ca1c21df91' } - plat = mock_platform('windows', {}, files) - plat.uuid.must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91' + ENV["HOMEDRIVE"] = 'C:\\' + ENV["HOMEPATH"] = 'Users\test' + files = { 'C:\Users\test\.chef\chef_guid' => "5e430326-b5aa-56f8-975f-c3ca1c21df91" } + plat = mock_platform("windows", {}, files) + plat.uuid.must_equal "5e430326-b5aa-56f8-975f-c3ca1c21df91" end - it 'generates a uuid from a string' do - plat = mock_platform('linux') + it "generates a uuid from a string" do + plat = mock_platform("linux") uuid = Train::Platforms::Detect::UUID.new(plat) - uuid.uuid_from_string('123141dsfadf').must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91' + uuid.uuid_from_string("123141dsfadf").must_equal "5e430326-b5aa-56f8-975f-c3ca1c21df91" end - it 'finds a aws uuid' do - plat = mock_platform('aws') - plat.backend.stubs(:unique_identifier).returns('158551926027') - plat.uuid.must_equal '1d74ce61-ac15-5c48-9ee3-5aa8207ac37f' + it "finds a aws uuid" do + plat = mock_platform("aws") + plat.backend.stubs(:unique_identifier).returns("158551926027") + plat.uuid.must_equal "1d74ce61-ac15-5c48-9ee3-5aa8207ac37f" end - it 'finds an azure uuid' do - plat = mock_platform('azure') - plat.backend.stubs(:unique_identifier).returns('1d74ce61-ac15-5c48-9ee3-5aa8207ac37f') - plat.uuid.must_equal '2c2e4fa9-7287-5dee-85a3-6527face7b7b' + it "finds an azure uuid" do + plat = mock_platform("azure") + plat.backend.stubs(:unique_identifier).returns("1d74ce61-ac15-5c48-9ee3-5aa8207ac37f") + plat.uuid.must_equal "2c2e4fa9-7287-5dee-85a3-6527face7b7b" end end diff --git a/test/unit/platforms/family_test.rb b/test/unit/platforms/family_test.rb index 4b81a3bb..f8dd2ff6 100644 --- a/test/unit/platforms/family_test.rb +++ b/test/unit/platforms/family_test.rb @@ -1,32 +1,32 @@ # encoding: utf-8 -require 'helper' +require "helper" -describe 'platform family' do +describe "platform family" do def mock_family(x) - Train::Platforms.families[x] = nil if x == 'mock' + Train::Platforms.families[x] = nil if x == "mock" Train::Platforms.family(x) end - it 'set family title' do - plat = mock_family('mock') - plat.title.must_equal('Mock Family') - plat.title('The Best Mock Family') - plat.title.must_equal('The Best Mock Family') + it "set family title" do + plat = mock_family("mock") + plat.title.must_equal("Mock Family") + plat.title("The Best Mock Family") + plat.title.must_equal("The Best Mock Family") end - it 'set family in a family' do - plat = mock_family('family1') - plat.in_family('family2') - plat.families.keys[0].name.must_equal('family2') + it "set family in a family" do + plat = mock_family("family1") + plat.in_family("family2") + plat.families.keys[0].name.must_equal("family2") - plat = mock_family('family2') - plat.children.keys[0].name.must_equal('family1') + plat = mock_family("family2") + plat.children.keys[0].name.must_equal("family1") end - it 'set family in a family with condition' do - plat = Train::Platforms.family('family4', arch: '= x68_64').in_family('family5') - plat.families.keys[0].name.must_equal('family5') - plat.families.values[0].must_equal({ arch: '= x68_64' }) + it "set family in a family with condition" do + plat = Train::Platforms.family("family4", arch: "= x68_64").in_family("family5") + plat.families.keys[0].name.must_equal("family5") + plat.families.values[0].must_equal({ arch: "= x68_64" }) end end diff --git a/test/unit/platforms/os_detect_test.rb b/test/unit/platforms/os_detect_test.rb index 0c3f1a0b..caa92bc8 100644 --- a/test/unit/platforms/os_detect_test.rb +++ b/test/unit/platforms/os_detect_test.rb @@ -1,18 +1,18 @@ # encoding: utf-8 -require 'helper' -require 'train/transports/mock' +require "helper" +require "train/transports/mock" class OsDetectTester include Train::Platforms::Detect::Helpers::OSCommon end -describe 'os_detect' do +describe "os_detect" do let(:detector) { OsDetectTester.new } def scan_with_files(uname, files) mock = Train::Transports::Mock::Connection.new - mock.mock_command('uname -s', uname) - mock.mock_command('uname -r', 'test-release') + mock.mock_command("uname -s", uname) + mock.mock_command("uname -r", "test-release") files.each do |path, data| mock.mock_command("test -f #{path}") mock.mock_command("test -f #{path} && cat #{path}", data) @@ -20,256 +20,256 @@ def scan_with_files(uname, files) Train::Platforms::Detect.scan(mock) end - def scan_with_windows() + def scan_with_windows mock = Train::Transports::Mock::Connection.new - mock.mock_command('cmd.exe /c ver', 'Microsoft Windows [Version 6.3.9600]') + mock.mock_command("cmd.exe /c ver", "Microsoft Windows [Version 6.3.9600]") Train::Platforms::Detect.scan(mock) end ## Detect all linux distros - describe '/etc/enterprise-release' do - it 'sets the correct family/release for oracle' do - path = '/etc/enterprise-release' - platform = scan_with_files('linux', { path => 'release 7' }) - - platform[:name].must_equal('oracle') - platform[:family].must_equal('redhat') - platform[:release].must_equal('7') + describe "/etc/enterprise-release" do + it "sets the correct family/release for oracle" do + path = "/etc/enterprise-release" + platform = scan_with_files("linux", { path => "release 7" }) + + platform[:name].must_equal("oracle") + platform[:family].must_equal("redhat") + platform[:release].must_equal("7") end end - describe '/etc/redhat-release' do - describe 'and /etc/os-release' do - it 'sets the correct family, name, and release on centos' do + describe "/etc/redhat-release" do + describe "and /etc/os-release" do + it "sets the correct family, name, and release on centos" do files = { - '/etc/redhat-release' => "CentOS Linux release 7.2.1511 (Core) \n", - '/etc/os-release' => "NAME=\"CentOS Linux\"\nVERSION=\"7 (Core)\"\nID=\"centos\"\nID_LIKE=\"rhel fedora\"\n", + "/etc/redhat-release" => "CentOS Linux release 7.2.1511 (Core) \n", + "/etc/os-release" => "NAME=\"CentOS Linux\"\nVERSION=\"7 (Core)\"\nID=\"centos\"\nID_LIKE=\"rhel fedora\"\n", } - platform = scan_with_files('linux', files) - platform[:name].must_equal('centos') - platform[:family].must_equal('redhat') - platform[:release].must_equal('7.2.1511') + platform = scan_with_files("linux", files) + platform[:name].must_equal("centos") + platform[:family].must_equal("redhat") + platform[:release].must_equal("7.2.1511") end - it 'sets the correct family, name, and release on scientific linux' do + it "sets the correct family, name, and release on scientific linux" do files = { - '/etc/redhat-release' => "Scientific Linux release 7.4 (Nitrogen)\n", - '/etc/os-release' => "NAME=\"Scientific Linux\"\nVERSION=\"7.4 (Nitrogen)\"\nID=\"rhel\"\nID_LIKE=\"scientific centos fedora\"\nVERSION_ID=\"7.4\"\nPRETTY_NAME=\"Scientific Linux 7.4 (Nitrogen)\"\nANSI_COLOR=\"0;31\"\nCPE_NAME=\"cpe:/o:scientificlinux:scientificlinux:7.4:GA\"\nHOME_URL=\"http://www.scientificlinux.org//\"\nBUG_REPORT_URL=\"mailto:scientific-linux-devel@listserv.fnal.gov\"\n\nREDHAT_BUGZILLA_PRODUCT=\"Scientific Linux 7\"\nREDHAT_BUGZILLA_PRODUCT_VERSION=7.4\nREDHAT_SUPPORT_PRODUCT=\"Scientific Linux\"\nREDHAT_SUPPORT_PRODUCT_VERSION=\"7.4\"\n", + "/etc/redhat-release" => "Scientific Linux release 7.4 (Nitrogen)\n", + "/etc/os-release" => "NAME=\"Scientific Linux\"\nVERSION=\"7.4 (Nitrogen)\"\nID=\"rhel\"\nID_LIKE=\"scientific centos fedora\"\nVERSION_ID=\"7.4\"\nPRETTY_NAME=\"Scientific Linux 7.4 (Nitrogen)\"\nANSI_COLOR=\"0;31\"\nCPE_NAME=\"cpe:/o:scientificlinux:scientificlinux:7.4:GA\"\nHOME_URL=\"http://www.scientificlinux.org//\"\nBUG_REPORT_URL=\"mailto:scientific-linux-devel@listserv.fnal.gov\"\n\nREDHAT_BUGZILLA_PRODUCT=\"Scientific Linux 7\"\nREDHAT_BUGZILLA_PRODUCT_VERSION=7.4\nREDHAT_SUPPORT_PRODUCT=\"Scientific Linux\"\nREDHAT_SUPPORT_PRODUCT_VERSION=\"7.4\"\n", } - platform = scan_with_files('linux', files) - platform[:name].must_equal('scientific') - platform[:family].must_equal('redhat') - platform[:release].must_equal('7.4') + platform = scan_with_files("linux", files) + platform[:name].must_equal("scientific") + platform[:family].must_equal("redhat") + platform[:release].must_equal("7.4") end - it 'sets the correct family, name, and release on CloudLinux' do + it "sets the correct family, name, and release on CloudLinux" do files = { - '/etc/redhat-release' => "CloudLinux release 7.4 (Georgy Grechko)\n", - '/etc/os-release' => "NAME=\"CloudLinux\"\nVERSION=\"7.4 (Georgy Grechko)\"\nID=\"cloudlinux\"\nID_LIKE=\"rhel fedora centos\"\nVERSION_ID=\"7.4\"\nPRETTY_NAME=\"CloudLinux 7.4 (Georgy Grechko)\"\nANSI_COLOR=\"0;31\"\nCPE_NAME=\"cpe:/o:cloudlinux:cloudlinux:7.4:GA:server\"\nHOME_URL=\"https://www.cloudlinux.com//\"\nBUG_REPORT_URL=\"https://www.cloudlinux.com/support\"\n", + "/etc/redhat-release" => "CloudLinux release 7.4 (Georgy Grechko)\n", + "/etc/os-release" => "NAME=\"CloudLinux\"\nVERSION=\"7.4 (Georgy Grechko)\"\nID=\"cloudlinux\"\nID_LIKE=\"rhel fedora centos\"\nVERSION_ID=\"7.4\"\nPRETTY_NAME=\"CloudLinux 7.4 (Georgy Grechko)\"\nANSI_COLOR=\"0;31\"\nCPE_NAME=\"cpe:/o:cloudlinux:cloudlinux:7.4:GA:server\"\nHOME_URL=\"https://www.cloudlinux.com//\"\nBUG_REPORT_URL=\"https://www.cloudlinux.com/support\"\n", } - platform = scan_with_files('linux', files) - platform[:name].must_equal('cloudlinux') - platform[:family].must_equal('redhat') - platform[:release].must_equal('7.4') + platform = scan_with_files("linux", files) + platform[:name].must_equal("cloudlinux") + platform[:family].must_equal("redhat") + platform[:release].must_equal("7.4") end - it 'sets the correct family, name, and release on SLES ESR RHEL' do + it "sets the correct family, name, and release on SLES ESR RHEL" do files = { - '/etc/redhat-release' => "Red Hat Enterprise Linux Server release 7.4 (Maipo)\n# This is a \"SLES Expanded Support platform release 7.4\"\n# The above \"Red Hat Enterprise Linux Server\" string is only used to \n# keep software compatibility.\n", - '/etc/os-release' => "NAME=\"Red Hat Enterprise Linux Server\"\nVERSION=\"7.4 (Maipo)\"\nID=\"rhel\"\nID_LIKE=\"fedora\"\nVERSION_ID=\"7.4\"\nPRETTY_NAME=\"Red Hat Enterprise Linux Server 7.4\"\nANSI_COLOR=\"0;31\"\nCPE_NAME=\"cpe:/o:redhat:enterprise_linux:7.4:GA:server\"\nHOME_URL=\"https://www.redhat.com/\"\nBUG_REPORT_URL=\"https://bugzilla.redhat.com/\"\n\nREDHAT_BUGZILLA_PRODUCT=\"Red Hat Enterprise Linux 7\"\nREDHAT_BUGZILLA_PRODUCT_VERSION=7.4\nREDHAT_SUPPORT_PRODUCT=\"Red Hat Enterprise Linux\"\nREDHAT_SUPPORT_PRODUCT_VERSION=7.4\n# This is a \"SLES Expanded Support platform release 7.4\"\n# The above \"Red Hat Enterprise Linux Server\" string is only used to\n# keep software compatibility.\n", + "/etc/redhat-release" => "Red Hat Enterprise Linux Server release 7.4 (Maipo)\n# This is a \"SLES Expanded Support platform release 7.4\"\n# The above \"Red Hat Enterprise Linux Server\" string is only used to \n# keep software compatibility.\n", + "/etc/os-release" => "NAME=\"Red Hat Enterprise Linux Server\"\nVERSION=\"7.4 (Maipo)\"\nID=\"rhel\"\nID_LIKE=\"fedora\"\nVERSION_ID=\"7.4\"\nPRETTY_NAME=\"Red Hat Enterprise Linux Server 7.4\"\nANSI_COLOR=\"0;31\"\nCPE_NAME=\"cpe:/o:redhat:enterprise_linux:7.4:GA:server\"\nHOME_URL=\"https://www.redhat.com/\"\nBUG_REPORT_URL=\"https://bugzilla.redhat.com/\"\n\nREDHAT_BUGZILLA_PRODUCT=\"Red Hat Enterprise Linux 7\"\nREDHAT_BUGZILLA_PRODUCT_VERSION=7.4\nREDHAT_SUPPORT_PRODUCT=\"Red Hat Enterprise Linux\"\nREDHAT_SUPPORT_PRODUCT_VERSION=7.4\n# This is a \"SLES Expanded Support platform release 7.4\"\n# The above \"Red Hat Enterprise Linux Server\" string is only used to\n# keep software compatibility.\n", } - platform = scan_with_files('linux', files) - platform[:name].must_equal('redhat') - platform[:family].must_equal('redhat') - platform[:release].must_equal('7.4') + platform = scan_with_files("linux", files) + platform[:name].must_equal("redhat") + platform[:family].must_equal("redhat") + platform[:release].must_equal("7.4") end end end - describe 'darwin' do - describe 'mac_os_x' do - it 'sets the correct family, name, and release on os_x' do + describe "darwin" do + describe "mac_os_x" do + it "sets the correct family, name, and release on os_x" do files = { - '/System/Library/CoreServices/SystemVersion.plist' => 'Mac OS X', + "/System/Library/CoreServices/SystemVersion.plist" => "Mac OS X", } - platform = scan_with_files('darwin', files) - platform[:name].must_equal('mac_os_x') - platform[:family].must_equal('darwin') - platform[:release].must_equal('test-release') + platform = scan_with_files("darwin", files) + platform[:name].must_equal("mac_os_x") + platform[:family].must_equal("darwin") + platform[:release].must_equal("test-release") end end - describe 'generic darwin' do - it 'sets the correct family, name, and release on darwin' do + describe "generic darwin" do + it "sets the correct family, name, and release on darwin" do files = { - '/usr/bin/sw_vers' => "ProductVersion: 17.0.1\nBuildVersion: alpha.x1", + "/usr/bin/sw_vers" => "ProductVersion: 17.0.1\nBuildVersion: alpha.x1", } - platform = scan_with_files('darwin', files) - platform[:name].must_equal('darwin') - platform[:family].must_equal('darwin') - platform[:release].must_equal('17.0.1') - platform[:build].must_equal('alpha.x1') + platform = scan_with_files("darwin", files) + platform[:name].must_equal("darwin") + platform[:family].must_equal("darwin") + platform[:release].must_equal("17.0.1") + platform[:build].must_equal("alpha.x1") end end end - describe '/etc/debian_version' do + describe "/etc/debian_version" do def debian_scan(id, version) lsb_release = "DISTRIB_ID=#{id}\nDISTRIB_RELEASE=#{version}" files = { - '/etc/lsb-release' => lsb_release, - '/etc/debian_version' => '11', + "/etc/lsb-release" => lsb_release, + "/etc/debian_version" => "11", } - scan_with_files('linux', files) + scan_with_files("linux", files) end - describe 'ubuntu' do - it 'sets the correct family/release for ubuntu' do - platform = debian_scan('ubuntu', '16.04') + describe "ubuntu" do + it "sets the correct family/release for ubuntu" do + platform = debian_scan("ubuntu", "16.04") - platform[:name].must_equal('ubuntu') - platform[:family].must_equal('debian') - platform[:release].must_equal('16.04') + platform[:name].must_equal("ubuntu") + platform[:family].must_equal("debian") + platform[:release].must_equal("16.04") end end - describe 'linuxmint' do - it 'sets the correct family/release for linuxmint' do - platform = debian_scan('linuxmint', '12') + describe "linuxmint" do + it "sets the correct family/release for linuxmint" do + platform = debian_scan("linuxmint", "12") - platform[:name].must_equal('linuxmint') - platform[:family].must_equal('debian') - platform[:release].must_equal('12') + platform[:name].must_equal("linuxmint") + platform[:family].must_equal("debian") + platform[:release].must_equal("12") end end - describe 'raspbian' do - it 'sets the correct family/release for raspbian ' do + describe "raspbian" do + it "sets the correct family/release for raspbian " do files = { - '/usr/bin/raspi-config' => 'data', - '/etc/debian_version' => '13.6', + "/usr/bin/raspi-config" => "data", + "/etc/debian_version" => "13.6", } - platform = scan_with_files('linux', files) + platform = scan_with_files("linux", files) - platform[:name].must_equal('raspbian') - platform[:family].must_equal('debian') - platform[:release].must_equal('13.6') + platform[:name].must_equal("raspbian") + platform[:family].must_equal("debian") + platform[:release].must_equal("13.6") end end - describe 'windows' do - it 'sets the correct family/release for windows ' do + describe "windows" do + it "sets the correct family/release for windows " do platform = scan_with_windows() - platform[:name].must_equal('windows_6.3.9600') - platform[:family].must_equal('windows') - platform[:release].must_equal('6.3.9600') + platform[:name].must_equal("windows_6.3.9600") + platform[:family].must_equal("windows") + platform[:release].must_equal("6.3.9600") end end - describe 'everything else' do - it 'sets the correct family/release for debian ' do - platform = debian_scan('some_debian', '12.99') + describe "everything else" do + it "sets the correct family/release for debian " do + platform = debian_scan("some_debian", "12.99") - platform[:name].must_equal('debian') - platform[:family].must_equal('debian') - platform[:release].must_equal('11') + platform[:name].must_equal("debian") + platform[:family].must_equal("debian") + platform[:release].must_equal("11") end end end - describe '/etc/coreos/update.conf' do - it 'sets the correct family/release for coreos' do + describe "/etc/coreos/update.conf" do + it "sets the correct family/release for coreos" do lsb_release = "DISTRIB_ID=Container Linux by CoreOS\nDISTRIB_RELEASE=27.9" files = { - '/etc/lsb-release' => lsb_release, - '/etc/coreos/update.conf' => 'data', + "/etc/lsb-release" => lsb_release, + "/etc/coreos/update.conf" => "data", } - platform = scan_with_files('linux', files) + platform = scan_with_files("linux", files) - platform[:name].must_equal('coreos') - platform[:family].must_equal('linux') - platform[:release].must_equal('27.9') + platform[:name].must_equal("coreos") + platform[:family].must_equal("linux") + platform[:release].must_equal("27.9") end end - describe '/etc/os-release' do - describe 'when not on a wrlinux build' do - it 'fail back to genaric linux' do + describe "/etc/os-release" do + describe "when not on a wrlinux build" do + it "fail back to genaric linux" do os_release = "ID_LIKE=cisco-unkwown\nVERSION=unknown" files = { - '/etc/os-release' => os_release, + "/etc/os-release" => os_release, } - platform = scan_with_files('linux', files) + platform = scan_with_files("linux", files) - platform[:name].must_equal('linux') - platform[:family].must_equal('linux') + platform[:name].must_equal("linux") + platform[:family].must_equal("linux") end end - describe 'when on a wrlinux build' do - it 'sets the correct family/release for wrlinux' do + describe "when on a wrlinux build" do + it "sets the correct family/release for wrlinux" do os_release = "ID_LIKE=cisco-wrlinux\nVERSION=cisco123" files = { - '/etc/os-release' => os_release, + "/etc/os-release" => os_release, } - platform = scan_with_files('linux', files) + platform = scan_with_files("linux", files) - platform[:name].must_equal('wrlinux') - platform[:family].must_equal('redhat') - platform[:release].must_equal('cisco123') + platform[:name].must_equal("wrlinux") + platform[:family].must_equal("redhat") + platform[:release].must_equal("cisco123") end end end - describe 'qnx' do - it 'sets the correct info for qnx platform' do - platform = scan_with_files('qnx', {}) + describe "qnx" do + it "sets the correct info for qnx platform" do + platform = scan_with_files("qnx", {}) - platform[:name].must_equal('qnx') - platform[:family].must_equal('qnx') - platform[:release].must_equal('test-release') + platform[:name].must_equal("qnx") + platform[:family].must_equal("qnx") + platform[:release].must_equal("test-release") end end - describe 'cisco' do - it 'recognizes Cisco IOS12' do + describe "cisco" do + it "recognizes Cisco IOS12" do mock = Train::Transports::Mock::Connection.new - mock.mock_command('show version', "Cisco IOS Software, C3750E Software (C3750E-UNIVERSALK9-M), Version 12.2(58)SE") + mock.mock_command("show version", "Cisco IOS Software, C3750E Software (C3750E-UNIVERSALK9-M), Version 12.2(58)SE") platform = Train::Platforms::Detect.scan(mock) - platform[:name].must_equal('cisco_ios') - platform[:family].must_equal('cisco') - platform[:release].must_equal('12.2') + platform[:name].must_equal("cisco_ios") + platform[:family].must_equal("cisco") + platform[:release].must_equal("12.2") end - it 'recognizes Cisco IOS XE' do + it "recognizes Cisco IOS XE" do mock = Train::Transports::Mock::Connection.new - mock.mock_command('show version', "Cisco IOS Software, IOS-XE Software, Catalyst L3 Switch Software (CAT3K_CAA-UNIVERSALK9-M), Version 03.03.03SE RELEASE SOFTWARE (fc2)") + mock.mock_command("show version", "Cisco IOS Software, IOS-XE Software, Catalyst L3 Switch Software (CAT3K_CAA-UNIVERSALK9-M), Version 03.03.03SE RELEASE SOFTWARE (fc2)") platform = Train::Platforms::Detect.scan(mock) - platform[:name].must_equal('cisco_ios_xe') - platform[:family].must_equal('cisco') - platform[:release].must_equal('03.03.03SE') + platform[:name].must_equal("cisco_ios_xe") + platform[:family].must_equal("cisco") + platform[:release].must_equal("03.03.03SE") end - it 'recognizes Cisco Nexus' do + it "recognizes Cisco Nexus" do mock = Train::Transports::Mock::Connection.new - mock.mock_command('show version', "Cisco Nexus Operating System (NX-OS) Software\n system: version 5.2(1)N1(8b)\n") + mock.mock_command("show version", "Cisco Nexus Operating System (NX-OS) Software\n system: version 5.2(1)N1(8b)\n") platform = Train::Platforms::Detect.scan(mock) - platform[:name].must_equal('cisco_nexus') - platform[:family].must_equal('cisco') - platform[:release].must_equal('5.2') + platform[:name].must_equal("cisco_nexus") + platform[:family].must_equal("cisco") + platform[:release].must_equal("5.2") end end - describe 'brocade' do - it 'recognizes Brocade FOS-based SAN switches' do + describe "brocade" do + it "recognizes Brocade FOS-based SAN switches" do mock = Train::Transports::Mock::Connection.new - mock.mock_command('version', "Kernel: 2.6.14.2\nFabric OS: v7.4.2a\nMade on: Thu Jun 29 19:22:14 2017\nFlash: Sat Sep 9 17:30:42 2017\nBootProm: 1.0.11") + mock.mock_command("version", "Kernel: 2.6.14.2\nFabric OS: v7.4.2a\nMade on: Thu Jun 29 19:22:14 2017\nFlash: Sat Sep 9 17:30:42 2017\nBootProm: 1.0.11") platform = Train::Platforms::Detect.scan(mock) - platform[:name].must_equal('brocade_fos') - platform[:family].must_equal('brocade') - platform[:release].must_equal('7.4.2a') + platform[:name].must_equal("brocade_fos") + platform[:family].must_equal("brocade") + platform[:release].must_equal("7.4.2a") end end end diff --git a/test/unit/platforms/platform_test.rb b/test/unit/platforms/platform_test.rb index 6b09e9c2..716eda3a 100644 --- a/test/unit/platforms/platform_test.rb +++ b/test/unit/platforms/platform_test.rb @@ -1,8 +1,8 @@ # encoding: utf-8 -require 'helper' +require "helper" -describe 'platform' do +describe "platform" do def mock_platform(x) plat = Train::Platforms.name(x) plat.family_hierarchy = mock_os_hierarchy(plat).flatten @@ -12,7 +12,7 @@ def mock_platform(x) end def mock_platform_family(x) - Train::Platforms.list[x] = nil if x == 'mock' + Train::Platforms.list[x] = nil if x == "mock" plat = Train::Platforms.name(x).in_family(x) plat.family_hierarchy = mock_os_hierarchy(plat).flatten plat.platform[:family] = plat.family_hierarchy[0] @@ -27,93 +27,93 @@ def mock_os_hierarchy(plat) end end - it 'set platform title' do - plat = mock_platform_family('mock') - plat.title.must_equal('Mock') - plat.title('The Best Mock') - plat.title.must_equal('The Best Mock') + it "set platform title" do + plat = mock_platform_family("mock") + plat.title.must_equal("Mock") + plat.title("The Best Mock") + plat.title.must_equal("The Best Mock") end - it 'clean init name' do - plat = mock_platform_family('Mo ck') - plat.name.must_equal('mo_ck') + it "clean init name" do + plat = mock_platform_family("Mo ck") + plat.name.must_equal("mo_ck") end - it 'set name and name override' do - plat = mock_platform_family('mock') - plat.name.must_equal('mock') - plat[:name].must_equal('mock') - plat.platform[:name] = 'Mock 2020' + it "set name and name override" do + plat = mock_platform_family("mock") + plat.name.must_equal("mock") + plat[:name].must_equal("mock") + plat.platform[:name] = "Mock 2020" plat.add_platform_methods - plat.name.must_equal('mock_2020') - plat[:name].must_equal('mock_2020') + plat.name.must_equal("mock_2020") + plat[:name].must_equal("mock_2020") end - it 'check families' do - plat = mock_platform_family('mock') - plat.families.keys[0].name.must_equal('mock') + it "check families" do + plat = mock_platform_family("mock") + plat.families.keys[0].name.must_equal("mock") end - it 'check families with condition' do - Train::Platforms.list['mock'] = nil - plat = Train::Platforms.name('mock', arch: '= x86_64').in_family('linux') - plat.families.keys[0].name.must_equal('linux') - plat.families.values[0].must_equal({ arch: '= x86_64' }) + it "check families with condition" do + Train::Platforms.list["mock"] = nil + plat = Train::Platforms.name("mock", arch: "= x86_64").in_family("linux") + plat.families.keys[0].name.must_equal("linux") + plat.families.values[0].must_equal({ arch: "= x86_64" }) end - it 'finds family hierarchy' do - plat = Train::Platforms.name('linux') + it "finds family hierarchy" do + plat = Train::Platforms.name("linux") plat.find_family_hierarchy - plat.family_hierarchy.must_equal ['linux', 'unix', 'os'] + plat.family_hierarchy.must_equal %w{linux unix os} end - it 'return direct families' do - plat = mock_platform_family('mock') - plat.in_family('mock2') - plat.in_family('mock3') - plat.direct_families.must_equal(["mock", "mock2", "mock3"]) + it "return direct families" do + plat = mock_platform_family("mock") + plat.in_family("mock2") + plat.in_family("mock3") + plat.direct_families.must_equal(%w{mock mock2 mock3}) end - it 'return to_hash' do - plat = mock_platform_family('mock') + it "return to_hash" do + plat = mock_platform_family("mock") plat.to_hash.must_equal({ family: "mock" }) end - it 'return unknown release' do - plat = mock_platform_family('mock') - plat[:release].must_equal('unknown') + it "return unknown release" do + plat = mock_platform_family("mock") + plat[:release].must_equal("unknown") end - it 'return name?' do - plat = Train::Platforms.name('windows_rc1') + it "return name?" do + plat = Train::Platforms.name("windows_rc1") defined?(plat.windows_rc1?).must_be_nil plat.add_platform_methods plat.windows_rc1?.must_equal(true) end - it 'add platform methods' do - Train::Platforms.list['mock'] = nil - plat = Train::Platforms.name('mock').in_family('linux') + it "add platform methods" do + Train::Platforms.list["mock"] = nil + plat = Train::Platforms.name("mock").in_family("linux") defined?(plat.linux?).must_be_nil plat.family_hierarchy = mock_os_hierarchy(plat).flatten plat.add_platform_methods plat.linux?.must_equal(true) end - it 'provides a method to access platform data' do - family = 'test-os' + it "provides a method to access platform data" do + family = "test-os" os = mock_platform_family(family) os[:family].must_equal family end - it 'provides an accessor for the full hash' do - x = 'test-os' + it "provides an accessor for the full hash" do + x = "test-os" os = mock_platform_family(x) os.to_hash.must_equal({ family: x }) end - describe 'with platform set to redhat' do - let(:os) { mock_platform('redhat') } + describe "with platform set to redhat" do + let(:os) { mock_platform("redhat") } it { os.redhat?.must_equal(true) } it { os.debian?.must_equal(false) } it { os.suse?.must_equal(false) } @@ -121,8 +121,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to oracle' do - let(:os) { mock_platform('oracle') } + describe "with platform set to oracle" do + let(:os) { mock_platform("oracle") } it { os.redhat?.must_equal(true) } it { os.debian?.must_equal(false) } it { os.suse?.must_equal(false) } @@ -130,8 +130,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to centos' do - let(:os) { mock_platform('centos') } + describe "with platform set to centos" do + let(:os) { mock_platform("centos") } it { os.redhat?.must_equal(true) } it { os.debian?.must_equal(false) } it { os.suse?.must_equal(false) } @@ -139,8 +139,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to cloudlinux' do - let(:os) { mock_platform('cloudlinux') } + describe "with platform set to cloudlinux" do + let(:os) { mock_platform("cloudlinux") } it { os.redhat?.must_equal(true) } it { os.debian?.must_equal(false) } it { os.suse?.must_equal(false) } @@ -148,8 +148,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to fedora' do - let(:os) { mock_platform('fedora') } + describe "with platform set to fedora" do + let(:os) { mock_platform("fedora") } it { os.fedora?.must_equal(true) } it { os.redhat?.must_equal(false) } it { os.debian?.must_equal(false) } @@ -158,8 +158,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to amazon' do - let(:os) { mock_platform('amazon') } + describe "with platform set to amazon" do + let(:os) { mock_platform("amazon") } it { os.fedora?.must_equal(false) } it { os.redhat?.must_equal(true) } it { os.debian?.must_equal(false) } @@ -168,8 +168,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to debian' do - let(:os) { mock_platform('debian') } + describe "with platform set to debian" do + let(:os) { mock_platform("debian") } it { os.redhat?.must_equal(false) } it { os.debian?.must_equal(true) } it { os.suse?.must_equal(false) } @@ -177,8 +177,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to ubuntu' do - let(:os) { mock_platform('ubuntu') } + describe "with platform set to ubuntu" do + let(:os) { mock_platform("ubuntu") } it { os.redhat?.must_equal(false) } it { os.debian?.must_equal(true) } it { os.suse?.must_equal(false) } @@ -186,8 +186,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to linuxmint' do - let(:os) { mock_platform('linuxmint') } + describe "with platform set to linuxmint" do + let(:os) { mock_platform("linuxmint") } it { os.redhat?.must_equal(false) } it { os.debian?.must_equal(true) } it { os.suse?.must_equal(false) } @@ -195,8 +195,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to raspbian' do - let(:os) { mock_platform('raspbian') } + describe "with platform set to raspbian" do + let(:os) { mock_platform("raspbian") } it { os.redhat?.must_equal(false) } it { os.debian?.must_equal(true) } it { os.suse?.must_equal(false) } @@ -204,8 +204,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to suse' do - let(:os) { mock_platform('suse') } + describe "with platform set to suse" do + let(:os) { mock_platform("suse") } it { os.redhat?.must_equal(false) } it { os.debian?.must_equal(false) } it { os.suse?.must_equal(true) } @@ -213,8 +213,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to opensuse' do - let(:os) { mock_platform('opensuse') } + describe "with platform set to opensuse" do + let(:os) { mock_platform("opensuse") } it { os.redhat?.must_equal(false) } it { os.debian?.must_equal(false) } it { os.suse?.must_equal(true) } @@ -222,8 +222,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to alpine' do - let(:os) { mock_platform('alpine') } + describe "with platform set to alpine" do + let(:os) { mock_platform("alpine") } it { os.redhat?.must_equal(false) } it { os.debian?.must_equal(false) } it { os.suse?.must_equal(false) } @@ -231,8 +231,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to arch' do - let(:os) { mock_platform('arch') } + describe "with platform set to arch" do + let(:os) { mock_platform("arch") } it { os.redhat?.must_equal(false) } it { os.debian?.must_equal(false) } it { os.suse?.must_equal(false) } @@ -240,8 +240,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to coreos' do - let(:os) { mock_platform('coreos') } + describe "with platform set to coreos" do + let(:os) { mock_platform("coreos") } it { os.redhat?.must_equal(false) } it { os.debian?.must_equal(false) } it { os.suse?.must_equal(false) } @@ -249,8 +249,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to exherbo' do - let(:os) { mock_platform('exherbo') } + describe "with platform set to exherbo" do + let(:os) { mock_platform("exherbo") } it { os.redhat?.must_equal(false) } it { os.debian?.must_equal(false) } it { os.suse?.must_equal(false) } @@ -258,8 +258,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to gentoo' do - let(:os) { mock_platform('gentoo') } + describe "with platform set to gentoo" do + let(:os) { mock_platform("gentoo") } it { os.redhat?.must_equal(false) } it { os.debian?.must_equal(false) } it { os.suse?.must_equal(false) } @@ -267,8 +267,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to slackware' do - let(:os) { mock_platform('slackware') } + describe "with platform set to slackware" do + let(:os) { mock_platform("slackware") } it { os.redhat?.must_equal(false) } it { os.debian?.must_equal(false) } it { os.suse?.must_equal(false) } @@ -276,8 +276,8 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to wrlinux' do - let(:os) { mock_platform('wrlinux') } + describe "with platform set to wrlinux" do + let(:os) { mock_platform("wrlinux") } it { os.redhat?.must_equal(true) } it { os.debian?.must_equal(false) } it { os.suse?.must_equal(false) } @@ -285,105 +285,105 @@ def mock_os_hierarchy(plat) it { os.unix?.must_equal(true) } end - describe 'with platform set to linux' do - let(:os) { mock_platform('linux') } + describe "with platform set to linux" do + let(:os) { mock_platform("linux") } it { os.linux?.must_equal(true) } it { os.unix?.must_equal(true) } end - describe 'with platform set to freebsd' do - let(:os) { mock_platform('freebsd') } + describe "with platform set to freebsd" do + let(:os) { mock_platform("freebsd") } it { os.bsd?.must_equal(true) } it { os.linux?.must_equal(false) } it { os.unix?.must_equal(true) } end - describe 'with platform set to netbsd' do - let(:os) { mock_platform('netbsd') } + describe "with platform set to netbsd" do + let(:os) { mock_platform("netbsd") } it { os.bsd?.must_equal(true) } it { os.linux?.must_equal(false) } it { os.unix?.must_equal(true) } end - describe 'with platform set to openbsd' do - let(:os) { mock_platform('openbsd') } + describe "with platform set to openbsd" do + let(:os) { mock_platform("openbsd") } it { os.bsd?.must_equal(true) } it { os.linux?.must_equal(false) } it { os.unix?.must_equal(true) } end - describe 'with platform set to darwin' do - let(:os) { mock_platform('darwin') } + describe "with platform set to darwin" do + let(:os) { mock_platform("darwin") } it { os.bsd?.must_equal(true) } it { os.linux?.must_equal(false) } it { os.unix?.must_equal(true) } end - describe 'with platform set to solaris' do - let(:os) { mock_platform('solaris') } + describe "with platform set to solaris" do + let(:os) { mock_platform("solaris") } it { os.solaris?.must_equal(true) } it { os.linux?.must_equal(false) } it { os.unix?.must_equal(true) } end - describe 'with platform set to smartos' do - let(:os) { mock_platform('smartos') } + describe "with platform set to smartos" do + let(:os) { mock_platform("smartos") } it { os.solaris?.must_equal(true) } it { os.linux?.must_equal(false) } it { os.unix?.must_equal(true) } end - describe 'with platform set to openindiana' do - let(:os) { mock_platform('openindiana') } + describe "with platform set to openindiana" do + let(:os) { mock_platform("openindiana") } it { os.solaris?.must_equal(true) } it { os.linux?.must_equal(false) } it { os.unix?.must_equal(true) } end - describe 'with platform set to opensolaris' do - let(:os) { mock_platform('opensolaris') } + describe "with platform set to opensolaris" do + let(:os) { mock_platform("opensolaris") } it { os.solaris?.must_equal(true) } it { os.linux?.must_equal(false) } it { os.unix?.must_equal(true) } end - describe 'with platform set to nexentacore' do - let(:os) { mock_platform('nexentacore') } + describe "with platform set to nexentacore" do + let(:os) { mock_platform("nexentacore") } it { os.solaris?.must_equal(true) } it { os.linux?.must_equal(false) } it { os.unix?.must_equal(true) } end - describe 'with platform set to windows' do - let(:os) { mock_platform('windows') } + describe "with platform set to windows" do + let(:os) { mock_platform("windows") } it { os.solaris?.must_equal(false) } it { os.bsd?.must_equal(false) } it { os.linux?.must_equal(false) } it { os.unix?.must_equal(false) } end - describe 'with platform set to hpux' do - let(:os) { mock_platform('hpux') } + describe "with platform set to hpux" do + let(:os) { mock_platform("hpux") } it { os.solaris?.must_equal(false) } it { os.linux?.must_equal(false) } it { os.unix?.must_equal(true) } it { os.hpux?.must_equal(true) } end - describe 'with platform set to esx' do - let(:os) { mock_platform('vmkernel') } + describe "with platform set to esx" do + let(:os) { mock_platform("vmkernel") } it { os.solaris?.must_equal(false) } it { os.linux?.must_equal(false) } - it { os[:family].must_equal('esx') } + it { os[:family].must_equal("esx") } it { os.unix?.must_equal(false) } it { os.esx?.must_equal(true) } end - describe 'with platform set to darwin' do - let(:os) { mock_platform('darwin') } + describe "with platform set to darwin" do + let(:os) { mock_platform("darwin") } it { os.solaris?.must_equal(false) } it { os.linux?.must_equal(false) } - it { os[:family].must_equal('darwin') } + it { os[:family].must_equal("darwin") } it { os.bsd?.must_equal(true) } it { os.darwin?.must_equal(true) } it { os.unix?.must_equal(true) } @@ -391,11 +391,11 @@ def mock_os_hierarchy(plat) it { os.esx?.must_equal(false) } end - describe 'with platform set to mac_os_x' do - let(:os) { mock_platform('mac_os_x') } + describe "with platform set to mac_os_x" do + let(:os) { mock_platform("mac_os_x") } it { os.solaris?.must_equal(false) } it { os.linux?.must_equal(false) } - it { os[:family].must_equal('darwin') } + it { os[:family].must_equal("darwin") } it { os.bsd?.must_equal(true) } it { os.darwin?.must_equal(true) } it { os.unix?.must_equal(true) } diff --git a/test/unit/platforms/platforms_test.rb b/test/unit/platforms/platforms_test.rb index 52c5275e..ebb93631 100644 --- a/test/unit/platforms/platforms_test.rb +++ b/test/unit/platforms/platforms_test.rb @@ -1,52 +1,52 @@ # encoding: utf-8 -require 'helper' +require "helper" -describe 'platforms' do +describe "platforms" do - it 'create platform' do - Train::Platforms.list['mock'] = nil - plat = Train::Platforms.name('mock') - Train::Platforms.name('mock').in_family('test') - Train::Platforms.name('mock').detect { true } - plat.title.must_equal('Mock') + it "create platform" do + Train::Platforms.list["mock"] = nil + plat = Train::Platforms.name("mock") + Train::Platforms.name("mock").in_family("test") + Train::Platforms.name("mock").detect { true } + plat.title.must_equal("Mock") plat.detect.call.must_equal(true) - plat.families.keys[0].name.must_equal('test') + plat.families.keys[0].name.must_equal("test") end - it 'create family' do - Train::Platforms.families['mock'] = nil - fam = Train::Platforms.family('mock') - Train::Platforms.family('mock').in_family('test') - Train::Platforms.family('mock').detect { true } - fam.title.must_equal('Mock Family') + it "create family" do + Train::Platforms.families["mock"] = nil + fam = Train::Platforms.family("mock") + Train::Platforms.family("mock").in_family("test") + Train::Platforms.family("mock").detect { true } + fam.title.must_equal("Mock Family") fam.detect.call.must_equal(true) - fam.families.keys[0].name.must_equal('test') + fam.families.keys[0].name.must_equal("test") end - it 'return top platforms empty' do + it "return top platforms empty" do Train::Platforms.stubs(:list).returns({}) Train::Platforms.stubs(:families).returns({}) top = Train::Platforms.top_platforms top.count.must_equal(0) end - it 'return top platforms with data' do - plat = Train::Platforms.name('linux') + it "return top platforms with data" do + plat = Train::Platforms.name("linux") plat.stubs(:families).returns({}) - Train::Platforms.stubs(:list).returns({ 'linux' => plat }) + Train::Platforms.stubs(:list).returns({ "linux" => plat }) Train::Platforms.stubs(:families).returns({}) top = Train::Platforms.top_platforms top.count.must_equal(1) end - it 'return platforms export with data' do + it "return platforms export with data" do Train::Platforms.__reset Train::Platforms::Detect::Specifications::OS.load export = Train::Platforms.export export.size.must_be :>, 10 - export[0][:name].must_equal 'aix' - expected_families = ['aix', 'unix', 'os'] + export[0][:name].must_equal "aix" + expected_families = %w{aix unix os} export[0][:families].must_equal expected_families end end diff --git a/test/unit/plugins/connection_test.rb b/test/unit/plugins/connection_test.rb index db8fd7e4..05198cad 100644 --- a/test/unit/plugins/connection_test.rb +++ b/test/unit/plugins/connection_test.rb @@ -1,65 +1,65 @@ # encoding: utf-8 -require 'helper' +require "helper" -describe 'v1 Connection Plugin' do - describe 'empty v1 connection plugin' do +describe "v1 Connection Plugin" do + describe "empty v1 connection plugin" do let(:cls) { Train::Plugins::Transport::BaseConnection } let(:connection) { cls.new({}) } - it 'provides a close method' do + it "provides a close method" do connection.close # wont raise end - it 'raises an exception for run_command' do - proc { connection.run_command('') }.must_raise NotImplementedError + it "raises an exception for run_command" do + proc { connection.run_command("") }.must_raise NotImplementedError end - it 'raises an exception for run_command_via_connection' do - proc { connection.send(:run_command_via_connection, '') }.must_raise NotImplementedError + it "raises an exception for run_command_via_connection" do + proc { connection.send(:run_command_via_connection, "") }.must_raise NotImplementedError end - it 'raises an exception for os method' do + it "raises an exception for os method" do proc { connection.os }.must_raise NotImplementedError end - it 'raises an exception for file method' do - proc { connection.file('') }.must_raise NotImplementedError + it "raises an exception for file method" do + proc { connection.file("") }.must_raise NotImplementedError end - it 'raises an exception for file_via_connection method' do - proc { connection.send(:file_via_connection, '') }.must_raise NotImplementedError + it "raises an exception for file_via_connection method" do + proc { connection.send(:file_via_connection, "") }.must_raise NotImplementedError end - it 'raises an exception for login command method' do + it "raises an exception for login command method" do proc { connection.login_command }.must_raise NotImplementedError end - it 'can wait until ready' do + it "can wait until ready" do connection.wait_until_ready # wont raise end - it 'provides a default logger' do + it "provides a default logger" do connection.method(:logger).call .must_be_instance_of(Logger) end - it 'provides direct platform' do - plat = connection.force_platform!('mac_os_x') - plat.name.must_equal 'mac_os_x' + it "provides direct platform" do + plat = connection.force_platform!("mac_os_x") + plat.name.must_equal "mac_os_x" plat.linux?.must_equal false plat.cloud?.must_equal false plat.unix?.must_equal true - plat.family.must_equal 'darwin' - plat.family_hierarchy.must_equal ['darwin', 'bsd', 'unix', 'os'] + plat.family.must_equal "darwin" + plat.family_hierarchy.must_equal %w{darwin bsd unix os} end - it 'must use the user-provided logger' do + it "must use the user-provided logger" do l = rand - cls.new({logger: l}) + cls.new({ logger: l }) .method(:logger).call.must_equal(l) end - describe 'cached_client helper' do + describe "cached_client helper" do class DemoConnection < Train::Plugins::Transport::BaseConnection def initialize(options = {}) super(options) @@ -77,7 +77,7 @@ class DemoClient end end - it 'returns a new connection when cached disabled' do + it "returns a new connection when cached disabled" do conn = DemoConnection.new conn.disable_cache(:api_call) @@ -87,7 +87,7 @@ class DemoClient client1.wont_be_same_as client2 end - it 'returns a new connection when cache enabled and not hydrated' do + it "returns a new connection when cache enabled and not hydrated" do conn = DemoConnection.new conn.enable_cache(:api_call) @@ -96,7 +96,7 @@ class DemoClient client1.must_be_instance_of DemoConnection::DemoClient end - it 'returns a cached connection when cache enabled and hydrated' do + it "returns a cached connection when cache enabled and hydrated" do conn = DemoConnection.new conn.enable_cache(:api_call) @@ -107,92 +107,92 @@ class DemoClient end end - describe 'create cache connection' do - it 'default connection cache settings' do + describe "create cache connection" do + it "default connection cache settings" do connection.cache_enabled?(:file).must_equal true connection.cache_enabled?(:command).must_equal false connection.cache_enabled?(:api_call).must_equal false end end - describe 'disable/enable caching' do - it 'disable file cache via connection' do + describe "disable/enable caching" do + it "disable file cache via connection" do connection.disable_cache(:file) connection.cache_enabled?(:file).must_equal false end - it 'enable command cache via cache_connection' do + it "enable command cache via cache_connection" do connection.enable_cache(:command) connection.cache_enabled?(:command).must_equal true end - it 'raises an exception for unknown cache type' do + it "raises an exception for unknown cache type" do proc { connection.enable_cache(:fake) }.must_raise Train::UnknownCacheType proc { connection.disable_cache(:fake) }.must_raise Train::UnknownCacheType end end - describe 'cache enable check' do - it 'returns true when cache is enabled' do + describe "cache enable check" do + it "returns true when cache is enabled" do cache_enabled = connection.instance_variable_get(:@cache_enabled) cache_enabled[:test] = true connection.cache_enabled?(:test).must_equal true end - it 'returns false when cache is disabled' do + it "returns false when cache is disabled" do cache_enabled = connection.instance_variable_get(:@cache_enabled) cache_enabled[:test] = false connection.cache_enabled?(:test).must_equal false end end - describe 'clear cache' do - it 'clear file cache' do + describe "clear cache" do + it "clear file cache" do cache = connection.instance_variable_get(:@cache) - cache[:file]['/tmp'] = 'test' + cache[:file]["/tmp"] = "test" connection.send(:clear_cache, :file) cache = connection.instance_variable_get(:@cache) cache[:file].must_equal({}) end end - describe 'load file' do - it 'with caching' do + describe "load file" do + it "with caching" do connection.enable_cache(:file) - connection.expects(:file_via_connection).once.returns('test_file') - connection.file('/tmp/test').must_equal('test_file') - connection.file('/tmp/test').must_equal('test_file') - assert = { '/tmp/test' => 'test_file' } + connection.expects(:file_via_connection).once.returns("test_file") + connection.file("/tmp/test").must_equal("test_file") + connection.file("/tmp/test").must_equal("test_file") + assert = { "/tmp/test" => "test_file" } cache = connection.instance_variable_get(:@cache) cache[:file].must_equal(assert) end - it 'without caching' do + it "without caching" do connection.disable_cache(:file) - connection.expects(:file_via_connection).twice.returns('test_file') - connection.file('/tmp/test').must_equal('test_file') - connection.file('/tmp/test').must_equal('test_file') + connection.expects(:file_via_connection).twice.returns("test_file") + connection.file("/tmp/test").must_equal("test_file") + connection.file("/tmp/test").must_equal("test_file") cache = connection.instance_variable_get(:@cache) cache[:file].must_equal({}) end end - describe 'run command' do - it 'with caching' do + describe "run command" do + it "with caching" do connection.enable_cache(:command) - connection.expects(:run_command_via_connection).once.returns('test_user') - connection.run_command('whoami').must_equal('test_user') - connection.run_command('whoami').must_equal('test_user') - assert = { 'whoami' => 'test_user' } + connection.expects(:run_command_via_connection).once.returns("test_user") + connection.run_command("whoami").must_equal("test_user") + connection.run_command("whoami").must_equal("test_user") + assert = { "whoami" => "test_user" } cache = connection.instance_variable_get(:@cache) cache[:command].must_equal(assert) end - it 'without caching' do + it "without caching" do connection.disable_cache(:command) - connection.expects(:run_command_via_connection).twice.returns('test_user') - connection.run_command('whoami').must_equal('test_user') - connection.run_command('whoami').must_equal('test_user') + connection.expects(:run_command_via_connection).twice.returns("test_user") + connection.run_command("whoami").must_equal("test_user") + connection.run_command("whoami").must_equal("test_user") cache = connection.instance_variable_get(:@cache) cache[:command].must_equal({}) end diff --git a/test/unit/plugins/transport_test.rb b/test/unit/plugins/transport_test.rb index 62660e14..b94d8e13 100644 --- a/test/unit/plugins/transport_test.rb +++ b/test/unit/plugins/transport_test.rb @@ -1,53 +1,52 @@ -# encoding: utf-8 -require 'helper' +require "helper" -describe 'v1 Transport Plugin' do - describe 'empty v1 transport plugin' do +describe "v1 Transport Plugin" do + describe "empty v1 transport plugin" do let(:plugin) { Class.new(Train.plugin(1)) } - it 'initializes an empty configuration' do + it "initializes an empty configuration" do plugin.new.options.must_equal({}) end - it 'saves the provided configuration' do + it "saves the provided configuration" do conf = { a: rand } plugin.new(conf).options.must_equal(conf) end - it 'saves the provided configuration' do + it "saves the provided configuration" do conf = { a: rand } plugin.new(conf).options.must_equal(conf) end - it 'provides a default logger' do + it "provides a default logger" do conf = { a: rand } plugin.new(conf) .method(:logger).call .must_be_instance_of(Logger) end - it 'can configure custom loggers' do + it "can configure custom loggers" do l = rand plugin.new({ logger: l }) .method(:logger).call .must_equal(l) end - it 'provides a connection method' do + it "provides a connection method" do proc { plugin.new.connection }.must_raise Train::ClientError end end - describe 'registered with a name' do + describe "registered with a name" do before do Train::Plugins.registry.clear end - it 'doesnt have any plugins in the registry if none were configured' do + it "doesnt have any plugins in the registry if none were configured" do Train::Plugins.registry.empty?.must_equal true end - it 'is is added to the plugins registry' do + it "is is added to the plugins registry" do plugin_name = rand Train::Plugins.registry.wont_include(plugin_name) @@ -59,7 +58,7 @@ end end - describe 'with options' do + describe "with options" do def train_class(opts = {}) name = rand.to_s plugin = Class.new(Train.plugin(1)) do @@ -68,44 +67,44 @@ def train_class(opts = {}) [name, plugin] end - it 'exposes the parameters via api' do + it "exposes the parameters via api" do name, plugin = train_class plugin.default_options.keys.must_equal [name] end - it 'exposes the parameters via api' do + it "exposes the parameters via api" do default = rand.to_s name, plugin = train_class({ default: default }) plugin.default_options[name][:default].must_equal default end - it 'option must be required' do + it "option must be required" do name, plugin = train_class(required: true) plugin.default_options[name][:required].must_equal true end - it 'default option must not be required' do + it "default option must not be required" do name, plugin = train_class plugin.default_options[name][:required].must_be_nil end - it 'can include options from another module' do - nameA, pluginA = train_class + it "can include options from another module" do + name_a, plugin_a = train_class b = Class.new(Train.plugin(1)) do - include_options(pluginA) + include_options(plugin_a) end - b.default_options[nameA].wont_be_nil + b.default_options[name_a].wont_be_nil end - it 'overwrites existing options when including' do + it "overwrites existing options when including" do old = rand.to_s nu = rand.to_s - nameA, pluginA = train_class({ default: nu }) + name_a, plugin_a = train_class({ default: nu }) b = Class.new(Train.plugin(1)) do - option nameA, default: old - include_options(pluginA) + option name_a, default: old + include_options(plugin_a) end - b.default_options[nameA][:default].must_equal nu + b.default_options[name_a][:default].must_equal nu end end end diff --git a/test/unit/plugins_test.rb b/test/unit/plugins_test.rb index 19ab2bd1..6a0522b7 100644 --- a/test/unit/plugins_test.rb +++ b/test/unit/plugins_test.rb @@ -1,22 +1,22 @@ # encoding: utf-8 -require 'helper' +require "helper" describe Train::Plugins do - it 'provides a method to create new v1 transport plugins' do + it "provides a method to create new v1 transport plugins" do Train.plugin(1).must_equal Train::Plugins::Transport end - it 'fails when called with an unsupported plugin version' do + it "fails when called with an unsupported plugin version" do proc { Train.plugin(2) }.must_raise Train::ClientError end - it 'defaults to v1 plugins' do + it "defaults to v1 plugins" do Train.plugin.must_equal Train::Plugins::Transport end - it 'provides a registry of plugins' do + it "provides a registry of plugins" do Train::Plugins.registry.must_be_instance_of(Hash) end end diff --git a/test/unit/train_test.rb b/test/unit/train_test.rb index f1cf25d1..16cd9ffe 100644 --- a/test/unit/train_test.rb +++ b/test/unit/train_test.rb @@ -1,7 +1,7 @@ # encoding: utf-8 # # Author:: Dominik Richter () -require 'helper' +require "helper" $:.concat Dir["test/fixtures/plugins/*/lib"] # HACK? I honestly can't tell @@ -10,111 +10,111 @@ Train::Plugins.registry.clear end - describe '#create' do - it 'raises an error if the plugin isnt found' do - proc { Train.create('missing') }.must_raise Train::UserError - proc { Train.create('missing') }.must_raise Train::PluginLoadError + describe "#create" do + it "raises an error if the plugin isnt found" do + proc { Train.create("missing") }.must_raise Train::UserError + proc { Train.create("missing") }.must_raise Train::PluginLoadError end - it 'loads a core plugin if it isnt in the registry yet via symbol' do + it "loads a core plugin if it isnt in the registry yet via symbol" do Kernel.stub :require, true do - ex = Class.new(Train.plugin 1) { name 'existing' } + ex = Class.new(Train.plugin 1) { name "existing" } train = Train.create(:existing) train.class.must_equal ex end end - it 'loads a core plugin if it isnt in the registry yet via string' do + it "loads a core plugin if it isnt in the registry yet via string" do Kernel.stub :require, true do - ex = Class.new(Train.plugin 1) { name 'existing' } - train = Train.create('existing') + ex = Class.new(Train.plugin 1) { name "existing" } + train = Train.create("existing") train.class.must_equal ex end end - it 'loads a gem plugin if it isnt in the registry yet via string' do + it "loads a gem plugin if it isnt in the registry yet via string" do # The 'train-test-fixture' gem is located in test/fixtures/plugins/train-test-fixture and is # lib/train/trainsports, and Train will need to pre-pend 'train-' to the # transport name to get the gem name. - transport = Train.create('test-fixture') + transport = Train.create("test-fixture") # Normally one would call transport.class.name, but that's been overridden to be a write-only DSL method # So use to_s - transport.class.to_s.must_equal 'TrainPlugins::TestFixture::Transport' + transport.class.to_s.must_equal "TrainPlugins::TestFixture::Transport" end end - describe '#options' do - it 'raises exception if a given transport plugin isnt found' do - proc { Train.options('missing') }.must_raise Train::UserError - proc { Train.options('missing') }.must_raise Train::PluginLoadError + describe "#options" do + it "raises exception if a given transport plugin isnt found" do + proc { Train.options("missing") }.must_raise Train::UserError + proc { Train.options("missing") }.must_raise Train::PluginLoadError end - it 'provides empty options of a transport plugin' do - Class.new(Train.plugin 1) { name 'none' } - Train.options('none').must_equal({}) + it "provides empty options of a transport plugin" do + Class.new(Train.plugin 1) { name "none" } + Train.options("none").must_equal({}) end - it 'provides all options of a transport plugin' do - Class.new(Train.plugin 1) { - name 'one' + it "provides all options of a transport plugin" do + Class.new(Train.plugin 1) do + name "one" option :one, required: true, default: 123 - } - Train.options('one').must_equal({ + end + Train.options("one").must_equal({ one: { required: true, default: 123, - } + }, }) end end - describe '#target_config - URI parsing' do - it 'configures resolves target' do + describe "#target_config - URI parsing" do + it "configures resolves target" do org = { - target: 'ssh://user:pass@host.com:123/path', + target: "ssh://user:pass@host.com:123/path", } res = Train.target_config(org) - res[:backend].must_equal 'ssh' - res[:host].must_equal 'host.com' - res[:user].must_equal 'user' - res[:password].must_equal 'pass' + res[:backend].must_equal "ssh" + res[:host].must_equal "host.com" + res[:user].must_equal "user" + res[:password].must_equal "pass" res[:port].must_equal 123 res[:target].must_equal org[:target] - res[:path].must_equal '/path' + res[:path].must_equal "/path" org.keys.must_equal [:target] end - it 'resolves a target while keeping existing fields' do + it "resolves a target while keeping existing fields" do org = { - target: 'ssh://user:pass@host.com:123/path', - backend: rand, - host: rand, - user: rand, + target: "ssh://user:pass@host.com:123/path", + backend: rand, + host: rand, + user: rand, password: rand, - port: rand, - path: rand + port: rand, + path: rand, } res = Train.target_config(org) res.must_equal org end - it 'resolves a winrm target' do + it "resolves a winrm target" do org = { - target: 'winrm://Administrator@192.168.10.140', - backend: 'winrm', - host: '192.168.10.140', - user: 'Administrator', + target: "winrm://Administrator@192.168.10.140", + backend: "winrm", + host: "192.168.10.140", + user: "Administrator", password: nil, - port: nil, - path: nil + port: nil, + path: nil, } res = Train.target_config(org) res.must_equal org end - it 'keeps the configuration when incorrect target is supplied' do + it "keeps the configuration when incorrect target is supplied" do org = { - target: 'wrong', + target: "wrong", } res = Train.target_config(org) res[:backend].must_be_nil @@ -126,28 +126,28 @@ res[:target].must_equal org[:target] end - it 'always transforms config fields into ruby symbols' do + it "always transforms config fields into ruby symbols" do org = { - 'target' => 'ssh://user:pass@host.com:123/path', - 'backend' => rand, - 'host' => rand, - 'user' => rand, - 'password' => rand, - 'port' => rand, - 'path' => rand + "target" => "ssh://user:pass@host.com:123/path", + "backend" => rand, + "host" => rand, + "user" => rand, + "password" => rand, + "port" => rand, + "path" => rand, } - nu = org.each_with_object({}) { |(x, y), acc| + nu = org.each_with_object({}) do |(x, y), acc| acc[x.to_sym] = y; acc - } + end res = Train.target_config(org) res.must_equal nu end - it 'supports IPv4 URIs' do - org = { target: 'mock://1.2.3.4:123' } + it "supports IPv4 URIs" do + org = { target: "mock://1.2.3.4:123" } res = Train.target_config(org) - res[:backend].must_equal 'mock' - res[:host].must_equal '1.2.3.4' + res[:backend].must_equal "mock" + res[:host].must_equal "1.2.3.4" res[:user].must_be_nil res[:password].must_be_nil res[:port].must_equal 123 @@ -155,11 +155,11 @@ res[:target].must_equal org[:target] end - it 'supports IPv6 URIs' do - org = { target: 'mock://[abc::def]:123' } + it "supports IPv6 URIs" do + org = { target: "mock://[abc::def]:123" } res = Train.target_config(org) - res[:backend].must_equal 'mock' - res[:host].must_equal 'abc::def' + res[:backend].must_equal "mock" + res[:host].must_equal "abc::def" res[:user].must_be_nil res[:password].must_be_nil res[:port].must_equal 123 @@ -167,10 +167,10 @@ res[:target].must_equal org[:target] end - it 'supports empty URIs with schema://' do - org = { target: 'mock://' } + it "supports empty URIs with schema://" do + org = { target: "mock://" } res = Train.target_config(org) - res[:backend].must_equal 'mock' + res[:backend].must_equal "mock" res[:host].must_be_nil res[:user].must_be_nil res[:password].must_be_nil @@ -179,10 +179,10 @@ res[:target].must_equal org[:target] end - it 'supports empty URIs with schema:' do - org = { target: 'mock:' } + it "supports empty URIs with schema:" do + org = { target: "mock:" } res = Train.target_config(org) - res[:backend].must_equal 'mock' + res[:backend].must_equal "mock" res[:host].must_be_nil res[:user].must_be_nil res[:password].must_be_nil @@ -191,58 +191,58 @@ res[:target].must_equal org[:target] end - it 'supports www-form encoded passwords when the option is set' do + it "supports www-form encoded passwords when the option is set" do raw_password = '+!@#$%^&*()_-\';:"\\|/?.>,<][}{=`~' encoded_password = URI.encode_www_form_component(raw_password) orig = { target: "mock://username:#{encoded_password}@1.2.3.4:100", - www_form_encoded_password: true} + www_form_encoded_password: true } result = Train.target_config(orig) - result[:backend].must_equal 'mock' - result[:host].must_equal '1.2.3.4' - result[:user].must_equal 'username' + result[:backend].must_equal "mock" + result[:host].must_equal "1.2.3.4" + result[:user].must_equal "username" result[:password].must_equal raw_password result[:port].must_equal 100 result[:target].must_equal orig[:target] end - it 'ignores www-form-encoded password value when there is no password' do + it "ignores www-form-encoded password value when there is no password" do org = { target: "mock://username@1.2.3.4:100", - www_form_encoded_password: true} + www_form_encoded_password: true } res = Train.target_config(org) - res[:backend].must_equal 'mock' - res[:host].must_equal '1.2.3.4' - res[:user].must_equal 'username' + res[:backend].must_equal "mock" + res[:host].must_equal "1.2.3.4" + res[:user].must_equal "username" res[:password].must_be_nil res[:port].must_equal 100 res[:target].must_equal org[:target] end - it 'it raises UserError on invalid URIs' do - org = { target: 'mock world' } + it "it raises UserError on invalid URIs" do + org = { target: "mock world" } proc { Train.target_config(org) }.must_raise Train::UserError end end - describe '#validate_backend' do - it 'just returns the backend if it is provided' do + describe "#validate_backend" do + it "just returns the backend if it is provided" do x = rand Train.validate_backend({ backend: x }).must_equal x end - it 'returns the local backend if nothing was provided' do - Train.validate_backend({}).must_equal 'local' + it "returns the local backend if nothing was provided" do + Train.validate_backend({}).must_equal "local" end - it 'returns the default backend if nothing was provided' do + it "returns the default backend if nothing was provided" do x = rand Train.validate_backend({}, x).must_equal x end - it 'fails if no backend was given but a target is provided' do + it "fails if no backend was given but a target is provided" do proc { Train.validate_backend({ target: rand }) }.must_raise Train::UserError end - it 'fails if no backend was given but a host is provided' do + it "fails if no backend was given but a host is provided" do proc { Train.validate_backend({ host: rand }) }.must_raise Train::UserError end end diff --git a/test/unit/transports/azure_test.rb b/test/unit/transports/azure_test.rb index ff9a549a..6abd6af7 100644 --- a/test/unit/transports/azure_test.rb +++ b/test/unit/transports/azure_test.rb @@ -1,19 +1,19 @@ # encoding: utf-8 -require 'helper' +require "helper" # Required because this test file acesses classes under Azure:: -require 'azure_mgmt_resources' +require "azure_mgmt_resources" -describe 'azure transport' do +describe "azure transport" do def transport(options = nil) - ENV['AZURE_TENANT_ID'] = 'test_tenant_id' - ENV['AZURE_CLIENT_ID'] = 'test_client_id' - ENV['AZURE_CLIENT_SECRET'] = 'test_client_secret' - ENV['AZURE_SUBSCRIPTION_ID'] = 'test_subscription_id' + ENV["AZURE_TENANT_ID"] = "test_tenant_id" + ENV["AZURE_CLIENT_ID"] = "test_client_id" + ENV["AZURE_CLIENT_SECRET"] = "test_client_secret" + ENV["AZURE_SUBSCRIPTION_ID"] = "test_subscription_id" # need to require this at here as it captures the envs on load - require 'train/transports/azure' + require "train/transports/azure" Train::Transports::Azure.new(options) end let(:connection) { transport.connection } @@ -21,40 +21,40 @@ def transport(options = nil) let(:cache) { connection.instance_variable_get(:@cache) } let(:credentials) { connection.instance_variable_get(:@credentials) } - describe 'options' do - it 'defaults to env options' do - options[:tenant_id].must_equal 'test_tenant_id' - options[:client_id].must_equal 'test_client_id' - options[:client_secret].must_equal 'test_client_secret' - options[:subscription_id].must_equal 'test_subscription_id' + describe "options" do + it "defaults to env options" do + options[:tenant_id].must_equal "test_tenant_id" + options[:client_id].must_equal "test_client_id" + options[:client_secret].must_equal "test_client_secret" + options[:subscription_id].must_equal "test_subscription_id" end - it 'allows for options override' do - transport = transport(subscription_id: '102', client_id: '717') + it "allows for options override" do + transport = transport(subscription_id: "102", client_id: "717") options = transport.connection.instance_variable_get(:@options) - options[:tenant_id].must_equal 'test_tenant_id' - options[:client_id].must_equal '717' - options[:client_secret].must_equal 'test_client_secret' - options[:subscription_id].must_equal '102' + options[:tenant_id].must_equal "test_tenant_id" + options[:client_id].must_equal "717" + options[:client_secret].must_equal "test_client_secret" + options[:subscription_id].must_equal "102" end - it 'allows uri parse override' do - transport = transport(host: '999') + it "allows uri parse override" do + transport = transport(host: "999") options = transport.connection.instance_variable_get(:@options) - options[:tenant_id].must_equal 'test_tenant_id' - options[:subscription_id].must_equal '999' + options[:tenant_id].must_equal "test_tenant_id" + options[:subscription_id].must_equal "999" end end - describe 'platform' do - it 'returns platform' do + describe "platform" do + it "returns platform" do plat = connection.platform - plat.name.must_equal 'azure' - plat.family_hierarchy.must_equal ['cloud', 'api'] + plat.name.must_equal "azure" + plat.family_hierarchy.must_equal %w{cloud api} end end - describe 'azure_client' do + describe "azure_client" do class AzureResource attr_reader :hash def initialize(hash) @@ -62,14 +62,14 @@ def initialize(hash) end end - it 'can use azure_client with caching' do + it "can use azure_client with caching" do connection.instance_variable_set(:@credentials, {}) client = connection.azure_client(AzureResource) client.is_a?(AzureResource).must_equal true cache[:api_call].count.must_equal 1 end - it 'can use azure_client without caching' do + it "can use azure_client without caching" do connection.instance_variable_set(:@credentials, {}) connection.disable_cache(:api_call) client = connection.azure_client(AzureResource) @@ -77,25 +77,25 @@ def initialize(hash) cache[:api_call].count.must_equal 0 end - it 'can use azure_client default client' do + it "can use azure_client default client" do management_api_client = Azure::Resources::Profiles::Latest::Mgmt::Client client = connection.azure_client client.class.must_equal management_api_client end - it 'can use azure_client graph client' do + it "can use azure_client graph client" do graph_api_client = Azure::GraphRbac::Profiles::Latest::Client client = connection.azure_client(graph_api_client) client.class.must_equal graph_api_client end - it 'can use azure_client vault client' do + it "can use azure_client vault client" do vault_api_client = ::Azure::KeyVault::Profiles::Latest::Mgmt::Client - client = connection.azure_client(vault_api_client, vault_name: 'Test Vault') + client = connection.azure_client(vault_api_client, vault_name: "Test Vault") client.class.must_equal vault_api_client end - it 'cannot instantiate azure_client vault client without a vault name' do + it "cannot instantiate azure_client vault client without a vault name" do vault_api_client = ::Azure::KeyVault::Profiles::Latest::Mgmt::Client assert_raises(Train::UserError) do connection.azure_client(vault_api_client) @@ -103,20 +103,20 @@ def initialize(hash) end end - describe 'connect' do - it 'validate credentials' do + describe "connect" do + it "validate credentials" do connection.connect token = credentials[:credentials].instance_variable_get(:@token_provider) token.class.must_equal MsRestAzure::ApplicationTokenProvider credentials[:credentials].class.must_equal MsRest::TokenCredentials - credentials[:tenant_id].must_equal 'test_tenant_id' - credentials[:client_id].must_equal 'test_client_id' - credentials[:client_secret].must_equal 'test_client_secret' - credentials[:subscription_id].must_equal 'test_subscription_id' + credentials[:tenant_id].must_equal "test_tenant_id" + credentials[:client_id].must_equal "test_client_id" + credentials[:client_secret].must_equal "test_client_secret" + credentials[:subscription_id].must_equal "test_subscription_id" end - it 'validate msi credentials' do + it "validate msi credentials" do options[:client_id] = nil options[:client_secret] = nil Train::Transports::Azure::Connection.any_instance.stubs(:port_open?).returns(true) @@ -126,23 +126,23 @@ def initialize(hash) token.class.must_equal MsRestAzure::MSITokenProvider credentials[:credentials].class.must_equal MsRest::TokenCredentials - credentials[:tenant_id].must_equal 'test_tenant_id' - credentials[:subscription_id].must_equal 'test_subscription_id' + credentials[:tenant_id].must_equal "test_tenant_id" + credentials[:subscription_id].must_equal "test_subscription_id" credentials[:client_id].must_be_nil credentials[:client_secret].must_be_nil options[:msi_port].must_equal 50342 end end - describe 'unique_identifier' do - it 'returns a subscription id' do - connection.unique_identifier.must_equal 'test_subscription_id' + describe "unique_identifier" do + it "returns a subscription id" do + connection.unique_identifier.must_equal "test_subscription_id" end - it 'returns a tenant id' do + it "returns a tenant id" do options = connection.instance_variable_get(:@options) options[:subscription_id] = nil - connection.unique_identifier.must_equal 'test_tenant_id' + connection.unique_identifier.must_equal "test_tenant_id" end end end diff --git a/test/unit/transports/cisco_ios_connection_test.rb b/test/unit/transports/cisco_ios_connection_test.rb index 2faa90d2..151f6b79 100644 --- a/test/unit/transports/cisco_ios_connection_test.rb +++ b/test/unit/transports/cisco_ios_connection_test.rb @@ -1,11 +1,11 @@ # encoding: utf-8 -require 'helper' -require 'train/transports/ssh' +require "helper" +require "train/transports/ssh" -describe 'CiscoIOSConnection' do +describe "CiscoIOSConnection" do let(:cls) do - plat = Train::Platforms.name('mock').in_family('cisco_ios') + plat = Train::Platforms.name("mock").in_family("cisco_ios") plat.add_platform_methods plat.stubs(:cisco_ios?).returns(true) Train::Platforms::Detect.stubs(:scan).returns(plat) @@ -14,9 +14,9 @@ let(:opts) do { - host: 'fakehost', - user: 'fakeuser', - password: 'fakepassword', + host: "fakehost", + user: "fakeuser", + password: "fakepassword", } end @@ -24,65 +24,65 @@ cls.new(opts).connection end - describe '#initialize' do - it 'provides a uri' do - connection.uri.must_equal 'ssh://fakeuser@fakehost:22' + describe "#initialize" do + it "provides a uri" do + connection.uri.must_equal "ssh://fakeuser@fakehost:22" end end - describe '#unique_identifier' do - it 'returns the correct identifier' do + describe "#unique_identifier" do + it "returns the correct identifier" do output = "\r\nProcessor board ID 1111111111\r\n" Train::Transports::SSH::CiscoIOSConnection.any_instance .expects(:run_command_via_connection) - .with('show version | include Processor') + .with("show version | include Processor") .returns(OpenStruct.new(stdout: output)) - connection.unique_identifier.must_equal('1111111111') + connection.unique_identifier.must_equal("1111111111") end end - describe '#format_result' do - it 'returns correctly when result is `good`' do - output = 'good' - Train::Extras::CommandResult.expects(:new).with(output, '', 0) - connection.send(:format_result, 'good') + describe "#format_result" do + it "returns correctly when result is `good`" do + output = "good" + Train::Extras::CommandResult.expects(:new).with(output, "", 0) + connection.send(:format_result, "good") end - it 'returns correctly when result matches /Bad IP address/' do + it "returns correctly when result matches /Bad IP address/" do output = "Translating \"nope\"\r\n\r\nTranslating \"nope\"\r\n\r\n% Bad IP address or host name\r\n% Unknown command or computer name, or unable to find computer address\r\n" - Train::Extras::CommandResult.expects(:new).with('', output, 1) + Train::Extras::CommandResult.expects(:new).with("", output, 1) connection.send(:format_result, output) end - it 'returns correctly when result matches /Incomplete command/' do + it "returns correctly when result matches /Incomplete command/" do output = "% Incomplete command.\r\n\r\n" - Train::Extras::CommandResult.expects(:new).with('', output, 1) + Train::Extras::CommandResult.expects(:new).with("", output, 1) connection.send(:format_result, output) end - it 'returns correctly when result matches /Invalid input detected/' do + it "returns correctly when result matches /Invalid input detected/" do output = " ^\r\n% Invalid input detected at '^' marker.\r\n\r\n" - Train::Extras::CommandResult.expects(:new).with('', output, 1) + Train::Extras::CommandResult.expects(:new).with("", output, 1) connection.send(:format_result, output) end - it 'returns correctly when result matches /Unrecognized host/' do + it "returns correctly when result matches /Unrecognized host/" do output = "Translating \"nope\"\r\n% Unrecognized host or address, or protocol not running.\r\n\r\n" - Train::Extras::CommandResult.expects(:new).with('', output, 1) + Train::Extras::CommandResult.expects(:new).with("", output, 1) connection.send(:format_result, output) end end - describe '#format_output' do - it 'returns the correct output' do - cmd = 'show calendar' + describe "#format_output" do + it "returns the correct output" do + cmd = "show calendar" output = "show calendar\r\n10:35:50 UTC Fri Mar 23 2018\r\n7200_ios_12#\r\n7200_ios_12#" result = connection.send(:format_output, output, cmd) - result.must_equal '10:35:50 UTC Fri Mar 23 2018' + result.must_equal "10:35:50 UTC Fri Mar 23 2018" end - it 'returns the correct output when a pipe is used' do - cmd = 'show running-config | section line con 0' + it "returns the correct output when a pipe is used" do + cmd = "show running-config | section line con 0" output = "show running-config | section line con 0\r\nline con 0\r\n exec-timeout 0 0\r\n privilege level 15\r\n logging synchronous\r\n stopbits 1\r\n7200_ios_12#\r\n7200_ios_12#" result = connection.send(:format_output, output, cmd) result.must_equal "line con 0\r\n exec-timeout 0 0\r\n privilege level 15\r\n logging synchronous\r\n stopbits 1" diff --git a/test/unit/transports/gcp_test.rb b/test/unit/transports/gcp_test.rb index d85de52e..9d8f0b66 100644 --- a/test/unit/transports/gcp_test.rb +++ b/test/unit/transports/gcp_test.rb @@ -1,20 +1,20 @@ # encoding: utf-8 -require 'helper' -require 'train/transports/gcp' +require "helper" +require "train/transports/gcp" -describe 'gcp transport' do +describe "gcp transport" do let(:credentials_file) do - require 'tempfile' - file = Tempfile.new('application_default_credentials.json') - info = <<-INFO -{ - "client_id": "asdfasf-asdfasdf.apps.googleusercontent.com", - "client_secret": "d-asdfasdf", - "refresh_token": "1/adsfasdf-lCkju3-yQmjr20xVZonrfkE48L", - "type": "authorized_user" -} + require "tempfile" + file = Tempfile.new("application_default_credentials.json") + info = <<~INFO + { + "client_id": "asdfasf-asdfasdf.apps.googleusercontent.com", + "client_secret": "d-asdfasdf", + "refresh_token": "1/adsfasdf-lCkju3-yQmjr20xVZonrfkE48L", + "type": "authorized_user" + } INFO file.write(info) file.close @@ -22,15 +22,15 @@ end let(:credentials_file_override) do - require 'tempfile' - file = Tempfile.new('application_default_credentials.json') - info = <<-INFO -{ - "client_id": "asdfasf-asdfasdf.apps.googleusercontent.com", - "client_secret": "d-asdfasdf", - "refresh_token": "1/adsfasdf-lCkju3-yQmjr20xVZonrfkE48L", - "type": "authorized_user" -} + require "tempfile" + file = Tempfile.new("application_default_credentials.json") + info = <<~INFO + { + "client_id": "asdfasf-asdfasdf.apps.googleusercontent.com", + "client_secret": "d-asdfasdf", + "refresh_token": "1/adsfasdf-lCkju3-yQmjr20xVZonrfkE48L", + "type": "authorized_user" + } INFO file.write(info) file.close @@ -38,8 +38,8 @@ end def transport(options = nil) - ENV['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_file.path - ENV['GOOGLE_CLOUD_PROJECT'] = 'test_project' + ENV["GOOGLE_APPLICATION_CREDENTIALS"] = credentials_file.path + ENV["GOOGLE_CLOUD_PROJECT"] = "test_project" Train::Transports::Gcp.new(options) end @@ -47,36 +47,36 @@ def transport(options = nil) let(:options) { connection.instance_variable_get(:@options) } let(:cache) { connection.instance_variable_get(:@cache) } - describe 'options' do - it 'defaults to env options' do + describe "options" do + it "defaults to env options" do options[:google_application_credentials] = credentials_file.path - options[:google_cloud_project].must_equal 'test_project' + options[:google_cloud_project].must_equal "test_project" end end - it 'allows for options override' do + it "allows for options override" do transport = transport(google_application_credentials: credentials_file_override.path, google_cloud_project: "override_project") options = transport.connection.instance_variable_get(:@options) options[:google_application_credentials].must_equal credentials_file_override.path options[:google_cloud_project].must_equal "override_project" end - describe 'platform' do - it 'returns platform' do + describe "platform" do + it "returns platform" do platform = connection.platform - platform.name.must_equal 'gcp' - platform.family_hierarchy.must_equal ['cloud', 'api'] + platform.name.must_equal "gcp" + platform.family_hierarchy.must_equal %w{cloud api} end end - describe 'gcp_client' do - it 'test gcp_client with caching' do + describe "gcp_client" do + it "test gcp_client with caching" do client = connection.gcp_client(Object) client.is_a?(Object).must_equal true cache[:api_call].count.must_equal 1 end - it 'test gcp_client without caching' do + it "test gcp_client without caching" do connection.disable_cache(:api_call) client = connection.gcp_client(Object) client.is_a?(Object).must_equal true @@ -84,136 +84,135 @@ def transport(options = nil) end end - - describe 'gcp_compute_client' do - it 'test gcp_compute_client with caching' do + describe "gcp_compute_client" do + it "test gcp_compute_client with caching" do client = connection.gcp_compute_client client.is_a?(Google::Apis::ComputeV1::ComputeService).must_equal true cache[:api_call].count.must_equal 1 end - it 'test gcp_client without caching' do + it "test gcp_client without caching" do connection.disable_cache(:api_call) client = connection.gcp_compute_client client.is_a?(Google::Apis::ComputeV1::ComputeService).must_equal true cache[:api_call].count.must_equal 0 end - it 'test gcp_compute_client application name' do + it "test gcp_compute_client application name" do client = connection.gcp_compute_client client.is_a?(Google::Apis::ComputeV1::ComputeService).must_equal true - client.client_options.application_name.must_equal 'chef-inspec-train' + client.client_options.application_name.must_equal "chef-inspec-train" end - it 'test gcp_compute_client application version' do + it "test gcp_compute_client application version" do client = connection.gcp_compute_client client.is_a?(Google::Apis::ComputeV1::ComputeService).must_equal true client.client_options.application_version.must_equal Train::VERSION end end - describe 'gcp_iam_client' do - it 'test gcp_iam_client with caching' do + describe "gcp_iam_client" do + it "test gcp_iam_client with caching" do client = connection.gcp_iam_client client.is_a?(Google::Apis::IamV1::IamService).must_equal true cache[:api_call].count.must_equal 1 end - it 'test gcp_iam_client without caching' do + it "test gcp_iam_client without caching" do connection.disable_cache(:api_call) client = connection.gcp_iam_client client.is_a?(Google::Apis::IamV1::IamService).must_equal true cache[:api_call].count.must_equal 0 end - it 'test gcp_iam_client application name' do + it "test gcp_iam_client application name" do client = connection.gcp_iam_client client.is_a?(Google::Apis::IamV1::IamService).must_equal true - client.client_options.application_name.must_equal 'chef-inspec-train' + client.client_options.application_name.must_equal "chef-inspec-train" end - it 'test gcp_iam_client application version' do + it "test gcp_iam_client application version" do client = connection.gcp_iam_client client.is_a?(Google::Apis::IamV1::IamService).must_equal true client.client_options.application_version.must_equal Train::VERSION end end - describe 'gcp_project_client' do - it 'test gcp_project_client with caching' do + describe "gcp_project_client" do + it "test gcp_project_client with caching" do client = connection.gcp_project_client client.is_a?(Google::Apis::CloudresourcemanagerV1::CloudResourceManagerService).must_equal true cache[:api_call].count.must_equal 1 end - it 'test gcp_project_client without caching' do + it "test gcp_project_client without caching" do connection.disable_cache(:api_call) client = connection.gcp_project_client client.is_a?(Google::Apis::CloudresourcemanagerV1::CloudResourceManagerService).must_equal true cache[:api_call].count.must_equal 0 end - it 'test gcp_project_client application name' do + it "test gcp_project_client application name" do client = connection.gcp_project_client client.is_a?(Google::Apis::CloudresourcemanagerV1::CloudResourceManagerService).must_equal true - client.client_options.application_name.must_equal 'chef-inspec-train' + client.client_options.application_name.must_equal "chef-inspec-train" end - it 'test gcp_project_client application version' do + it "test gcp_project_client application version" do client = connection.gcp_project_client client.is_a?(Google::Apis::CloudresourcemanagerV1::CloudResourceManagerService).must_equal true client.client_options.application_version.must_equal Train::VERSION end end - describe 'gcp_storage_client' do - it 'test gcp_storage_client with caching' do + describe "gcp_storage_client" do + it "test gcp_storage_client with caching" do client = connection.gcp_storage_client client.is_a?(Google::Apis::StorageV1::StorageService).must_equal true cache[:api_call].count.must_equal 1 end - it 'test gcp_storage_client without caching' do + it "test gcp_storage_client without caching" do connection.disable_cache(:api_call) client = connection.gcp_storage_client client.is_a?(Google::Apis::StorageV1::StorageService).must_equal true cache[:api_call].count.must_equal 0 end - it 'test gcp_storage_client application name' do + it "test gcp_storage_client application name" do client = connection.gcp_storage_client client.is_a?(Google::Apis::StorageV1::StorageService).must_equal true - client.client_options.application_name.must_equal 'chef-inspec-train' + client.client_options.application_name.must_equal "chef-inspec-train" end - it 'test gcp_storage_client application version' do + it "test gcp_storage_client application version" do client = connection.gcp_storage_client client.is_a?(Google::Apis::StorageV1::StorageService).must_equal true client.client_options.application_version.must_equal Train::VERSION end end - describe 'gcp_admin_client' do - it 'test gcp_admin_client with caching' do + describe "gcp_admin_client" do + it "test gcp_admin_client with caching" do client = connection.gcp_admin_client client.is_a?(Google::Apis::AdminDirectoryV1::DirectoryService).must_equal true cache[:api_call].count.must_equal 1 end - it 'test gcp_admin_client without caching' do + it "test gcp_admin_client without caching" do connection.disable_cache(:api_call) client = connection.gcp_admin_client client.is_a?(Google::Apis::AdminDirectoryV1::DirectoryService).must_equal true cache[:api_call].count.must_equal 0 end - it 'test gcp_admin_client application name' do + it "test gcp_admin_client application name" do client = connection.gcp_admin_client client.is_a?(Google::Apis::AdminDirectoryV1::DirectoryService).must_equal true - client.client_options.application_name.must_equal 'chef-inspec-train' + client.client_options.application_name.must_equal "chef-inspec-train" end - it 'test gcp_admin_client application version' do + it "test gcp_admin_client application version" do client = connection.gcp_admin_client client.is_a?(Google::Apis::AdminDirectoryV1::DirectoryService).must_equal true client.client_options.application_version.must_equal Train::VERSION @@ -221,45 +220,45 @@ def transport(options = nil) end # test options override of env vars in connect - describe 'connect' do + describe "connect" do let(:creds) do - require 'tempfile' - file = Tempfile.new('creds') - info = <<-INFO -{ - "client_id": "asdfasf-asdfasdf.apps.googleusercontent.com", - "client_secret": "d-asdfasdf", - "refresh_token": "1/adsfasdf-lCkju3-yQmjr20xVZonrfkE48L", - "type": "authorized_user" -} + require "tempfile" + file = Tempfile.new("creds") + info = <<~INFO + { + "client_id": "asdfasf-asdfasdf.apps.googleusercontent.com", + "client_secret": "d-asdfasdf", + "refresh_token": "1/adsfasdf-lCkju3-yQmjr20xVZonrfkE48L", + "type": "authorized_user" + } INFO file.write(info) file.close file end - it 'validate gcp connection with credentials' do + it "validate gcp connection with credentials" do options[:google_application_credentials] = creds.path connection.connect - ENV['GOOGLE_APPLICATION_CREDENTIALS'].must_equal creds.path + ENV["GOOGLE_APPLICATION_CREDENTIALS"].must_equal creds.path end - it 'validate gcp connection with project' do - options[:google_cloud_project] = 'project' + it "validate gcp connection with project" do + options[:google_cloud_project] = "project" connection.connect - ENV['GOOGLE_CLOUD_PROJECT'].must_equal 'project' + ENV["GOOGLE_CLOUD_PROJECT"].must_equal "project" end end - describe 'unique_identifier' do - it 'test connection unique identifier' do + describe "unique_identifier" do + it "test connection unique identifier" do client = connection - client.unique_identifier.must_equal 'asdfasf-asdfasdf.apps.googleusercontent.com' + client.unique_identifier.must_equal "asdfasf-asdfasdf.apps.googleusercontent.com" end end - describe 'uri' do - it 'test uri' do + describe "uri" do + it "test uri" do client = connection - client.uri.must_equal 'gcp://asdfasf-asdfasdf.apps.googleusercontent.com' + client.uri.must_equal "gcp://asdfasf-asdfasdf.apps.googleusercontent.com" end end end diff --git a/test/unit/transports/helpers/azure/file_credentials_test.rb b/test/unit/transports/helpers/azure/file_credentials_test.rb index ea2b92f5..34425e7c 100644 --- a/test/unit/transports/helpers/azure/file_credentials_test.rb +++ b/test/unit/transports/helpers/azure/file_credentials_test.rb @@ -1,12 +1,12 @@ # encoding: utf-8 -require 'helper' -require 'tempfile' -require 'train/transports/helpers/azure/file_credentials' +require "helper" +require "tempfile" +require "train/transports/helpers/azure/file_credentials" -describe 'parse_credentials_file' do +describe "parse_credentials_file" do let(:cred_file_single_entry) do - file = Tempfile.new('cred_file') + file = Tempfile.new("cred_file") info = <<-INFO [my_subscription_id] client_id = "my_client_id" @@ -19,7 +19,7 @@ end let(:cred_file_multiple_entries) do - file = Tempfile.new('cred_file') + file = Tempfile.new("cred_file") info = <<-INFO [my_subscription_id] client_id = "my_client_id" @@ -38,7 +38,7 @@ let(:options) { { credentials_file: cred_file_multiple_entries.path } } - it 'handles a nil file' do + it "handles a nil file" do options[:credentials_file] = nil result = Train::Transports::Helpers::Azure::FileCredentials.parse(options) @@ -46,84 +46,84 @@ assert_empty(result) end - it 'returns empty hash when no credentials file detected' do + it "returns empty hash when no credentials file detected" do result = Train::Transports::Helpers::Azure::FileCredentials.parse({}) assert_empty(result) end - it 'loads only entry from file when no subscription id given' do + it "loads only entry from file when no subscription id given" do options[:credentials_file] = cred_file_single_entry.path result = Train::Transports::Helpers::Azure::FileCredentials.parse(options) - assert_equal('my_tenant_id', result[:tenant_id]) - assert_equal('my_client_id', result[:client_id]) - assert_equal('my_client_secret', result[:client_secret]) - assert_equal('my_subscription_id', result[:subscription_id]) + assert_equal("my_tenant_id", result[:tenant_id]) + assert_equal("my_client_id", result[:client_id]) + assert_equal("my_client_secret", result[:client_secret]) + assert_equal("my_subscription_id", result[:subscription_id]) end - it 'raises an error when no subscription id given and multiple entries' do + it "raises an error when no subscription id given and multiple entries" do error = assert_raises RuntimeError do Train::Transports::Helpers::Azure::FileCredentials.parse(options) end - assert_equal('Credentials file must have one entry. Check your credentials file. If you have more than one entry set AZURE_SUBSCRIPTION_ID environment variable.', error.message) + assert_equal("Credentials file must have one entry. Check your credentials file. If you have more than one entry set AZURE_SUBSCRIPTION_ID environment variable.", error.message) end - it 'loads entry when subscription id is given' do - options[:subscription_id] = 'my_subscription_id' + it "loads entry when subscription id is given" do + options[:subscription_id] = "my_subscription_id" result = Train::Transports::Helpers::Azure::FileCredentials.parse(options) - assert_equal('my_tenant_id', result[:tenant_id]) - assert_equal('my_client_id', result[:client_id]) - assert_equal('my_client_secret', result[:client_secret]) - assert_equal('my_subscription_id', result[:subscription_id]) + assert_equal("my_tenant_id", result[:tenant_id]) + assert_equal("my_client_id", result[:client_id]) + assert_equal("my_client_secret", result[:client_secret]) + assert_equal("my_subscription_id", result[:subscription_id]) end - it 'raises an error when subscription id not found' do - options[:subscription_id] = 'missing_subscription_id' + it "raises an error when subscription id not found" do + options[:subscription_id] = "missing_subscription_id" error = assert_raises RuntimeError do Train::Transports::Helpers::Azure::FileCredentials.parse(options) end - assert_equal('No credentials found for subscription number missing_subscription_id', error.message) + assert_equal("No credentials found for subscription number missing_subscription_id", error.message) end - it 'loads entry based on index' do - ENV['AZURE_SUBSCRIPTION_NUMBER'] = '2' + it "loads entry based on index" do + ENV["AZURE_SUBSCRIPTION_NUMBER"] = "2" result = Train::Transports::Helpers::Azure::FileCredentials.parse(options) - ENV.delete('AZURE_SUBSCRIPTION_NUMBER') + ENV.delete("AZURE_SUBSCRIPTION_NUMBER") - assert_equal('my_tenant_id2', result[:tenant_id]) - assert_equal('my_client_id2', result[:client_id]) - assert_equal('my_client_secret2', result[:client_secret]) - assert_equal('my_subscription_id2', result[:subscription_id]) + assert_equal("my_tenant_id2", result[:tenant_id]) + assert_equal("my_client_id2", result[:client_id]) + assert_equal("my_client_secret2", result[:client_secret]) + assert_equal("my_subscription_id2", result[:subscription_id]) end - it 'raises an error when index is out of bounds' do - ENV['AZURE_SUBSCRIPTION_NUMBER'] = '3' + it "raises an error when index is out of bounds" do + ENV["AZURE_SUBSCRIPTION_NUMBER"] = "3" error = assert_raises RuntimeError do Train::Transports::Helpers::Azure::FileCredentials.parse(options) end - ENV.delete('AZURE_SUBSCRIPTION_NUMBER') + ENV.delete("AZURE_SUBSCRIPTION_NUMBER") - assert_equal('Your credentials file only contains 2 subscriptions. You specified number 3.', error.message) + assert_equal("Your credentials file only contains 2 subscriptions. You specified number 3.", error.message) end - it 'raises an error when index 0 is given' do - ENV['AZURE_SUBSCRIPTION_NUMBER'] = '0' + it "raises an error when index 0 is given" do + ENV["AZURE_SUBSCRIPTION_NUMBER"] = "0" error = assert_raises RuntimeError do Train::Transports::Helpers::Azure::FileCredentials.parse(options) end - ENV.delete('AZURE_SUBSCRIPTION_NUMBER') + ENV.delete("AZURE_SUBSCRIPTION_NUMBER") - assert_equal('Index must be greater than 0.', error.message) + assert_equal("Index must be greater than 0.", error.message) end end diff --git a/test/unit/transports/local_test.rb b/test/unit/transports/local_test.rb index 63c89cac..39a32f0b 100644 --- a/test/unit/transports/local_test.rb +++ b/test/unit/transports/local_test.rb @@ -1,13 +1,13 @@ # encoding: utf-8 -require 'helper' -require 'train/transports/local' +require "helper" +require "train/transports/local" class TransportHelper attr_accessor :transport def initialize(user_opts = {}) - opts = {platform_name: 'mock', family_hierarchy: ['mock']}.merge(user_opts) + opts = { platform_name: "mock", family_hierarchy: ["mock"] }.merge(user_opts) plat = Train::Platforms.name(opts[:platform_name]) plat.family_hierarchy = opts[:family_hierarchy] plat.add_platform_methods @@ -16,46 +16,46 @@ def initialize(user_opts = {}) end end -describe 'local transport' do +describe "local transport" do let(:transport) { TransportHelper.new.transport } let(:connection) { transport.connection } - it 'can be instantiated' do + it "can be instantiated" do transport.wont_be_nil end - it 'gets the connection' do + it "gets the connection" do connection.must_be_kind_of Train::Transports::Local::Connection end - it 'provides a uri' do - connection.uri.must_equal 'local://' + it "provides a uri" do + connection.uri.must_equal "local://" end - it 'doesnt wait to be read' do + it "doesnt wait to be read" do connection.wait_until_ready.must_be_nil end - it 'can be closed' do + it "can be closed" do connection.close.must_be_nil end - it 'has no login command' do + it "has no login command" do connection.login_command.must_be_nil end - it 'provides a run_command_via_connection method' do + it "provides a run_command_via_connection method" do methods = connection.class.private_instance_methods(false) methods.include?(:run_command_via_connection).must_equal true end - it 'provides a file_via_connection method' do + it "provides a file_via_connection method" do methods = connection.class.private_instance_methods(false) methods.include?(:file_via_connection).must_equal true end - describe 'when overriding runner selection' do - it 'can select the `GenericRunner`' do + describe "when overriding runner selection" do + it "can select the `GenericRunner`" do Train::Transports::Local::Connection::GenericRunner .expects(:new) @@ -70,7 +70,7 @@ def initialize(user_opts = {}) Train::Transports::Local::Connection.new(command_runner: :generic) end - it 'can select the `WindowsPipeRunner`' do + it "can select the `WindowsPipeRunner`" do Train::Transports::Local::Connection::GenericRunner .expects(:new) .never @@ -85,7 +85,7 @@ def initialize(user_opts = {}) Train::Transports::Local::Connection.new(command_runner: :windows_pipe) end - it 'can select the `WindowsShellRunner`' do + it "can select the `WindowsShellRunner`" do Train::Transports::Local::Connection::GenericRunner .expects(:new) .never @@ -100,23 +100,23 @@ def initialize(user_opts = {}) Train::Transports::Local::Connection.new(command_runner: :windows_shell) end - it 'throws a RuntimeError when an invalid runner type is passed' do + it "throws a RuntimeError when an invalid runner type is passed" do proc { Train::Transports::Local::Connection.new(command_runner: :nope ) } .must_raise(RuntimeError, "Runner type `:nope` not supported") end end - describe 'when running a local command' do + describe "when running a local command" do let(:cmd_runner) { Minitest::Mock.new } def mock_run_cmd(cmd, &block) cmd_runner.expect :run_command, nil Mixlib::ShellOut.stub :new, cmd_runner do |*args| - block.call() + yield end end - it 'gets stdout' do + it "gets stdout" do mock_run_cmd(rand) do x = rand cmd_runner.expect :stdout, x @@ -126,7 +126,7 @@ def mock_run_cmd(cmd, &block) end end - it 'gets stderr' do + it "gets stderr" do mock_run_cmd(rand) do x = rand cmd_runner.expect :stdout, nil @@ -136,7 +136,7 @@ def mock_run_cmd(cmd, &block) end end - it 'gets exit_status' do + it "gets exit_status" do mock_run_cmd(rand) do x = rand cmd_runner.expect :stdout, nil @@ -147,13 +147,13 @@ def mock_run_cmd(cmd, &block) end end - describe 'when running on Windows' do + describe "when running on Windows" do let(:connection) do - TransportHelper.new(family_hierarchy: ['windows']).transport.connection + TransportHelper.new(family_hierarchy: ["windows"]).transport.connection end let(:runner) { mock } - it 'uses `WindowsPipeRunner` by default' do + it "uses `WindowsPipeRunner` by default" do Train::Transports::Local::Connection::WindowsPipeRunner .expects(:new) .returns(runner) @@ -162,11 +162,11 @@ def mock_run_cmd(cmd, &block) .expects(:new) .never - runner.expects(:run_command).with('not actually executed') - connection.run_command('not actually executed') + runner.expects(:run_command).with("not actually executed") + connection.run_command("not actually executed") end - it 'uses `WindowsShellRunner` when a named pipe is not available' do + it "uses `WindowsShellRunner` when a named pipe is not available" do Train::Transports::Local::Connection::WindowsPipeRunner .expects(:new) .raises(Train::Transports::Local::PipeError) @@ -175,8 +175,8 @@ def mock_run_cmd(cmd, &block) .expects(:new) .returns(runner) - runner.expects(:run_command).with('not actually executed') - connection.run_command('not actually executed') + runner.expects(:run_command).with("not actually executed") + connection.run_command("not actually executed") end end end diff --git a/test/unit/transports/mock_test.rb b/test/unit/transports/mock_test.rb index 5e254fcb..5a1b32e0 100644 --- a/test/unit/transports/mock_test.rb +++ b/test/unit/transports/mock_test.rb @@ -1,79 +1,79 @@ # encoding: utf-8 -require 'helper' -require 'train/transports/mock' -require 'digest/sha2' +require "helper" +require "train/transports/mock" +require "digest/sha2" -describe 'mock transport' do +describe "mock transport" do let(:transport) { Train::Transports::Mock.new(verbose: true) } let(:connection) { transport.connection } - it 'can be instantiated' do + it "can be instantiated" do transport.wont_be_nil end - it 'can create a connection' do + it "can create a connection" do connection.wont_be_nil end - it 'provides a uri' do - connection.uri.must_equal 'mock://' + it "provides a uri" do + connection.uri.must_equal "mock://" end - it 'provides a run_command_via_connection method' do + it "provides a run_command_via_connection method" do methods = connection.class.private_instance_methods(false) methods.include?(:run_command_via_connection).must_equal true end - it 'provides a file_via_connection method' do + it "provides a file_via_connection method" do methods = connection.class.private_instance_methods(false) methods.include?(:file_via_connection).must_equal true end - describe 'when running a mocked command' do - let(:mock_cmd) { } + describe "when running a mocked command" do + let(:mock_cmd) {} - it 'has a simple mock command creator' do + it "has a simple mock command creator" do out = rand cls = Train::Transports::Mock::Connection::Command - res = cls.new(out, '', 0) - connection.mock_command('test', out).must_equal res + res = cls.new(out, "", 0) + connection.mock_command("test", out).must_equal res end - it 'handles nil commands' do + it "handles nil commands" do assert_output "", /Command not mocked/ do - connection.run_command(nil).stdout.must_equal('') + connection.run_command(nil).stdout.must_equal("") end end - it 'can mock up nil commands' do + it "can mock up nil commands" do out = rand - connection.mock_command('', rand) # don't pull this result! always mock the input + connection.mock_command("", rand) # don't pull this result! always mock the input connection.mock_command(nil, out) # pull this result connection.run_command(nil).stdout.must_equal(out) end - it 'gets results for stdout' do + it "gets results for stdout" do out = rand cmd = rand connection.mock_command(cmd, out) connection.run_command(cmd).stdout.must_equal(out) end - it 'gets results for stderr' do + it "gets results for stderr" do err = rand cmd = rand connection.mock_command(cmd, nil, err) connection.run_command(cmd).stderr.must_equal(err) end - it 'gets results for exit_status' do + it "gets results for exit_status" do code = rand cmd = rand connection.mock_command(cmd, nil, nil, code) connection.run_command(cmd).exit_status.must_equal(code) end - it 'can mock a command via its SHA2 sum' do + it "can mock a command via its SHA2 sum" do out = rand.to_s cmd = rand.to_s shacmd = Digest::SHA256.hexdigest cmd @@ -82,56 +82,56 @@ end end - describe 'when accessing a mocked os' do - it 'has the default mock os faily set to mock' do - connection.os[:name].must_equal 'mock' - connection.platform[:name].must_equal 'mock' + describe "when accessing a mocked os" do + it "has the default mock os faily set to mock" do + connection.os[:name].must_equal "mock" + connection.platform[:name].must_equal "mock" end - it 'sets the OS to the mocked value' do - connection.mock_os({ name: 'centos', family: 'redhat' }) + it "sets the OS to the mocked value" do + connection.mock_os({ name: "centos", family: "redhat" }) connection.os.linux?.must_equal true connection.os.redhat?.must_equal true - connection.os[:family].must_equal 'redhat' + connection.os[:family].must_equal "redhat" end - it 'allows the setting of the name' do - connection.mock_os({ name: 'foo' }) - connection.os[:name].must_equal 'foo' + it "allows the setting of the name" do + connection.mock_os({ name: "foo" }) + connection.os[:name].must_equal "foo" end - it 'allows setting of the family' do - connection.mock_os({ family: 'foo' }) - connection.os[:family].must_equal 'foo' + it "allows setting of the family" do + connection.mock_os({ family: "foo" }) + connection.os[:family].must_equal "foo" end - it 'allows setting of the release' do - connection.mock_os({ release: '1.2.3' }) - connection.os[:release].must_equal '1.2.3' + it "allows setting of the release" do + connection.mock_os({ release: "1.2.3" }) + connection.os[:release].must_equal "1.2.3" end - it 'allows setting of the arch' do - connection.mock_os({ arch: 'amd123' }) - connection.os[:arch].must_equal 'amd123' + it "allows setting of the arch" do + connection.mock_os({ arch: "amd123" }) + connection.os[:arch].must_equal "amd123" end - it 'allow setting of multiple values' do - connection.mock_os({ name: 'foo', family: 'bar' }) - connection.os[:name].must_equal 'foo' - connection.os[:family].must_equal 'bar' - connection.os[:arch].must_equal 'unknown' - connection.os[:release].must_equal 'unknown' + it "allow setting of multiple values" do + connection.mock_os({ name: "foo", family: "bar" }) + connection.os[:name].must_equal "foo" + connection.os[:family].must_equal "bar" + connection.os[:arch].must_equal "unknown" + connection.os[:release].must_equal "unknown" end - it 'properly handles a nil value' do + it "properly handles a nil value" do connection.mock_os(nil) - connection.os[:name].must_equal 'mock' - connection.os[:family].must_equal 'mock' + connection.os[:name].must_equal "mock" + connection.os[:family].must_equal "mock" end end - describe 'when accessing a mocked file' do - it 'handles a non-existing file' do + describe "when accessing a mocked file" do + it "handles a non-existing file" do x = rand.to_s assert_output "", /File not mocked/ do f = connection.file(x) @@ -143,7 +143,7 @@ # tests if all fields between the local json and resulting mock file # are equal - JSON_DATA = Train.create('local').connection.file(__FILE__).to_json + JSON_DATA = Train.create("local").connection.file(__FILE__).to_json RES = Train::Transports::Mock::Connection::File.from_json(JSON_DATA) %w{ content mode owner group }.each do |f| it "can be initialized from json (field #{f})" do diff --git a/test/unit/transports/ssh_connection_test.rb b/test/unit/transports/ssh_connection_test.rb index b24c6d1b..030b8f1c 100644 --- a/test/unit/transports/ssh_connection_test.rb +++ b/test/unit/transports/ssh_connection_test.rb @@ -1,6 +1,6 @@ -require 'helper' -require 'train/transports/ssh' -require 'train/transports/ssh_connection' +require "helper" +require "train/transports/ssh" +require "train/transports/ssh_connection" # Mocha limitations don't let us mock a function # such that it can receive a block, so here's a minimal @@ -11,6 +11,7 @@ def exec(cmd) @cmd = cmd yield("ignored", true) end + def data_handler @handler end @@ -25,31 +26,32 @@ def mock_inbound_data(data) end def on_extended_data; end + def on_request(any); end end - -describe 'ssh connection' do +describe "ssh connection" do let(:cls) do - plat = Train::Platforms.name('mock').in_family('linux') + plat = Train::Platforms.name("mock").in_family("linux") plat.add_platform_methods Train::Platforms::Detect.stubs(:scan).returns(plat) Train::Transports::SSH::Connection end - let(:conf) {{ + let(:conf) do + { host: rand.to_s, password: rand.to_s, - transport_options: {} - }} + transport_options: {}, + } end - describe '#run_command_via_connection through BaseConnection::run_command' do + describe "#run_command_via_connection through BaseConnection::run_command" do let(:ssh) { cls.new(conf) } # A bit more mocking than I'd like to see, but there's no sane way around # it if we want to test output handling behavior. let(:inbound_data) { "testdata" } let(:channel_mock) { MockChannel.new } - let(:session_mock) { + let(:session_mock) do session_mock = mock session_mock.stubs(:closed?).returns false session_mock.stubs(:open_channel).yields(channel_mock) @@ -58,7 +60,7 @@ def on_request(any); end channel_mock.mock_inbound_data(inbound_data) end session_mock - } + end it "invokes the provided block when a block is provided and data is received" do ssh.stubs(:session).returns(session_mock) diff --git a/test/unit/transports/ssh_test.rb b/test/unit/transports/ssh_test.rb index 67f714a4..5c72348d 100644 --- a/test/unit/transports/ssh_test.rb +++ b/test/unit/transports/ssh_test.rb @@ -1,53 +1,54 @@ # encoding: utf-8 -require 'helper' -require 'train/transports/ssh' +require "helper" +require "train/transports/ssh" -describe 'ssh transport' do +describe "ssh transport" do let(:cls) do - plat = Train::Platforms.name('mock').in_family('linux') + plat = Train::Platforms.name("mock").in_family("linux") plat.add_platform_methods Train::Platforms::Detect.stubs(:scan).returns(plat) Train::Transports::SSH end - let(:conf) {{ + let(:conf) do + { host: rand.to_s, password: rand.to_s, key_files: rand.to_s, - proxy_command: 'ssh root@127.0.0.1 -W %h:%p', - }} + proxy_command: "ssh root@127.0.0.1 -W %h:%p", + } end let(:cls_agent) { cls.new({ host: rand.to_s }) } - describe 'default options' do - let(:ssh) { cls.new({ host: 'dummy' }) } + describe "default options" do + let(:ssh) { cls.new({ host: "dummy" }) } - it 'can be instantiated (with valid config)' do + it "can be instantiated (with valid config)" do ssh.wont_be_nil end - it 'configures the host' do - ssh.options[:host].must_equal 'dummy' + it "configures the host" do + ssh.options[:host].must_equal "dummy" end - it 'has default port' do + it "has default port" do ssh.options[:port].must_equal 22 end - it 'has default user' do - ssh.options[:user].must_equal 'root' + it "has default user" do + ssh.options[:user].must_equal "root" end - it 'by default does not request a pty' do + it "by default does not request a pty" do ssh.options[:pty].must_equal false end end - describe 'connection options' do - let(:ssh) { cls.new({ host: 'dummy' }) } - let(:opts) { { } } + describe "connection options" do + let(:ssh) { cls.new({ host: "dummy" }) } + let(:opts) { {} } let(:connection_options) { ssh.send(:connection_options, opts) } - it 'does not set a paranoid option - deprecated in net-ssh 4.2' do + it "does not set a paranoid option - deprecated in net-ssh 4.2" do connection_options.key?(:paranoid).must_equal false end @@ -59,89 +60,89 @@ if current_version < threshold_version it "maps correctly when net-ssh < 5.0" do { - 'true' => true, - 'false' => false, + "true" => true, + "false" => false, nil => false, }.each do |given, expected| - opts = { :verify_host_key => given } + opts = { verify_host_key: given } seen_opts = ssh.send(:connection_options, opts) seen_opts[:verify_host_key].must_equal expected end end - it 'defaults verify_host_key option to false' do + it "defaults verify_host_key option to false" do connection_options[:verify_host_key].must_equal false end else it "maps correctly when net-ssh > 5.0" do { - 'true' => :always, - 'false' => :never, + "true" => :always, + "false" => :never, true => :always, false => :never, - 'always' => :always, - 'never' => :never, + "always" => :always, + "never" => :never, nil => :never, }.each do |given, expected| - opts = { :verify_host_key => given } + opts = { verify_host_key: given } seen_opts = ssh.send(:connection_options, opts) seen_opts[:verify_host_key].must_equal expected end end - it 'defaults verify_host_key option to :never' do + it "defaults verify_host_key option to :never" do connection_options[:verify_host_key].must_equal :never end end end end - describe 'ssh options' do + describe "ssh options" do let(:ssh) { cls.new(conf) } let(:connection) { ssh.connection } - it 'includes BatchMode when :non_interactive is set' do + it "includes BatchMode when :non_interactive is set" do conf[:non_interactive] = true connection.ssh_opts.include?("BatchMode=yes").must_equal true end - it 'excludes BatchMode when :non_interactive is not set' do + it "excludes BatchMode when :non_interactive is not set" do connection.ssh_opts.include?("BatchMode=yes").must_equal false end end - describe 'opening a connection' do + describe "opening a connection" do let(:ssh) { cls.new(conf) } let(:connection) { ssh.connection } - it 'provides a run_command_via_connection method' do + it "provides a run_command_via_connection method" do methods = connection.class.private_instance_methods(false) methods.include?(:run_command_via_connection).must_equal true end - it 'provides a file_via_connection method' do + it "provides a file_via_connection method" do methods = connection.class.private_instance_methods(false) methods.include?(:file_via_connection).must_equal true end - it 'gets the connection' do + it "gets the connection" do connection.must_be_kind_of Train::Transports::SSH::Connection end - it 'provides a uri' do + it "provides a uri" do connection.uri.must_equal "ssh://root@#{conf[:host]}:22" end - it 'must respond to wait_until_ready' do + it "must respond to wait_until_ready" do connection.must_respond_to :wait_until_ready end - it 'can be closed' do + it "can be closed" do connection.close.must_be_nil end - it 'has a login command == ssh' do - connection.login_command.command.must_equal 'ssh' + it "has a login command == ssh" do + connection.login_command.command.must_equal "ssh" end - it 'has login command arguments' do + it "has login command arguments" do connection.login_command.arguments.must_equal([ "-o", "UserKnownHostsFile=/dev/null", "-o", "StrictHostKeyChecking=no", @@ -155,31 +156,31 @@ ]) end - it 'sets the right auth_methods when password is specified' do + it "sets the right auth_methods when password is specified" do conf[:key_files] = nil cls.new(conf).connection.method(:options).call[:auth_methods].must_equal ["none", "password", "keyboard-interactive"] end - it 'sets the right auth_methods when keys are specified' do + it "sets the right auth_methods when keys are specified" do conf[:password] = nil - cls.new(conf).connection.method(:options).call[:auth_methods].must_equal ["none", "publickey"] + cls.new(conf).connection.method(:options).call[:auth_methods].must_equal %w{none publickey} end - it 'sets the right auth_methods for agent auth' do - cls_agent.stubs(:ssh_known_identities).returns({:some => 'rsa_key'}) - cls_agent.connection.method(:options).call[:auth_methods].must_equal ['none', 'publickey'] + it "sets the right auth_methods for agent auth" do + cls_agent.stubs(:ssh_known_identities).returns({ some: "rsa_key" }) + cls_agent.connection.method(:options).call[:auth_methods].must_equal %w{none publickey} end - it 'works with ssh agent auth' do - cls_agent.stubs(:ssh_known_identities).returns({:some => 'rsa_key'}) + it "works with ssh agent auth" do + cls_agent.stubs(:ssh_known_identities).returns({ some: "rsa_key" }) cls_agent.connection end - it 'sets up a proxy when ssh proxy command is specified' do + it "sets up a proxy when ssh proxy command is specified" do mock = MiniTest::Mock.new mock.expect(:call, true) do |hostname, username, options| options[:proxy].kind_of?(Net::SSH::Proxy::Command) && - 'ssh root@127.0.0.1 -W %h:%p' == options[:proxy].command_line_template + "ssh root@127.0.0.1 -W %h:%p" == options[:proxy].command_line_template end connection.stubs(:run_command) Net::SSH.stub(:start, mock) do @@ -189,8 +190,8 @@ end end - describe 'converting connection to string for logging' do - it 'masks passwords' do + describe "converting connection to string for logging" do + it "masks passwords" do assert_output(/.*:password=>"".*/) do connection = cls.new(conf).connection puts "#{connection}" @@ -198,108 +199,109 @@ end end - describe 'failed configuration' do - it 'works with a minimum valid config' do + describe "failed configuration" do + it "works with a minimum valid config" do cls.new(conf).connection end - it 'does not like host == nil' do + it "does not like host == nil" do conf.delete(:host) proc { cls.new(conf).connection }.must_raise Train::ClientError end - it 'reverts to root on user == nil' do + it "reverts to root on user == nil" do conf[:user] = nil - cls.new(conf).connection.method(:options).call[:user] == 'root' + cls.new(conf).connection.method(:options).call[:user] == "root" end - it 'does not like key and password == nil' do + it "does not like key and password == nil" do cls_agent.stubs(:ssh_known_identities).returns({}) proc { cls_agent.connection }.must_raise Train::ClientError end - it 'wont connect if it is not possible' do + it "wont connect if it is not possible" do conf[:connection_timeout] = 1 conf[:connection_retries] = 1 - conf[:host] = 'localhost' + conf[:host] = "localhost" conf[:port] = 1 conf.delete :proxy_command conn = cls.new(conf).connection - proc { conn.run_command('uname') }.must_raise Train::Transports::SSHFailed + proc { conn.run_command("uname") }.must_raise Train::Transports::SSHFailed end end end -describe 'ssh transport with bastion' do +describe "ssh transport with bastion" do let(:cls) do - plat = Train::Platforms.name('mock').in_family('linux') + plat = Train::Platforms.name("mock").in_family("linux") plat.add_platform_methods Train::Platforms::Detect.stubs(:scan).returns(plat) Train::Transports::SSH end - let(:conf) {{ + let(:conf) do + { host: rand.to_s, password: rand.to_s, key_files: rand.to_s, - bastion_host: 'bastion_dummy', - }} + bastion_host: "bastion_dummy", + } end let(:cls_agent) { cls.new({ host: rand.to_s }) } - describe 'bastion' do - describe 'default options' do - let(:ssh) { cls.new({ bastion_host: 'bastion_dummy' }) } + describe "bastion" do + describe "default options" do + let(:ssh) { cls.new({ bastion_host: "bastion_dummy" }) } - it 'configures the host' do - ssh.options[:bastion_host].must_equal 'bastion_dummy' + it "configures the host" do + ssh.options[:bastion_host].must_equal "bastion_dummy" end - it 'has default port' do + it "has default port" do ssh.options[:bastion_port].must_equal 22 end - it 'has default user' do - ssh.options[:bastion_user].must_equal 'root' + it "has default user" do + ssh.options[:bastion_user].must_equal "root" end end - describe 'opening a connection' do + describe "opening a connection" do let(:ssh) { cls.new(conf) } let(:connection) { ssh.connection } - it 'provides a run_command_via_connection method' do + it "provides a run_command_via_connection method" do methods = connection.class.private_instance_methods(false) methods.include?(:run_command_via_connection).must_equal true end - it 'provides a file_via_connection method' do + it "provides a file_via_connection method" do methods = connection.class.private_instance_methods(false) methods.include?(:file_via_connection).must_equal true end - it 'gets the connection' do + it "gets the connection" do connection.must_be_kind_of Train::Transports::SSH::Connection end - it 'provides a uri' do + it "provides a uri" do connection.uri.must_equal "ssh://root@#{conf[:host]}:22" end - it 'must respond to wait_until_ready' do + it "must respond to wait_until_ready" do connection.must_respond_to :wait_until_ready end - it 'can be closed' do + it "can be closed" do connection.close.must_be_nil end - it 'has a login command == ssh' do - connection.login_command.command.must_equal 'ssh' + it "has a login command == ssh" do + connection.login_command.command.must_equal "ssh" end -make_my_diffs_pretty! + make_my_diffs_pretty! - it 'has login command arguments' do + it "has login command arguments" do connection.login_command.arguments.must_equal([ "-o", "UserKnownHostsFile=/dev/null", "-o", "StrictHostKeyChecking=no", @@ -313,27 +315,27 @@ ]) end - it 'sets the right auth_methods when password is specified' do + it "sets the right auth_methods when password is specified" do conf[:key_files] = nil cls.new(conf).connection.method(:options).call[:auth_methods].must_equal ["none", "password", "keyboard-interactive"] end - it 'sets the right auth_methods when keys are specified' do + it "sets the right auth_methods when keys are specified" do conf[:password] = nil - cls.new(conf).connection.method(:options).call[:auth_methods].must_equal ["none", "publickey"] + cls.new(conf).connection.method(:options).call[:auth_methods].must_equal %w{none publickey} end - it 'sets the right auth_methods for agent auth' do - cls_agent.stubs(:ssh_known_identities).returns({:some => 'rsa_key'}) - cls_agent.connection.method(:options).call[:auth_methods].must_equal ['none', 'publickey'] + it "sets the right auth_methods for agent auth" do + cls_agent.stubs(:ssh_known_identities).returns({ some: "rsa_key" }) + cls_agent.connection.method(:options).call[:auth_methods].must_equal %w{none publickey} end - it 'works with ssh agent auth' do - cls_agent.stubs(:ssh_known_identities).returns({:some => 'rsa_key'}) + it "works with ssh agent auth" do + cls_agent.stubs(:ssh_known_identities).returns({ some: "rsa_key" }) cls_agent.connection end - it 'sets up a proxy when ssh proxy command is specified' do + it "sets up a proxy when ssh proxy command is specified" do mock = MiniTest::Mock.new mock.expect(:call, true) do |hostname, username, options| options[:proxy].kind_of?(Net::SSH::Proxy::Command) && @@ -349,25 +351,26 @@ end end -describe 'ssh transport with bastion and proxy' do +describe "ssh transport with bastion and proxy" do let(:cls) do - plat = Train::Platforms.name('mock').in_family('linux') + plat = Train::Platforms.name("mock").in_family("linux") plat.add_platform_methods Train::Platforms::Detect.stubs(:scan).returns(plat) Train::Transports::SSH end - let(:conf) {{ + let(:conf) do + { host: rand.to_s, password: rand.to_s, key_files: rand.to_s, - bastion_host: 'bastion_dummy', - proxy_command: 'dummy' - }} + bastion_host: "bastion_dummy", + proxy_command: "dummy", + } end let(:cls_agent) { cls.new({ host: rand.to_s }) } - describe 'bastion and proxy' do - it 'will throw an exception when both proxy_command and bastion_host is specified' do + describe "bastion and proxy" do + it "will throw an exception when both proxy_command and bastion_host is specified" do proc { cls.new(conf).connection }.must_raise Train::ClientError end end diff --git a/test/unit/transports/vmware_test.rb b/test/unit/transports/vmware_test.rb index f3f6b2af..1b340d3f 100644 --- a/test/unit/transports/vmware_test.rb +++ b/test/unit/transports/vmware_test.rb @@ -1,23 +1,23 @@ # encoding: utf-8 -require 'helper' -require 'train/transports/vmware' +require "helper" +require "train/transports/vmware" -describe 'Train::Transports::VMware::Connection' do +describe "Train::Transports::VMware::Connection" do def add_stubs(stub_options) Train::Transports::VMware::Connection.any_instance .stubs(:detect_powershell_binary) .returns(stub_options[:powershell_binary] || :pwsh) Train::Transports::VMware::Connection.any_instance .stubs(:powercli_version) - .returns('10.1.1.8827525') + .returns("10.1.1.8827525") Train::Transports::VMware::Connection.any_instance .stubs(:run_command_via_connection) - .with('(Get-VMHost | Get-View).hardware.systeminfo.uuid') + .with("(Get-VMHost | Get-View).hardware.systeminfo.uuid") .returns(stub_options[:mock_uuid_result] || nil) if stub_options[:mock_connect_result] Train::Transports::VMware::Connection.any_instance .expects(:run_command_via_connection) - .with('Connect-VIServer 10.0.0.10 -User testuser -Password supersecurepassword | Out-Null') + .with("Connect-VIServer 10.0.0.10 -User testuser -Password supersecurepassword | Out-Null") .returns(stub_options[:mock_connect_result]) else Train::Transports::VMware::Connection.any_instance @@ -27,118 +27,118 @@ def add_stubs(stub_options) end def create_transport(options = {}) - ENV['VISERVER'] = '10.0.0.10' - ENV['VISERVER_USERNAME'] = 'testuser' - ENV['VISERVER_PASSWORD'] = 'supersecurepassword' + ENV["VISERVER"] = "10.0.0.10" + ENV["VISERVER_USERNAME"] = "testuser" + ENV["VISERVER_PASSWORD"] = "supersecurepassword" add_stubs(options[:stub_options] || {}) Train::Transports::VMware.new(options[:transport_options]) end - describe '#initialize' do - it 'defaults to ENV options' do + describe "#initialize" do + it "defaults to ENV options" do options = create_transport.connection.instance_variable_get(:@options) - options[:viserver].must_equal '10.0.0.10' - options[:username].must_equal 'testuser' - options[:password].must_equal 'supersecurepassword' + options[:viserver].must_equal "10.0.0.10" + options[:username].must_equal "testuser" + options[:password].must_equal "supersecurepassword" options[:insecure].must_equal false end - it 'allows for overriding options' do + it "allows for overriding options" do transport = create_transport( transport_options: { - viserver: '10.1.1.1', - username: 'anotheruser', - password: 'notsecurepassword', + viserver: "10.1.1.1", + username: "anotheruser", + password: "notsecurepassword", insecure: false, } ) options = transport.connection.instance_variable_get(:@options) - options[:viserver].must_equal '10.1.1.1' - options[:username].must_equal 'anotheruser' - options[:password].must_equal 'notsecurepassword' + options[:viserver].must_equal "10.1.1.1" + options[:username].must_equal "anotheruser" + options[:password].must_equal "notsecurepassword" options[:insecure].must_equal false end - it 'ignores certificate validation if --insecure is used' do + it "ignores certificate validation if --insecure is used" do Train::Transports::VMware::Connection.any_instance .expects(:run_command_via_connection) - .with('Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Scope Session -Confirm:$False') + .with("Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Scope Session -Confirm:$False") .returns(nil) transport = create_transport(transport_options: { insecure: true }) options = transport.connection.instance_variable_get(:@options) options[:insecure].must_equal true end - it 'uses the Local connection when Windows PowerShell is found' do - require 'train/transports/local' + it "uses the Local connection when Windows PowerShell is found" do + require "train/transports/local" Train::Transports::Local::Connection.expects(:new) create_transport( stub_options: { - powershell_binary: :powershell + powershell_binary: :powershell, } ).connection end end - describe '#connect' do + describe "#connect" do def mock_connect_result(stderr, exit_status) OpenStruct.new(stderr: stderr, exit_status: exit_status) end - it 'raises certificate error when stderr matches regular expression' do + it "raises certificate error when stderr matches regular expression" do e = proc { create_transport( stub_options: { mock_connect_result: mock_connect_result( - 'Invalid server certificate', 1 - ) + "Invalid server certificate", 1 + ), } ).connection }.must_raise(RuntimeError) - e.message.must_match /Unable to connect.*Please use `--insecure`/ + e.message.must_match(/Unable to connect.*Please use `--insecure`/) end - it 'raises auth error when stderr matches regular expression' do + it "raises auth error when stderr matches regular expression" do e = proc { create_transport( stub_options: { mock_connect_result: mock_connect_result( - 'incorrect user name or password', 1 - ) + "incorrect user name or password", 1 + ), } ).connection }.must_raise(RuntimeError) - e.message.must_match /Unable to connect.*Incorrect username/ + e.message.must_match(/Unable to connect.*Incorrect username/) end - it 'redacts the password when an unspecified error is raised' do + it "redacts the password when an unspecified error is raised" do e = proc { create_transport( stub_options: { mock_connect_result: mock_connect_result( - 'something unexpected -Password supersecret -AnotherOption', 1 - ) + "something unexpected -Password supersecret -AnotherOption", 1 + ), } ).connection }.must_raise(RuntimeError) - e.message.must_match /-Password REDACTED/ + e.message.must_match(/-Password REDACTED/) end end - describe '#platform' do - it 'returns correct platform details' do + describe "#platform" do + it "returns correct platform details" do platform = create_transport.connection.platform - platform.clean_name.must_equal 'vmware' - platform.family_hierarchy.must_equal ['cloud', 'api'] - platform.platform.must_equal(release: 'vmware-powercli-10.1.1.8827525') + platform.clean_name.must_equal "vmware" + platform.family_hierarchy.must_equal %w{cloud api} + platform.platform.must_equal(release: "vmware-powercli-10.1.1.8827525") platform.vmware?.must_equal true end end - describe '#unique_identifier' do - it 'returns the correct unique identifier' do - uuid = '1f261432-e23e-6911-841c-94c6911a02dd' + describe "#unique_identifier" do + it "returns the correct unique identifier" do + uuid = "1f261432-e23e-6911-841c-94c6911a02dd" mock_uuid_result = OpenStruct.new( stdout: uuid + "\n" ) @@ -150,9 +150,9 @@ def mock_connect_result(stderr, exit_status) end end - describe '#uri' do - it 'returns the correct URI' do - create_transport.connection.uri.must_equal 'vmware://testuser@10.0.0.10' + describe "#uri" do + it "returns the correct URI" do + create_transport.connection.uri.must_equal "vmware://testuser@10.0.0.10" end end end diff --git a/test/unit/transports/winrm_connection_test.rb b/test/unit/transports/winrm_connection_test.rb index b24a1195..62841112 100644 --- a/test/unit/transports/winrm_connection_test.rb +++ b/test/unit/transports/winrm_connection_test.rb @@ -1,30 +1,31 @@ -require 'helper' -require 'train/transports/winrm' -require 'train/transports/winrm_connection' -require 'winrm/output' +require "helper" +require "train/transports/winrm" +require "train/transports/winrm_connection" +require "winrm/output" -describe 'winrm connection' do +describe "winrm connection" do let(:cls) do - plat = Train::Platforms.name('mock').in_family('windows') + plat = Train::Platforms.name("mock").in_family("windows") plat.add_platform_methods Train::Platforms::Detect.stubs(:scan).returns(plat) Train::Transports::WinRM::Connection end - let(:conf) {{ + let(:conf) do + { hostname: rand.to_s, - }} - describe '#run_command_via_connection through BaseConnection::run_command' do + } end + describe "#run_command_via_connection through BaseConnection::run_command" do let(:winrm) { cls.new(conf) } - let(:session_mock) { + let(:session_mock) do session_mock = mock - session_mock.expects(:run). - with("test"). - yields('testdata', 'ignored'). - returns(WinRM::Output.new) + session_mock.expects(:run) + .with("test") + .yields("testdata", "ignored") + .returns(WinRM::Output.new) session_mock - } + end it "invokes the provided block when a block is provided and data is received" do called = false winrm.expects(:session).returns(session_mock) @@ -32,11 +33,10 @@ # We need to test run_command b/c run_command_via_connection is proviate. winrm.run_command("test") do |data| called = true - data.must_equal 'testdata' + data.must_equal "testdata" end called.must_equal true end end end - diff --git a/test/unit/transports/winrm_test.rb b/test/unit/transports/winrm_test.rb index 5cbad66a..fa30f42d 100644 --- a/test/unit/transports/winrm_test.rb +++ b/test/unit/transports/winrm_test.rb @@ -1,100 +1,103 @@ # encoding: utf-8 -require 'helper' -require 'train/transports/winrm' +require "helper" +require "train/transports/winrm" -describe 'winrm transport' do +describe "winrm transport" do let(:cls) do - plat = Train::Platforms.name('mock').in_family('windows') + plat = Train::Platforms.name("mock").in_family("windows") plat.add_platform_methods Train::Platforms::Detect.stubs(:scan).returns(plat) Train::Transports::WinRM end - let(:conf) {{ + let(:conf) do + { host: rand.to_s, password: rand.to_s, - }} + } end let(:cls_agent) { cls.new({ host: rand.to_s }) } - describe 'default options' do - let(:winrm) { cls.new({ host: 'dummy' }) } + describe "default options" do + let(:winrm) { cls.new({ host: "dummy" }) } - it 'can be instantiated (with valid config)' do + it "can be instantiated (with valid config)" do winrm.wont_be_nil end - it 'configures the host' do - winrm.options[:host].must_equal 'dummy' + it "configures the host" do + winrm.options[:host].must_equal "dummy" end - it 'has default endpoint' do + it "has default endpoint" do winrm.options[:endpoint].must_be_nil end - it 'has default path set' do - winrm.options[:path].must_equal '/wsman' + it "has default path set" do + winrm.options[:path].must_equal "/wsman" end - it 'has default ssl set' do + it "has default ssl set" do winrm.options[:ssl].must_equal false end - it 'has default self_signed set' do + it "has default self_signed set" do winrm.options[:self_signed].must_equal false end - it 'has default rdp_port set' do + it "has default rdp_port set" do winrm.options[:rdp_port].must_equal 3389 end - it 'has default winrm_transport set' do + it "has default winrm_transport set" do winrm.options[:winrm_transport].must_equal :negotiate end - it 'has default winrm_disable_sspi set' do + it "has default winrm_disable_sspi set" do winrm.options[:winrm_disable_sspi].must_equal false end - it 'has default winrm_basic_auth_only set' do + it "has default winrm_basic_auth_only set" do winrm.options[:winrm_basic_auth_only].must_equal false end - it 'has default user' do - winrm.options[:user].must_equal 'administrator' + it "has default user" do + winrm.options[:user].must_equal "administrator" end - it 'has default ca_trust_path set' do + it "has default ca_trust_path set" do winrm.options.key?(:ca_trust_path).must_equal true winrm.options[:ca_trust_path].must_be_nil end end - describe 'winrm options' do + describe "winrm options" do let(:winrm) { cls.new(conf) } let(:connection) { winrm.connection } - it 'without ssl genrates uri' do - conf[:host] = 'dummy_host' - connection.uri.must_equal 'winrm://administrator@http://dummy_host:5985/wsman:3389' + it "without ssl genrates uri" do + conf[:host] = "dummy_host" + connection.uri.must_equal "winrm://administrator@http://dummy_host:5985/wsman:3389" end - it 'without ssl genrates uri' do + it "without ssl genrates uri" do conf[:ssl] = true - conf[:host] = 'dummy_host_ssl' - connection.uri.must_equal 'winrm://administrator@https://dummy_host_ssl:5986/wsman:3389' + conf[:host] = "dummy_host_ssl" + connection.uri.must_equal "winrm://administrator@https://dummy_host_ssl:5986/wsman:3389" end end - describe 'when configuring the connection' do - let(:winrm) { + describe "when configuring the connection" do + let(:winrm) do cls.new(conf) - } + end - let(:conf) {{ - winrm_transport: :negotiate, - host: rand.to_s, - password: rand.to_s, - }} + let(:conf) do + { + winrm_transport: :negotiate, + host: rand.to_s, + password: rand.to_s, + } + end def connection_option_value(name) winrm.send(:connection_options, conf)[name] @@ -111,10 +114,10 @@ def connection_option_value(name) end end - describe 'options validation' do + describe "options validation" do let(:winrm) { cls.new(conf) } - it 'raises an error when a non-supported winrm_transport is specificed' do - conf[:winrm_transport] = 'invalid' + it "raises an error when a non-supported winrm_transport is specificed" do + conf[:winrm_transport] = "invalid" proc { winrm.connection }.must_raise Train::ClientError end end diff --git a/test/unit/version_test.rb b/test/unit/version_test.rb index f00195a6..12cc8b53 100644 --- a/test/unit/version_test.rb +++ b/test/unit/version_test.rb @@ -1,8 +1,8 @@ # encoding: utf-8 -require 'helper' +require "helper" describe Train do - it 'defines a version' do + it "defines a version" do Train::VERSION.must_be_instance_of String end end diff --git a/test/windows/local_test.rb b/test/windows/local_test.rb index f3c810ff..d4cfc62d 100644 --- a/test/windows/local_test.rb +++ b/test/windows/local_test.rb @@ -2,39 +2,39 @@ # author: Christoph Hartmann # author: Dominik Richter -require 'minitest/autorun' -require 'minitest/spec' -require 'mocha/setup' -require 'train' -require 'tempfile' +require "minitest/autorun" +require "minitest/spec" +require "mocha/setup" +require "train" +require "tempfile" # Loading here to ensure methods exist to be stubbed -require 'train/transports/local' +require "train/transports/local" -describe 'windows local command' do +describe "windows local command" do let(:backend) do # get final config target_config = Train.target_config({}) # initialize train - backend = Train.create('local', target_config) + Train.create("local", target_config) end let(:conn) { backend.connection } - it 'verify os' do + it "verify os" do os = conn.os os[:name].must_match(/windows_server.*_datacenter/) os[:family].must_equal "windows" os[:release].must_match(/\d+(\.\d+)+/) - os[:arch].must_equal 'x86_64' + os[:arch].must_equal "x86_64" end - it 'run echo test' do + it "run echo test" do cmd = conn.run_command('Write-Output "test"') cmd.stdout.must_equal "test\r\n" - cmd.stderr.must_equal '' + cmd.stderr.must_equal "" end - describe 'force 64 bit powershell command' do + describe "force 64 bit powershell command" do let(:runner) { conn.instance_variable_get(:@runner) } let(:powershell) { runner.instance_variable_get(:@powershell_cmd) } RUBY_PLATFORM_DUP = RUBY_PLATFORM.dup @@ -50,57 +50,57 @@ def override_platform(platform) ::Object.const_set(:RUBY_PLATFORM, RUBY_PLATFORM_DUP) end - it 'use normal powershell with PipeRunner' do + it "use normal powershell with PipeRunner" do Train::Transports::Local::Connection::WindowsPipeRunner .any_instance .expects(:acquire_pipe) - .returns('acquired') + .returns("acquired") - override_platform('x64-mingw32') - powershell.must_equal 'powershell' + override_platform("x64-mingw32") + powershell.must_equal "powershell" end - it 'use 64bit powershell with PipeRunner' do + it "use 64bit powershell with PipeRunner" do Train::Transports::Local::Connection::WindowsPipeRunner .any_instance .expects(:acquire_pipe) - .returns('acquired') + .returns("acquired") - override_platform('i386-mingw32') + override_platform("i386-mingw32") powershell.must_equal "#{ENV['SystemRoot']}\\sysnative\\WindowsPowerShell\\v1.0\\powershell.exe" end - it 'use normal powershell with ShellRunner' do + it "use normal powershell with ShellRunner" do Train::Transports::Local::Connection::WindowsPipeRunner .any_instance .expects(:acquire_pipe) .returns(nil) - override_platform('x64-mingw32') + override_platform("x64-mingw32") runner.class.must_equal Train::Transports::Local::Connection::WindowsShellRunner - powershell.must_equal 'powershell' + powershell.must_equal "powershell" end - it 'use 64bit powershell with ShellRunner' do + it "use 64bit powershell with ShellRunner" do Train::Transports::Local::Connection::WindowsPipeRunner .any_instance .expects(:acquire_pipe) .returns(nil) - override_platform('i386-mingw32') + override_platform("i386-mingw32") runner.class.must_equal Train::Transports::Local::Connection::WindowsShellRunner powershell.must_equal "#{ENV['SystemRoot']}\\sysnative\\WindowsPowerShell\\v1.0\\powershell.exe" end end - it 'use powershell piping' do + it "use powershell piping" do cmd = conn.run_command("New-Object -Type PSObject | Add-Member -MemberType NoteProperty -Name A -Value (Write-Output 'PropertyA') -PassThru | Add-Member -MemberType NoteProperty -Name B -Value (Write-Output 'PropertyB') -PassThru | ConvertTo-Json") cmd.stdout.must_equal "{\r\n \"A\": \"PropertyA\",\r\n \"B\": \"PropertyB\"\r\n}\r\n" - cmd.stderr.must_equal '' + cmd.stderr.must_equal "" end - it 'can execute a command using a named pipe' do - SecureRandom.expects(:hex).returns('via_pipe') + it "can execute a command using a named pipe" do + SecureRandom.expects(:hex).returns("via_pipe") Train::Transports::Local::Connection::WindowsShellRunner .any_instance @@ -108,12 +108,12 @@ def override_platform(platform) .never cmd = conn.run_command('Write-Output "Create pipe"') - File.exist?('//./pipe/inspec_via_pipe').must_equal true + File.exist?("//./pipe/inspec_via_pipe").must_equal true cmd.stdout.must_equal "Create pipe\r\n" - cmd.stderr.must_equal '' + cmd.stderr.must_equal "" end - it 'can execute a command via ShellRunner if pipe creation fails' do + it "can execute a command via ShellRunner if pipe creation fails" do # By forcing `acquire_pipe` to fail to return a pipe, any attempts to create # a `WindowsPipeRunner` object should fail. If we can still run a command, # then we know that it was successfully executed by `Mixlib::ShellOut`. @@ -128,88 +128,88 @@ def override_platform(platform) cmd = conn.run_command('Write-Output "test"') cmd.stdout.must_equal "test\r\n" - cmd.stderr.must_equal '' + cmd.stderr.must_equal "" end - describe 'file' do + describe "file" do before do - @temp = Tempfile.new('foo') + @temp = Tempfile.new("foo") @temp.write("hello world") @temp.rewind end let(:file) { conn.file(@temp.path) } - it 'exists' do + it "exists" do file.exist?.must_equal(true) end - it 'is a file' do + it "is a file" do file.file?.must_equal(true) end - it 'has type :file' do + it "has type :file" do file.type.must_equal(:file) end - it 'has content' do + it "has content" do file.content.must_equal("hello world") end - it 'returns basename of file' do + it "returns basename of file" do file_name = ::File.basename(@temp) file.basename.must_equal(file_name) end - it 'has owner name' do + it "has owner name" do file.owner.wont_be_nil end - it 'has no group name' do + it "has no group name" do file.group.must_be_nil end - it 'has no mode' do + it "has no mode" do file.mode.wont_be_nil end - it 'has an md5sum' do + it "has an md5sum" do file.md5sum.wont_be_nil end - it 'has an sha256sum' do + it "has an sha256sum" do file.sha256sum.wont_be_nil end - it 'has no modified time' do + it "has no modified time" do file.mtime.wont_be_nil end - it 'has no size' do + it "has no size" do file.size.wont_be_nil end - it 'has size 11' do + it "has size 11" do size = ::File.size(@temp) file.size.must_equal size end - it 'has no selinux_label handling' do + it "has no selinux_label handling" do file.selinux_label.must_be_nil end - it 'has product_version' do + it "has product_version" do file.product_version.wont_be_nil end - it 'has file_version' do + it "has file_version" do file.file_version.wont_be_nil end - it 'provides a json representation' do + it "provides a json representation" do j = file.to_json j.must_be_kind_of Hash - j['type'].must_equal :file + j["type"].must_equal :file end after do @@ -218,9 +218,9 @@ def override_platform(platform) end end - describe 'file' do + describe "file" do before do - @temp = Tempfile.new('foo bar') + @temp = Tempfile.new("foo bar") @temp.rewind end diff --git a/test/windows/winrm_test.rb b/test/windows/winrm_test.rb index d475fe9e..dca18a56 100644 --- a/test/windows/winrm_test.rb +++ b/test/windows/winrm_test.rb @@ -2,124 +2,123 @@ # author: Christoph Hartmann # author: Dominik Richter -require 'minitest/autorun' -require 'minitest/spec' -require 'mocha/setup' -require 'train' +require "minitest/autorun" +require "minitest/spec" +require "mocha/setup" +require "train" -describe 'windows winrm command' do - let(:conn) { +describe "windows winrm command" do + let(:conn) do # get final config target_config = Train.target_config({ - target: ENV['train_target'], - password: ENV['winrm_pass'], - ssl: ENV['train_ssl'], + target: ENV["train_target"], + password: ENV["winrm_pass"], + ssl: ENV["train_ssl"], self_signed: true, }) # initialize train - backend = Train.create('winrm', target_config) + backend = Train.create("winrm", target_config) # start or reuse a connection conn = backend.connection conn - } + end - it 'verify os' do + it "verify os" do os = conn.os os[:name].must_match(/windows_server.*_datacenter/) - os[:family].must_equal 'windows' + os[:family].must_equal "windows" os[:release].must_match(/\d+(\.\d+)+/) - os[:arch].must_equal 'x86_64' + os[:arch].must_equal "x86_64" end - it 'run echo test' do + it "run echo test" do cmd = conn.run_command('Write-Output "test"') cmd.stdout.must_equal "test\r\n" - cmd.stderr.must_equal '' + cmd.stderr.must_equal "" end - it 'use powershell piping' do + it "use powershell piping" do cmd = conn.run_command("New-Object -Type PSObject | Add-Member -MemberType NoteProperty -Name A -Value (Write-Output 'PropertyA') -PassThru | Add-Member -MemberType NoteProperty -Name B -Value (Write-Output 'PropertyB') -PassThru | ConvertTo-Json") cmd.stdout.must_equal "{\r\n \"A\": \"PropertyA\",\r\n \"B\": \"PropertyB\"\r\n}\r\n" - cmd.stderr.must_equal '' + cmd.stderr.must_equal "" end - - describe 'file' do + describe "file" do before do - @temp = Tempfile.new('foo') + @temp = Tempfile.new("foo") @temp.write("hello world") @temp.rewind end let(:file) { conn.file(@temp.path) } - it 'exists' do + it "exists" do file.exist?.must_equal(true) end - it 'is a file' do + it "is a file" do file.file?.must_equal(true) end - it 'has type :file' do + it "has type :file" do file.type.must_equal(:file) end - it 'has content' do + it "has content" do # TODO: this shouldn't include newlines that aren't in the original file file.content.must_equal("hello world\r\n") end - it 'has owner name' do + it "has owner name" do file.owner.wont_be_nil end - it 'has no group name' do + it "has no group name" do file.group.must_be_nil end - it 'has no mode' do + it "has no mode" do file.mode.must_be_nil end - it 'has the correct md5sum' do + it "has the correct md5sum" do # Must create unique file to prevent `ERROR_SHARING_VIOLATION` - tempfile = Tempfile.new('tempfile') - tempfile.write('easy to hash') + tempfile = Tempfile.new("tempfile") + tempfile.write("easy to hash") tempfile.close - conn.file(tempfile.path).md5sum.must_equal 'c15b41ade1221a532a38d89671ffaa20' + conn.file(tempfile.path).md5sum.must_equal "c15b41ade1221a532a38d89671ffaa20" tempfile.unlink end - it 'has the correct sha256sum' do + it "has the correct sha256sum" do # Must create unique file to prevent `ERROR_SHARING_VIOLATION` - tempfile = Tempfile.new('tempfile') - tempfile.write('easy to hash') + tempfile = Tempfile.new("tempfile") + tempfile.write("easy to hash") tempfile.close - conn.file(tempfile.path).sha256sum.must_equal '24ae25354d5f697566e715cd46e1df2f490d0b8367c21447962dbf03bf7225ba' + conn.file(tempfile.path).sha256sum.must_equal "24ae25354d5f697566e715cd46e1df2f490d0b8367c21447962dbf03bf7225ba" tempfile.unlink end - it 'has no modified time' do + it "has no modified time" do file.mtime.must_be_nil end - it 'has no size' do + it "has no size" do file.size.wont_be_nil end - it 'has size 11' do + it "has size 11" do size = ::File.size(@temp) file.size.must_equal size end - it 'has no selinux_label handling' do + it "has no selinux_label handling" do file.selinux_label.must_be_nil end - it 'has product_version' do + it "has product_version" do file.product_version.wont_be_nil end @@ -129,30 +128,30 @@ # file.basename.must_equal basename # end - it 'has file_version' do + it "has file_version" do file.file_version.wont_be_nil end - it 'returns nil for mounted' do + it "returns nil for mounted" do file.mounted.must_be_nil end - it 'has no link_path' do + it "has no link_path" do file.link_path.must_be_nil end - it 'has no uid' do + it "has no uid" do file.uid.must_be_nil end - it 'has no gid' do + it "has no gid" do file.gid.must_be_nil end - it 'provides a json representation' do + it "provides a json representation" do j = file.to_json j.must_be_kind_of Hash - j['type'].must_equal :file + j["type"].must_equal :file end after do @@ -161,9 +160,9 @@ end end - describe 'file' do + describe "file" do before do - @temp = Tempfile.new('foo bar') + @temp = Tempfile.new("foo bar") @temp.write("hello world") @temp.rewind end diff --git a/train-core.gemspec b/train-core.gemspec index 9b9818c5..eb816479 100644 --- a/train-core.gemspec +++ b/train-core.gemspec @@ -1,42 +1,42 @@ # encoding: utf-8 -lib = File.expand_path('../lib', __FILE__) +lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require 'train/version' +require "train/version" CORE_TRANSPORTS = [ - 'lib/train/transports/local.rb', - 'lib/train/transports/mock.rb', - 'lib/train/transports/ssh.rb', - 'lib/train/transports/ssh_connection.rb', - 'lib/train/transports/cisco_ios_connection.rb', - 'lib/train/transports/winrm.rb', - 'lib/train/transports/winrm_connection.rb', + "lib/train/transports/local.rb", + "lib/train/transports/mock.rb", + "lib/train/transports/ssh.rb", + "lib/train/transports/ssh_connection.rb", + "lib/train/transports/cisco_ios_connection.rb", + "lib/train/transports/winrm.rb", + "lib/train/transports/winrm_connection.rb", ].freeze Gem::Specification.new do |spec| - spec.name = 'train-core' + spec.name = "train-core" spec.version = Train::VERSION - spec.authors = ['Dominik Richter'] - spec.email = ['drichter@chef.io'] - spec.summary = 'Transport interface to talk to a selected set of backends.' - spec.description = 'A minimal Train with a backends for ssh and winrm.' - spec.homepage = 'https://github.com/inspec/train/' - spec.license = 'Apache-2.0' + spec.authors = ["Dominik Richter"] + spec.email = ["drichter@chef.io"] + spec.summary = "Transport interface to talk to a selected set of backends." + spec.description = "A minimal Train with a backends for ssh and winrm." + spec.homepage = "https://github.com/inspec/train/" + spec.license = "Apache-2.0" - spec.required_ruby_version = '>= 2.4' + spec.required_ruby_version = ">= 2.4" spec.files = %w{LICENSE} + Dir - .glob('lib/**/*', File::FNM_DOTMATCH) + .glob("lib/**/*", File::FNM_DOTMATCH) .reject { |f| f =~ %r{lib/train/transports} unless CORE_TRANSPORTS.include?(f) } .reject { |f| File.directory?(f) } spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } - spec.require_paths = ['lib'] + spec.require_paths = ["lib"] - spec.add_dependency 'json', '>= 1.8', '< 3.0' - spec.add_dependency 'mixlib-shellout', '>= 2.0', '< 4.0' - spec.add_dependency 'net-ssh', '>= 2.9', '< 6.0' - spec.add_dependency 'net-scp', '>= 1.2', '< 3.0' - spec.add_dependency 'winrm', '~> 2.0' - spec.add_dependency 'winrm-fs', '~> 1.0' + spec.add_dependency "json", ">= 1.8", "< 3.0" + spec.add_dependency "mixlib-shellout", ">= 2.0", "< 4.0" + spec.add_dependency "net-ssh", ">= 2.9", "< 6.0" + spec.add_dependency "net-scp", ">= 1.2", "< 3.0" + spec.add_dependency "winrm", "~> 2.0" + spec.add_dependency "winrm-fs", "~> 1.0" end diff --git a/train.gemspec b/train.gemspec index 179ad49e..24b08bd1 100644 --- a/train.gemspec +++ b/train.gemspec @@ -1,39 +1,39 @@ # coding: utf-8 -lib = File.expand_path('../lib', __FILE__) +lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require 'train/version' +require "train/version" Gem::Specification.new do |spec| - spec.name = 'train' + spec.name = "train" spec.version = Train::VERSION - spec.authors = ['Dominik Richter'] - spec.email = ['drichter@chef.io'] - spec.summary = 'Transport interface to talk to different backends.' - spec.description = 'Transport interface to talk to different backends.' - spec.homepage = 'https://github.com/inspec/train/' - spec.license = 'Apache-2.0' + spec.authors = ["Dominik Richter"] + spec.email = ["drichter@chef.io"] + spec.summary = "Transport interface to talk to different backends." + spec.description = "Transport interface to talk to different backends." + spec.homepage = "https://github.com/inspec/train/" + spec.license = "Apache-2.0" - spec.files = %w{LICENSE} + Dir.glob('lib/**/*', File::FNM_DOTMATCH).reject { |f| File.directory?(f) } + spec.files = %w{LICENSE} + Dir.glob("lib/**/*", File::FNM_DOTMATCH).reject { |f| File.directory?(f) } spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) - spec.require_paths = ['lib'] + spec.require_paths = ["lib"] - spec.required_ruby_version = '>= 2.4' + spec.required_ruby_version = ">= 2.4" - spec.add_dependency 'json', '>= 1.8', '< 3.0' - spec.add_dependency 'mixlib-shellout', '>= 2.0', '< 4.0' - spec.add_dependency 'net-ssh', '>= 2.9', '< 6.0' - spec.add_dependency 'net-scp', '>= 1.2', '< 3.0' - spec.add_dependency 'winrm', '~> 2.0' - spec.add_dependency 'winrm-fs', '~> 1.0' - spec.add_dependency 'docker-api', '~> 1.26' - spec.add_dependency 'azure_mgmt_resources', '~> 0.15' - spec.add_dependency 'azure_graph_rbac', '~> 0.16' - spec.add_dependency 'azure_mgmt_key_vault', '~> 0.17' - spec.add_dependency 'google-api-client', '~> 0.23.9' - spec.add_dependency 'googleauth', '~> 0.6.6' - spec.add_dependency 'inifile' + spec.add_dependency "json", ">= 1.8", "< 3.0" + spec.add_dependency "mixlib-shellout", ">= 2.0", "< 4.0" + spec.add_dependency "net-ssh", ">= 2.9", "< 6.0" + spec.add_dependency "net-scp", ">= 1.2", "< 3.0" + spec.add_dependency "winrm", "~> 2.0" + spec.add_dependency "winrm-fs", "~> 1.0" + spec.add_dependency "docker-api", "~> 1.26" + spec.add_dependency "azure_mgmt_resources", "~> 0.15" + spec.add_dependency "azure_graph_rbac", "~> 0.16" + spec.add_dependency "azure_mgmt_key_vault", "~> 0.17" + spec.add_dependency "google-api-client", "~> 0.23.9" + spec.add_dependency "googleauth", "~> 0.6.6" + spec.add_dependency "inifile" - spec.add_development_dependency 'mocha', '~> 1.1' + spec.add_development_dependency "mocha", "~> 1.1" end