diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..7e913e6 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,20 @@ +name: CI +on: + pull_request: + push: + branches: + - master +jobs: + rubocop: + runs-on: ubuntu-latest + env: + BUNDLE_SMART_PROXY: '0' + steps: + - uses: actions/checkout@v2 + - name: Setup Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: 2.5 + bundler-cache: true + - name: Run rubocop + run: bundle exec rubocop --format github diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..c4112e1 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,20 @@ +inherit_from: .rubocop_todo.yml + +inherit_gem: + theforeman-rubocop: + - default.yml + +inherit_mode: + merge: + - Exclude + +AllCops: + Exclude: + - 'vendor/bundle/**/*' + +Metrics/BlockLength: + Exclude: + - test/**/* + +Style/FrozenStringLiteralComment: + Enabled: false diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 0000000..5481e97 --- /dev/null +++ b/.rubocop_todo.yml @@ -0,0 +1,74 @@ +# This configuration was generated by +# `rubocop --auto-gen-config` +# on 2021-11-10 20:56:15 UTC using RuboCop version 1.22.3. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 5 +# Configuration parameters: IgnoredMethods, CountRepeatedAttributes. +Metrics/AbcSize: + Max: 32 + +# Offense count: 2 +# Configuration parameters: CountComments, CountAsOne. +Metrics/ClassLength: + Max: 201 + +# Offense count: 3 +# Configuration parameters: IgnoredMethods. +Metrics/CyclomaticComplexity: + Max: 13 + +# Offense count: 7 +# Configuration parameters: CountComments, CountAsOne, ExcludedMethods, IgnoredMethods. +Metrics/MethodLength: + Max: 16 + +# Offense count: 2 +# Configuration parameters: IgnoredMethods. +Metrics/PerceivedComplexity: + Max: 13 + +# Offense count: 9 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: nested, compact +Style/ClassAndModuleChildren: + Exclude: + - 'lib/smart_proxy_ansible/actions.rb' + - 'lib/smart_proxy_ansible/remote_execution_core/ansible_runner.rb' + - 'lib/smart_proxy_ansible/runner/ansible_runner.rb' + - 'lib/smart_proxy_ansible/runner/command_creator.rb' + - 'lib/smart_proxy_ansible/runner/playbook.rb' + - 'lib/smart_proxy_ansible/task_launcher/ansible_runner.rb' + - 'lib/smart_proxy_ansible/task_launcher/playbook.rb' + - 'test/ansible_runner_test.rb' + - 'test/task_launcher_test.rb' + +# Offense count: 1 +# Configuration parameters: MinBodyLength. +Style/GuardClause: + Exclude: + - 'lib/smart_proxy_ansible/runner/ansible_runner.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +Style/IfUnlessModifier: + Exclude: + - 'lib/smart_proxy_ansible/runner/ansible_runner.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: Mode. +Style/StringConcatenation: + Exclude: + - 'lib/smart_proxy_ansible/runner/ansible_runner.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. +# URISchemes: http, https +Layout/LineLength: + Max: 158 diff --git a/Gemfile b/Gemfile index 6642277..28c4ece 100644 --- a/Gemfile +++ b/Gemfile @@ -3,14 +3,19 @@ source 'https://rubygems.org' gemspec group :development do - gem 'smart_proxy', git: 'https://github.com/theforeman/smart-proxy', - branch: 'develop' - #gem 'smart_proxy', path: '../smart-proxy' gem 'pry' gem 'pry-byebug' + + if (smart_proxy_path = ENV.fetch('SMART_PROXY_PATH', nil)) + gem 'smart_proxy', path: smart_proxy_path + elsif ENV.fetch('BUNDLE_SMART_PROXY', '1') != '0' + gem 'smart_proxy', git: 'https://github.com/theforeman/smart-proxy', + branch: 'develop' + end end group :test do gem 'minitest' gem 'mocha' + gem 'theforeman-rubocop', '~> 0.1.0.pre' end diff --git a/Rakefile b/Rakefile index b3a8da5..fe5fb47 100644 --- a/Rakefile +++ b/Rakefile @@ -1,10 +1,6 @@ require 'rake' require 'rake/testtask' - -begin - require 'bundler/gem_tasks' -rescue LoadError -end +require 'bundler/gem_tasks' desc 'Default: run unit tests.' task default: :test diff --git a/lib/smart_proxy_ansible/api.rb b/lib/smart_proxy_ansible/api.rb index 4d57c07..2d7cad0 100644 --- a/lib/smart_proxy_ansible/api.rb +++ b/lib/smart_proxy_ansible/api.rb @@ -35,15 +35,15 @@ def extract_variables(role_name) role_name_parts = role_name.split('.') if role_name_parts.count == 3 RolesReader.collections_paths.split(':').each do |path| - variables[role_name] = VariablesExtractor - .extract_variables("#{path}/ansible_collections/#{role_name_parts[0]}/#{role_name_parts[1]}/roles/#{role_name_parts[2]}") if variables[role_name].nil? || variables[role_name].empty? + if variables[role_name].blank? + variables[role_name] = VariablesExtractor + .extract_variables("#{path}/ansible_collections/#{role_name_parts[0]}/#{role_name_parts[1]}/roles/#{role_name_parts[2]}") + end end else RolesReader.roles_path.split(':').each do |path| role_path = "#{path}/#{role_name}" - if File.directory?(role_path) - variables[role_name] ||= VariablesExtractor.extract_variables(role_path) - end + variables[role_name] ||= VariablesExtractor.extract_variables(role_path) if File.directory?(role_path) end end variables diff --git a/lib/smart_proxy_ansible/exception.rb b/lib/smart_proxy_ansible/exception.rb index 0f9df3c..f33ebf4 100644 --- a/lib/smart_proxy_ansible/exception.rb +++ b/lib/smart_proxy_ansible/exception.rb @@ -6,16 +6,18 @@ module Ansible # exception class Exception < ::StandardError def initialize(message, *params) + super() @message = message @params = params end def self.calculate_error_code(classname, message) return 'ERF00-0000' if classname.nil? || message.nil? + basename = classname.split(':').last class_hash = Zlib.crc32(basename) % 100 msg_hash = Zlib.crc32(message) % 10_000 - format 'ERF%02d-%04d', class_hash, msg_hash + format 'ERF%02d-%04d', clshash: class_hash, msghash: msg_hash end def code @@ -35,7 +37,9 @@ def to_s end class ReadConfigFileException < Proxy::Ansible::Exception; end + class ReadRolesException < Proxy::Ansible::Exception; end + class ReadVariablesException < Proxy::Ansible::Exception; end end end diff --git a/lib/smart_proxy_ansible/http_config.ru b/lib/smart_proxy_ansible/http_config.ru index f4fef03..b876881 100644 --- a/lib/smart_proxy_ansible/http_config.ru +++ b/lib/smart_proxy_ansible/http_config.ru @@ -1,5 +1,5 @@ require 'smart_proxy_ansible/api' -map "/ansible" do +map '/ansible' do run Proxy::Ansible::Api end diff --git a/lib/smart_proxy_ansible/plugin.rb b/lib/smart_proxy_ansible/plugin.rb index f4bb9fd..b0e59e1 100644 --- a/lib/smart_proxy_ansible/plugin.rb +++ b/lib/smart_proxy_ansible/plugin.rb @@ -5,8 +5,8 @@ class Plugin < Proxy::Plugin rackup_path File.expand_path('http_config.ru', __dir__) settings_file 'ansible.yml' plugin :ansible, Proxy::Ansible::VERSION - default_settings :ansible_dir => Dir.home - # :working_dir => nil + default_settings ansible_dir: Dir.home + # :working_dir => nil after_activation do require 'smart_proxy_dynflow' diff --git a/lib/smart_proxy_ansible/remote_execution_core/ansible_runner.rb b/lib/smart_proxy_ansible/remote_execution_core/ansible_runner.rb index 1666bbf..393261a 100644 --- a/lib/smart_proxy_ansible/remote_execution_core/ansible_runner.rb +++ b/lib/smart_proxy_ansible/remote_execution_core/ansible_runner.rb @@ -10,12 +10,12 @@ class AnsibleRunner < ::Proxy::Dynflow::Runner::CommandRunner CONNECTION_PROMPT = 'Are you sure you want to continue connecting (yes/no)? ' def initialize(options, suspended_action:) - super(options, :suspended_action => suspended_action) + super(options, suspended_action: suspended_action) @playbook_runner = Proxy::Ansible::Runner::Playbook.new( options['ansible_inventory'], options['script'], options, - :suspended_action => suspended_action + suspended_action: suspended_action ) end diff --git a/lib/smart_proxy_ansible/roles_reader.rb b/lib/smart_proxy_ansible/roles_reader.rb index f7c84aa..3eeac24 100644 --- a/lib/smart_proxy_ansible/roles_reader.rb +++ b/lib/smart_proxy_ansible/roles_reader.rb @@ -58,7 +58,6 @@ def read_roles(roles_path) def glob_path(path) Dir.glob path - end def read_collection_roles(collections_path) diff --git a/lib/smart_proxy_ansible/runner/ansible_runner.rb b/lib/smart_proxy_ansible/runner/ansible_runner.rb index 0c7d320..9883cfb 100644 --- a/lib/smart_proxy_ansible/runner/ansible_runner.rb +++ b/lib/smart_proxy_ansible/runner/ansible_runner.rb @@ -11,7 +11,7 @@ class AnsibleRunner < ::Proxy::Dynflow::Runner::Parent attr_reader :execution_timeout_interval, :command_pid def initialize(input, suspended_action:) - super input, :suspended_action => suspended_action + super input, suspended_action: suspended_action @inventory = rebuild_secrets(rebuild_inventory(input), input) action_input = input.values.first[:input][:action_input] @playbook = action_input[:script] @@ -30,7 +30,7 @@ def start prepare_directory_structure write_inventory write_playbook - write_ssh_key if !@passphrase.nil? && !@passphrase.empty? + write_ssh_key if @passphrase.present? start_ansible_runner end @@ -106,7 +106,7 @@ def handle_host_event(hostname, event) end def handle_broadcast_data(event) - log_event("broadcast", event) + log_event('broadcast', event) if event['event'] == 'playbook_on_stats' failures = event.dig('event_data', 'failures') || {} unreachable = event.dig('event_data', 'dark') || {} @@ -150,7 +150,7 @@ def write_ssh_key # to match line asking for password, given the limitation to match only first 100 chars # and the fact the line contains dynamically created temp directory, the regexp # mentions only things that are always there, such as artifacts directory and the key name - secrets = YAML.dump({ "for.*/artifacts/.*/ssh_key_data:" => @passphrase }) + secrets = YAML.dump({ 'for.*/artifacts/.*/ssh_key_data:' => @passphrase }) File.write(passwords_path, secrets, perm: 0o600) end @@ -201,7 +201,9 @@ def prepare_directory_structure def log_event(description, event) # TODO: replace this ugly code with block variant once https://github.com/Dynflow/dynflow/pull/323 # arrives in production - logger.debug("[foreman_ansible] - handling event #{description}: #{JSON.pretty_generate(event)}") if logger.level <= ::Logger::DEBUG + if logger.level <= ::Logger::DEBUG + logger.debug("[foreman_ansible] - handling event #{description}: #{JSON.pretty_generate(event)}") + end end # Each per-host task has inventory only for itself, we must @@ -241,7 +243,7 @@ def rebuild_secrets(inventory, input) new_secrets = { 'ansible_password' => inventory['ssh_password'] || per_host['ansible_password'], - 'ansible_become_password' => inventory['effective_user_password'] || per_host['ansible_become_password'] + 'ansible_become_password' => inventory['effective_user_password'] || per_host['ansible_become_password'], } inventory['_meta']['hostvars'][host].update(new_secrets) end diff --git a/lib/smart_proxy_ansible/runner/playbook.rb b/lib/smart_proxy_ansible/runner/playbook.rb index b08af15..9c25298 100644 --- a/lib/smart_proxy_ansible/runner/playbook.rb +++ b/lib/smart_proxy_ansible/runner/playbook.rb @@ -14,7 +14,7 @@ class Playbook < Proxy::Dynflow::Runner::CommandRunner attr_reader :command_out, :command_in, :command_pid def initialize(inventory, playbook, options = {}, suspended_action:) - super :suspended_action => suspended_action + super suspended_action: suspended_action @inventory = rebuild_secrets(inventory, options[:secrets]) unknown_hosts.each do |host| add_to_known_hosts(host) @@ -28,8 +28,8 @@ def start write_inventory write_playbook command = CommandCreator.new(inventory_file, - playbook_file, - @options).command + playbook_file, + @options).command logger.debug('[foreman_ansible] - Initializing Ansible Runner') Dir.chdir(@ansible_dir) do initialize_command(*command) @@ -126,7 +126,7 @@ def rebuild_secrets(inventory, secrets) new_secrets = { 'ansible_password' => inventory['ssh_password'] || per_host['ansible_password'], - 'ansible_become_password' => inventory['effective_user_password'] || per_host['ansible_become_password'] + 'ansible_become_password' => inventory['effective_user_password'] || per_host['ansible_become_password'], } inventory['_meta']['hostvars'][name].update(new_secrets) end diff --git a/lib/smart_proxy_ansible/task_launcher/playbook.rb b/lib/smart_proxy_ansible/task_launcher/playbook.rb index c803688..43dd519 100644 --- a/lib/smart_proxy_ansible/task_launcher/playbook.rb +++ b/lib/smart_proxy_ansible/task_launcher/playbook.rb @@ -6,19 +6,19 @@ class Playbook < Proxy::Dynflow::TaskLauncher::Batch class PlaybookRunnerAction < Proxy::Dynflow::Action::Runner def initiate_runner additional_options = { - :step_id => run_step_id, - :uuid => execution_plan_id + step_id: run_step_id, + uuid: execution_plan_id, } ::Proxy::Ansible::RemoteExecutionCore::AnsibleRunner.new( input.merge(additional_options), - :suspended_action => suspended_action + suspended_action: suspended_action ) end end def child_launcher(parent) - ::Proxy::Dynflow::TaskLauncher::Single.new(world, callback, :parent => parent, - :action_class_override => PlaybookRunnerAction) + ::Proxy::Dynflow::TaskLauncher::Single.new(world, callback, parent: parent, + action_class_override: PlaybookRunnerAction) end end end diff --git a/lib/smart_proxy_ansible/variables_extractor.rb b/lib/smart_proxy_ansible/variables_extractor.rb index 8ba375b..164932e 100644 --- a/lib/smart_proxy_ansible/variables_extractor.rb +++ b/lib/smart_proxy_ansible/variables_extractor.rb @@ -9,16 +9,19 @@ def extract_variables(role_path) role_files = Dir.glob("#{role_path}/defaults/**/*.yml") + Dir.glob("#{role_path}/defaults/**/*.yaml") role_files.reduce({}) do |memo, role_file| - loaded_yaml = {} - begin - loaded_yaml = YAML.load_file(role_file) - rescue Psych::SyntaxError - raise ReadVariablesException.new "#{role_file} is not YAML file" - end - raise ReadVariablesException.new "Could not parse YAML file: #{role_file}" unless loaded_yaml.is_a? Hash + loaded_yaml = load_role_file(role_file) + memo.merge loaded_yaml end end + + def load_role_file(file) + loaded_yaml = YAML.load_file(file) + raise ReadVariablesException, "Could not parse YAML file: #{file}" unless loaded_yaml.is_a? Hash + loaded_yaml + rescue Psych::SyntaxError + raise ReadVariablesException, "#{file} is not YAML file" + end end end end diff --git a/lib/smart_proxy_ansible/version.rb b/lib/smart_proxy_ansible/version.rb index e57b6c6..a2fad11 100644 --- a/lib/smart_proxy_ansible/version.rb +++ b/lib/smart_proxy_ansible/version.rb @@ -2,6 +2,6 @@ module Proxy # Version, this allows the proxy and other plugins know # what version of the Ansible plugin is running module Ansible - VERSION = '3.2.0' + VERSION = '3.2.0'.freeze end end diff --git a/smart_proxy_ansible.gemspec b/smart_proxy_ansible.gemspec index 09855c1..2e616ad 100644 --- a/smart_proxy_ansible.gemspec +++ b/smart_proxy_ansible.gemspec @@ -1,5 +1,4 @@ -# -*- encoding: utf-8 -*- -lib = File.expand_path('../lib', __FILE__) +lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'smart_proxy_ansible/version' @@ -10,28 +9,28 @@ Gem::Specification.new do |gem| gem.email = ['inecas@redhat.com', 'dlobatog@redhat.com'] gem.homepage = 'https://github.com/theforeman/smart_proxy_ansible' gem.summary = 'Smart-Proxy Ansible plugin' - gem.description = <<-EOS + gem.description = <<-DESCRIPTION Smart-Proxy ansible plugin - EOS + DESCRIPTION gem.files = Dir['bundler.d/ansible.rb', - 'settings.d/**/*', - 'LICENSE', 'README.md', - 'lib/smart_proxy_ansible.rb', - 'lib/smart_proxy_ansible/**/*', - 'bin/json_inventory.sh'] + 'settings.d/**/*', + 'LICENSE', 'README.md', + 'lib/smart_proxy_ansible.rb', + 'lib/smart_proxy_ansible/**/*', + 'bin/json_inventory.sh'] gem.extra_rdoc_files = ['README.md', 'LICENSE'] gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ['lib'] gem.license = 'GPL-3.0' gem.required_ruby_version = '>= 2.5' - gem.add_development_dependency 'rake', '~> 13.0' + gem.add_development_dependency('logger') gem.add_development_dependency('mocha', '~> 1') - gem.add_development_dependency('webmock', '~> 3') gem.add_development_dependency('rack-test', '~> 0') - gem.add_development_dependency('logger') + gem.add_development_dependency 'rake', '~> 13.0' gem.add_development_dependency('smart_proxy') + gem.add_development_dependency('webmock', '~> 3') gem.add_runtime_dependency('net-ssh') gem.add_runtime_dependency('smart_proxy_dynflow', '~> 0.5') gem.add_runtime_dependency('smart_proxy_remote_execution_ssh', '~> 0.4') diff --git a/test/command_creator_test.rb b/test/command_creator_test.rb index 2812743..8f7cdda 100644 --- a/test/command_creator_test.rb +++ b/test/command_creator_test.rb @@ -28,7 +28,7 @@ class CommandCreatorTest < Minitest::Test end test 'has no ANSIBLE_CALLBACK_WHITELIST set by default' do - refute environment_variables['ANSIBLE_CALLBACK_WHITELIST'] + assert_not environment_variables['ANSIBLE_CALLBACK_WHITELIST'] end test 'with a REX command it sets ANSIBLE_CALLBACK_WHITELIST to empty' do @@ -62,7 +62,7 @@ def command_parts def set_command_options(option, value) subject.instance_eval("@options[:#{option}] = \"#{value}\"", - __FILE__, __LINE__ - 1) + __FILE__, __LINE__ - 1) end end end diff --git a/test/playbook_runner_test.rb b/test/playbook_runner_test.rb index 38842d4..53ac13f 100644 --- a/test/playbook_runner_test.rb +++ b/test/playbook_runner_test.rb @@ -9,40 +9,40 @@ class PlaybookRunnerTest < Minitest::Test describe 'PlaybookRunner' do before do - Proxy::Ansible::Plugin.stubs(:settings).returns(OpenStruct.new(:ansible_dir => Dir.home)) + Proxy::Ansible::Plugin.stubs(:settings).returns(OpenStruct.new(ansible_dir: Dir.home)) end describe 'roles dir' do test 'reads default when none provided' do - Proxy::Ansible::Runner::Playbook.any_instance.stubs(:unknown_hosts). - returns([]) + Proxy::Ansible::Runner::Playbook.any_instance.stubs(:unknown_hosts) + .returns([]) File.expects(:exist?).with(Dir.home).returns(true) Proxy::Ansible::Runner::Playbook.any_instance.expects(:rebuild_secrets).returns(nil) - runner = Proxy::Ansible::Runner::Playbook.new(nil, nil, :suspended_action => nil) + runner = Proxy::Ansible::Runner::Playbook.new(nil, nil, suspended_action: nil) assert '/etc/ansible', runner.instance_variable_get('@ansible_dir') end end describe 'working_dir' do before do - Proxy::Ansible::Runner::Playbook.any_instance.stubs(:unknown_hosts). - returns([]) + Proxy::Ansible::Runner::Playbook.any_instance.stubs(:unknown_hosts) + .returns([]) end test 'creates temp one if not provided' do Dir.expects(:mktmpdir) File.expects(:exist?).with(Dir.home).returns(true) Proxy::Ansible::Runner::Playbook.any_instance.expects(:rebuild_secrets).returns(nil) - Proxy::Ansible::Runner::Playbook.new(nil, nil, :suspended_action => nil) + Proxy::Ansible::Runner::Playbook.new(nil, nil, suspended_action: nil) end test 'reads it when provided' do - settings = { :working_dir => '/foo', :ansible_dir => '/etc/foo' } + settings = { working_dir: '/foo', ansible_dir: '/etc/foo' } Proxy::Ansible::Plugin.expects(:settings).returns(settings) File.expects(:exist?).with(settings[:ansible_dir]).returns(true) Dir.expects(:mktmpdir).never Proxy::Ansible::Runner::Playbook.any_instance.expects(:rebuild_secrets).returns(nil) - runner = Proxy::Ansible::Runner::Playbook.new(nil, nil, :suspended_action => nil) + runner = Proxy::Ansible::Runner::Playbook.new(nil, nil, suspended_action: nil) assert '/foo', runner.instance_variable_get('@working_dir') end end @@ -52,35 +52,35 @@ class PlaybookRunnerTest < Minitest::Test @inventory = { 'all' => { 'hosts' => ['foreman.example.com'] } } @output = StringIO.new logger = Logger.new(@output) - Proxy::Ansible::Runner::Playbook.any_instance.stubs(:logger). - returns(logger) + Proxy::Ansible::Runner::Playbook.any_instance.stubs(:logger) + .returns(logger) end test 'ignores known hosts' do - Net::SSH::KnownHosts.expects(:search_for). - with('foreman.example.com').returns(['somekey']) - Proxy::Ansible::Runner::Playbook.any_instance. - expects(:add_to_known_hosts).never + Net::SSH::KnownHosts.expects(:search_for) + .with('foreman.example.com').returns(['somekey']) + Proxy::Ansible::Runner::Playbook.any_instance + .expects(:add_to_known_hosts).never Proxy::Ansible::Runner::Playbook.any_instance.expects(:rebuild_secrets).returns(@inventory) - Proxy::Ansible::Runner::Playbook.new(@inventory, nil, :suspended_action => nil) + Proxy::Ansible::Runner::Playbook.new(@inventory, nil, suspended_action: nil) end test 'adds unknown hosts to known_hosts' do - Net::SSH::KnownHosts.expects(:search_for). - with('foreman.example.com').returns([]) - Proxy::Ansible::Runner::Playbook.any_instance. - expects(:add_to_known_hosts).with('foreman.example.com') + Net::SSH::KnownHosts.expects(:search_for) + .with('foreman.example.com').returns([]) + Proxy::Ansible::Runner::Playbook.any_instance + .expects(:add_to_known_hosts).with('foreman.example.com') Proxy::Ansible::Runner::Playbook.any_instance.expects(:rebuild_secrets).returns(@inventory) - Proxy::Ansible::Runner::Playbook.new(@inventory, nil, :suspended_action => nil) + Proxy::Ansible::Runner::Playbook.new(@inventory, nil, suspended_action: nil) end test 'logs error when it cannot add to known_hosts' do - Net::SSH::KnownHosts.expects(:search_for). - with('foreman.example.com').returns([]) - Net::SSH::Transport::Session.expects(:new).with('foreman.example.com'). - raises(::Net::SSH::HostKeyError) + Net::SSH::KnownHosts.expects(:search_for) + .with('foreman.example.com').returns([]) + Net::SSH::Transport::Session.expects(:new).with('foreman.example.com') + .raises(::Net::SSH::HostKeyError) Proxy::Ansible::Runner::Playbook.any_instance.expects(:rebuild_secrets).returns(@inventory) - Proxy::Ansible::Runner::Playbook.new(@inventory, nil, :suspended_action => nil) + Proxy::Ansible::Runner::Playbook.new(@inventory, nil, suspended_action: nil) assert_match( /ERROR.*Failed to save host key for foreman.example.com: Net::SSH::HostKeyError/, @output.string diff --git a/test/roles_reader_test.rb b/test/roles_reader_test.rb index ecb529f..901a0e9 100644 --- a/test/roles_reader_test.rb +++ b/test/roles_reader_test.rb @@ -19,20 +19,20 @@ def self.expect_content_config(ansible_cfg_content) test 'detects commented roles_path' do RolesReaderTest.expect_content_config ['#roles_path = thisiscommented!'] assert_equal(ROLES_PATH, - Proxy::Ansible::RolesReader.roles_path) + Proxy::Ansible::RolesReader.roles_path) end test 'returns default path if no roles_path defined' do assert_equal(ROLES_PATH, - Proxy::Ansible::RolesReader.config_path(['#roles_path = thisiscommented!'], ROLES_PATH)) + Proxy::Ansible::RolesReader.config_path(['#roles_path = thisiscommented!'], ROLES_PATH)) end test 'returns roles_path if one is defined' do RolesReaderTest.expect_content_config [ - 'roles_path = /mycustom/ansibleroles/path' + 'roles_path = /mycustom/ansibleroles/path', ] assert_equal('/mycustom/ansibleroles/path', - Proxy::Ansible::RolesReader.roles_path) + Proxy::Ansible::RolesReader.roles_path) end end diff --git a/test/test_helper.rb b/test/test_helper.rb index 020e218..ab2d458 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -3,6 +3,11 @@ require 'mocha/minitest' require 'smart_proxy_for_testing' +# initialize the logger prior testing +# it uses Dir.glob, that we want to stub in some tests +# if those tests run first, it throws unexpected invocation of Dir.glob +::Proxy::LogBuffer::Decorator.instance + module Minitest # Modifications to allow a 'test 'nameoftest' do' syntax class Test @@ -10,7 +15,8 @@ class << self def test(name, &block) test_name = "test_#{name.gsub(/\s+/, '_')}".to_sym defined = method_defined? test_name - fail "#{test_name} is already defined in #{self}" if defined + raise "#{test_name} is already defined in #{self}" if defined + if block_given? define_method(test_name, &block) else diff --git a/test/variables_extractor_test.rb b/test/variables_extractor_test.rb index e07b6f5..baae62a 100644 --- a/test/variables_extractor_test.rb +++ b/test/variables_extractor_test.rb @@ -9,7 +9,7 @@ class VariablesExtractorTest < Minitest::Test assert_equal Hash, res.class assert_equal 13, res.count - assert_equal "postgres", res["postgresql_user"] + assert_equal 'postgres', res['postgresql_user'] end test 'raises when fails to parse' do