diff options
author | Lamont Granquist <lamont@scriptkiddie.org> | 2019-07-31 09:57:05 -0700 |
---|---|---|
committer | Lamont Granquist <lamont@scriptkiddie.org> | 2019-07-31 09:57:05 -0700 |
commit | 14b9553818265ecc35c037adfe479320e3a70e34 (patch) | |
tree | ec8f36c6f929f0c0b56f062484a280d6e645d61e | |
parent | f051b6e7912086edc03747f4b1c0285bfb6597f5 (diff) | |
download | chef-lcg/weirich-semantic-block.tar.gz |
For Discussion: Weirich Semantic Block stylelcg/weirich-semantic-block
Style/BlockDelimiters:
Enabled: true
EnforcedStyle: semantic
See, eg:
https://github.com/rubocop-hq/ruby-style-guide/issues/162
http://www.virtuouscode.com/2011/07/26/the-procedurefunction-block-convention-in-ruby/
Signed-off-by: Lamont Granquist <lamont@scriptkiddie.org>
339 files changed, 1536 insertions, 1536 deletions
diff --git a/chef-config/lib/chef-config/config.rb b/chef-config/lib/chef-config/config.rb index d136a8f79c..a90afeaddc 100644 --- a/chef-config/lib/chef-config/config.rb +++ b/chef-config/lib/chef-config/config.rb @@ -98,7 +98,7 @@ module ChefConfig def self.apply_extra_config_options(extra_config_options) if extra_config_options - extra_parsed_options = extra_config_options.inject({}) do |memo, option| + extra_parsed_options = extra_config_options.inject({}) { |memo, option| # Sanity check value. if option.empty? || !option.include?("=") raise UnparsableConfigOption, "Unparsable config option #{option.inspect}" @@ -111,7 +111,7 @@ module ChefConfig # runs a simple parse on the string for some common types. memo[key.to_sym] = YAML.safe_load(value) memo - end + } merge!(extra_parsed_options) end end @@ -153,7 +153,7 @@ module ChefConfig # So while this is basically identical to what method_missing would do, we pull # it up here and get a real method written so that things get dispatched # properly. - configurable(:daemonize).writes_value { |v| v } + configurable(:daemonize).writes_value do |v| v end # The root where all local chef object data is stored. cookbooks, data bags, # environments are all assumed to be in separate directories under this. @@ -203,23 +203,23 @@ module ChefConfig # Location of acls on disk. String or array of strings. # Defaults to <chef_repo_path>/acls. - default(:acl_path) { derive_path_from_chef_repo_path("acls") } + default(:acl_path) do derive_path_from_chef_repo_path("acls") end # Location of clients on disk. String or array of strings. # Defaults to <chef_repo_path>/clients. - default(:client_path) { derive_path_from_chef_repo_path("clients") } + default(:client_path) do derive_path_from_chef_repo_path("clients") end # Location of client keys on disk. String or array of strings. # Defaults to <chef_repo_path>/client_keys. - default(:client_key_path) { derive_path_from_chef_repo_path("client_keys") } + default(:client_key_path) do derive_path_from_chef_repo_path("client_keys") end # Location of containers on disk. String or array of strings. # Defaults to <chef_repo_path>/containers. - default(:container_path) { derive_path_from_chef_repo_path("containers") } + default(:container_path) do derive_path_from_chef_repo_path("containers") end # Location of cookbook_artifacts on disk. String or array of strings. # Defaults to <chef_repo_path>/cookbook_artifacts. - default(:cookbook_artifact_path) { derive_path_from_chef_repo_path("cookbook_artifacts") } + default(:cookbook_artifact_path) do derive_path_from_chef_repo_path("cookbook_artifacts") end # Location of cookbooks on disk. String or array of strings. # Defaults to <chef_repo_path>/cookbooks. If chef_repo_path @@ -235,39 +235,39 @@ module ChefConfig # Location of data bags on disk. String or array of strings. # Defaults to <chef_repo_path>/data_bags. - default(:data_bag_path) { derive_path_from_chef_repo_path("data_bags") } + default(:data_bag_path) do derive_path_from_chef_repo_path("data_bags") end # Location of environments on disk. String or array of strings. # Defaults to <chef_repo_path>/environments. - default(:environment_path) { derive_path_from_chef_repo_path("environments") } + default(:environment_path) do derive_path_from_chef_repo_path("environments") end # Location of groups on disk. String or array of strings. # Defaults to <chef_repo_path>/groups. - default(:group_path) { derive_path_from_chef_repo_path("groups") } + default(:group_path) do derive_path_from_chef_repo_path("groups") end # Location of nodes on disk. String or array of strings. # Defaults to <chef_repo_path>/nodes. - default(:node_path) { derive_path_from_chef_repo_path("nodes") } + default(:node_path) do derive_path_from_chef_repo_path("nodes") end # Location of policies on disk. String or array of strings. # Defaults to <chef_repo_path>/policies. - default(:policy_path) { derive_path_from_chef_repo_path("policies") } + default(:policy_path) do derive_path_from_chef_repo_path("policies") end # Location of policy_groups on disk. String or array of strings. # Defaults to <chef_repo_path>/policy_groups. - default(:policy_group_path) { derive_path_from_chef_repo_path("policy_groups") } + default(:policy_group_path) do derive_path_from_chef_repo_path("policy_groups") end # Location of roles on disk. String or array of strings. # Defaults to <chef_repo_path>/roles. - default(:role_path) { derive_path_from_chef_repo_path("roles") } + default(:role_path) do derive_path_from_chef_repo_path("roles") end # Location of users on disk. String or array of strings. # Defaults to <chef_repo_path>/users. - default(:user_path) { derive_path_from_chef_repo_path("users") } + default(:user_path) do derive_path_from_chef_repo_path("users") end # Location of policies on disk. String or array of strings. # Defaults to <chef_repo_path>/policies. - default(:policy_path) { derive_path_from_chef_repo_path("policies") } + default(:policy_path) do derive_path_from_chef_repo_path("policies") end # Turn on "path sanity" by default. default :enforce_path_sanity, false @@ -312,20 +312,20 @@ module ChefConfig end # Where cookbook files are stored on the server (by content checksum) - default(:checksum_path) { PathHelper.join(cache_path, "checksums") } + default(:checksum_path) do PathHelper.join(cache_path, "checksums") end # Where chef's cache files should be stored - default(:file_cache_path) { PathHelper.join(cache_path, "cache") } + default(:file_cache_path) do PathHelper.join(cache_path, "cache") end # Where backups of chef-managed files should go - default(:file_backup_path) { PathHelper.join(cache_path, "backup") } + default(:file_backup_path) do PathHelper.join(cache_path, "backup") end # The chef-client (or solo) lockfile. # # If your `file_cache_path` resides on a NFS (or non-flock()-supporting # fs), it's recommended to set this to something like # '/tmp/chef-client-running.pid' - default(:lockfile) { PathHelper.join(file_cache_path, "chef-client-running.pid") } + default(:lockfile) do PathHelper.join(file_cache_path, "chef-client-running.pid") end ## Daemonization Settings ## # What user should Chef run as? @@ -419,7 +419,7 @@ module ChefConfig config_context :chef_zero do config_strict_mode true - default(:enabled) { ChefConfig::Config.local_mode } + default(:enabled) do ChefConfig::Config.local_mode end default :host, "localhost" default :port, 8889.upto(9999) # Will try ports from 8889-9999 until one works @@ -509,7 +509,7 @@ module ChefConfig # When consuming Ohai plugins from cookbook segments, we place those plugins in this directory. # Subsequent chef client runs will wipe and re-populate the directory to ensure cleanliness - default(:ohai_segment_plugin_path) { PathHelper.join(config_dir, "ohai", "cookbook_plugins") } + default(:ohai_segment_plugin_path) do PathHelper.join(config_dir, "ohai", "cookbook_plugins") end ### # Policyfile Settings @@ -572,7 +572,7 @@ module ChefConfig # regardless of the :ssl_verify_mode setting. This is set to `true` when # running in local-mode. # NOTE: This is a workaround until verify_peer is enabled by default. - default(:verify_api_cert) { ChefConfig::Config.local_mode } + default(:verify_api_cert) do ChefConfig::Config.local_mode end # Path to the default CA bundle files. default :ssl_ca_path, nil @@ -589,17 +589,17 @@ module ChefConfig # certificates in this directory will be added to whatever CA bundle ruby # is using. Use this to add self-signed certs for your Chef Server or local # HTTP file servers. - default(:trusted_certs_dir) { PathHelper.join(config_dir, "trusted_certs") } + default(:trusted_certs_dir) do PathHelper.join(config_dir, "trusted_certs") end # A directory that contains additional configuration scripts to load for chef-client - default(:client_d_dir) { PathHelper.join(config_dir, "client.d") } + default(:client_d_dir) do PathHelper.join(config_dir, "client.d") end # A directory that contains additional configuration scripts to load for solo - default(:solo_d_dir) { PathHelper.join(config_dir, "solo.d") } + default(:solo_d_dir) do PathHelper.join(config_dir, "solo.d") end # A directory that contains additional configuration scripts to load for # the workstation config - default(:config_d_dir) { PathHelper.join(config_dir, "config.d") } + default(:config_d_dir) do PathHelper.join(config_dir, "config.d") end # Where should chef-solo download recipes from? default :recipe_url, nil @@ -702,7 +702,7 @@ module ChefConfig # The `validation_key` is never used if the `client_key` exists. # # If chef-zero is enabled, this defaults to nil (no authentication). - default(:validation_key) { chef_zero.enabled ? nil : platform_specific_path("/etc/chef/validation.pem") } + default(:validation_key) do chef_zero.enabled ? nil : platform_specific_path("/etc/chef/validation.pem") end default :validation_client_name do # If the URL is set and looks like a normal Chef Server URL, extract the # org name and use that as part of the default. @@ -723,7 +723,7 @@ module ChefConfig # # The default value is `true`. Set to `false` to disable client-side key # generation (server generates client keys). - default(:local_key_generation) { true } + default(:local_key_generation) do true end # Zypper package provider gpg checks. Set to false to disable package # gpg signature checking globally. This will warn you that it is a @@ -749,11 +749,11 @@ module ChefConfig # the new (and preferred) configuration setting. If not set, knife will # fall back to using cache_options[:path], which is deprecated but exists in # many client configs generated by pre-Chef-11 bootstrappers. - default(:syntax_check_cache_path) { cache_options[:path] } + default(:syntax_check_cache_path) do cache_options[:path] end # Deprecated: # Move this to the default value of syntax_cache_path when this is removed. - default(:cache_options) { { path: PathHelper.join(config_dir, "syntaxcache") } } + default(:cache_options) do { path: PathHelper.join(config_dir, "syntaxcache") } end # Whether errors should be raised for deprecation warnings. When set to # `false` (the default setting), a warning is emitted but code using @@ -863,7 +863,7 @@ module ChefConfig end # returns a platform specific path to the user home dir if set, otherwise default to current directory. - default( :user_home ) { PathHelper.home || Dir.pwd } + default( :user_home ) do PathHelper.home || Dir.pwd end # Enable file permission fixup for selinux. Fixup will be done # only if selinux is enabled in the system. diff --git a/chef-config/lib/chef-config/workstation_config_loader.rb b/chef-config/lib/chef-config/workstation_config_loader.rb index d38cae3d88..45d1fb66d2 100644 --- a/chef-config/lib/chef-config/workstation_config_loader.rb +++ b/chef-config/lib/chef-config/workstation_config_loader.rb @@ -205,7 +205,7 @@ module ChefConfig message = "You have an error in your config file #{config_file_path}\n\n" message << "#{e.class.name}: #{e.message}\n" filtered_trace = e.backtrace.grep(/#{Regexp.escape(config_file_path)}/) - filtered_trace.each { |bt_line| message << " " << bt_line << "\n" } + filtered_trace.each do |bt_line| message << " " << bt_line << "\n" end unless filtered_trace.empty? line_nr = filtered_trace.first[/#{Regexp.escape(config_file_path)}:([\d]+)/, 1] message << highlight_config_error(config_file_path, line_nr.to_i) @@ -265,7 +265,7 @@ module ChefConfig def highlight_config_error(file, line) config_file_lines = [] - IO.readlines(file).each_with_index { |l, i| config_file_lines << "#{(i + 1).to_s.rjust(3)}: #{l.chomp}" } + IO.readlines(file).each_with_index do |l, i| config_file_lines << "#{(i + 1).to_s.rjust(3)}: #{l.chomp}" end if line == 1 lines = config_file_lines[0..3] else diff --git a/chef-config/spec/unit/config_spec.rb b/chef-config/spec/unit/config_spec.rb index dec5b8755f..b70fa05786 100644 --- a/chef-config/spec/unit/config_spec.rb +++ b/chef-config/spec/unit/config_spec.rb @@ -297,7 +297,7 @@ RSpec.describe ChefConfig::Config do end context "when local mode is enabled" do - before { ChefConfig::Config[:local_mode] = true } + before do ChefConfig::Config[:local_mode] = true end it "returns nil" do expect(ChefConfig::Config.client_key).to be_nil @@ -521,7 +521,7 @@ RSpec.describe ChefConfig::Config do context "when local mode is enabled" do - before { ChefConfig::Config[:local_mode] = true } + before do ChefConfig::Config[:local_mode] = true end it "defaults to 'hosted_everything'" do expect(ChefConfig::Config[:repo_mode]).to eq("hosted_everything") @@ -529,7 +529,7 @@ RSpec.describe ChefConfig::Config do context "and osc_compat is enabled" do - before { ChefConfig::Config.chef_zero.osc_compat = true } + before do ChefConfig::Config.chef_zero.osc_compat = true end it "defaults to 'everything'" do expect(ChefConfig::Config[:repo_mode]).to eq("everything") @@ -541,7 +541,7 @@ RSpec.describe ChefConfig::Config do context "and the chef_server_url is multi-tenant" do - before { ChefConfig::Config[:chef_server_url] = "https://chef.example/organizations/example" } + before do ChefConfig::Config[:chef_server_url] = "https://chef.example/organizations/example" end it "defaults to 'hosted_everything'" do expect(ChefConfig::Config[:repo_mode]).to eq("hosted_everything") @@ -551,7 +551,7 @@ RSpec.describe ChefConfig::Config do context "and the chef_server_url is not multi-tenant" do - before { ChefConfig::Config[:chef_server_url] = "https://chef.example/" } + before do ChefConfig::Config[:chef_server_url] = "https://chef.example/" end it "defaults to 'everything'" do expect(ChefConfig::Config[:repo_mode]).to eq("everything") @@ -564,7 +564,7 @@ RSpec.describe ChefConfig::Config do context "when cookbook_path is set to a single path" do - before { ChefConfig::Config[:cookbook_path] = "/home/anne/repo/cookbooks" } + before do ChefConfig::Config[:cookbook_path] = "/home/anne/repo/cookbooks" end it "is set to a path one directory up from the cookbook_path" do expected = File.expand_path("/home/anne/repo") @@ -605,7 +605,7 @@ RSpec.describe ChefConfig::Config do context "when cookbook_path is not set" do - before { ChefConfig::Config[:cookbook_path] = nil } + before do ChefConfig::Config[:cookbook_path] = nil end it "is set to the cache_path" do expect(ChefConfig::Config[:chef_repo_path]).to eq(ChefConfig::Config[:cache_path]) @@ -1285,7 +1285,7 @@ RSpec.describe ChefConfig::Config do describe "validation_client_name" do context "with a normal server URL" do - before { ChefConfig::Config[:chef_server_url] = "https://chef.example/organizations/myorg" } + before do ChefConfig::Config[:chef_server_url] = "https://chef.example/organizations/myorg" end it "sets the validation client to myorg-validator" do expect(ChefConfig::Config[:validation_client_name]).to eq "myorg-validator" @@ -1293,7 +1293,7 @@ RSpec.describe ChefConfig::Config do end context "with an unusual server URL" do - before { ChefConfig::Config[:chef_server_url] = "https://chef.example/myorg" } + before do ChefConfig::Config[:chef_server_url] = "https://chef.example/myorg" end it "sets the validation client to chef-validator" do expect(ChefConfig::Config[:validation_client_name]).to eq "chef-validator" diff --git a/chef-config/spec/unit/fips_spec.rb b/chef-config/spec/unit/fips_spec.rb index d53096cead..980ffb0979 100644 --- a/chef-config/spec/unit/fips_spec.rb +++ b/chef-config/spec/unit/fips_spec.rb @@ -104,7 +104,7 @@ RSpec.describe "ChefConfig.fips?" do context "on 32 bit ruby" do let(:arch) { Win32::Registry::KEY_READ | 0x100 } - before { stub_const("::RbConfig::CONFIG", { "target_cpu" => "i386" } ) } + before do stub_const("::RbConfig::CONFIG", { "target_cpu" => "i386" } ) end it_behaves_like "fips_detection" end @@ -112,7 +112,7 @@ RSpec.describe "ChefConfig.fips?" do context "on 64 bit ruby" do let(:arch) { Win32::Registry::KEY_READ | 0x200 } - before { stub_const("::RbConfig::CONFIG", { "target_cpu" => "x86_64" } ) } + before do stub_const("::RbConfig::CONFIG", { "target_cpu" => "x86_64" } ) end it_behaves_like "fips_detection" end @@ -120,7 +120,7 @@ RSpec.describe "ChefConfig.fips?" do context "on unknown ruby" do let(:arch) { Win32::Registry::KEY_READ } - before { stub_const("::RbConfig::CONFIG", { "target_cpu" => nil } ) } + before do stub_const("::RbConfig::CONFIG", { "target_cpu" => nil } ) end it_behaves_like "fips_detection" end diff --git a/chef-config/spec/unit/workstation_config_loader_spec.rb b/chef-config/spec/unit/workstation_config_loader_spec.rb index e1cab3d4d0..5eb24cdea8 100644 --- a/chef-config/spec/unit/workstation_config_loader_spec.rb +++ b/chef-config/spec/unit/workstation_config_loader_spec.rb @@ -255,7 +255,7 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do tempfile.path end - after { File.unlink(explicit_config_location) if File.exist?(explicit_config_location) } + after do File.unlink(explicit_config_location) if File.exist?(explicit_config_location) end context "and is valid" do diff --git a/lib/chef/action_collection.rb b/lib/chef/action_collection.rb index 7b1997cfaf..892a4e5a51 100644 --- a/lib/chef/action_collection.rb +++ b/lib/chef/action_collection.rb @@ -104,14 +104,14 @@ class Chef # @return [Chef::ActionCollection] # def filtered_collection(max_nesting: nil, up_to_date: true, skipped: true, updated: true, failed: true, unprocessed: true) - subrecords = action_records.select do |rec| + subrecords = action_records.select { |rec| ( max_nesting.nil? || rec.nesting_level <= max_nesting ) && ( rec.status == :up_to_date && up_to_date || rec.status == :skipped && skipped || rec.status == :updated && updated || rec.status == :failed && failed || rec.status == :unprocessed && unprocessed ) - end + } self.class.new(events, run_context, subrecords) end diff --git a/lib/chef/application.rb b/lib/chef/application.rb index a632a97319..5c998d303b 100644 --- a/lib/chef/application.rb +++ b/lib/chef/application.rb @@ -323,7 +323,7 @@ class Chef def fork_chef_client logger.info "Forking #{Chef::Dist::PRODUCT} instance to converge..." - pid = fork do + pid = fork { # Want to allow forked processes to finish converging when # TERM singal is received (exit gracefully) trap("TERM") do @@ -342,7 +342,7 @@ class Chef else exit 0 end - end + } logger.trace "Fork successful. Waiting for new chef pid: #{pid}" result = Process.waitpid2(pid) handle_child_exit(result) @@ -367,7 +367,7 @@ class Chef rescue Exception => error logger.fatal("Configuration error #{error.class}: #{error.message}") filtered_trace = error.backtrace.grep(/#{Regexp.escape(config_file_path)}/) - filtered_trace.each { |line| logger.fatal(" " + line ) } + filtered_trace.each do |line| logger.fatal(" " + line ) end Chef::Application.fatal!("Aborting due to error in '#{config_file_path}'", error) end diff --git a/lib/chef/chef_fs/chef_fs_data_store.rb b/lib/chef/chef_fs/chef_fs_data_store.rb index 807d5e0155..9cf5dfbf81 100644 --- a/lib/chef/chef_fs/chef_fs_data_store.rb +++ b/lib/chef/chef_fs/chef_fs_data_store.rb @@ -541,12 +541,12 @@ class Chef elsif %w{cookbooks cookbook_artifacts}.include?(path[0]) && path.length == 2 if chef_fs.versioned_cookbooks || path[0] == "cookbook_artifacts" - result = with_entry([ path[0] ]) do |entry| + result = with_entry([ path[0] ]) { |entry| # list /cookbooks/name = filter /cookbooks/name-version down to name entry.children.map { |child| split_name_version(child.name) } .select { |name, version| name == path[1] } .map { |name, version| version } - end + } if result.empty? raise ChefZero::DataStore::DataNotFoundError.new(path) end @@ -559,7 +559,7 @@ class Chef end else - result = with_entry(path) do |entry| + result = with_entry(path) { |entry| begin entry.children.map { |c| zero_filename(c) }.sort rescue Chef::ChefFS::FileSystem::NotFoundError => e @@ -570,7 +570,7 @@ class Chef raise ChefZero::DataStore::DataNotFoundError.new(to_zero_path(e.entry), e) end end - end + } # Older versions of chef-zero do not understand policies and cookbook_artifacts, # don't give that stuff to them diff --git a/lib/chef/chef_fs/command_line.rb b/lib/chef/chef_fs/command_line.rb index 265b95e22d..5ae4010f9a 100644 --- a/lib/chef/chef_fs/command_line.rb +++ b/lib/chef/chef_fs/command_line.rb @@ -140,9 +140,9 @@ class Chef end def self.diff(pattern, old_root, new_root, recurse_depth, get_content) - Chef::ChefFS::Parallelizer.parallelize(Chef::ChefFS::FileSystem.list_pairs(pattern, old_root, new_root)) do |old_entry, new_entry| + Chef::ChefFS::Parallelizer.parallelize(Chef::ChefFS::FileSystem.list_pairs(pattern, old_root, new_root)) { |old_entry, new_entry| diff_entries(old_entry, new_entry, recurse_depth, get_content) - end.flatten(1) + }.flatten(1) end # Diff two known entries (could be files or dirs) @@ -153,9 +153,9 @@ class Chef if recurse_depth == 0 [ [ :common_subdirectories, old_entry, new_entry ] ] else - Chef::ChefFS::Parallelizer.parallelize(Chef::ChefFS::FileSystem.child_pairs(old_entry, new_entry)) do |old_child, new_child| + Chef::ChefFS::Parallelizer.parallelize(Chef::ChefFS::FileSystem.child_pairs(old_entry, new_entry)) { |old_child, new_child| Chef::ChefFS::CommandLine.diff_entries(old_child, new_child, recurse_depth ? recurse_depth - 1 : nil, get_content) - end.flatten(1) + }.flatten(1) end # If old is a directory and new is a file @@ -255,7 +255,7 @@ class Chef json_object.map { |o| sort_keys(o) } elsif json_object.is_a?(Hash) new_hash = {} - json_object.keys.sort.each { |key| new_hash[key] = sort_keys(json_object[key]) } + json_object.keys.sort.each do |key| new_hash[key] = sort_keys(json_object[key]) end new_hash else json_object diff --git a/lib/chef/chef_fs/config.rb b/lib/chef/chef_fs/config.rb index 83e82bfa0c..a3f1e77e8c 100644 --- a/lib/chef/chef_fs/config.rb +++ b/lib/chef/chef_fs/config.rb @@ -45,7 +45,7 @@ class Chef "policies" => "policy", "policy_groups" => "policy_group", }.freeze - INFLECTIONS.each { |k, v| k.freeze; v.freeze } + INFLECTIONS.each do |k, v| k.freeze; v.freeze end INFLECTIONS.freeze # ChefFS supports three modes of operation: "static", "everything", and diff --git a/lib/chef/chef_fs/data_handler/data_handler_base.rb b/lib/chef/chef_fs/data_handler/data_handler_base.rb index d51e54e8ab..8913c35d0f 100644 --- a/lib/chef/chef_fs/data_handler/data_handler_base.rb +++ b/lib/chef/chef_fs/data_handler/data_handler_base.rb @@ -96,7 +96,7 @@ class Chef # name to recipe[name]. Then calls uniq on the result. # def normalize_run_list(run_list) - run_list.map do |item| + run_list.map { |item| case item.to_s when /^recipe\[.*\]$/ item # explicit recipe @@ -105,7 +105,7 @@ class Chef else "recipe[#{item}]" end - end.uniq + }.uniq end # diff --git a/lib/chef/chef_fs/file_system/chef_server/acls_dir.rb b/lib/chef/chef_fs/file_system/chef_server/acls_dir.rb index 03b003586b..f24c6bc9f8 100644 --- a/lib/chef/chef_fs/file_system/chef_server/acls_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/acls_dir.rb @@ -48,7 +48,7 @@ class Chef def children if @children.nil? - @children = ENTITY_TYPES.map do |entity_type| + @children = ENTITY_TYPES.map { |entity_type| # All three of these can be versioned (NAME-VERSION), but only have # one ACL that covers them all (NAME.json). case entity_type @@ -59,7 +59,7 @@ class Chef else AclDir.new(entity_type, self) end - end + } @children << AclEntry.new("organization.json", self, true) # the org acl is retrieved as GET /organizations/ORGNAME/ANYTHINGATALL/_acl end @children diff --git a/lib/chef/chef_fs/file_system/chef_server/cookbook_dir.rb b/lib/chef/chef_fs/file_system/chef_server/cookbook_dir.rb index 15729b7206..0db52326ab 100644 --- a/lib/chef/chef_fs/file_system/chef_server/cookbook_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/cookbook_dir.rb @@ -62,7 +62,7 @@ class Chef # we need to make sure we don't rethrow the exception. (child(name) # is not supposed to fail.) - children.find { |child| child.name == name } + children.find do |child| child.name == name end rescue Chef::ChefFS::FileSystem::NotFoundError nil end diff --git a/lib/chef/chef_fs/file_system/chef_server/nodes_dir.rb b/lib/chef/chef_fs/file_system/chef_server/nodes_dir.rb index 76897df093..b9b9c7cb41 100644 --- a/lib/chef/chef_fs/file_system/chef_server/nodes_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/nodes_dir.rb @@ -28,9 +28,9 @@ class Chef class NodesDir < RestListDir # Identical to RestListDir.children, except supports environments def children - @children ||= root.get_json(env_api_path).keys.sort.map do |key| + @children ||= root.get_json(env_api_path).keys.sort.map { |key| make_child_entry(key, true) - end + } rescue Timeout::Error => e raise Chef::ChefFS::FileSystem::OperationFailedError.new(:children, self, e, "Timeout retrieving children: #{e}") rescue Net::HTTPClientException => e diff --git a/lib/chef/chef_fs/file_system/chef_server/rest_list_dir.rb b/lib/chef/chef_fs/file_system/chef_server/rest_list_dir.rb index d2c5bdc9b7..cf672e3c22 100644 --- a/lib/chef/chef_fs/file_system/chef_server/rest_list_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/rest_list_dir.rb @@ -72,9 +72,9 @@ class Chef # def children # Grab the names of the children, append json, and make child entries - @children ||= root.get_json(api_path).keys.sort.map do |key| + @children ||= root.get_json(api_path).keys.sort.map { |key| make_child_entry(key, true) - end + } rescue Timeout::Error => e raise Chef::ChefFS::FileSystem::OperationFailedError.new(:children, self, e, "Timeout retrieving children: #{e}") rescue Net::HTTPClientException => e diff --git a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_root_dir.rb b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_root_dir.rb index de1f071fb3..a05923b017 100644 --- a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_root_dir.rb +++ b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_root_dir.rb @@ -163,11 +163,11 @@ class Chef def root_dir existing_paths = root_paths.select { |path| File.exists?(path) } if existing_paths.size > 0 - MultiplexedDir.new(existing_paths.map do |path| + MultiplexedDir.new(existing_paths.map { |path| dir = FileSystemEntry.new(name, parent, path) dir.write_pretty_json = !!write_pretty_json dir - end) + }) end end diff --git a/lib/chef/chef_fs/file_system/repository/file_system_entry.rb b/lib/chef/chef_fs/file_system/repository/file_system_entry.rb index 7c2d3e1522..279e2a801f 100644 --- a/lib/chef/chef_fs/file_system/repository/file_system_entry.rb +++ b/lib/chef/chef_fs/file_system/repository/file_system_entry.rb @@ -82,7 +82,7 @@ class Chef # Except cookbooks and data bag dirs, all things must be json files Dir.entries(file_path).sort .map { |child_name| make_child_entry(child_name) } - .select { |new_child| new_child.fs_entry_valid? && can_have_child?(new_child.name, new_child.dir?) } + .select do |new_child| new_child.fs_entry_valid? && can_have_child?(new_child.name, new_child.dir?) end rescue Errno::ENOENT raise Chef::ChefFS::FileSystem::NotFoundError.new(self, $!) end diff --git a/lib/chef/cookbook/manifest_v0.rb b/lib/chef/cookbook/manifest_v0.rb index a4c60e5827..4edf5d3dd2 100644 --- a/lib/chef/cookbook/manifest_v0.rb +++ b/lib/chef/cookbook/manifest_v0.rb @@ -30,7 +30,7 @@ class Chef def from_hash(hash) response = Mash.new(hash) - response[:all_files] = COOKBOOK_SEGMENTS.inject([]) do |memo, segment| + response[:all_files] = COOKBOOK_SEGMENTS.inject([]) { |memo, segment| next memo if hash[segment].nil? || hash[segment].empty? hash[segment].each do |file| @@ -39,7 +39,7 @@ class Chef end response.delete(segment) memo - end + } response end diff --git a/lib/chef/cookbook/manifest_v2.rb b/lib/chef/cookbook/manifest_v2.rb index 2b98c3550c..ff7b9605a0 100644 --- a/lib/chef/cookbook/manifest_v2.rb +++ b/lib/chef/cookbook/manifest_v2.rb @@ -31,7 +31,7 @@ class Chef def to_h(manifest) result = manifest.manifest.dup - result["all_files"].map! { |file| file.delete("full_path"); file } + result["all_files"].map! do |file| file.delete("full_path"); file end result["frozen?"] = manifest.frozen_version? result["chef_type"] = "cookbook_version" result.to_hash diff --git a/lib/chef/cookbook/metadata.rb b/lib/chef/cookbook/metadata.rb index d5821a799e..617607df98 100644 --- a/lib/chef/cookbook/metadata.rb +++ b/lib/chef/cookbook/metadata.rb @@ -397,9 +397,9 @@ class Chef # @return [Array<Array<String>]] Simple object representation of version constraints (for json) def gem_requirements_to_array(*deps) deps.map do |dep| - dep.requirement.requirements.map do |op, version| + dep.requirement.requirements.map { |op, version| "#{op} #{version}" - end.sort + }.sort end end diff --git a/lib/chef/cookbook/synchronizer.rb b/lib/chef/cookbook/synchronizer.rb index b6bcd2c150..72762a4189 100644 --- a/lib/chef/cookbook/synchronizer.rb +++ b/lib/chef/cookbook/synchronizer.rb @@ -122,7 +122,7 @@ class Chef [] end - @files ||= cookbooks.inject([]) do |memo, cookbook| + @files ||= cookbooks.inject([]) { |memo, cookbook| cookbook.each_file do |manifest_record| part = manifest_record[:name].split("/")[0] if lazy.include?(part) @@ -134,7 +134,7 @@ class Chef end end memo - end + } end def files_by_cookbook diff --git a/lib/chef/cookbook/syntax_check.rb b/lib/chef/cookbook/syntax_check.rb index 6c1f710f6d..8b8c1e85d0 100644 --- a/lib/chef/cookbook/syntax_check.rb +++ b/lib/chef/cookbook/syntax_check.rb @@ -214,7 +214,7 @@ class Chef def invalid_erb_file(erb_file, error_message) file_relative_path = erb_file[/^#{Regexp.escape(cookbook_path + File::Separator)}(.*)/, 1] Chef::Log.fatal("Erb template #{file_relative_path} has a syntax error:") - error_message.each_line { |l| Chef::Log.fatal(l.chomp) } + error_message.each_line do |l| Chef::Log.fatal(l.chomp) end nil end @@ -249,7 +249,7 @@ class Chef def invalid_ruby_file(ruby_file, error_message) file_relative_path = ruby_file[/^#{Regexp.escape(cookbook_path + File::Separator)}(.*)/, 1] Chef::Log.fatal("Cookbook file #{file_relative_path} has a ruby syntax error:") - error_message.each_line { |l| Chef::Log.fatal(l.chomp) } + error_message.each_line do |l| Chef::Log.fatal(l.chomp) end false end diff --git a/lib/chef/cookbook_manifest.rb b/lib/chef/cookbook_manifest.rb index b16eeccbca..2005c67a5c 100644 --- a/lib/chef/cookbook_manifest.rb +++ b/lib/chef/cookbook_manifest.rb @@ -192,7 +192,7 @@ class Chef def by_parent_directory @by_parent_directory ||= - manifest[:all_files].inject({}) do |memo, file| + manifest[:all_files].inject({}) { |memo, file| parts = file[:name].split("/") parent = if parts.length == 1 "root_files" @@ -203,7 +203,7 @@ class Chef memo[parent] ||= [] memo[parent] << file memo - end + } end def root_files diff --git a/lib/chef/cookbook_version.rb b/lib/chef/cookbook_version.rb index d546724fa0..0adfff3a48 100644 --- a/lib/chef/cookbook_version.rb +++ b/lib/chef/cookbook_version.rb @@ -249,13 +249,13 @@ class Chef error_message << error_locations.join("\n") existing_files = segment_filenames(segment) # Strip the root_dir prefix off all files for readability - pretty_existing_files = existing_files.map do |path| + pretty_existing_files = existing_files.map { |path| if root_dir path[root_dir.length + 1..-1] else path end - end + } # Show the files that the cookbook does have. If the user made a typo, # hopefully they'll see it here. unless pretty_existing_files.empty? @@ -280,7 +280,7 @@ class Chef def relative_filenames_in_preferred_directory(node, segment, dirname) preferences = preferences_for_path(node, segment, dirname) filenames_by_pref = {} - preferences.each { |pref| filenames_by_pref[pref] = [] } + preferences.each do |pref| filenames_by_pref[pref] = [] end files_for(segment).each do |manifest_record| manifest_record_path = manifest_record[:path] @@ -320,7 +320,7 @@ class Chef def preferred_manifest_records_for_directory(node, segment, dirname) preferences = preferences_for_path(node, segment, dirname) records_by_pref = {} - preferences.each { |pref| records_by_pref[pref] = [] } + preferences.each do |pref| records_by_pref[pref] = [] end files_for(segment).each do |manifest_record| manifest_record_path = manifest_record[:path] diff --git a/lib/chef/data_collector/config_validation.rb b/lib/chef/data_collector/config_validation.rb index 8bc409f03c..931f1a8d46 100644 --- a/lib/chef/data_collector/config_validation.rb +++ b/lib/chef/data_collector/config_validation.rb @@ -105,7 +105,7 @@ class Chef # validate an output_location file def validate_file!(file) - open(file, "a") {} + open(file, "a") do end rescue Errno::ENOENT raise Chef::Exceptions::ConfigurationError, "Chef::Config[:data_collector][:output_locations][:files] contains the location #{file}, which is a non existent file path." diff --git a/lib/chef/deprecated.rb b/lib/chef/deprecated.rb index cda8e197d3..3f855530eb 100644 --- a/lib/chef/deprecated.rb +++ b/lib/chef/deprecated.rb @@ -80,7 +80,7 @@ class Chef # Don't buffer the whole file in memory, so read it one line at a time. line_no = $2.to_i location_file = ::File.open($1) - (line_no - 1).times { location_file.readline } # Read all the lines we don't care about. + (line_no - 1).times do location_file.readline end # Read all the lines we don't care about. relevant_line = location_file.readline relevant_line.match?(/#.*chef:silence_deprecation($|[^:]|:#{self.class.deprecation_key})/) end diff --git a/lib/chef/dsl/platform_introspection.rb b/lib/chef/dsl/platform_introspection.rb index 3f79782798..50ab57cb4f 100644 --- a/lib/chef/dsl/platform_introspection.rb +++ b/lib/chef/dsl/platform_introspection.rb @@ -110,7 +110,7 @@ class Chef @values["default"] = value else assert_valid_platform_values!(platforms, value) - Array(platforms).each { |platform| @values[platform.to_s] = normalize_keys(value) } + Array(platforms).each do |platform| @values[platform.to_s] = normalize_keys(value) end value end end @@ -211,7 +211,7 @@ class Chef if platform_family.to_s == "default" @values["default"] = value else - Array(platform_family).each { |family| @values[family.to_s] = value } + Array(platform_family).each do |family| @values[family.to_s] = value end value end end diff --git a/lib/chef/encrypted_data_bag_item/decryptor.rb b/lib/chef/encrypted_data_bag_item/decryptor.rb index 1ddc99391d..88c800341c 100644 --- a/lib/chef/encrypted_data_bag_item/decryptor.rb +++ b/lib/chef/encrypted_data_bag_item/decryptor.rb @@ -192,7 +192,7 @@ class Chef::EncryptedDataBagItem expected_bytes = expected_hmac.bytes.to_a candidate_hmac_bytes = Base64.decode64(@encrypted_data["hmac"]).bytes.to_a valid = expected_bytes.size ^ candidate_hmac_bytes.size - expected_bytes.zip(candidate_hmac_bytes) { |x, y| valid |= x ^ y.to_i } + expected_bytes.zip(candidate_hmac_bytes) do |x, y| valid |= x ^ y.to_i end valid == 0 end end diff --git a/lib/chef/event_loggers/base.rb b/lib/chef/event_loggers/base.rb index b1a2f84988..5a29c9f7fe 100644 --- a/lib/chef/event_loggers/base.rb +++ b/lib/chef/event_loggers/base.rb @@ -36,9 +36,9 @@ class Chef end def self.available_event_loggers - event_loggers_by_name.select do |key, val| + event_loggers_by_name.select { |key, val| val.available? - end.keys + }.keys end def self.new(name) diff --git a/lib/chef/exceptions.rb b/lib/chef/exceptions.rb index 2d7ac374cb..18423245a7 100644 --- a/lib/chef/exceptions.rb +++ b/lib/chef/exceptions.rb @@ -491,13 +491,13 @@ class Chef attr_reader :resources_found def initialize(resources_found) @resources_found = resources_found - matches_info = @resources_found.each do |r| + matches_info = @resources_found.each { |r| if r["Module"].nil? "Resource #{r["Name"]} was found in #{r["Module"]["Name"]}" else "Resource #{r["Name"]} is a binary resource" end - end + } super "Found multiple resources matching #{matches_info[0]["Module"]["Name"]}:\n#{(matches_info.map { |f| f["Module"]["Version"] }).uniq.join("\n")}" end end diff --git a/lib/chef/file_access_control/unix.rb b/lib/chef/file_access_control/unix.rb index 4d3ac84eb0..77782fb55f 100644 --- a/lib/chef/file_access_control/unix.rb +++ b/lib/chef/file_access_control/unix.rb @@ -129,7 +129,7 @@ class Chef end rescue ArgumentError provider.requirements.assert(:create, :create_if_missing, :touch) do |a| - a.assertion { false } + a.assertion do false end a.failure_message(Chef::Exceptions::GroupIDNotFound, "cannot determine group id for '#{resource.group}', does the group exist on this system?") a.whyrun("Assuming group #{resource.group} would have been created") end @@ -278,7 +278,7 @@ class Chef end rescue ArgumentError provider.requirements.assert(:create, :create_if_missing, :touch) do |a| - a.assertion { false } + a.assertion do false end a.failure_message(Chef::Exceptions::UserIDNotFound, "cannot determine user id for '#{resource.owner}', does the user exist on this system?") a.whyrun("Assuming user #{resource.owner} would have been created") end diff --git a/lib/chef/formatters/error_inspectors/run_list_expansion_error_inspector.rb b/lib/chef/formatters/error_inspectors/run_list_expansion_error_inspector.rb index e33e5cea1a..4672f15226 100644 --- a/lib/chef/formatters/error_inspectors/run_list_expansion_error_inspector.rb +++ b/lib/chef/formatters/error_inspectors/run_list_expansion_error_inspector.rb @@ -60,9 +60,9 @@ class Chef end def missing_roles_explained - run_list_expansion.missing_roles_with_including_role.map do |role, includer| + run_list_expansion.missing_roles_with_including_role.map { |role, includer| "* #{role} included by '#{includer}'" - end.join("\n") + }.join("\n") end def run_list_expansion diff --git a/lib/chef/guard_interpreter/resource_guard_interpreter.rb b/lib/chef/guard_interpreter/resource_guard_interpreter.rb index adab16f5bf..5400f053ce 100644 --- a/lib/chef/guard_interpreter/resource_guard_interpreter.rb +++ b/lib/chef/guard_interpreter/resource_guard_interpreter.rb @@ -71,7 +71,7 @@ class Chef # Coerce to an array to be safe. This could happen with a legacy # resource or something overriding the default_action code in a # subclass. - Array(run_action).each { |action_to_run| @resource.run_action(action_to_run) } + Array(run_action).each do |action_to_run| @resource.run_action(action_to_run) end resource_updated = @resource.updated rescue Mixlib::ShellOut::ShellCommandFailed resource_updated = nil diff --git a/lib/chef/http.rb b/lib/chef/http.rb index 5546156031..8a2eea703a 100644 --- a/lib/chef/http.rb +++ b/lib/chef/http.rb @@ -179,12 +179,12 @@ class Chef method = :GET method, url, processed_headers, data = apply_request_middleware(method, url, headers, data) - response, rest_request, return_value = send_http_request(method, url, processed_headers, data) do |http_response| + response, rest_request, return_value = send_http_request(method, url, processed_headers, data) { |http_response| if http_response.is_a?(Net::HTTPSuccess) tempfile = stream_to_tempfile(url, http_response, tempfile, &progress_block) end apply_stream_complete_middleware(http_response, rest_request, return_value) - end + } return nil if response.is_a?(Net::HTTPRedirection) unless response.is_a?(Net::HTTPSuccess) @@ -226,12 +226,12 @@ class Chef method = :GET method, url, processed_headers, data = apply_request_middleware(method, url, headers, data) - response, rest_request, return_value = send_http_request(method, url, processed_headers, data) do |http_response| + response, rest_request, return_value = send_http_request(method, url, processed_headers, data) { |http_response| if http_response.is_a?(Net::HTTPSuccess) tempfile = stream_to_tempfile(url, http_response, tempfile) end apply_stream_complete_middleware(http_response, rest_request, return_value) - end + } return nil if response.is_a?(Net::HTTPRedirection) diff --git a/lib/chef/http/json_input.rb b/lib/chef/http/json_input.rb index f7204d4ccc..fa7bc9c196 100644 --- a/lib/chef/http/json_input.rb +++ b/lib/chef/http/json_input.rb @@ -33,7 +33,7 @@ class Chef def handle_request(method, url, headers = {}, data = false) if data && should_encode_as_json?(headers) - headers.delete_if { |key, _value| key.casecmp("content-type") == 0 } + headers.delete_if do |key, _value| key.casecmp("content-type") == 0 end headers["Content-Type"] = "application/json" json_opts = {} json_opts[:validate_utf8] = opts[:validate_utf8] if opts.key?(:validate_utf8) diff --git a/lib/chef/knife.rb b/lib/chef/knife.rb index 28634d9e44..fd4db6e3d1 100644 --- a/lib/chef/knife.rb +++ b/lib/chef/knife.rb @@ -301,16 +301,16 @@ class Chef # Mixlib::CLI ignores the embedded name_args @name_args = parse_options(argv) @name_args.delete(command_name_words.join("-")) - @name_args.reject! { |name_arg| command_name_words.delete(name_arg) } + @name_args.reject! do |name_arg| command_name_words.delete(name_arg) end # knife node run_list add requires that we have extra logic to handle # the case that command name words could be joined by an underscore :/ command_name_joined = command_name_words.join("_") - @name_args.reject! { |name_arg| command_name_joined == name_arg } + @name_args.reject! do |name_arg| command_name_joined == name_arg end # Similar handling for hyphens. command_name_joined = command_name_words.join("-") - @name_args.reject! { |name_arg| command_name_joined == name_arg } + @name_args.reject! do |name_arg| command_name_joined == name_arg end if config[:help] msg opt_parser diff --git a/lib/chef/knife/bootstrap.rb b/lib/chef/knife/bootstrap.rb index e892f1f2c9..3eeb10fb61 100644 --- a/lib/chef/knife/bootstrap.rb +++ b/lib/chef/knife/bootstrap.rb @@ -502,14 +502,14 @@ class Chef bootstrap_files = [] bootstrap_files << File.join(File.dirname(__FILE__), "bootstrap/templates", "#{template}.erb") bootstrap_files << File.join(Knife.chef_config_dir, "bootstrap", "#{template}.erb") if Chef::Knife.chef_config_dir - Chef::Util::PathHelper.home(".chef", "bootstrap", "#{template}.erb") { |p| bootstrap_files << p } + Chef::Util::PathHelper.home(".chef", "bootstrap", "#{template}.erb") do |p| bootstrap_files << p end bootstrap_files << Gem.find_files(File.join("chef", "knife", "bootstrap", "#{template}.erb")) bootstrap_files.flatten! - template_file = Array(bootstrap_files).find do |bootstrap_template| + template_file = Array(bootstrap_files).find { |bootstrap_template| Chef::Log.trace("Looking for bootstrap template in #{File.dirname(bootstrap_template)}") File.exists?(bootstrap_template) - end + } unless template_file ui.info("Can not find bootstrap definition for #{template}") @@ -604,9 +604,9 @@ class Chef def perform_bootstrap(remote_bootstrap_script_path) ui.info("Bootstrapping #{ui.color(server_name, :bold)}") cmd = bootstrap_command(remote_bootstrap_script_path) - r = connection.run_command(cmd) do |data| + r = connection.run_command(cmd) { |data| ui.msg("#{ui.color(" [#{connection.hostname}]", :cyan)} #{data}") - end + } if r.exit_status != 0 ui.error("The following error occurred on #{server_name}:") ui.error(r.stderr) @@ -644,9 +644,9 @@ class Chef raise else ui.warn("Failed to authenticate #{opts[:user]} to #{server_name} - trying password auth") - password = ui.ask("Enter password for #{opts[:user]}@#{server_name}.") do |q| + password = ui.ask("Enter password for #{opts[:user]}@#{server_name}.") { |q| q.echo = false - end + } end opts.merge! force_ssh_password_opts(password) diff --git a/lib/chef/knife/config_list_profiles.rb b/lib/chef/knife/config_list_profiles.rb index fb40b30b0a..86f25243c1 100644 --- a/lib/chef/knife/config_list_profiles.rb +++ b/lib/chef/knife/config_list_profiles.rb @@ -38,7 +38,7 @@ class Chef end current_profile = self.class.config_loader.credentials_profile(config[:profile]) - profiles = credentials_data.keys.map do |profile| + profiles = credentials_data.keys.map { |profile| if config[:ignore_knife_rb] # Don't do any fancy loading nonsense, just the raw data. profile_data = credentials_data[profile] @@ -64,7 +64,7 @@ class Chef server_url: Chef::Config[:chef_server_url], } end - end + } # Try to reset the config. unless config[:ignore_knife_rb] @@ -90,9 +90,9 @@ class Chef profile[:client_key] = profile[:client_key].to_s.gsub(/^#{Regexp.escape(Dir.home)}/, "~") if profile[:client_key] end # Render the data to a 2D array that will be used for the table. - table_data = [["", "Profile", "Client", "Key", "Server"]] + profiles.map do |profile| + table_data = [["", "Profile", "Client", "Key", "Server"]] + profiles.map { |profile| [profile[:active] ? "*" : ""] + profile.values_at(:profile, :client_name, :client_key, :server_url).map(&:to_s) - end + } # Compute column widths. column_widths = Array.new(table_data.first.length) do |i| table_data.map { |row| row[i].length + padding }.max diff --git a/lib/chef/knife/cookbook_delete.rb b/lib/chef/knife/cookbook_delete.rb index 98e54f486d..ab1e793f08 100644 --- a/lib/chef/knife/cookbook_delete.rb +++ b/lib/chef/knife/cookbook_delete.rb @@ -85,9 +85,9 @@ class Chef end def available_versions - @available_versions ||= rest.get("cookbooks/#{@cookbook_name}").map do |name, url_and_version| + @available_versions ||= rest.get("cookbooks/#{@cookbook_name}").map { |name, url_and_version| url_and_version["versions"].map { |url_by_version| url_by_version["version"] } - end.flatten + }.flatten rescue Net::HTTPClientException => e if e.to_s =~ /^404/ ui.error("Cannot find a cookbook named #{@cookbook_name} to delete.") @@ -112,13 +112,13 @@ class Chef ui.error("No versions specified, exiting") exit(1) end - versions = responses.map do |response| + versions = responses.map { |response| if version = valid_responses[response] version else ui.error("#{response} is not a valid choice, skipping it") end - end + } versions.compact end diff --git a/lib/chef/knife/cookbook_download.rb b/lib/chef/knife/cookbook_download.rb index aa6458a5d0..2a58478cd5 100644 --- a/lib/chef/knife/cookbook_download.rb +++ b/lib/chef/knife/cookbook_download.rb @@ -112,7 +112,7 @@ class Chef @available_versions ||= begin versions = Chef::CookbookVersion.available_versions(@cookbook_name) unless versions.nil? - versions.map! { |version| Chef::Version.new(version) } + versions.map! do |version| Chef::Version.new(version) end versions.sort! end versions diff --git a/lib/chef/knife/cookbook_upload.rb b/lib/chef/knife/cookbook_upload.rb index d73fa9ae68..1f9f232b60 100644 --- a/lib/chef/knife/cookbook_upload.rb +++ b/lib/chef/knife/cookbook_upload.rb @@ -217,9 +217,9 @@ class Chef # MUST!! dup the cookbook version object--it memoizes its # manifest object, but the manifest becomes invalid when you # regenerate the metadata - broken_files = cookbook.dup.manifest_records_by_path.select do |path, info| + broken_files = cookbook.dup.manifest_records_by_path.select { |path, info| info[CHECKSUM].nil? || info[CHECKSUM] !~ MATCH_CHECKSUM - end + } unless broken_files.empty? broken_filenames = Array(broken_files).map { |path, info| path } ui.error "The cookbook #{cookbook.name} has one or more broken files" @@ -232,9 +232,9 @@ class Chef def check_for_dependencies!(cookbook) # for all dependencies, check if the version is on the server, or # the version is in the cookbooks being uploaded. If not, exit and warn the user. - missing_dependencies = cookbook.metadata.dependencies.reject do |cookbook_name, version| + missing_dependencies = cookbook.metadata.dependencies.reject { |cookbook_name, version| check_server_side_cookbooks(cookbook_name, version) || check_uploading_cookbooks(cookbook_name, version) - end + } unless missing_dependencies.empty? missing_cookbook_names = missing_dependencies.map { |cookbook_name, version| "'#{cookbook_name}' version '#{version}'" } diff --git a/lib/chef/knife/core/gem_glob_loader.rb b/lib/chef/knife/core/gem_glob_loader.rb index 8fe228b848..a133515bdf 100644 --- a/lib/chef/knife/core/gem_glob_loader.rb +++ b/lib/chef/knife/core/gem_glob_loader.rb @@ -81,19 +81,19 @@ class Chef files = [] if check_load_path - files = $LOAD_PATH.map do |load_path| + files = $LOAD_PATH.map { |load_path| Dir["#{File.expand_path glob, Chef::Util::PathHelper.escape_glob_dir(load_path)}#{Gem.suffix_pattern}"] - end.flatten.select { |file| File.file? file.untaint } + }.flatten.select { |file| File.file? file.untaint } end - gem_files = latest_gem_specs.map do |spec| + gem_files = latest_gem_specs.map { |spec| # Gem::Specification#matches_for_glob wasn't added until RubyGems 1.8 if spec.respond_to? :matches_for_glob spec.matches_for_glob("#{glob}#{Gem.suffix_pattern}") else check_spec_for_glob(spec, glob) end - end.flatten + }.flatten files.concat gem_files files.uniq! if check_load_path diff --git a/lib/chef/knife/core/generic_presenter.rb b/lib/chef/knife/core/generic_presenter.rb index 90f529a3d9..e3bb7d366d 100644 --- a/lib/chef/knife/core/generic_presenter.rb +++ b/lib/chef/knife/core/generic_presenter.rb @@ -214,10 +214,10 @@ class Chef collected end else - versions_by_cookbook = item.inject({}) do |collected, ( cookbook, versions )| + versions_by_cookbook = item.inject({}) { |collected, ( cookbook, versions )| collected[cookbook] = versions["versions"].map { |v| v["version"] } collected - end + } key_length = versions_by_cookbook.empty? ? 0 : versions_by_cookbook.keys.map(&:size).max + 2 versions_by_cookbook.sort.map do |cookbook, versions| "#{cookbook.ljust(key_length)} #{versions.join(" ")}" diff --git a/lib/chef/knife/core/node_editor.rb b/lib/chef/knife/core/node_editor.rb index 753ee01704..5dc88cb4cc 100644 --- a/lib/chef/knife/core/node_editor.rb +++ b/lib/chef/knife/core/node_editor.rb @@ -67,9 +67,9 @@ class Chef policy_name policy_group run_list - }.reject do |key| + }.reject { |key| pristine_copy[key] == updated_copy[key] - end + } updated_properties.any? && updated_properties end diff --git a/lib/chef/knife/core/object_loader.rb b/lib/chef/knife/core/object_loader.rb index 087213fadf..a7630a65f7 100644 --- a/lib/chef/knife/core/object_loader.rb +++ b/lib/chef/knife/core/object_loader.rb @@ -80,7 +80,7 @@ class Chef def find_all_object_dirs(path) path = File.join(Chef::Util::PathHelper.escape_glob_dir(File.expand_path(path)), "*") objects = Dir.glob(path) - objects.delete_if { |o| !File.directory?(o) } + objects.delete_if do |o| !File.directory?(o) end objects.map { |o| File.basename(o) } end diff --git a/lib/chef/knife/core/subcommand_loader.rb b/lib/chef/knife/core/subcommand_loader.rb index 5b9474515a..60f6a9adff 100644 --- a/lib/chef/knife/core/subcommand_loader.rb +++ b/lib/chef/knife/core/subcommand_loader.rb @@ -83,7 +83,7 @@ class Chef def load_commands return true if @loaded - subcommand_files.each { |subcommand| Kernel.load subcommand } + subcommand_files.each do |subcommand| Kernel.load subcommand end @loaded = true end diff --git a/lib/chef/knife/diff.rb b/lib/chef/knife/diff.rb index 3e9336aacc..1dfa1777a4 100644 --- a/lib/chef/knife/diff.rb +++ b/lib/chef/knife/diff.rb @@ -64,9 +64,9 @@ class Chef error = false begin patterns.each do |pattern| - found_error = Chef::ChefFS::CommandLine.diff_print(pattern, chef_fs, local_fs, config[:recurse] ? nil : 1, output_mode, proc { |entry| format_path(entry) }, config[:diff_filter], ui ) do |diff| + found_error = Chef::ChefFS::CommandLine.diff_print(pattern, chef_fs, local_fs, config[:recurse] ? nil : 1, output_mode, proc { |entry| format_path(entry) }, config[:diff_filter], ui ) { |diff| stdout.print diff - end + } error = true if found_error end rescue Chef::ChefFS::FileSystem::OperationFailedError => e diff --git a/lib/chef/knife/environment_compare.rb b/lib/chef/knife/environment_compare.rb index 38e259a856..3c9ef3c013 100644 --- a/lib/chef/knife/environment_compare.rb +++ b/lib/chef/knife/environment_compare.rb @@ -94,19 +94,19 @@ class Chef def cookbook_list(constraints) result = {} - constraints.each_value { |cb| result.merge!(cb) } + constraints.each_value do |cb| result.merge!(cb) end result end def matrix_output(cookbooks, constraints) rows = [ "" ] environments = [] - constraints.each_key { |e| environments << e.to_s } + constraints.each_key do |e| environments << e.to_s end columns = environments.count + 1 - environments.each { |env| rows << ui.color(env, :bold) } + environments.each do |env| rows << ui.color(env, :bold) end cookbooks.each_key do |c| total = [] - environments.each { |n| total << constraints[n][c] } + environments.each do |n| total << constraints[n][c] end if total.uniq.count == 1 next if config[:mismatch] diff --git a/lib/chef/knife/exec.rb b/lib/chef/knife/exec.rb index 4b7f570aec..9455d76571 100644 --- a/lib/chef/knife/exec.rb +++ b/lib/chef/knife/exec.rb @@ -44,7 +44,7 @@ class Chef::Knife::Exec < Chef::Knife # Default script paths are chef-repo/.chef/scripts and ~/.chef/scripts config[:script_path] << File.join(Chef::Knife.chef_config_dir, "scripts") if Chef::Knife.chef_config_dir - Chef::Util::PathHelper.home(".chef", "scripts") { |p| config[:script_path] << p } + Chef::Util::PathHelper.home(".chef", "scripts") do |p| config[:script_path] << p end scripts = Array(name_args) context = Object.new diff --git a/lib/chef/knife/list.rb b/lib/chef/knife/list.rb index e5e196ecea..d4b169e832 100644 --- a/lib/chef/knife/list.rb +++ b/lib/chef/knife/list.rb @@ -65,7 +65,7 @@ class Chef patterns = name_args.length == 0 ? [""] : name_args # Get the top-level matches - all_results = parallelize(pattern_args_from(patterns)) do |pattern| + all_results = parallelize(pattern_args_from(patterns)) { |pattern| pattern_results = Chef::ChefFS::FileSystem.list(config[:local] ? local_fs : chef_fs, pattern).to_a if pattern_results.first && !pattern_results.first.exists? && pattern.exact_path @@ -73,13 +73,13 @@ class Chef self.exit_code = 1 end pattern_results - end.flatten(1).to_a + }.flatten(1).to_a # Process directories if !config[:bare_directories] - dir_results = parallelize(all_results.select(&:dir?)) do |result| + dir_results = parallelize(all_results.select(&:dir?)) { |result| add_dir_result(result) - end.flatten(1) + }.flatten(1) else dir_results = [] diff --git a/lib/chef/knife/node_run_list_add.rb b/lib/chef/knife/node_run_list_add.rb index 9b50e2483a..5d962415ca 100644 --- a/lib/chef/knife/node_run_list_add.rb +++ b/lib/chef/knife/node_run_list_add.rb @@ -43,9 +43,9 @@ class Chef node = Chef::Node.load(@name_args[0]) if @name_args.size > 2 # Check for nested lists and create a single plain one - entries = @name_args[1..-1].map do |entry| + entries = @name_args[1..-1].map { |entry| entry.split(",").map(&:strip) - end.flatten + }.flatten else # Convert to array and remove the extra spaces entries = @name_args[1].split(",").map(&:strip) diff --git a/lib/chef/knife/node_run_list_remove.rb b/lib/chef/knife/node_run_list_remove.rb index 36c98a724b..f5d1795e4a 100644 --- a/lib/chef/knife/node_run_list_remove.rb +++ b/lib/chef/knife/node_run_list_remove.rb @@ -34,9 +34,9 @@ class Chef if @name_args.size > 2 # Check for nested lists and create a single plain one - entries = @name_args[1..-1].map do |entry| + entries = @name_args[1..-1].map { |entry| entry.split(",").map(&:strip) - end.flatten + }.flatten else # Convert to array and remove the extra spaces entries = @name_args[1].split(",").map(&:strip) diff --git a/lib/chef/knife/node_run_list_set.rb b/lib/chef/knife/node_run_list_set.rb index eae05003ff..9b35edb70d 100644 --- a/lib/chef/knife/node_run_list_set.rb +++ b/lib/chef/knife/node_run_list_set.rb @@ -36,9 +36,9 @@ class Chef exit 1 elsif @name_args.size > 2 # Check for nested lists and create a single plain one - entries = @name_args[1..-1].map do |entry| + entries = @name_args[1..-1].map { |entry| entry.split(",").map(&:strip) - end.flatten + }.flatten else # Convert to array and remove the extra spaces entries = @name_args[1].split(",").map(&:strip) diff --git a/lib/chef/knife/role_env_run_list_add.rb b/lib/chef/knife/role_env_run_list_add.rb index 8f6a5cadba..e37e920360 100644 --- a/lib/chef/knife/role_env_run_list_add.rb +++ b/lib/chef/knife/role_env_run_list_add.rb @@ -56,7 +56,7 @@ class Chef role.run_list_for(environment).each do |entry| nlist << entry end - entries.each { |e| nlist << e } + entries.each do |e| nlist << e end role.env_run_lists_add(environment => nlist) end end @@ -68,9 +68,9 @@ class Chef if @name_args.size > 2 # Check for nested lists and create a single plain one - entries = @name_args[2..-1].map do |entry| + entries = @name_args[2..-1].map { |entry| entry.split(",").map(&:strip) - end.flatten + }.flatten else # Convert to array and remove the extra spaces entries = @name_args[2].split(",").map(&:strip) diff --git a/lib/chef/knife/role_env_run_list_set.rb b/lib/chef/knife/role_env_run_list_set.rb index 084bc02aff..3723bf65b7 100644 --- a/lib/chef/knife/role_env_run_list_set.rb +++ b/lib/chef/knife/role_env_run_list_set.rb @@ -37,7 +37,7 @@ class Chef unless role.env_run_lists.key?(environment) role.env_run_lists_add(environment => nlist) end - entries.each { |e| nlist << e } + entries.each do |e| nlist << e end role.env_run_lists_add(environment => nlist) end @@ -51,9 +51,9 @@ class Chef exit 1 elsif @name_args.size > 2 # Check for nested lists and create a single plain one - entries = @name_args[2..-1].map do |entry| + entries = @name_args[2..-1].map { |entry| entry.split(",").map(&:strip) - end.flatten + }.flatten else # Convert to array and remove the extra spaces entries = @name_args[2].split(",").map(&:strip) diff --git a/lib/chef/knife/role_run_list_add.rb b/lib/chef/knife/role_run_list_add.rb index 3c4961cbe1..7a6f23b9e4 100644 --- a/lib/chef/knife/role_run_list_add.rb +++ b/lib/chef/knife/role_run_list_add.rb @@ -56,7 +56,7 @@ class Chef role.run_list_for(environment).each do |entry| nlist << entry end - entries.each { |e| nlist << e } + entries.each do |e| nlist << e end role.env_run_lists_add(environment => nlist) end end @@ -68,9 +68,9 @@ class Chef if @name_args.size > 1 # Check for nested lists and create a single plain one - entries = @name_args[1..-1].map do |entry| + entries = @name_args[1..-1].map { |entry| entry.split(",").map(&:strip) - end.flatten + }.flatten else # Convert to array and remove the extra spaces entries = @name_args[1].split(",").map(&:strip) diff --git a/lib/chef/knife/role_run_list_set.rb b/lib/chef/knife/role_run_list_set.rb index 7302797c33..604b162a3a 100644 --- a/lib/chef/knife/role_run_list_set.rb +++ b/lib/chef/knife/role_run_list_set.rb @@ -36,7 +36,7 @@ class Chef unless role.env_run_lists.key?(environment) role.env_run_lists_add(environment => nlist) end - entries.each { |e| nlist << e } + entries.each do |e| nlist << e end role.env_run_lists_add(environment => nlist) end @@ -50,9 +50,9 @@ class Chef exit 1 elsif @name_args.size > 1 # Check for nested lists and create a single plain one - entries = @name_args[1..-1].map do |entry| + entries = @name_args[1..-1].map { |entry| entry.split(",").map(&:strip) - end.flatten + }.flatten else # Convert to array and remove the extra spaces entries = @name_args[1].split(",").map(&:strip) diff --git a/lib/chef/knife/show.rb b/lib/chef/knife/show.rb index 0e5ab9d0fe..7bce07dfcf 100644 --- a/lib/chef/knife/show.rb +++ b/lib/chef/knife/show.rb @@ -36,7 +36,7 @@ class Chef def run # Get the matches (recursively) error = false - entry_values = parallelize(pattern_args) do |pattern| + entry_values = parallelize(pattern_args) { |pattern| parallelize(Chef::ChefFS::FileSystem.list(config[:local] ? local_fs : chef_fs, pattern)) do |entry| if entry.dir? ui.error "#{format_path(entry)}: is a directory" if pattern.exact_path @@ -56,7 +56,7 @@ class Chef end end end - end.flatten(1) + }.flatten(1) entry_values.each do |entry, value| if entry output "#{format_path(entry)}:" diff --git a/lib/chef/knife/ssh.rb b/lib/chef/knife/ssh.rb index 2a4334570e..164cca195f 100644 --- a/lib/chef/knife/ssh.rb +++ b/lib/chef/knife/ssh.rb @@ -474,13 +474,13 @@ class Chef new_window_cmds = lambda do if session.servers_for.size > 1 - [""] + session.servers_for[1..-1].map do |server| + [""] + session.servers_for[1..-1].map { |server| if config[:tmux_split] "split-window #{ssh_dest.call(server)}; tmux select-layout tiled" else "new-window -a -n '#{server.host}' #{ssh_dest.call(server)}" end - end + } else [] end.join(" \\; ") diff --git a/lib/chef/knife/status.rb b/lib/chef/knife/status.rb index 074488e003..0aa854df56 100644 --- a/lib/chef/knife/status.rb +++ b/lib/chef/knife/status.rb @@ -84,13 +84,13 @@ class Chef all_nodes << node end - output(all_nodes.sort do |n1, n2| + output(all_nodes.sort { |n1, n2| if config[:sort_reverse] || Chef::Config[:knife][:sort_status_reverse] (n2["ohai_time"] || 0) <=> (n1["ohai_time"] || 0) else (n1["ohai_time"] || 0) <=> (n2["ohai_time"] || 0) end - end) + }) end end diff --git a/lib/chef/knife/supermarket_list.rb b/lib/chef/knife/supermarket_list.rb index 700d928af8..0a94e42dba 100644 --- a/lib/chef/knife/supermarket_list.rb +++ b/lib/chef/knife/supermarket_list.rb @@ -40,7 +40,7 @@ class Chef def run if config[:with_uri] cookbooks = {} - get_cookbook_list.each { |k, v| cookbooks[k] = v["cookbook"] } + get_cookbook_list.each do |k, v| cookbooks[k] = v["cookbook"] end ui.output(format_for_display(cookbooks)) else ui.msg(ui.list(get_cookbook_list.keys.sort, :columns_down)) diff --git a/lib/chef/mash.rb b/lib/chef/mash.rb index 404d6d622f..5384aa327c 100644 --- a/lib/chef/mash.rb +++ b/lib/chef/mash.rb @@ -117,7 +117,7 @@ class Mash < Hash # # @return [Mash] The updated mash. def update(other_hash) - other_hash.each_pair { |key, value| regular_writer(convert_key(key), convert_value(value)) } + other_hash.each_pair do |key, value| regular_writer(convert_key(key), convert_value(value)) end self end @@ -183,7 +183,7 @@ class Mash < Hash # @return [Hash] The mash as a Hash with symbolized keys. def symbolize_keys h = Hash.new(default) - each { |key, val| h[key.to_sym] = val } + each do |key, val| h[key.to_sym] = val end h end diff --git a/lib/chef/mixin/convert_to_class_name.rb b/lib/chef/mixin/convert_to_class_name.rb index c5944c3985..6a37854e2f 100644 --- a/lib/chef/mixin/convert_to_class_name.rb +++ b/lib/chef/mixin/convert_to_class_name.rb @@ -43,7 +43,7 @@ class Chef def convert_to_snake_case(str, namespace = nil) str = str.dup str.sub!(/^#{namespace}(\:\:)?/, "") if namespace - str.gsub!(/[A-Z]/) { |s| "_" + s } + str.gsub!(/[A-Z]/) do |s| "_" + s end str.downcase! str.sub!(/^\_/, "") str @@ -109,12 +109,12 @@ class Chef # Go down the ancestors to check if it is owned directly. The check # stops when we reach Object or the end of ancestors tree. - constant = constant.ancestors.inject do |const, ancestor| + constant = constant.ancestors.inject { |const, ancestor| break const if ancestor == Object break ancestor if ancestor.const_defined?(name, false) const - end + } # owner is in Object, so raise constant.const_get(name, false) diff --git a/lib/chef/mixin/params_validate.rb b/lib/chef/mixin/params_validate.rb index ad7eddb48a..5a9f1f5e11 100644 --- a/lib/chef/mixin/params_validate.rb +++ b/lib/chef/mixin/params_validate.rb @@ -414,7 +414,7 @@ class Chef value = _pv_opts_lookup(opts, key) to_be = [ to_be ].flatten(1) errors = [] - passed = to_be.any? do |tb| + passed = to_be.any? { |tb| case tb when Proc raise Exceptions::CannotValidateStaticallyError, "is: proc { } must be evaluated once for each resource" if self == Chef::Mixin::ParamsValidate @@ -434,7 +434,7 @@ class Chef else tb === value end - end + } if passed true else diff --git a/lib/chef/mixin/powershell_type_coercions.rb b/lib/chef/mixin/powershell_type_coercions.rb index a75022c771..c09929b7a3 100644 --- a/lib/chef/mixin/powershell_type_coercions.rb +++ b/lib/chef/mixin/powershell_type_coercions.rb @@ -49,16 +49,16 @@ class Chef private def translate_hash(x) - translated = x.inject([]) do |memo, (k, v)| + translated = x.inject([]) { |memo, (k, v)| memo << "#{k}=#{translate_type(v)}" - end + } "@{#{translated.join(";")}}" end def translate_array(x) - translated = x.map do |v| + translated = x.map { |v| translate_type(v) - end + } "@(#{translated.join(",")})" end diff --git a/lib/chef/mixin/properties.rb b/lib/chef/mixin/properties.rb index ecb589e015..91b63072f5 100644 --- a/lib/chef/mixin/properties.rb +++ b/lib/chef/mixin/properties.rb @@ -20,7 +20,7 @@ class Chef def properties(include_superclass = true) if include_superclass result = {} - ancestors.reverse_each { |c| result.merge!(c.properties(false)) if c.respond_to?(:properties) } + ancestors.reverse_each do |c| result.merge!(c.properties(false)) if c.respond_to?(:properties) end result else @properties ||= {} diff --git a/lib/chef/mixin/versioned_api.rb b/lib/chef/mixin/versioned_api.rb index 17c9838d29..3a62c98fe1 100644 --- a/lib/chef/mixin/versioned_api.rb +++ b/lib/chef/mixin/versioned_api.rb @@ -44,12 +44,12 @@ class Chef end def get_class_for(type) - versioned_interfaces.select do |klass| + versioned_interfaces.select { |klass| version = klass.send(:minimum_api_version) # min and max versions will be nil if we've not made a request to the server yet, # in which case we'll just start with the highest version and see what happens ServerAPIVersions.instance.min_server_version.nil? || (version >= ServerAPIVersions.instance.min_server_version && version <= ServerAPIVersions.instance.send(type)) - end + } .sort { |a, b| a.send(:minimum_api_version) <=> b.send(:minimum_api_version) } .last end diff --git a/lib/chef/mixin/which.rb b/lib/chef/mixin/which.rb index a51963b6c2..87946038ef 100644 --- a/lib/chef/mixin/which.rb +++ b/lib/chef/mixin/which.rb @@ -28,12 +28,12 @@ class Chef # NOTE: unnecessarily duplicates function of path_sanity extra_path ||= [ "/bin", "/usr/bin", "/sbin", "/usr/sbin" ] paths = env_path.split(File::PATH_SEPARATOR) + Array(extra_path) - cmds.map do |cmd| - paths.map do |path| + cmds.map { |cmd| + paths.map { |path| filename = Chef.path_to(File.join(path, cmd)) filename if valid_executable?(filename, &block) - end.compact - end.flatten + }.compact + }.flatten end private diff --git a/lib/chef/node.rb b/lib/chef/node.rb index dfd2c685e1..f0be72e68f 100644 --- a/lib/chef/node.rb +++ b/lib/chef/node.rb @@ -582,7 +582,7 @@ class Chef def self.list_by_environment(environment, inflate = false) if inflate response = {} - Chef::Search::Query.new.search(:node, "chef_environment:#{environment}") { |n| response[n.name] = n unless n.nil? } + Chef::Search::Query.new.search(:node, "chef_environment:#{environment}") do |n| response[n.name] = n unless n.nil? end response else Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("environments/#{environment}/nodes") diff --git a/lib/chef/node/attribute.rb b/lib/chef/node/attribute.rb index bc4983384b..7804766301 100644 --- a/lib/chef/node/attribute.rb +++ b/lib/chef/node/attribute.rb @@ -487,9 +487,9 @@ class Chef end def inspect - "#<#{self.class} " << (COMPONENTS + %i{@merged_attributes @properties}).map do |iv| + "#<#{self.class} " << (COMPONENTS + %i{@merged_attributes @properties}).map { |iv| "#{iv}=#{instance_variable_get(iv).inspect}" - end.join(", ") << ">" + }.join(", ") << ">" end private @@ -546,9 +546,9 @@ class Chef apply_path(@automatic, path), ] - ret = components.inject(NIL) do |merged, component| + ret = components.inject(NIL) { |merged, component| hash_only_merge!(merged, component) - end + } ret == NIL ? nil : ret end @@ -559,10 +559,10 @@ class Chef # @param path [Array] Array of args to method chain to descend into the node object # @return [attr] Deep Merged values (may be VividMash, Hash, Array, etc) from the node object def merge_defaults(path) - ret = DEFAULT_COMPONENTS.inject(NIL) do |merged, component_ivar| + ret = DEFAULT_COMPONENTS.inject(NIL) { |merged, component_ivar| component_value = apply_path(instance_variable_get(component_ivar), path) deep_merge!(merged, component_value) - end + } ret end @@ -573,10 +573,10 @@ class Chef # @param path [Array] Array of args to method chain to descend into the node object # @return [attr] Deep Merged values (may be VividMash, Hash, Array, etc) from the node object def merge_overrides(path) - ret = OVERRIDE_COMPONENTS.inject(NIL) do |merged, component_ivar| + ret = OVERRIDE_COMPONENTS.inject(NIL) { |merged, component_ivar| component_value = apply_path(instance_variable_get(component_ivar), path) deep_merge!(merged, component_value) - end + } ret end diff --git a/lib/chef/node/common_api.rb b/lib/chef/node/common_api.rb index 1ea1067113..8fbb84b561 100644 --- a/lib/chef/node/common_api.rb +++ b/lib/chef/node/common_api.rb @@ -35,7 +35,7 @@ class Chef value = block_given? ? yield : args.pop last = args.pop prev_memo = prev_key = nil - chain = args.inject(self) do |memo, key| + chain = args.inject(self) { |memo, key| unless valid_container?(memo, key) prev_memo[prev_key] = {} memo = prev_memo[prev_key] @@ -43,7 +43,7 @@ class Chef prev_memo = memo prev_key = key memo[key] - end + } unless valid_container?(chain, last) prev_memo[prev_key] = {} chain = prev_memo[prev_key] @@ -57,11 +57,11 @@ class Chef def write!(*args, &block) value = block_given? ? yield : args.pop last = args.pop - obj = args.inject(self) do |memo, key| + obj = args.inject(self) { |memo, key| raise Chef::Exceptions::AttributeTypeMismatch unless valid_container?(memo, key) memo[key] - end + } raise Chef::Exceptions::AttributeTypeMismatch unless valid_container?(obj, last) obj[last] = value diff --git a/lib/chef/node/immutable_collections.rb b/lib/chef/node/immutable_collections.rb index b4a7a39ba0..b75fde39d5 100644 --- a/lib/chef/node/immutable_collections.rb +++ b/lib/chef/node/immutable_collections.rb @@ -82,7 +82,7 @@ class Chef end def to_a - Array.new(map do |v| + Array.new(map { |v| case v when ImmutableArray v.to_a @@ -91,7 +91,7 @@ class Chef else safe_dup(v) end - end) + }) end alias_method :to_array, :to_a diff --git a/lib/chef/node_map.rb b/lib/chef/node_map.rb index dd118c26cf..47defacfe3 100644 --- a/lib/chef/node_map.rb +++ b/lib/chef/node_map.rb @@ -142,9 +142,9 @@ class Chef def list(node, key, canonical: nil) return [] unless map.key?(key) - map[key].select do |matcher| + map[key].select { |matcher| node_matches?(node, matcher) && canonical_matches?(canonical, matcher) - end.map { |matcher| matcher[:klass] } + }.map { |matcher| matcher[:klass] } end # Remove a class from all its matchers in the node_map, will remove mappings completely if its the last matcher left @@ -180,7 +180,7 @@ class Chef def delete_canonical(key, klass) remaining = map[key] if remaining - remaining.delete_if { |matcher| matcher[:canonical] && Array(matcher[:klass]) == Array(klass) } + remaining.delete_if do |matcher| matcher[:canonical] && Array(matcher[:klass]) == Array(klass) end if remaining.empty? map.delete(key) remaining = nil diff --git a/lib/chef/policy_builder/expand_node_object.rb b/lib/chef/policy_builder/expand_node_object.rb index 4afb4d7d60..f87de2da2a 100644 --- a/lib/chef/policy_builder/expand_node_object.rb +++ b/lib/chef/policy_builder/expand_node_object.rb @@ -186,10 +186,10 @@ class Chef cookbook_hash = api_service.post("environments/#{node.chef_environment}/cookbook_versions", { run_list: @expanded_run_list_with_versions }) - cookbook_hash = cookbook_hash.inject({}) do |memo, (key, value)| + cookbook_hash = cookbook_hash.inject({}) { |memo, (key, value)| memo[key] = Chef::CookbookVersion.from_hash(value) memo - end + } rescue Exception => e # TODO: wrap/munge exception to provide helpful error output events.cookbook_resolution_failed(@expanded_run_list_with_versions, e) diff --git a/lib/chef/policy_builder/policyfile.rb b/lib/chef/policy_builder/policyfile.rb index 70a2e44635..959c2d6746 100644 --- a/lib/chef/policy_builder/policyfile.rb +++ b/lib/chef/policy_builder/policyfile.rb @@ -59,9 +59,9 @@ class Chef # # Skipped will always be false as it can only be true when two expanded # roles contain the same recipe. - expanded_run_list = recipes.map do |r| + expanded_run_list = recipes.map { |r| { type: "recipe", name: r, skipped: false, version: nil } - end + } data_collector_hash = {} data_collector_hash[:id] = "_policy_node" data_collector_hash[:run_list] = expanded_run_list @@ -259,10 +259,10 @@ class Chef # a RunListExpansion object, to satisfy the API contract of # #expand_run_list def run_list_expansion_ish - recipes = run_list.map do |recipe_spec| + recipes = run_list.map { |recipe_spec| cookbook, recipe = parse_recipe_spec(recipe_spec) "#{cookbook}::#{recipe}" - end + } RunListExpansionIsh.new(recipes, []) end @@ -341,9 +341,9 @@ class Chef errors << "Policyfile is missing cookbook_locks element" end if run_list.is_a?(Array) - run_list_errors = run_list.select do |maybe_recipe_spec| + run_list_errors = run_list.select { |maybe_recipe_spec| validate_recipe_spec(maybe_recipe_spec) - end + } errors += run_list_errors else errors << "Policyfile run_list is malformed, must be an array of `recipe[cb_name::recipe_name]` items: #{policy["run_list"]}" @@ -459,10 +459,10 @@ class Chef @cookbook_to_sync ||= begin events.cookbook_resolution_start(run_list_with_versions_for_display) - cookbook_versions_by_name = cookbook_locks.inject({}) do |cb_map, (name, lock_data)| + cookbook_versions_by_name = cookbook_locks.inject({}) { |cb_map, (name, lock_data)| cb_map[name] = manifest_for(name, lock_data) cb_map - end + } events.cookbook_resolution_complete(cookbook_versions_by_name) cookbook_versions_by_name diff --git a/lib/chef/property.rb b/lib/chef/property.rb index 6aa76a5236..8618cd98db 100644 --- a/lib/chef/property.rb +++ b/lib/chef/property.rb @@ -321,9 +321,9 @@ class Chef # @return [Hash<Symbol,Object>] # def validation_options - @validation_options ||= options.reject do |k, v| + @validation_options ||= options.reject { |k, v| %i{declared_in name instance_variable_name desired_state identity default name_property coerce required nillable sensitive description introduced deprecated default_description skip_docs}.include?(k) - end + } end # diff --git a/lib/chef/provider.rb b/lib/chef/provider.rb index 6d1985bbbb..661a4b5162 100644 --- a/lib/chef/provider.rb +++ b/lib/chef/provider.rb @@ -280,13 +280,13 @@ class Chef properties_str = if new_resource.sensitive specified_properties.join(", ") else - specified_properties.map do |property| + specified_properties.map { |property| "#{property}=" << if new_resource.class.properties[property].sensitive? "(suppressed sensitive property)" else new_resource.send(property).inspect end - end.join(", ") + }.join(", ") end logger.debug("Skipping update of #{new_resource}: has not changed any of the specified properties #{properties_str}.") return false @@ -308,7 +308,7 @@ class Chef # The resource doesn't exist. Mark that we are *creating* this, and # write down any properties we are setting. property_size = properties.map(&:size).max - created = properties.map do |property| + created = properties.map { |property| default = " (default value)" unless new_resource.property_is_set?(property) properties_str = if new_resource.sensitive || new_resource.class.properties[property].sensitive? "(suppressed sensitive property)" @@ -316,7 +316,7 @@ class Chef new_resource.send(property).inspect end " set #{property.to_s.ljust(property_size)} to #{properties_str}#{default}" - end + } converge_by([ "create #{new_resource.identity}" ] + created, &converge_block) end @@ -357,8 +357,8 @@ class Chef provider_class = self @included_resource_dsl_module = Module.new do extend Forwardable - define_singleton_method(:to_s) { "forwarder module for #{provider_class}" } - define_singleton_method(:inspect) { to_s } + define_singleton_method(:to_s) do "forwarder module for #{provider_class}" end + define_singleton_method(:inspect) do to_s end # this magic, stated simply, is that any instance method declared directly on # the resource we are building, will be accessible from the action_class(provider) # instance. methods declared on Chef::Resource and properties are not inherited. diff --git a/lib/chef/provider/apt_repository.rb b/lib/chef/provider/apt_repository.rb index 85fac1d2da..e4dc0db99d 100644 --- a/lib/chef/provider/apt_repository.rb +++ b/lib/chef/provider/apt_repository.rb @@ -117,11 +117,11 @@ class Chef # @return [Array] an array of fingerprints def extract_fingerprints_from_cmd(*cmd) so = shell_out(*cmd) - so.stdout.split(/\n/).map do |t| + so.stdout.split(/\n/).map { |t| if z = t.match(/^fpr:+([0-9A-F]+):/) z[1].split.join end - end.compact + }.compact end # validate the key against the apt keystore to see if that version is expired @@ -201,7 +201,7 @@ class Chef key_name = key.gsub(/[^0-9A-Za-z\-]/, "_") cached_keyfile = ::File.join(Chef::Config[:file_cache_path], key_name) tmp_dir = Dir.mktmpdir(".gpg") - at_exit { FileUtils.remove_entry(tmp_dir) } + at_exit do FileUtils.remove_entry(tmp_dir) end declare_resource(key_type(key), cached_keyfile) do source key @@ -216,7 +216,7 @@ class Chef default_env true sensitive new_resource.sensitive action :run - not_if { no_new_keys?(cached_keyfile) } + not_if do no_new_keys?(cached_keyfile) end notifies :run, "execute[apt-cache gencaches]", :immediately end end @@ -252,9 +252,9 @@ class Chef default_env true sensitive new_resource.sensitive not_if do - present = extract_fingerprints_from_cmd(*LIST_APT_KEY_FINGERPRINTS).any? do |fp| + present = extract_fingerprints_from_cmd(*LIST_APT_KEY_FINGERPRINTS).any? { |fp| fp.end_with? key.upcase - end + } present && key_is_valid?(key.upcase) end notifies :run, "execute[apt-cache gencaches]", :immediately diff --git a/lib/chef/provider/dsc_resource.rb b/lib/chef/provider/dsc_resource.rb index da8b17ed04..7b1c77b780 100644 --- a/lib/chef/provider/dsc_resource.rb +++ b/lib/chef/provider/dsc_resource.rb @@ -46,7 +46,7 @@ class Chef def define_resource_requirements requirements.assert(:run) do |a| - a.assertion { supports_dsc_invoke_resource? } + a.assertion do supports_dsc_invoke_resource? end err = ["You must have PowerShell version >= 5.0.10018.0 to use dsc_resource."] a.failure_message Chef::Exceptions::ProviderNotFound, err @@ -54,7 +54,7 @@ class Chef a.block_action! end requirements.assert(:run) do |a| - a.assertion { supports_refresh_mode_enabled? || dsc_refresh_mode_disabled? } + a.assertion do supports_refresh_mode_enabled? || dsc_refresh_mode_disabled? end err = ["The LCM must have its RefreshMode set to Disabled for" \ " PowerShell versions before 5.0.10586.0."] a.failure_message Chef::Exceptions::ProviderNotFound, err.join(" ") @@ -62,7 +62,7 @@ class Chef a.block_action! end requirements.assert(:run) do |a| - a.assertion { module_usage_valid? } + a.assertion do module_usage_valid? end err = ["module_name must be supplied along with module_version."] a.failure_message Chef::Exceptions::DSCModuleNameMissing, err diff --git a/lib/chef/provider/dsc_script.rb b/lib/chef/provider/dsc_script.rb index 999ea9f33e..510fa2a843 100644 --- a/lib/chef/provider/dsc_script.rb +++ b/lib/chef/provider/dsc_script.rb @@ -52,9 +52,9 @@ class Chef def load_current_resource if supports_dsc? @dsc_resources_info = run_configuration(:test) - @resource_converged = @dsc_resources_info.all? do |resource| + @resource_converged = @dsc_resources_info.all? { |resource| !resource.changes_state? - end + } end end @@ -65,7 +65,7 @@ class Chef powershell_info_str, "PowerShell 4.0 or higher was not detected on your system and is required to use the dsc_script resource.", ] - a.assertion { supports_dsc? } + a.assertion do supports_dsc? end a.failure_message Chef::Exceptions::ProviderNotFound, err.join(" ") a.whyrun err + ["Assuming a previous resource installs PowerShell 4.0 or higher."] a.block_action! @@ -157,7 +157,7 @@ class Chef def generate_description ["converge DSC configuration '#{configuration_friendly_name}'"] + - @dsc_resources_info.map do |resource| + @dsc_resources_info.map { |resource| if resource.changes_state? # We ignore the last log message because it only contains the time it took, which looks weird cleaned_messages = resource.change_log[0..-2].map { |c| c.sub(/^#{Regexp.escape(resource.name)}/, "").strip } @@ -170,7 +170,7 @@ class Chef # This is needed because a dsc script can have resources that are both converged and not "converge DSC resource #{resource.name} by doing nothing because it is already converged" end - end + } end def powershell_info_str diff --git a/lib/chef/provider/file.rb b/lib/chef/provider/file.rb index 054b9718c3..cf297a3f8f 100644 --- a/lib/chef/provider/file.rb +++ b/lib/chef/provider/file.rb @@ -112,7 +112,7 @@ class Chef # Make sure the parent directory exists, otherwise fail. For why-run assume it would have been created. requirements.assert(:create, :create_if_missing, :touch) do |a| parent_directory = ::File.dirname(new_resource.path) - a.assertion { ::File.directory?(parent_directory) } + a.assertion do ::File.directory?(parent_directory) end a.failure_message(Chef::Exceptions::EnclosingDirectoryDoesNotExist, "Parent directory #{parent_directory} does not exist.") a.whyrun("Assuming directory #{parent_directory} would have been created") end @@ -120,14 +120,14 @@ class Chef # Make sure the file is deletable if it exists, otherwise fail. if ::File.exist?(new_resource.path) requirements.assert(:delete) do |a| - a.assertion { ::File.writable?(new_resource.path) } + a.assertion do ::File.writable?(new_resource.path) end a.failure_message(Chef::Exceptions::InsufficientPermissions, "File #{new_resource.path} exists but is not writable so it cannot be deleted") end end error, reason, whyrun_message = inspect_existing_fs_entry requirements.assert(:create) do |a| - a.assertion { error.nil? } + a.assertion do error.nil? end a.failure_message(error, reason) a.whyrun(whyrun_message) # Subsequent attempts to read the fs entry at the path (e.g., for diff --git a/lib/chef/provider/git.rb b/lib/chef/provider/git.rb index b7ca81b3f8..90cfd081eb 100644 --- a/lib/chef/provider/git.rb +++ b/lib/chef/provider/git.rb @@ -44,14 +44,14 @@ class Chef # Parent directory of the target must exist. requirements.assert(:checkout, :sync) do |a| dirname = ::File.dirname(cwd) - a.assertion { ::File.directory?(dirname) } + a.assertion do ::File.directory?(dirname) end a.whyrun("Directory #{dirname} does not exist, this run will fail unless it has been previously created. Assuming it would have been created.") a.failure_message(Chef::Exceptions::MissingParentDirectory, "Cannot clone #{new_resource} to #{cwd}, the enclosing directory #{dirname} does not exist") end requirements.assert(:all_actions) do |a| - a.assertion { !(new_resource.revision =~ %r{^origin/}) } + a.assertion do !(new_resource.revision =~ %r{^origin/}) end a.failure_message Chef::Exceptions::InvalidRemoteGitReference, "Deploying remote branches is not supported. " + "Specify the remote branch as a local branch for " + @@ -63,7 +63,7 @@ class Chef # this can't be recovered from in why-run mode, because nothing that # we do in the course of a run is likely to create a valid target_revision # if we can't resolve it up front. - a.assertion { !target_revision.nil? } + a.assertion do !target_revision.nil? end a.failure_message Chef::Exceptions::UnresolvableGitReference, "Unable to parse SHA reference for '#{new_resource.revision}' in repository '#{new_resource.repository}'. " + "Verify your (case-sensitive) repository URL and revision.\n" + diff --git a/lib/chef/provider/group.rb b/lib/chef/provider/group.rb index 1c8a18c037..86ff6fdbe1 100644 --- a/lib/chef/provider/group.rb +++ b/lib/chef/provider/group.rb @@ -55,7 +55,7 @@ class Chef def define_resource_requirements requirements.assert(:modify) do |a| - a.assertion { @group_exists } + a.assertion do @group_exists end a.failure_message(Chef::Exceptions::Group, "Cannot modify #{new_resource} - group does not exist!") a.whyrun("Group #{new_resource} does not exist. Unless it would have been created earlier in this run, this attempt to modify it would fail.") end @@ -65,7 +65,7 @@ class Chef # user names in the members and exclude_members properties. if !new_resource.members.nil? && !new_resource.excluded_members.nil? common_members = new_resource.members & new_resource.excluded_members - a.assertion { common_members.empty? } + a.assertion do common_members.empty? end a.failure_message(Chef::Exceptions::ConflictingMembersInGroup, "Attempting to both add and remove users from a group: '#{common_members.join(", ")}'") # No why-run alternative end diff --git a/lib/chef/provider/group/dscl.rb b/lib/chef/provider/group/dscl.rb index decad69e40..d8370ff57e 100644 --- a/lib/chef/provider/group/dscl.rb +++ b/lib/chef/provider/group/dscl.rb @@ -30,8 +30,8 @@ class Chef status = shell_out(shellcmd) stdout_result = "" stderr_result = "" - status.stdout.each_line { |line| stdout_result << line } - status.stderr.each_line { |line| stderr_result << line } + status.stdout.each_line do |line| stdout_result << line end + status.stderr.each_line do |line| stderr_result << line end [shellcmd.flatten.compact.join(" "), status, stdout_result, stderr_result] end @@ -142,7 +142,7 @@ class Chef def define_resource_requirements super requirements.assert(:all_actions) do |a| - a.assertion { ::File.exist?("/usr/bin/dscl") } + a.assertion do ::File.exist?("/usr/bin/dscl") end a.failure_message Chef::Exceptions::Group, "Could not find binary /usr/bin/dscl for #{new_resource.name}" # No whyrun alternative: this component should be available in the base install of any given system that uses it end diff --git a/lib/chef/provider/group/gpasswd.rb b/lib/chef/provider/group/gpasswd.rb index 5d769befa4..6eaf4cc991 100644 --- a/lib/chef/provider/group/gpasswd.rb +++ b/lib/chef/provider/group/gpasswd.rb @@ -31,7 +31,7 @@ class Chef def define_resource_requirements super requirements.assert(:all_actions) do |a| - a.assertion { ::File.exist?("/usr/bin/gpasswd") } + a.assertion do ::File.exist?("/usr/bin/gpasswd") end a.failure_message Chef::Exceptions::Group, "Could not find binary /usr/bin/gpasswd for #{new_resource}" # No whyrun alternative: this component should be available in the base install of any given system that uses it end diff --git a/lib/chef/provider/group/groupadd.rb b/lib/chef/provider/group/groupadd.rb index eca104b565..9671ec35de 100644 --- a/lib/chef/provider/group/groupadd.rb +++ b/lib/chef/provider/group/groupadd.rb @@ -35,7 +35,7 @@ class Chef super required_binaries.each do |required_binary| requirements.assert(:all_actions) do |a| - a.assertion { ::File.exist?(required_binary) } + a.assertion do ::File.exist?(required_binary) end a.failure_message Chef::Exceptions::Group, "Could not find binary #{required_binary} for #{new_resource}" # No whyrun alternative: this component should be available in the base install of any given system that uses it end diff --git a/lib/chef/provider/group/pw.rb b/lib/chef/provider/group/pw.rb index c018de8d4d..ecad8f44ba 100644 --- a/lib/chef/provider/group/pw.rb +++ b/lib/chef/provider/group/pw.rb @@ -30,7 +30,7 @@ class Chef super requirements.assert(:all_actions) do |a| - a.assertion { ::File.exist?("/usr/sbin/pw") } + a.assertion do ::File.exist?("/usr/sbin/pw") end a.failure_message Chef::Exceptions::Group, "Could not find binary /usr/sbin/pw for #{new_resource}" # No whyrun alternative: this component should be available in the base install of any given system that uses it end diff --git a/lib/chef/provider/group/solaris.rb b/lib/chef/provider/group/solaris.rb index 75768297db..fe33f06917 100644 --- a/lib/chef/provider/group/solaris.rb +++ b/lib/chef/provider/group/solaris.rb @@ -35,7 +35,7 @@ class Chef super requirements.assert(:all_actions) do |a| - a.assertion { ::File.exist?("/usr/sbin/usermod") && ::File.exist?("/usr/sbin/groupmod") } + a.assertion do ::File.exist?("/usr/sbin/usermod") && ::File.exist?("/usr/sbin/groupmod") end a.failure_message Chef::Exceptions::Group, "Could not find binary /usr/sbin/usermod or /usr/sbin/groupmod for #{new_resource}" # No whyrun alternative: this component should be available in the base install of any given system that uses it end diff --git a/lib/chef/provider/group/suse.rb b/lib/chef/provider/group/suse.rb index 7bd9700a15..76026eea51 100644 --- a/lib/chef/provider/group/suse.rb +++ b/lib/chef/provider/group/suse.rb @@ -32,7 +32,7 @@ class Chef def define_resource_requirements super requirements.assert(:all_actions) do |a| - a.assertion { ::File.exist?("/usr/sbin/groupmod") } + a.assertion do ::File.exist?("/usr/sbin/groupmod") end a.failure_message Chef::Exceptions::Group, "Could not find binary /usr/sbin/groupmod for #{new_resource.name}" # No whyrun alternative: this component should be available in the base install of any given system that uses it end @@ -40,7 +40,7 @@ class Chef requirements.assert(:create, :manage, :modify) do |a| a.assertion do begin - to_add(new_resource.members).all? { |member| Etc.getpwnam(member) } + to_add(new_resource.members).all? do |member| Etc.getpwnam(member) end rescue false end diff --git a/lib/chef/provider/group/usermod.rb b/lib/chef/provider/group/usermod.rb index b4e93580ff..9f414d7feb 100644 --- a/lib/chef/provider/group/usermod.rb +++ b/lib/chef/provider/group/usermod.rb @@ -33,19 +33,19 @@ class Chef super requirements.assert(:all_actions) do |a| - a.assertion { ::File.exist?("/usr/sbin/usermod") } + a.assertion do ::File.exist?("/usr/sbin/usermod") end a.failure_message Chef::Exceptions::Group, "Could not find binary /usr/sbin/usermod for #{new_resource}" # No whyrun alternative: this component should be available in the base install of any given system that uses it end requirements.assert(:modify, :manage) do |a| - a.assertion { new_resource.members.empty? || new_resource.append } + a.assertion do new_resource.members.empty? || new_resource.append end a.failure_message Chef::Exceptions::Group, "setting group members directly is not supported by #{self}, must set append true in group" # No whyrun alternative - this action is simply not supported. end requirements.assert(:all_actions) do |a| - a.assertion { new_resource.excluded_members.empty? } + a.assertion do new_resource.excluded_members.empty? end a.failure_message Chef::Exceptions::Group, "excluded_members is not supported by #{self}" # No whyrun alternative - this action is simply not supported. end diff --git a/lib/chef/provider/ifconfig.rb b/lib/chef/provider/ifconfig.rb index 93db827e97..bf2e0f6704 100644 --- a/lib/chef/provider/ifconfig.rb +++ b/lib/chef/provider/ifconfig.rb @@ -152,7 +152,7 @@ class Chef def define_resource_requirements requirements.assert(:all_actions) do |a| - a.assertion { @status.exitstatus == 0 } + a.assertion do @status.exitstatus == 0 end a.failure_message Chef::Exceptions::Ifconfig, "ifconfig failed - #{@status.inspect}!" # no whyrun - if the base ifconfig used in load_current_resource fails # there's no reasonable action that could have been taken in the course of diff --git a/lib/chef/provider/ifconfig/aix.rb b/lib/chef/provider/ifconfig/aix.rb index 2f83336f8d..f87198594b 100644 --- a/lib/chef/provider/ifconfig/aix.rb +++ b/lib/chef/provider/ifconfig/aix.rb @@ -85,7 +85,7 @@ class Chef def hex_to_dec_netmask(netmask) # example '0xffff0000' -> '255.255.0.0' dec = netmask[2..3].to_i(16).to_s(10) - [4, 6, 8].each { |n| dec = dec + "." + netmask[n..n + 1].to_i(16).to_s(10) } + [4, 6, 8].each do |n| dec = dec + "." + netmask[n..n + 1].to_i(16).to_s(10) end dec end diff --git a/lib/chef/provider/launchd.rb b/lib/chef/provider/launchd.rb index 4f20a417a6..9974a9a786 100644 --- a/lib/chef/provider/launchd.rb +++ b/lib/chef/provider/launchd.rb @@ -164,7 +164,7 @@ class Chef :create, :create_if_missing, :delete, :enable, :disable ) do |a| type = new_resource.type - a.assertion { %w{daemon agent}.include?(type.to_s) } + a.assertion do %w{daemon agent}.include?(type.to_s) end error_msg = "type must be daemon or agent." a.failure_message Chef::Exceptions::ValidationFailed, error_msg end diff --git a/lib/chef/provider/mount/solaris.rb b/lib/chef/provider/mount/solaris.rb index 24f3a1f7ec..1a235415dd 100644 --- a/lib/chef/provider/mount/solaris.rb +++ b/lib/chef/provider/mount/solaris.rb @@ -53,21 +53,21 @@ class Chef def define_resource_requirements requirements.assert(:mount, :remount) do |a| - a.assertion { !device_should_exist? || ::File.exist?(device) } + a.assertion do !device_should_exist? || ::File.exist?(device) end a.failure_message(Chef::Exceptions::Mount, "Device #{device} does not exist") a.whyrun("Assuming device #{device} would have been created") end unless fsck_device == "-" requirements.assert(:mount, :remount) do |a| - a.assertion { ::File.exist?(fsck_device) } + a.assertion do ::File.exist?(fsck_device) end a.failure_message(Chef::Exceptions::Mount, "Device #{fsck_device} does not exist") a.whyrun("Assuming device #{fsck_device} would have been created") end end requirements.assert(:mount, :remount) do |a| - a.assertion { ::File.exist?(mount_point) } + a.assertion do ::File.exist?(mount_point) end a.failure_message(Chef::Exceptions::Mount, "Mount point #{mount_point} does not exist") a.whyrun("Assuming mount point #{mount_point} would have been created") end diff --git a/lib/chef/provider/osx_profile.rb b/lib/chef/provider/osx_profile.rb index f05cd198e3..c011bca6a3 100644 --- a/lib/chef/provider/osx_profile.rb +++ b/lib/chef/provider/osx_profile.rb @@ -53,9 +53,9 @@ class Chef current_profile = nil if all_profiles && all_profiles.key?("_computerlevel") - current_profile = all_profiles["_computerlevel"].find do |item| + current_profile = all_profiles["_computerlevel"].find { |item| item["ProfileIdentifier"] == @new_profile_identifier - end + } end current_resource.profile(current_profile) end diff --git a/lib/chef/provider/package.rb b/lib/chef/provider/package.rb index 5ccb264adf..c89564a337 100644 --- a/lib/chef/provider/package.rb +++ b/lib/chef/provider/package.rb @@ -67,7 +67,7 @@ class Chef # XXX: upgrade with a specific version doesn't make a whole lot of sense, but why don't we throw this anyway if it happens? # if not, shouldn't we raise to tell the user to use install instead of upgrade if they want to pin a version? requirements.assert(:install) do |a| - a.assertion { candidates_exist_for_all_forced_changes? } + a.assertion do candidates_exist_for_all_forced_changes? end a.failure_message(Chef::Exceptions::Package, "No version specified, and no candidate version available for #{forced_packages_missing_candidates.join(", ")}") a.whyrun("Assuming a repository that offers #{forced_packages_missing_candidates.join(", ")} would have been configured") end @@ -76,7 +76,7 @@ class Chef # not, but as with the above comment, we don't yet enforce such a thing, # so we'll just leave things as-is for now. requirements.assert(:upgrade, :install) do |a| - a.assertion { candidates_exist_for_all_uninstalled? || new_resource.source } + a.assertion do candidates_exist_for_all_uninstalled? || new_resource.source end a.failure_message(Chef::Exceptions::Package, "No candidate version available for #{packages_missing_candidates.join(", ")}") a.whyrun("Assuming a repository that offers #{packages_missing_candidates.join(", ")} would have been configured") end diff --git a/lib/chef/provider/package/apt.rb b/lib/chef/provider/package/apt.rb index 744e5b2e83..8cee5cdcd7 100644 --- a/lib/chef/provider/package/apt.rb +++ b/lib/chef/provider/package/apt.rb @@ -45,7 +45,7 @@ class Chef super requirements.assert(:all_actions) do |a| - a.assertion { !new_resource.source } + a.assertion do !new_resource.source end a.failure_message(Chef::Exceptions::Package, "apt package provider cannot handle source property. Use dpkg provider instead") end end @@ -89,9 +89,9 @@ class Chef end def install_package(name, version) - package_name = name.zip(version).map do |n, v| + package_name = name.zip(version).map { |n, v| package_data[n][:virtual] ? n : "#{n}=#{v}" - end + } dgrade = "--allow-downgrades" if supports_allow_downgrade? && allow_downgrade run_noninteractive("apt-get", "-q", "-y", dgrade, config_file_options, default_release_options, options, "install", package_name) end @@ -101,16 +101,16 @@ class Chef end def remove_package(name, version) - package_name = name.map do |n| + package_name = name.map { |n| package_data[n][:virtual] ? resolve_virtual_package_name(n) : n - end + } run_noninteractive("apt-get", "-q", "-y", options, "remove", package_name) end def purge_package(name, version) - package_name = name.map do |n| + package_name = name.map { |n| package_data[n][:virtual] ? resolve_virtual_package_name(n) : n - end + } run_noninteractive("apt-get", "-q", "-y", options, "purge", package_name) end diff --git a/lib/chef/provider/package/bff.rb b/lib/chef/provider/package/bff.rb index 0b358dcb46..77d5277fa2 100644 --- a/lib/chef/provider/package/bff.rb +++ b/lib/chef/provider/package/bff.rb @@ -33,11 +33,11 @@ class Chef def define_resource_requirements super requirements.assert(:install) do |a| - a.assertion { new_resource.source } + a.assertion do new_resource.source end a.failure_message Chef::Exceptions::Package, "Source for package #{new_resource.package_name} required for action install" end requirements.assert(:all_actions) do |a| - a.assertion { !new_resource.source || package_source_found? } + a.assertion do !new_resource.source || package_source_found? end a.failure_message Chef::Exceptions::Package, "Package #{new_resource.package_name} not found: #{new_resource.source}" a.whyrun "would assume #{new_resource.source} would be have previously been made available" end diff --git a/lib/chef/provider/package/cab.rb b/lib/chef/provider/package/cab.rb index fd099811e0..7488ec8c9b 100644 --- a/lib/chef/provider/package/cab.rb +++ b/lib/chef/provider/package/cab.rb @@ -51,11 +51,11 @@ class Chef end def source_resource - @source_resource ||= declare_resource(:remote_file, new_resource.name) do + @source_resource ||= declare_resource(:remote_file, new_resource.name) { path default_download_cache_path source new_resource.source backup false - end + } end def default_download_cache_path @@ -90,12 +90,12 @@ class Chef package = new_cab_identity # Search for just the package name to catch a different version being installed logger.trace("#{new_resource} searching for installed package #{package["name"]}") - existing_package_identities = installed_packages.map do |p| + existing_package_identities = installed_packages.map { |p| split_package_identity(p["package_identity"]) - end - found_packages = existing_package_identities.select do |existing_package_ident| + } + found_packages = existing_package_identities.select { |existing_package_ident| existing_package_ident["name"] == package["name"] - end + } if found_packages.empty? nil elsif found_packages.length == 1 diff --git a/lib/chef/provider/package/chocolatey.rb b/lib/chef/provider/package/chocolatey.rb index a09bbf55de..8bf1427200 100644 --- a/lib/chef/provider/package/chocolatey.rb +++ b/lib/chef/provider/package/chocolatey.rb @@ -58,7 +58,7 @@ class Chef # and not a package specific alternate source like other providers # so we want to assert candidates exist for the alternate source requirements.assert(:upgrade, :install) do |a| - a.assertion { candidates_exist_for_all_uninstalled? } + a.assertion do candidates_exist_for_all_uninstalled? end a.failure_message(Chef::Exceptions::Package, "No candidate version available for #{packages_missing_candidates.join(", ")}") a.whyrun("Assuming a repository that offers #{packages_missing_candidates.join(", ")} would have been configured") end diff --git a/lib/chef/provider/package/dnf.rb b/lib/chef/provider/package/dnf.rb index d7b61e0789..fc142cc855 100644 --- a/lib/chef/provider/package/dnf.rb +++ b/lib/chef/provider/package/dnf.rb @@ -73,7 +73,7 @@ class Chef def define_resource_requirements requirements.assert(:install, :upgrade, :remove, :purge) do |a| - a.assertion { !new_resource.source || ::File.exist?(new_resource.source) } + a.assertion do !new_resource.source || ::File.exist?(new_resource.source) end a.failure_message Chef::Exceptions::Package, "Package #{new_resource.package_name} not found: #{new_resource.source}" a.whyrun "assuming #{new_resource.source} would have previously been created" end diff --git a/lib/chef/provider/package/dnf/python_helper.rb b/lib/chef/provider/package/dnf/python_helper.rb index c5edbfbc3a..8039bbbe0d 100644 --- a/lib/chef/provider/package/dnf/python_helper.rb +++ b/lib/chef/provider/package/dnf/python_helper.rb @@ -38,9 +38,9 @@ class Chef def dnf_command # platform-python is used for system tools on RHEL 8 and is installed under /usr/libexec - @dnf_command ||= which("platform-python", "python", "python3", "python2", "python2.7", extra_path: "/usr/libexec") do |f| + @dnf_command ||= which("platform-python", "python", "python3", "python2", "python2.7", extra_path: "/usr/libexec") { |f| shell_out("#{f} -c 'import dnf'").exitstatus == 0 - end + " #{DNF_HELPER}" + } + " #{DNF_HELPER}" end def start diff --git a/lib/chef/provider/package/dpkg.rb b/lib/chef/provider/package/dpkg.rb index e6012edee8..89b6fce07a 100644 --- a/lib/chef/provider/package/dpkg.rb +++ b/lib/chef/provider/package/dpkg.rb @@ -38,12 +38,12 @@ class Chef super requirements.assert(:install, :upgrade) do |a| - a.assertion { !resolved_source_array.compact.empty? } + a.assertion do !resolved_source_array.compact.empty? end a.failure_message Chef::Exceptions::Package, "#{new_resource} the source property is required for action :install or :upgrade" end requirements.assert(:install, :upgrade) do |a| - a.assertion { source_files_exist? } + a.assertion do source_files_exist? end a.failure_message Chef::Exceptions::Package, "#{new_resource} source file(s) do not exist: #{missing_sources}" a.whyrun "Assuming they would have been previously created." end @@ -176,11 +176,11 @@ class Chef def name_pkginfo @name_pkginfo ||= begin - pkginfos = resolved_source_array.map do |src| + pkginfos = resolved_source_array.map { |src| logger.trace("#{new_resource} checking #{src} dpkg status") status = shell_out!("dpkg-deb", "-W", src) status.stdout - end + } Hash[*package_name_array.zip(pkginfos).flatten] end end diff --git a/lib/chef/provider/package/ips.rb b/lib/chef/provider/package/ips.rb index 686ffe96ee..fb96c0af40 100644 --- a/lib/chef/provider/package/ips.rb +++ b/lib/chef/provider/package/ips.rb @@ -35,7 +35,7 @@ class Chef super requirements.assert(:all_actions) do |a| - a.assertion { !@candidate_version.nil? } + a.assertion do !@candidate_version.nil? end a.failure_message Chef::Exceptions::Package, "Package #{new_resource.package_name} not found" a.whyrun "Assuming package #{new_resource.package_name} would have been made available." end diff --git a/lib/chef/provider/package/msu.rb b/lib/chef/provider/package/msu.rb index a00b3f3471..9f5c5abe30 100644 --- a/lib/chef/provider/package/msu.rb +++ b/lib/chef/provider/package/msu.rb @@ -89,12 +89,12 @@ class Chef end def source_resource - @source_resource ||= declare_resource(:remote_file, new_resource.name) do + @source_resource ||= declare_resource(:remote_file, new_resource.name) { path default_download_cache_path source new_resource.source checksum new_resource.checksum backup false - end + } end def default_download_cache_path diff --git a/lib/chef/provider/package/openbsd.rb b/lib/chef/provider/package/openbsd.rb index 38ff84f105..62b4ea6d4a 100644 --- a/lib/chef/provider/package/openbsd.rb +++ b/lib/chef/provider/package/openbsd.rb @@ -52,7 +52,7 @@ class Chef # Below are incomplete/missing features for this package provider requirements.assert(:all_actions) do |a| - a.assertion { !new_resource.source } + a.assertion do !new_resource.source end a.failure_message(Chef::Exceptions::Package, "The openbsd package provider does not support the source property") end requirements.assert(:all_actions) do |a| diff --git a/lib/chef/provider/package/portage.rb b/lib/chef/provider/package/portage.rb index 889d262d1e..2c9c629615 100644 --- a/lib/chef/provider/package/portage.rb +++ b/lib/chef/provider/package/portage.rb @@ -39,11 +39,11 @@ class Chef globsafe_category = category ? Chef::Util::PathHelper.escape_glob_dir(category) : nil globsafe_pkg = Chef::Util::PathHelper.escape_glob_dir(pkg) possibilities = Dir["/var/db/pkg/#{globsafe_category || "*"}/#{globsafe_pkg}-*"].map { |d| d.sub(%r{/var/db/pkg/}, "") } - versions = possibilities.map do |entry| + versions = possibilities.map { |entry| if entry =~ %r{[^/]+/#{Regexp.escape(pkg)}\-(\d[\.\d]*[a-z]?((_(alpha|beta|pre|rc|p)\d*)*)?(-r\d+)?)} [$&, $1] end - end.compact + }.compact if versions.size > 1 atoms = versions.map(&:first).sort diff --git a/lib/chef/provider/package/powershell.rb b/lib/chef/provider/package/powershell.rb index a27f7fa6c8..26f8206f10 100644 --- a/lib/chef/provider/package/powershell.rb +++ b/lib/chef/provider/package/powershell.rb @@ -41,7 +41,7 @@ class Chef end requirements.assert(:install) do |a| - a.assertion { candidates_exist_for_all_uninstalled? } + a.assertion do candidates_exist_for_all_uninstalled? end a.failure_message(Chef::Exceptions::Package, "No candidate version available for #{packages_missing_candidates.join(", ")}") a.whyrun("Assuming a repository that offers #{packages_missing_candidates.join(", ")} would have been configured") end diff --git a/lib/chef/provider/package/rpm.rb b/lib/chef/provider/package/rpm.rb index 75b41a26e4..1f62aa84c4 100644 --- a/lib/chef/provider/package/rpm.rb +++ b/lib/chef/provider/package/rpm.rb @@ -32,12 +32,12 @@ class Chef super requirements.assert(:all_actions) do |a| - a.assertion { @package_source_exists } + a.assertion do @package_source_exists end a.failure_message Chef::Exceptions::Package, "Package #{new_resource.package_name} not found: #{new_resource.source}" a.whyrun "Assuming package #{new_resource.package_name} would have been made available." end requirements.assert(:all_actions) do |a| - a.assertion { !@rpm_status.nil? && (@rpm_status.exitstatus == 0 || @rpm_status.exitstatus == 1) } + a.assertion do !@rpm_status.nil? && (@rpm_status.exitstatus == 0 || @rpm_status.exitstatus == 1) end a.failure_message Chef::Exceptions::Package, "Unable to determine current version due to RPM failure. Detail: #{@rpm_status.inspect}" a.whyrun "Assuming current version would have been determined for package #{new_resource.package_name}." end diff --git a/lib/chef/provider/package/rubygems.rb b/lib/chef/provider/package/rubygems.rb index 876a90392c..031c49c0eb 100644 --- a/lib/chef/provider/package/rubygems.rb +++ b/lib/chef/provider/package/rubygems.rb @@ -100,7 +100,7 @@ class Chef # Filter down to only to only stubs we actually want. The name # filter is needed in case of things like `foo-*.gemspec` also # matching a gem named `foo-bar`. - stubs.select! { |stub| stub.name == gem_dep.name && gem_dep.requirement.satisfied_by?(stub.version) } + stubs.select! do |stub| stub.name == gem_dep.name && gem_dep.requirement.satisfied_by?(stub.version) end # This isn't sorting before returning beacuse the only code that # uses this method calls `max_by` so it doesn't need to be sorted. stubs @@ -151,11 +151,11 @@ class Chef def candidate_version_from_file(gem_dependency, source) spec = spec_from_file(source) if spec.satisfies_requirement?(gem_dependency) - logger.trace { "found candidate gem version #{spec.version} from local gem package #{source}" } + logger.trace do "found candidate gem version #{spec.version} from local gem package #{source}" end spec.version else # This is probably going to end badly... - logger.warn { "gem package #{source} does not satisfy the requirements #{gem_dependency}" } + logger.warn do "gem package #{source} does not satisfy the requirements #{gem_dependency}" end nil end end @@ -196,11 +196,11 @@ class Chef version = spec && spec.version if version - logger.trace { "found gem #{spec.name} version #{version} for platform #{spec.platform} from #{source}" } + logger.trace do "found gem #{spec.name} version #{version} for platform #{spec.platform} from #{source}" end version else source_list = sources.compact.empty? ? "[#{Gem.sources.to_a.join(", ")}]" : "[#{sources.join(", ")}]" - logger.warn { "failed to find gem #{gem_dependency} from #{source_list}" } + logger.warn do "failed to find gem #{gem_dependency} from #{source_list}" end nil end end @@ -459,16 +459,16 @@ class Chef # is the current version if !matching_installed_versions.empty? gemspec = matching_installed_versions.max_by(&:version) - logger.trace { "#{new_resource} found installed gem #{gemspec.name} version #{gemspec.version} matching #{gem_dependency}" } + logger.trace do "#{new_resource} found installed gem #{gemspec.name} version #{gemspec.version} matching #{gem_dependency}" end gemspec # If no version matching the requirements exists, the latest installed # version is the current version. elsif !all_installed_versions.empty? gemspec = all_installed_versions.max_by(&:version) - logger.trace { "#{new_resource} newest installed version of gem #{gemspec.name} is #{gemspec.version}" } + logger.trace do "#{new_resource} newest installed version of gem #{gemspec.name} is #{gemspec.version}" end gemspec else - logger.trace { "#{new_resource} no installed version found for #{gem_dependency}" } + logger.trace do "#{new_resource} no installed version found for #{gem_dependency}" end nil end end @@ -500,7 +500,7 @@ class Chef def cleanup_after_converge if @cleanup_gem_env - logger.trace { "#{new_resource} resetting gem environment to default" } + logger.trace do "#{new_resource} resetting gem environment to default" end Gem.clear_paths end end diff --git a/lib/chef/provider/package/snap.rb b/lib/chef/provider/package/snap.rb index cb639ff77f..7be0266afe 100644 --- a/lib/chef/provider/package/snap.rb +++ b/lib/chef/provider/package/snap.rb @@ -42,7 +42,7 @@ class Chef def define_resource_requirements requirements.assert(:install, :upgrade, :remove, :purge) do |a| - a.assertion { !new_resource.source || ::File.exist?(new_resource.source) } + a.assertion do !new_resource.source || ::File.exist?(new_resource.source) end a.failure_message Chef::Exceptions::Package, "Package #{new_resource.package_name} not found: #{new_resource.source}" a.whyrun "assuming #{new_resource.source} would have previously been created" end @@ -238,14 +238,14 @@ class Chef # @param path [String] Path to the package on disk # @param content_length [Integer] byte size of the snap file def generate_multipart_form_data(snap_name, action, options, path, content_length) - snap_options = options.map do |k, v| + snap_options = options.map { |k, v| <<~SNAP_OPTION Content-Disposition: form-data; name="#{k}" #{v} --#{snap_name} SNAP_OPTION - end + } multipart_form_data = <<~SNAP_S Host: diff --git a/lib/chef/provider/package/solaris.rb b/lib/chef/provider/package/solaris.rb index fb0e88ecdb..28c33f4299 100644 --- a/lib/chef/provider/package/solaris.rb +++ b/lib/chef/provider/package/solaris.rb @@ -37,11 +37,11 @@ class Chef def define_resource_requirements super requirements.assert(:install) do |a| - a.assertion { new_resource.source } + a.assertion do new_resource.source end a.failure_message Chef::Exceptions::Package, "Source for package #{new_resource.package_name} required for action install" end requirements.assert(:all_actions) do |a| - a.assertion { !new_resource.source || @package_source_found } + a.assertion do !new_resource.source || @package_source_found end a.failure_message Chef::Exceptions::Package, "Package #{new_resource.package_name} not found: #{new_resource.source}" a.whyrun "would assume #{new_resource.source} would be have previously been made available" end diff --git a/lib/chef/provider/package/windows.rb b/lib/chef/provider/package/windows.rb index d21c6576b6..8bde66fad3 100644 --- a/lib/chef/provider/package/windows.rb +++ b/lib/chef/provider/package/windows.rb @@ -36,13 +36,13 @@ class Chef def define_resource_requirements requirements.assert(:install) do |a| - a.assertion { new_resource.source || msi? } + a.assertion do new_resource.source || msi? end a.failure_message Chef::Exceptions::NoWindowsPackageSource, "Source for package #{new_resource.package_name} must be specified in the resource's source property for package to be installed because the package_name property is used to test for the package installation state for this package type." end unless uri_scheme?(new_resource.source) requirements.assert(:install) do |a| - a.assertion { ::File.exist?(new_resource.source) } + a.assertion do ::File.exist?(new_resource.source) end a.failure_message Chef::Exceptions::Package, "Source for package #{new_resource.package_name} does not exist" a.whyrun "Assuming source file #{new_resource.source} would have been created." end diff --git a/lib/chef/provider/package/yum.rb b/lib/chef/provider/package/yum.rb index e32457cc0c..ad528f9463 100644 --- a/lib/chef/provider/package/yum.rb +++ b/lib/chef/provider/package/yum.rb @@ -66,7 +66,7 @@ class Chef def define_resource_requirements requirements.assert(:install, :upgrade, :remove, :purge) do |a| - a.assertion { !new_resource.source || ::File.exist?(new_resource.source) } + a.assertion do !new_resource.source || ::File.exist?(new_resource.source) end a.failure_message Chef::Exceptions::Package, "Package #{new_resource.package_name} not found: #{new_resource.source}" a.whyrun "assuming #{new_resource.source} would have previously been created" end diff --git a/lib/chef/provider/package/yum/python_helper.rb b/lib/chef/provider/package/yum/python_helper.rb index f99b17bcce..bc1124818d 100644 --- a/lib/chef/provider/package/yum/python_helper.rb +++ b/lib/chef/provider/package/yum/python_helper.rb @@ -40,9 +40,9 @@ class Chef YUM_HELPER = ::File.expand_path(::File.join(::File.dirname(__FILE__), "yum_helper.py")).freeze def yum_command - @yum_command ||= which("platform-python", "python", "python2", "python2.7", extra_path: "/usr/libexec") do |f| + @yum_command ||= which("platform-python", "python", "python2", "python2.7", extra_path: "/usr/libexec") { |f| shell_out("#{f} -c 'import yum'").exitstatus == 0 - end + " #{YUM_HELPER}" + } + " #{YUM_HELPER}" end def start diff --git a/lib/chef/provider/package/zypper.rb b/lib/chef/provider/package/zypper.rb index a828da1c6c..286bc04c62 100644 --- a/lib/chef/provider/package/zypper.rb +++ b/lib/chef/provider/package/zypper.rb @@ -56,9 +56,9 @@ class Chef def versions @versions ||= begin - raw_versions = package_name_array.map do |package_name| + raw_versions = package_name_array.map { |package_name| get_versions(package_name) - end + } Hash[*package_name_array.zip(raw_versions).flatten] end end diff --git a/lib/chef/provider/registry_key.rb b/lib/chef/provider/registry_key.rb index 5dcb9f1959..359d171748 100644 --- a/lib/chef/provider/registry_key.rb +++ b/lib/chef/provider/registry_key.rb @@ -75,39 +75,39 @@ class Chef def define_resource_requirements requirements.assert(:create, :create_if_missing, :delete, :delete_key) do |a| - a.assertion { registry.hive_exists?(new_resource.key) } + a.assertion do registry.hive_exists?(new_resource.key) end a.failure_message(Chef::Exceptions::Win32RegHiveMissing, "Hive #{new_resource.key.split('\\').shift} does not exist") end requirements.assert(:create) do |a| - a.assertion { registry.key_exists?(new_resource.key) } + a.assertion do registry.key_exists?(new_resource.key) end a.whyrun("Key #{new_resource.key} does not exist. Unless it would have been created before, attempt to modify its values would fail.") end requirements.assert(:create, :create_if_missing) do |a| # If keys missing in the path and recursive == false - a.assertion { !registry.keys_missing?(current_resource.key) || new_resource.recursive } + a.assertion do !registry.keys_missing?(current_resource.key) || new_resource.recursive end a.failure_message(Chef::Exceptions::Win32RegNoRecursive, "Intermediate keys missing but recursive is set to false") a.whyrun("Intermediate keys in #{new_resource.key} do not exist. Unless they would have been created earlier, attempt to modify them would fail.") end requirements.assert(:delete_key) do |a| # If key to be deleted has subkeys but recurssive == false - a.assertion { !registry.key_exists?(new_resource.key) || !registry.has_subkeys?(new_resource.key) || new_resource.recursive } + a.assertion do !registry.key_exists?(new_resource.key) || !registry.has_subkeys?(new_resource.key) || new_resource.recursive end a.failure_message(Chef::Exceptions::Win32RegNoRecursive, "#{new_resource.key} has subkeys but recursive is set to false.") a.whyrun("#{current_resource.key} has subkeys, but recursive is set to false. attempt to delete would fails unless subkeys were deleted prior to this action.") end requirements.assert(:create, :create_if_missing) do |a| # If type key missing in the RegistryKey values hash - a.assertion { !key_missing?(new_resource.values, :type) } + a.assertion do !key_missing?(new_resource.values, :type) end a.failure_message(Chef::Exceptions::RegKeyValuesTypeMissing, "Missing type key in RegistryKey values hash") a.whyrun("Type key does not exist. Attempt would fail unless the complete values hash containing all the keys does not exist for registry_key resource's create action.") end requirements.assert(:create, :create_if_missing) do |a| # If data key missing in the RegistryKey values hash - a.assertion { !key_missing?(new_resource.values, :data) } + a.assertion do !key_missing?(new_resource.values, :data) end a.failure_message(Chef::Exceptions::RegKeyValuesDataMissing, "Missing data key in RegistryKey values hash") a.whyrun("Data key does not exist. Attempt would fail unless the complete values hash containing all the keys does not exist for registry_key resource's create action.") end diff --git a/lib/chef/provider/remote_file/http.rb b/lib/chef/provider/remote_file/http.rb index 86c7b84858..d94c84fa20 100644 --- a/lib/chef/provider/remote_file/http.rb +++ b/lib/chef/provider/remote_file/http.rb @@ -65,9 +65,9 @@ class Chef http = Chef::HTTP::Simple.new(uri, http_client_opts) orig_tempfile = Chef::FileContentManagement::Tempfile.new(@new_resource).tempfile if want_progress? - tempfile = http.streaming_request_with_progress(uri, headers, orig_tempfile) do |size, total| + tempfile = http.streaming_request_with_progress(uri, headers, orig_tempfile) { |size, total| events.resource_update_progress(new_resource, size, total, progress_interval) - end + } else tempfile = http.streaming_request(uri, headers, orig_tempfile) end diff --git a/lib/chef/provider/service.rb b/lib/chef/provider/service.rb index af96e08b20..0d83d725dd 100644 --- a/lib/chef/provider/service.rb +++ b/lib/chef/provider/service.rb @@ -58,7 +58,7 @@ class Chef # subclasses should override this if they do implement user services def user_services_requirements requirements.assert(:all_actions) do |a| - a.assertion { new_resource.user.nil? } + a.assertion do new_resource.user.nil? end a.failure_message Chef::Exceptions::UnsupportedAction, "#{self} does not support user services" end end @@ -69,7 +69,7 @@ class Chef def define_resource_requirements requirements.assert(:reload) do |a| - a.assertion { supports[:reload] || new_resource.reload_command } + a.assertion do supports[:reload] || new_resource.reload_command end a.failure_message Chef::Exceptions::UnsupportedAction, "#{self} does not support :reload" # if a service is not declared to support reload, that won't # typically change during the course of a run - so no whyrun diff --git a/lib/chef/provider/service/aix.rb b/lib/chef/provider/service/aix.rb index 77e3b69d35..6e787bd99c 100644 --- a/lib/chef/provider/service/aix.rb +++ b/lib/chef/provider/service/aix.rb @@ -75,7 +75,7 @@ class Chef def shared_resource_requirements super requirements.assert(:all_actions) do |a| - a.assertion { @status_load_success } + a.assertion do @status_load_success end a.whyrun ["Service status not available. Assuming a prior action would have installed the service.", "Assuming status of not running."] end end diff --git a/lib/chef/provider/service/aixinit.rb b/lib/chef/provider/service/aixinit.rb index 05cdc2befe..9875aa1e07 100644 --- a/lib/chef/provider/service/aixinit.rb +++ b/lib/chef/provider/service/aixinit.rb @@ -57,7 +57,7 @@ class Chef end def enable_service - Dir.glob(["/etc/rc.d/rc2.d/[SK][0-9][0-9]#{@new_resource.service_name}", "/etc/rc.d/rc2.d/[SK]#{@new_resource.service_name}"]).each { |f| ::File.delete(f) } + Dir.glob(["/etc/rc.d/rc2.d/[SK][0-9][0-9]#{@new_resource.service_name}", "/etc/rc.d/rc2.d/[SK]#{@new_resource.service_name}"]).each do |f| ::File.delete(f) end if @new_resource.priority.is_a? Integer create_symlink(2, "S", @new_resource.priority) @@ -72,7 +72,7 @@ class Chef end def disable_service - Dir.glob(["/etc/rc.d/rc2.d/[SK][0-9][0-9]#{@new_resource.service_name}", "/etc/rc.d/rc2.d/[SK]#{@new_resource.service_name}"]).each { |f| ::File.delete(f) } + Dir.glob(["/etc/rc.d/rc2.d/[SK][0-9][0-9]#{@new_resource.service_name}", "/etc/rc.d/rc2.d/[SK]#{@new_resource.service_name}"]).each do |f| ::File.delete(f) end if @new_resource.priority.is_a? Integer create_symlink(2, "K", 100 - @new_resource.priority) diff --git a/lib/chef/provider/service/debian.rb b/lib/chef/provider/service/debian.rb index 9f48504d5e..2039151d99 100644 --- a/lib/chef/provider/service/debian.rb +++ b/lib/chef/provider/service/debian.rb @@ -45,14 +45,14 @@ class Chef shared_resource_requirements requirements.assert(:all_actions) do |a| update_rcd = "/usr/sbin/update-rc.d" - a.assertion { ::File.exists? update_rcd } + a.assertion do ::File.exists? update_rcd end a.failure_message Chef::Exceptions::Service, "#{update_rcd} does not exist!" # no whyrun recovery - this is a base system component of debian # distros and must be present end requirements.assert(:all_actions) do |a| - a.assertion { @got_priority == true } + a.assertion do @got_priority == true end a.failure_message Chef::Exceptions::Service, "Unable to determine priority for service" # This can happen if the service is not yet installed,so we'll fake it. a.whyrun ["Unable to determine priority of service, assuming service would have been correctly installed earlier in the run.", diff --git a/lib/chef/provider/service/freebsd.rb b/lib/chef/provider/service/freebsd.rb index 7733831945..98e539ae98 100644 --- a/lib/chef/provider/service/freebsd.rb +++ b/lib/chef/provider/service/freebsd.rb @@ -60,20 +60,20 @@ class Chef shared_resource_requirements requirements.assert(:start, :enable, :reload, :restart) do |a| - a.assertion { init_command } + a.assertion do init_command end a.failure_message Chef::Exceptions::Service, "#{new_resource}: unable to locate the rc.d script" a.whyrun("Assuming rc.d script will be installed by a previous action.") end requirements.assert(:all_actions) do |a| - a.assertion { enabled_state_found } + a.assertion do enabled_state_found end # for consistentcy with original behavior, this will not fail in non-whyrun mode; # rather it will silently set enabled state=>false a.whyrun "Unable to determine enabled/disabled state, assuming this will be correct for an actual run. Assuming disabled." end requirements.assert(:start, :enable, :reload, :restart) do |a| - a.assertion { !service_enable_variable_name.nil? } + a.assertion do !service_enable_variable_name.nil? end a.failure_message Chef::Exceptions::Service, "Could not find the service name in #{init_command} and rcvar" # No recovery in whyrun mode - the init file is present but not correct. end @@ -179,7 +179,7 @@ class Chef def set_service_enable(value) lines = read_rc_conf # Remove line that set the old value - lines.delete_if { |line| line =~ /^\#?\s*#{Regexp.escape(service_enable_variable_name)}=/ } + lines.delete_if do |line| line =~ /^\#?\s*#{Regexp.escape(service_enable_variable_name)}=/ end # And append the line that sets the new value at the end lines << "#{service_enable_variable_name}=\"#{value}\"" write_rc_conf(lines) diff --git a/lib/chef/provider/service/gentoo.rb b/lib/chef/provider/service/gentoo.rb index 88616c4947..da0fc8fed2 100644 --- a/lib/chef/provider/service/gentoo.rb +++ b/lib/chef/provider/service/gentoo.rb @@ -32,13 +32,13 @@ class Chef::Provider::Service::Gentoo < Chef::Provider::Service::Init super @current_resource.enabled( - Dir.glob("/etc/runlevels/**/#{Chef::Util::PathHelper.escape_glob_dir(@current_resource.service_name)}").any? do |file| + Dir.glob("/etc/runlevels/**/#{Chef::Util::PathHelper.escape_glob_dir(@current_resource.service_name)}").any? { |file| @found_script = true exists = ::File.exists? file readable = ::File.readable? file logger.trace "#{@new_resource} exists: #{exists}, readable: #{readable}" exists && readable - end + } ) logger.trace "#{@new_resource} enabled: #{@current_resource.enabled}" @@ -47,14 +47,14 @@ class Chef::Provider::Service::Gentoo < Chef::Provider::Service::Init def define_resource_requirements requirements.assert(:all_actions) do |a| - a.assertion { ::File.exists?("/sbin/rc-update") } + a.assertion do ::File.exists?("/sbin/rc-update") end a.failure_message Chef::Exceptions::Service, "/sbin/rc-update does not exist" # no whyrun recovery -t his is a core component whose presence is # unlikely to be affected by what we do in the course of a chef run end requirements.assert(:all_actions) do |a| - a.assertion { @found_script } + a.assertion do @found_script end # No failure, just informational output from whyrun a.whyrun "Could not find service #{@new_resource.service_name} under any runlevel" end diff --git a/lib/chef/provider/service/macosx.rb b/lib/chef/provider/service/macosx.rb index 746581df73..38165bd06c 100644 --- a/lib/chef/provider/service/macosx.rb +++ b/lib/chef/provider/service/macosx.rb @@ -36,7 +36,7 @@ class Chef /Library/LaunchDaemons /System/Library/LaunchAgents /System/Library/LaunchDaemons } - Chef::Util::PathHelper.home("Library", "LaunchAgents") { |p| locations << p } + Chef::Util::PathHelper.home("Library", "LaunchAgents") do |p| locations << p end locations end @@ -79,24 +79,24 @@ class Chef end requirements.assert(:all_actions) do |a| - a.assertion { @plist_size < 2 } + a.assertion do @plist_size < 2 end a.failure_message Chef::Exceptions::Service, "Several plist files match service name. Please use full service name." end requirements.assert(:all_actions) do |a| - a.assertion { ::File.exists?(@plist.to_s) } + a.assertion do ::File.exists?(@plist.to_s) end a.failure_message Chef::Exceptions::Service, "Could not find plist for #{@new_resource}" end requirements.assert(:enable, :disable) do |a| - a.assertion { !@service_label.to_s.empty? } + a.assertion do !@service_label.to_s.empty? end a.failure_message Chef::Exceptions::Service, "Could not find service's label in plist file '#{@plist}'!" end requirements.assert(:all_actions) do |a| - a.assertion { @plist_size > 0 } + a.assertion do @plist_size > 0 end # No failure here in original code - so we also will not # fail. Instead warn that the service is potentially missing a.whyrun "Assuming that the service would have been previously installed and is currently disabled." do @@ -235,13 +235,13 @@ class Chef end def find_service_plist - plists = PLIST_DIRS.inject([]) do |results, dir| + plists = PLIST_DIRS.inject([]) { |results, dir| edir = ::File.expand_path(dir) entries = Dir.glob( "#{edir}/*#{Chef::Util::PathHelper.escape_glob_dir(@current_resource.service_name)}*.plist" ) entries.any? ? results << entries : results - end + } plists.flatten! @plist_size = plists.size plists.first diff --git a/lib/chef/provider/service/openbsd.rb b/lib/chef/provider/service/openbsd.rb index c368815418..47f0a7989e 100644 --- a/lib/chef/provider/service/openbsd.rb +++ b/lib/chef/provider/service/openbsd.rb @@ -59,19 +59,19 @@ class Chef shared_resource_requirements requirements.assert(:start, :enable, :reload, :restart) do |a| - a.assertion { init_command } + a.assertion do init_command end a.failure_message Chef::Exceptions::Service, "#{new_resource}: unable to locate the rc.d script" end requirements.assert(:all_actions) do |a| - a.assertion { enabled_state_found } + a.assertion do enabled_state_found end # for consistency with original behavior, this will not fail in non-whyrun mode; # rather it will silently set enabled state=>false a.whyrun "Unable to determine enabled/disabled state, assuming this will be correct for an actual run. Assuming disabled." end requirements.assert(:start, :enable, :reload, :restart) do |a| - a.assertion { init_command && !builtin_service_enable_variable_name.nil? } + a.assertion do init_command && !builtin_service_enable_variable_name.nil? end a.failure_message Chef::Exceptions::Service, "Could not find the service name in #{init_command} and rcvar" # No recovery in whyrun mode - the init file is present but not correct. end diff --git a/lib/chef/provider/service/redhat.rb b/lib/chef/provider/service/redhat.rb index 8751090d44..e25e53fbfb 100644 --- a/lib/chef/provider/service/redhat.rb +++ b/lib/chef/provider/service/redhat.rb @@ -56,12 +56,12 @@ class Chef requirements.assert(:all_actions) do |a| chkconfig_file = "/sbin/chkconfig" - a.assertion { ::File.exists? chkconfig_file } + a.assertion do ::File.exists? chkconfig_file end a.failure_message Chef::Exceptions::Service, "#{chkconfig_file} does not exist!" end requirements.assert(:enable) do |a| - a.assertion { !@service_missing } + a.assertion do !@service_missing end a.failure_message Chef::Exceptions::Service, "#{new_resource}: Service is not known to chkconfig." a.whyrun "Assuming service would be enabled. The init script is not presently installed." end diff --git a/lib/chef/provider/service/simple.rb b/lib/chef/provider/service/simple.rb index 754437b4a0..a76c656764 100644 --- a/lib/chef/provider/service/simple.rb +++ b/lib/chef/provider/service/simple.rb @@ -43,7 +43,7 @@ class Chef def shared_resource_requirements super requirements.assert(:all_actions) do |a| - a.assertion { @status_load_success } + a.assertion do @status_load_success end a.whyrun ["Service status not available. Assuming a prior action would have installed the service.", "Assuming status of not running."] end end @@ -52,21 +52,21 @@ class Chef # FIXME? need reload from service.rb shared_resource_requirements requirements.assert(:start) do |a| - a.assertion { @new_resource.start_command } + a.assertion do @new_resource.start_command end a.failure_message Chef::Exceptions::Service, "#{self} requires that start_command be set" end requirements.assert(:stop) do |a| - a.assertion { @new_resource.stop_command } + a.assertion do @new_resource.stop_command end a.failure_message Chef::Exceptions::Service, "#{self} requires that stop_command be set" end requirements.assert(:restart) do |a| - a.assertion { @new_resource.restart_command || ( @new_resource.start_command && @new_resource.stop_command ) } + a.assertion do @new_resource.restart_command || ( @new_resource.start_command && @new_resource.stop_command ) end a.failure_message Chef::Exceptions::Service, "#{self} requires a restart_command or both start_command and stop_command be set in order to perform a restart" end requirements.assert(:reload) do |a| - a.assertion { @new_resource.reload_command } + a.assertion do @new_resource.reload_command end a.failure_message Chef::Exceptions::UnsupportedAction, "#{self} requires a reload_command be set in order to perform a reload" end @@ -78,7 +78,7 @@ class Chef a.failure_message Chef::Exceptions::Service, "#{@new_resource} could not determine how to inspect the process table, please set this node's 'command.ps' attribute" end requirements.assert(:all_actions) do |a| - a.assertion { !@ps_command_failed } + a.assertion do !@ps_command_failed end a.failure_message Chef::Exceptions::Service, "Command #{ps_cmd} failed to execute, cannot determine service current status" end end diff --git a/lib/chef/provider/service/systemd.rb b/lib/chef/provider/service/systemd.rb index 565668c081..abcb7eab53 100644 --- a/lib/chef/provider/service/systemd.rb +++ b/lib/chef/provider/service/systemd.rb @@ -67,7 +67,7 @@ class Chef::Provider::Service::Systemd < Chef::Provider::Service::Simple def define_resource_requirements shared_resource_requirements requirements.assert(:all_actions) do |a| - a.assertion { status_check_success } + a.assertion do status_check_success end # We won't stop in any case, but in whyrun warn and tell what we're doing. a.whyrun ["Failed to determine status of #{new_resource}, using command #{new_resource.status_command}.", "Assuming service would have been installed and is disabled"] diff --git a/lib/chef/provider/service/upstart.rb b/lib/chef/provider/service/upstart.rb index 8b2db84f35..983389f807 100644 --- a/lib/chef/provider/service/upstart.rb +++ b/lib/chef/provider/service/upstart.rb @@ -90,13 +90,13 @@ class Chef "Could not determine upstart state for service" end end - a.assertion { @command_success } + a.assertion do @command_success end # no failure here, just document the assumptions made. a.whyrun "#{whyrun_msg} Assuming service installed and not running." end requirements.assert(:all_actions) do |a| - a.assertion { @config_file_found } + a.assertion do @config_file_found end # no failure here, just document the assumptions made. a.whyrun "Could not find #{@upstart_job_dir}/#{@new_resource.service_name}#{@upstart_conf_suffix}. Assuming service is disabled." end diff --git a/lib/chef/provider/subversion.rb b/lib/chef/provider/subversion.rb index dd3ece4786..7e929c45dc 100644 --- a/lib/chef/provider/subversion.rb +++ b/lib/chef/provider/subversion.rb @@ -48,7 +48,7 @@ class Chef # Make sure the parent dir exists, or else fail. # for why run, print a message explaining the potential error. parent_directory = ::File.dirname(new_resource.destination) - a.assertion { ::File.directory?(parent_directory) } + a.assertion do ::File.directory?(parent_directory) end a.failure_message(Chef::Exceptions::MissingParentDirectory, "Cannot clone #{new_resource} to #{new_resource.destination}, the enclosing directory #{parent_directory} does not exist") a.whyrun("Directory #{parent_directory} does not exist, assuming it would have been created") @@ -166,13 +166,13 @@ class Chef end def extract_revision_info(svn_info) - repo_attrs = svn_info.lines.inject({}) do |attrs, line| + repo_attrs = svn_info.lines.inject({}) { |attrs, line| if line =~ SVN_INFO_PATTERN property, value = $1, $2 attrs[property] = value end attrs - end + } rev = (repo_attrs["Last Changed Rev"] || repo_attrs["Revision"]) rev.strip! if rev raise "Could not parse `svn info` data: #{svn_info}" if repo_attrs.empty? diff --git a/lib/chef/provider/systemd_unit.rb b/lib/chef/provider/systemd_unit.rb index 81a56d959a..1e4fdab46e 100644 --- a/lib/chef/provider/systemd_unit.rb +++ b/lib/chef/provider/systemd_unit.rb @@ -51,7 +51,7 @@ class Chef super requirements.assert(:create) do |a| - a.assertion { IniParse.parse(new_resource.to_ini) } + a.assertion do IniParse.parse(new_resource.to_ini) end a.failure_message "Unit content is not valid INI text" end end diff --git a/lib/chef/provider/template.rb b/lib/chef/provider/template.rb index f506462268..9b527d7413 100644 --- a/lib/chef/provider/template.rb +++ b/lib/chef/provider/template.rb @@ -39,7 +39,7 @@ class Chef super requirements.assert(:create, :create_if_missing) do |a| - a.assertion { ::File.exists?(content.template_location) } + a.assertion do ::File.exists?(content.template_location) end a.failure_message "Template source #{content.template_location} could not be found." a.whyrun "Template source #{content.template_location} does not exist. Assuming it would have been created." a.block_action! diff --git a/lib/chef/provider/user.rb b/lib/chef/provider/user.rb index 38fe233d76..44cfbb000e 100644 --- a/lib/chef/provider/user.rb +++ b/lib/chef/provider/user.rb @@ -84,18 +84,18 @@ class Chef def define_resource_requirements requirements.assert(:create, :modify, :manage, :lock, :unlock) do |a| - a.assertion { @group_name_resolved } + a.assertion do @group_name_resolved end a.failure_message Chef::Exceptions::User, "Couldn't lookup integer GID for group name #{new_resource.gid}" a.whyrun "group name #{new_resource.gid} does not exist. This will cause group assignment to fail. Assuming this group will have been created previously." end requirements.assert(:all_actions) do |a| - a.assertion { @shadow_lib_ok } + a.assertion do @shadow_lib_ok end a.failure_message Chef::Exceptions::MissingLibrary, "You must have ruby-shadow installed for password support!" a.whyrun "ruby-shadow is not installed. Attempts to set user password will cause failure. Assuming that this gem will have been previously installed." \ "Note that user update converge may report false-positive on the basis of mismatched password. " end requirements.assert(:modify, :lock, :unlock) do |a| - a.assertion { @user_exists } + a.assertion do @user_exists end a.failure_message(Chef::Exceptions::User, "Cannot modify user #{new_resource.username} - does not exist!") a.whyrun("Assuming user #{new_resource.username} would have been created") end diff --git a/lib/chef/provider/user/dscl.rb b/lib/chef/provider/user/dscl.rb index b8f85618da..4bed747bd3 100644 --- a/lib/chef/provider/user/dscl.rb +++ b/lib/chef/provider/user/dscl.rb @@ -61,12 +61,12 @@ class Chef super requirements.assert(:all_actions) do |a| - a.assertion { ::File.exist?("/usr/bin/dscl") } + a.assertion do ::File.exist?("/usr/bin/dscl") end a.failure_message(Chef::Exceptions::User, "Cannot find binary '/usr/bin/dscl' on the system for #{new_resource}!") end requirements.assert(:all_actions) do |a| - a.assertion { ::File.exist?("/usr/bin/plutil") } + a.assertion do ::File.exist?("/usr/bin/plutil") end a.failure_message(Chef::Exceptions::User, "Cannot find binary '/usr/bin/plutil' on the system for #{new_resource}!") end diff --git a/lib/chef/provider/windows_env.rb b/lib/chef/provider/windows_env.rb index 3fd4b18cfa..35c010be20 100644 --- a/lib/chef/provider/windows_env.rb +++ b/lib/chef/provider/windows_env.rb @@ -107,9 +107,9 @@ class Chef return true # do not delete the key else new_value = - current_values.select do |item| + current_values.select { |item| not new_values.include?(item) - end.join(new_resource.delim) + }.join(new_resource.delim) if new_value.empty? return false # nothing left here, delete the key diff --git a/lib/chef/provider/windows_task.rb b/lib/chef/provider/windows_task.rb index b94b6b875c..feba79a711 100644 --- a/lib/chef/provider/windows_task.rb +++ b/lib/chef/provider/windows_task.rb @@ -308,13 +308,13 @@ class Chef def frequency_modifier_contains_last_week?(frequency_modifier) frequency_modifier = frequency_modifier.to_s.split(",") - frequency_modifier.map! { |value| value.strip.upcase } + frequency_modifier.map! do |value| value.strip.upcase end frequency_modifier.include?("LAST") end def day_includes_last_or_lastday?(day) day = day.to_s.split(",") - day.map! { |value| value.strip.upcase } + day.map! do |value| value.strip.upcase end day.include?("LAST") || day.include?("LASTDAY") end @@ -435,7 +435,7 @@ class Chef weeks_of_month = [] if new_resource.frequency_modifier weeks = new_resource.frequency_modifier.split(",") - weeks.map! { |week| week.to_s.strip.upcase } + weeks.map! do |week| week.to_s.strip.upcase end weeks.delete("LAST") if weeks.include?("LAST") weeks_of_month = get_binary_values_from_constants(weeks, WEEKS_OF_MONTH) end @@ -447,7 +447,7 @@ class Chef days_of_month = [] if new_resource.day days = new_resource.day.to_s.split(",") - days.map! { |day| day.to_s.strip.upcase } + days.map! do |day| day.to_s.strip.upcase end days.delete("LAST") if days.include?("LAST") days.delete("LASTDAY") if days.include?("LASTDAY") if days - (1..31).to_a @@ -467,7 +467,7 @@ class Chef # this line of code is just to support backward compatibility of wild card * new_resource.day = "mon, tue, wed, thu, fri, sat, sun" if new_resource.day == "*" && new_resource.frequency == :weekly days = new_resource.day.to_s.split(",") - days.map! { |day| day.to_s.strip.upcase } + days.map! do |day| day.to_s.strip.upcase end weeks_days = get_binary_values_from_constants(days, DAYS_OF_WEEK) else # following condition will make the frequency :weekly idempotent if start_day is not provided by user setting day as the current_resource day @@ -490,7 +490,7 @@ class Chef # this line of code is just to support backward compatibility of wild card * new_resource.months = "jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec" if new_resource.months == "*" && new_resource.frequency == :monthly months = new_resource.months.split(",") - months.map! { |month| month.to_s.strip.upcase } + months.map! do |month| month.to_s.strip.upcase end months_of_year = get_binary_values_from_constants(months, MONTHS) else MONTHS.each do |key, value| diff --git a/lib/chef/provider/zypper_repository.rb b/lib/chef/provider/zypper_repository.rb index 764979cb3a..0985be11f9 100644 --- a/lib/chef/provider/zypper_repository.rb +++ b/lib/chef/provider/zypper_repository.rb @@ -158,7 +158,7 @@ class Chef declare_resource(:execute, "import gpg key from #{new_resource.gpgkey}") do command "/bin/rpm --import #{cached_keyfile}" - not_if { key_installed?(cached_keyfile) } + not_if do key_installed?(cached_keyfile) end action :run end end diff --git a/lib/chef/resource.rb b/lib/chef/resource.rb index 7f0895d6c9..b43c31ad3c 100644 --- a/lib/chef/resource.rb +++ b/lib/chef/resource.rb @@ -666,9 +666,9 @@ class Chef def inspect ivars = instance_variables.map(&:to_sym) - FORBIDDEN_IVARS - ivars.inject("<#{self}") do |str, ivar| + ivars.inject("<#{self}") { |str, ivar| str << " #{ivar}: #{instance_variable_get(ivar).inspect}" - end << ">" + } << ">" end # as_json does most of the to_json heavy lifted. It exists here in case activesupport diff --git a/lib/chef/resource/apt_preference.rb b/lib/chef/resource/apt_preference.rb index 810a8dcad8..1980eedc6a 100644 --- a/lib/chef/resource/apt_preference.rb +++ b/lib/chef/resource/apt_preference.rb @@ -23,7 +23,7 @@ class Chef # @since 13.3 class AptPreference < Chef::Resource resource_name :apt_preference - provides(:apt_preference) { true } + provides(:apt_preference) do true end description "The apt_preference resource allows for the creation of APT preference files. Preference files are used to control which package versions and sources are prioritized during installation." introduced "13.3" diff --git a/lib/chef/resource/apt_repository.rb b/lib/chef/resource/apt_repository.rb index dff8139647..845aaaca41 100644 --- a/lib/chef/resource/apt_repository.rb +++ b/lib/chef/resource/apt_repository.rb @@ -22,7 +22,7 @@ class Chef class Resource class AptRepository < Chef::Resource resource_name :apt_repository - provides(:apt_repository) { true } + provides(:apt_repository) do true end description "Use the apt_repository resource to specify additional APT repositories. Adding a new repository will update the APT package cache immediately." introduced "12.9" diff --git a/lib/chef/resource/apt_update.rb b/lib/chef/resource/apt_update.rb index e11d35664f..d4c2f0d799 100644 --- a/lib/chef/resource/apt_update.rb +++ b/lib/chef/resource/apt_update.rb @@ -22,7 +22,7 @@ class Chef class Resource class AptUpdate < Chef::Resource resource_name :apt_update - provides(:apt_update) { true } + provides(:apt_update) do true end description "Use the apt_update resource to manage APT repository updates on Debian and Ubuntu platforms." introduced "12.7" diff --git a/lib/chef/resource/build_essential.rb b/lib/chef/resource/build_essential.rb index b38ec6b24a..9b3e54bc11 100644 --- a/lib/chef/resource/build_essential.rb +++ b/lib/chef/resource/build_essential.rb @@ -20,7 +20,7 @@ class Chef class Resource class BuildEssential < Chef::Resource resource_name :build_essential - provides(:build_essential) { true } + provides(:build_essential) do true end description "Use the build_essential resource to install packages required for compiling C software from source." introduced "14.0" diff --git a/lib/chef/resource/chef_handler.rb b/lib/chef/resource/chef_handler.rb index 2fa5173401..3585f3e302 100644 --- a/lib/chef/resource/chef_handler.rb +++ b/lib/chef/resource/chef_handler.rb @@ -22,7 +22,7 @@ class Chef class Resource class ChefHandler < Chef::Resource resource_name :chef_handler - provides(:chef_handler) { true } + provides(:chef_handler) do true end description "Use the chef_handler resource to install or uninstall reporting/exception handlers." introduced "14.0" diff --git a/lib/chef/resource/dmg_package.rb b/lib/chef/resource/dmg_package.rb index 403716cad7..d5516671e3 100644 --- a/lib/chef/resource/dmg_package.rb +++ b/lib/chef/resource/dmg_package.rb @@ -21,7 +21,7 @@ class Chef class Resource class DmgPackage < Chef::Resource resource_name :dmg_package - provides(:dmg_package) { true } + provides(:dmg_package) do true end description "Use the dmg_package resource to install a dmg 'package'. The resource will retrieve the dmg file from a remote URL, mount it using OS X's hdidutil, copy the application (.app directory) to the specified destination (/Applications), and detach the image using hdiutil. The dmg file will be stored in the Chef::Config[:file_cache_path]." introduced "14.0" diff --git a/lib/chef/resource/dsc_resource.rb b/lib/chef/resource/dsc_resource.rb index fe47d7fd1a..a5bad94100 100644 --- a/lib/chef/resource/dsc_resource.rb +++ b/lib/chef/resource/dsc_resource.rb @@ -34,14 +34,14 @@ class Chef # to dump the actual ivars class ToTextHash < Hash def to_text - descriptions = map do |(property, obj)| + descriptions = map { |(property, obj)| obj_text = if obj.respond_to?(:to_text) obj.to_text else obj.inspect end "#{property}=>#{obj_text}" - end + } "{#{descriptions.join(", ")}}" end end diff --git a/lib/chef/resource/homebrew_cask.rb b/lib/chef/resource/homebrew_cask.rb index 70e1d7c6bb..db224dbf15 100644 --- a/lib/chef/resource/homebrew_cask.rb +++ b/lib/chef/resource/homebrew_cask.rb @@ -24,7 +24,7 @@ class Chef class Resource class HomebrewCask < Chef::Resource resource_name :homebrew_cask - provides(:homebrew_cask) { true } + provides(:homebrew_cask) do true end description "Use the homebrew_cask resource to install binaries distributed via the Homebrew package manager." introduced "14.0" diff --git a/lib/chef/resource/homebrew_tap.rb b/lib/chef/resource/homebrew_tap.rb index 23738d6e51..f373e626da 100644 --- a/lib/chef/resource/homebrew_tap.rb +++ b/lib/chef/resource/homebrew_tap.rb @@ -24,7 +24,7 @@ class Chef class Resource class HomebrewTap < Chef::Resource resource_name :homebrew_tap - provides(:homebrew_tap) { true } + provides(:homebrew_tap) do true end description "Use the homebrew_tap resource to add additional formula repositories to the Homebrew package manager." introduced "14.0" diff --git a/lib/chef/resource/hostname.rb b/lib/chef/resource/hostname.rb index dab599c272..a141e56d2d 100644 --- a/lib/chef/resource/hostname.rb +++ b/lib/chef/resource/hostname.rb @@ -49,7 +49,7 @@ class Chef action_class do def append_replacing_matching_lines(path, regex, string) text = IO.read(path).split("\n") - text.reject! { |s| s =~ regex } + text.reject! do |s| s =~ regex end text += [ string ] file path do content text.join("\n") + "\n" @@ -91,7 +91,7 @@ class Chef # set the hostname via /bin/hostname declare_resource(:execute, "set hostname to #{new_resource.hostname}") do command "/bin/hostname #{new_resource.hostname}" - not_if { shell_out!("hostname").stdout.chomp == new_resource.hostname } + not_if do shell_out!("hostname").stdout.chomp == new_resource.hostname end notifies :reload, "ohai[reload hostname]" end @@ -111,18 +111,18 @@ class Chef # darwin declare_resource(:execute, "set HostName via scutil") do command "/usr/sbin/scutil --set HostName #{new_resource.hostname}" - not_if { shell_out!("/usr/sbin/scutil --get HostName").stdout.chomp == new_resource.hostname } + not_if do shell_out!("/usr/sbin/scutil --get HostName").stdout.chomp == new_resource.hostname end notifies :reload, "ohai[reload hostname]" end declare_resource(:execute, "set ComputerName via scutil") do command "/usr/sbin/scutil --set ComputerName #{new_resource.hostname}" - not_if { shell_out!("/usr/sbin/scutil --get ComputerName").stdout.chomp == new_resource.hostname } + not_if do shell_out!("/usr/sbin/scutil --get ComputerName").stdout.chomp == new_resource.hostname end notifies :reload, "ohai[reload hostname]" end shortname = new_resource.hostname[/[^\.]*/] declare_resource(:execute, "set LocalHostName via scutil") do command "/usr/sbin/scutil --set LocalHostName #{shortname}" - not_if { shell_out!("/usr/sbin/scutil --get LocalHostName").stdout.chomp == shortname } + not_if do shell_out!("/usr/sbin/scutil --get LocalHostName").stdout.chomp == shortname end notifies :reload, "ohai[reload hostname]" end when node["os"] == "linux" diff --git a/lib/chef/resource/locale.rb b/lib/chef/resource/locale.rb index 8edb278e48..a29fae018a 100644 --- a/lib/chef/resource/locale.rb +++ b/lib/chef/resource/locale.rb @@ -81,13 +81,13 @@ class Chef # def define_resource_requirements requirements.assert(:all_actions) do |a| - a.assertion { LOCALE_PLATFORM_FAMILIES.include?(node[:platform_family]) } + a.assertion do LOCALE_PLATFORM_FAMILIES.include?(node[:platform_family]) end a.failure_message(Chef::Exceptions::ProviderNotFound, "The locale resource is not supported on platform family: #{node[:platform_family]}") end requirements.assert(:all_actions) do |a| # RHEL/CentOS type platforms don't have locale-gen - a.assertion { shell_out("locale-gen") } + a.assertion do shell_out("locale-gen") end a.failure_message(Chef::Exceptions::ProviderNotFound, "The locale resource requires the locale-gen tool") end end diff --git a/lib/chef/resource/macos_userdefaults.rb b/lib/chef/resource/macos_userdefaults.rb index 02d65baee4..c55c39b1d8 100644 --- a/lib/chef/resource/macos_userdefaults.rb +++ b/lib/chef/resource/macos_userdefaults.rb @@ -22,8 +22,8 @@ class Chef class MacosUserDefaults < Chef::Resource # align with apple's marketing department resource_name :macos_userdefaults - provides(:mac_os_x_userdefaults) { true } - provides(:macos_userdefaults) { true } + provides(:mac_os_x_userdefaults) do true end + provides(:macos_userdefaults) do true end description "Use the macos_userdefaults resource to manage the macOS user defaults system. The properties of this resource are passed to the defaults command, and the parameters follow the convention of that command. See the defaults(1) man page for details on how the tool works." introduced "14.0" diff --git a/lib/chef/resource/ohai_hint.rb b/lib/chef/resource/ohai_hint.rb index 30d7a3bd0c..227ea46ace 100644 --- a/lib/chef/resource/ohai_hint.rb +++ b/lib/chef/resource/ohai_hint.rb @@ -21,7 +21,7 @@ class Chef class Resource class OhaiHint < Chef::Resource resource_name :ohai_hint - provides(:ohai_hint) { true } + provides(:ohai_hint) do true end description "Use the ohai_hint resource to aid in configuration detection by passing hint data to Ohai." introduced "14.0" diff --git a/lib/chef/resource/openssl_dhparam.rb b/lib/chef/resource/openssl_dhparam.rb index 254a840a48..a9fe069bb8 100644 --- a/lib/chef/resource/openssl_dhparam.rb +++ b/lib/chef/resource/openssl_dhparam.rb @@ -24,7 +24,7 @@ class Chef include Chef::Mixin::OpenSSLHelper resource_name :openssl_dhparam - provides(:openssl_dhparam) { true } + provides(:openssl_dhparam) do true end description "Use the openssl_dhparam resource to generate dhparam.pem files. If a valid dhparam.pem file is found at the specified location, no new file will be created. If a file is found at the specified location but it is not a valid dhparam file, it will be overwritten." introduced "14.0" diff --git a/lib/chef/resource/openssl_rsa_private_key.rb b/lib/chef/resource/openssl_rsa_private_key.rb index 38ffa2c394..1170a56a71 100644 --- a/lib/chef/resource/openssl_rsa_private_key.rb +++ b/lib/chef/resource/openssl_rsa_private_key.rb @@ -24,8 +24,8 @@ class Chef include Chef::Mixin::OpenSSLHelper resource_name :openssl_rsa_private_key - provides(:openssl_rsa_private_key) { true } - provides(:openssl_rsa_key) { true } # legacy cookbook resource name + provides(:openssl_rsa_private_key) do true end + provides(:openssl_rsa_key) do true end # legacy cookbook resource name description "Use the openssl_rsa_private_key resource to generate RSA private key files. If a valid RSA key file can be opened at the specified location, no new file will be created. If the RSA key file cannot be opened, either because it does not exist or because the password to the RSA key file does not match the password in the recipe, it will be overwritten." introduced "14.0" diff --git a/lib/chef/resource/openssl_rsa_public_key.rb b/lib/chef/resource/openssl_rsa_public_key.rb index c7c125fb9e..f3c47794cd 100644 --- a/lib/chef/resource/openssl_rsa_public_key.rb +++ b/lib/chef/resource/openssl_rsa_public_key.rb @@ -24,7 +24,7 @@ class Chef include Chef::Mixin::OpenSSLHelper resource_name :openssl_rsa_public_key - provides(:openssl_rsa_public_key) { true } + provides(:openssl_rsa_public_key) do true end description "Use the openssl_rsa_public_key resource to generate RSA public key files for a given RSA private key." introduced "14.0" diff --git a/lib/chef/resource/openssl_x509_certificate.rb b/lib/chef/resource/openssl_x509_certificate.rb index 20cf998239..edb045ae52 100644 --- a/lib/chef/resource/openssl_x509_certificate.rb +++ b/lib/chef/resource/openssl_x509_certificate.rb @@ -25,7 +25,7 @@ class Chef include Chef::Mixin::OpenSSLHelper resource_name :openssl_x509_certificate - provides(:openssl_x509) { true } # legacy cookbook name. + provides(:openssl_x509) do true end # legacy cookbook name. description "Use the openssl_x509_certificate resource to generate signed or self-signed, PEM-formatted x509 certificates. If no existing key is specified, the resource will automatically generate a passwordless key with the certificate. If a CA private key and certificate are provided, the certificate will be signed with them. Note: This resource was renamed from openssl_x509 to openssl_x509_certificate. The legacy name will continue to function, but cookbook code should be updated for the new resource name." introduced "14.4" diff --git a/lib/chef/resource/registry_key.rb b/lib/chef/resource/registry_key.rb index a5c99313bf..552fbd05bb 100644 --- a/lib/chef/resource/registry_key.rb +++ b/lib/chef/resource/registry_key.rb @@ -23,7 +23,7 @@ class Chef class Resource class RegistryKey < Chef::Resource resource_name :registry_key - provides(:registry_key) { true } + provides(:registry_key) do true end description "Use the registry_key resource to create and delete registry keys in Microsoft Windows." introduced "11.0" diff --git a/lib/chef/resource/rhsm_errata.rb b/lib/chef/resource/rhsm_errata.rb index 7442bf99f2..9b637f197c 100644 --- a/lib/chef/resource/rhsm_errata.rb +++ b/lib/chef/resource/rhsm_errata.rb @@ -21,7 +21,7 @@ class Chef class Resource class RhsmErrata < Chef::Resource resource_name :rhsm_errata - provides(:rhsm_errata) { true } + provides(:rhsm_errata) do true end description "Use the rhsm_errata resource to install packages associated with a given Red"\ " Hat Subscription Manager Errata ID. This is helpful if packages"\ diff --git a/lib/chef/resource/rhsm_errata_level.rb b/lib/chef/resource/rhsm_errata_level.rb index 2bb0006a38..e95f669e8e 100644 --- a/lib/chef/resource/rhsm_errata_level.rb +++ b/lib/chef/resource/rhsm_errata_level.rb @@ -21,7 +21,7 @@ class Chef class Resource class RhsmErrataLevel < Chef::Resource resource_name :rhsm_errata_level - provides(:rhsm_errata_level) { true } + provides(:rhsm_errata_level) do true end description "Use the rhsm_errata_level resource to install all packages of a specified errata level from the Red Hat Subscription Manager. For example, you can ensure that all packages associated with errata marked at a 'Critical' security level are installed." introduced "14.0" diff --git a/lib/chef/resource/rhsm_register.rb b/lib/chef/resource/rhsm_register.rb index cfaa55124c..f3b9776bb2 100644 --- a/lib/chef/resource/rhsm_register.rb +++ b/lib/chef/resource/rhsm_register.rb @@ -22,7 +22,7 @@ class Chef class Resource class RhsmRegister < Chef::Resource resource_name :rhsm_register - provides(:rhsm_register) { true } + provides(:rhsm_register) do true end description "Use the rhsm_register resource to register a node with the Red Hat Subscription Manager"\ " or a local Red Hat Satellite server." @@ -105,7 +105,7 @@ class Chef command "subscription-manager unregister" default_env true action :run - only_if { registered_with_rhsm? } + only_if do registered_with_rhsm? end notifies :run, "execute[Clean RHSM Config]", :immediately end diff --git a/lib/chef/resource/rhsm_repo.rb b/lib/chef/resource/rhsm_repo.rb index feb2aa0802..5e4068a7a7 100644 --- a/lib/chef/resource/rhsm_repo.rb +++ b/lib/chef/resource/rhsm_repo.rb @@ -21,7 +21,7 @@ class Chef class Resource class RhsmRepo < Chef::Resource resource_name :rhsm_repo - provides(:rhsm_repo) { true } + provides(:rhsm_repo) do true end description "Use the rhsm_repo resource to enable or disable Red Hat Subscription Manager"\ " repositories that are made available via attached subscriptions." diff --git a/lib/chef/resource/rhsm_subscription.rb b/lib/chef/resource/rhsm_subscription.rb index 7bbf53f07d..d5a16adfe7 100644 --- a/lib/chef/resource/rhsm_subscription.rb +++ b/lib/chef/resource/rhsm_subscription.rb @@ -21,7 +21,7 @@ class Chef class Resource class RhsmSubscription < Chef::Resource resource_name :rhsm_subscription - provides(:rhsm_subscription) { true } + provides(:rhsm_subscription) do true end description "Use the rhsm_subscription resource to add or remove Red Hat Subscription Manager"\ " subscriptions from your host. This can be used when a host's activation_key"\ diff --git a/lib/chef/resource/sudo.rb b/lib/chef/resource/sudo.rb index eb89687411..e1fbcd18b2 100644 --- a/lib/chef/resource/sudo.rb +++ b/lib/chef/resource/sudo.rb @@ -25,7 +25,7 @@ class Chef class Resource class Sudo < Chef::Resource resource_name :sudo - provides(:sudo) { true } + provides(:sudo) do true end description "Use the sudo resource to add or remove individual sudo entries using sudoers.d files."\ " Sudo version 1.7.2 or newer is required to use the sudo resource, as it relies on the"\ @@ -148,10 +148,10 @@ class Chef validate_properties if docker? # don't even put this into resource collection unless we're in docker - declare_resource(:package, "sudo") do + declare_resource(:package, "sudo") { action :nothing not_if "which sudo" - end.run_action(:install) + }.run_action(:install) end target = "#{new_resource.config_prefix}/sudoers.d/" diff --git a/lib/chef/resource/swap_file.rb b/lib/chef/resource/swap_file.rb index 2efe040c47..6c2fde50df 100644 --- a/lib/chef/resource/swap_file.rb +++ b/lib/chef/resource/swap_file.rb @@ -21,7 +21,7 @@ class Chef class Resource class SwapFile < Chef::Resource resource_name :swap_file - provides(:swap_file) { true } + provides(:swap_file) do true end description "Use the swap_file resource to create or delete swap files on Linux systems, and optionally to manage the swappiness configuration for a host." introduced "14.0" diff --git a/lib/chef/resource/sysctl.rb b/lib/chef/resource/sysctl.rb index a6c316c5bc..81faad0210 100644 --- a/lib/chef/resource/sysctl.rb +++ b/lib/chef/resource/sysctl.rb @@ -21,8 +21,8 @@ class Chef class Resource class Sysctl < Chef::Resource resource_name :sysctl - provides(:sysctl) { true } - provides(:sysctl_param) { true } + provides(:sysctl) do true end + provides(:sysctl_param) do true end description "Use the sysctl resource to set or remove kernel parameters using the sysctl"\ " command line tool and configuration files in the system's sysctl.d directory. "\ diff --git a/lib/chef/resource/systemd_unit.rb b/lib/chef/resource/systemd_unit.rb index 973fdf9491..4ee8d2e5cd 100644 --- a/lib/chef/resource/systemd_unit.rb +++ b/lib/chef/resource/systemd_unit.rb @@ -23,7 +23,7 @@ require "iniparse" class Chef class Resource class SystemdUnit < Chef::Resource - resource_name(:systemd_unit) { true } + resource_name(:systemd_unit) do true end description "Use the systemd_unit resource to create, manage, and run systemd units." introduced "12.11" @@ -67,7 +67,7 @@ class Chef def to_ini case content when Hash - IniParse.gen do |doc| + IniParse.gen { |doc| content.each_pair do |sect, opts| doc.section(sect) do |section| opts.each_pair do |opt, val| @@ -77,7 +77,7 @@ class Chef end end end - end.to_s + }.to_s else content.to_s end diff --git a/lib/chef/resource/timezone.rb b/lib/chef/resource/timezone.rb index 16a7f1031e..e8227853d3 100644 --- a/lib/chef/resource/timezone.rb +++ b/lib/chef/resource/timezone.rb @@ -68,7 +68,7 @@ class Chef execute "tzdata-update" do command "/usr/sbin/tzdata-update" action :nothing - only_if { ::File.executable?("/usr/sbin/tzdata-update") } + only_if do ::File.executable?("/usr/sbin/tzdata-update") end subscribes :run, "file[/etc/sysconfig/clock]", :immediately end diff --git a/lib/chef/resource/windows_auto_run.rb b/lib/chef/resource/windows_auto_run.rb index c0d0910e5f..c5b4164068 100644 --- a/lib/chef/resource/windows_auto_run.rb +++ b/lib/chef/resource/windows_auto_run.rb @@ -22,7 +22,7 @@ class Chef class Resource class WindowsAutorun < Chef::Resource resource_name :windows_auto_run - provides(:windows_auto_run) { true } + provides(:windows_auto_run) do true end description "Use the windows_auto_run resource to set applications to run at login." introduced "14.0" diff --git a/lib/chef/resource/windows_feature.rb b/lib/chef/resource/windows_feature.rb index cc80284019..6b5c3fe68b 100644 --- a/lib/chef/resource/windows_feature.rb +++ b/lib/chef/resource/windows_feature.rb @@ -22,7 +22,7 @@ class Chef class Resource class WindowsFeature < Chef::Resource resource_name :windows_feature - provides(:windows_feature) { true } + provides(:windows_feature) do true end description "Use the windows_feature resource to add, remove or entirely delete Windows features and roles. This resource calls the 'windows_feature_dism' or 'windows_feature_powershell' resources depending on the specified installation method and defaults to dism, which is available on both Workstation and Server editions of Windows." introduced "14.0" diff --git a/lib/chef/resource/windows_feature_dism.rb b/lib/chef/resource/windows_feature_dism.rb index faeb0b0762..0d365dae2b 100644 --- a/lib/chef/resource/windows_feature_dism.rb +++ b/lib/chef/resource/windows_feature_dism.rb @@ -23,7 +23,7 @@ class Chef class Resource class WindowsFeatureDism < Chef::Resource resource_name :windows_feature_dism - provides(:windows_feature_dism) { true } + provides(:windows_feature_dism) do true end description "Use the windows_feature_dism resource to add, remove, or entirely delete Windows features and roles using DISM." introduced "14.0" diff --git a/lib/chef/resource/windows_feature_powershell.rb b/lib/chef/resource/windows_feature_powershell.rb index 5cdbe1f74c..15ae4183ad 100644 --- a/lib/chef/resource/windows_feature_powershell.rb +++ b/lib/chef/resource/windows_feature_powershell.rb @@ -25,7 +25,7 @@ class Chef class Resource class WindowsFeaturePowershell < Chef::Resource resource_name :windows_feature_powershell - provides(:windows_feature_powershell) { true } + provides(:windows_feature_powershell) do true end description "Use the windows_feature_powershell resource to add, remove, or entirely delete Windows features and roles using PowerShell. This resource offers significant speed benefits over the windows_feature_dism resource, but requires installing the Remote Server Administration Tools on non-server releases of Windows." introduced "14.0" diff --git a/lib/chef/resource/windows_font.rb b/lib/chef/resource/windows_font.rb index 64644a815f..5a976644e0 100644 --- a/lib/chef/resource/windows_font.rb +++ b/lib/chef/resource/windows_font.rb @@ -23,7 +23,7 @@ class Chef require_relative "../util/path_helper" resource_name :windows_font - provides(:windows_font) { true } + provides(:windows_font) do true end description "Use the windows_font resource to install font files on Windows. By default, the font is sourced from the cookbook using the resource, but a URI source can be specified as well." introduced "14.0" @@ -53,17 +53,17 @@ class Chef def retrieve_cookbook_font font_file = new_resource.font_name if new_resource.source - declare_resource(:remote_file, font_file) do + declare_resource(:remote_file, font_file) { action :nothing source source_uri path Chef::Util::PathHelper.join(ENV["TEMP"], font_file) - end.run_action(:create) + }.run_action(:create) else - declare_resource(:cookbook_file, font_file) do + declare_resource(:cookbook_file, font_file) { action :nothing cookbook cookbook_name.to_s unless cookbook_name.nil? path Chef::Util::PathHelper.join(ENV["TEMP"], font_file) - end.run_action(:create) + }.run_action(:create) end end diff --git a/lib/chef/resource/windows_package.rb b/lib/chef/resource/windows_package.rb index 5592e537b4..ec49510b1d 100644 --- a/lib/chef/resource/windows_package.rb +++ b/lib/chef/resource/windows_package.rb @@ -27,7 +27,7 @@ class Chef include Chef::Mixin::Uris resource_name :windows_package - provides(:windows_package) { true } + provides(:windows_package) do true end provides :package, os: "windows" description "Use the windows_package resource to manage Microsoft Installer Package (MSI) packages for the Microsoft Windows platform." diff --git a/lib/chef/resource/windows_pagefile.rb b/lib/chef/resource/windows_pagefile.rb index 03a7511f47..5a69e21eff 100644 --- a/lib/chef/resource/windows_pagefile.rb +++ b/lib/chef/resource/windows_pagefile.rb @@ -21,7 +21,7 @@ class Chef class Resource class WindowsPagefile < Chef::Resource resource_name :windows_pagefile - provides(:windows_pagefile) { true } + provides(:windows_pagefile) do true end description "Use the windows_pagefile resource to configure pagefile settings on Windows." introduced "14.0" diff --git a/lib/chef/resource/windows_path.rb b/lib/chef/resource/windows_path.rb index 0067de5baf..f649f9a1e1 100644 --- a/lib/chef/resource/windows_path.rb +++ b/lib/chef/resource/windows_path.rb @@ -22,7 +22,7 @@ class Chef class Resource class WindowsPath < Chef::Resource resource_name :windows_path - provides(:windows_path) { true } + provides(:windows_path) do true end description "Use the windows_path resource to manage the path environment variable on Microsoft Windows." introduced "13.4" diff --git a/lib/chef/resource/windows_printer.rb b/lib/chef/resource/windows_printer.rb index d782c1b360..cd301d07d7 100644 --- a/lib/chef/resource/windows_printer.rb +++ b/lib/chef/resource/windows_printer.rb @@ -25,7 +25,7 @@ class Chef require "resolv" resource_name :windows_printer - provides(:windows_printer) { true } + provides(:windows_printer) do true end description "Use the windows_printer resource to setup Windows printers. Note that this doesn't currently install a printer driver. You must already have the driver installed on the system." introduced "14.0" diff --git a/lib/chef/resource/windows_printer_port.rb b/lib/chef/resource/windows_printer_port.rb index cd1a5f55c2..28d81fbbd7 100644 --- a/lib/chef/resource/windows_printer_port.rb +++ b/lib/chef/resource/windows_printer_port.rb @@ -25,7 +25,7 @@ class Chef require "resolv" resource_name :windows_printer_port - provides(:windows_printer_port) { true } + provides(:windows_printer_port) do true end description "Use the windows_printer_port resource to create and delete TCP/IPv4 printer ports on Windows." introduced "14.0" diff --git a/lib/chef/resource/windows_service.rb b/lib/chef/resource/windows_service.rb index b8ee4edf9c..3832fe4b7c 100644 --- a/lib/chef/resource/windows_service.rb +++ b/lib/chef/resource/windows_service.rb @@ -33,7 +33,7 @@ class Chef # Until #1773 is resolved, you need to manually specify the windows_service resource # to use action :configure_startup and properties startup_type - provides(:windows_service) { true } + provides(:windows_service) do true end provides :service, os: "windows" description "Use the windows_service resource to create, delete, or manage a service on the Microsoft Windows platform." diff --git a/lib/chef/resource/windows_shortcut.rb b/lib/chef/resource/windows_shortcut.rb index 0c6dc63e6e..1fbeb428ea 100644 --- a/lib/chef/resource/windows_shortcut.rb +++ b/lib/chef/resource/windows_shortcut.rb @@ -22,7 +22,7 @@ class Chef class Resource class WindowsShortcut < Chef::Resource resource_name :windows_shortcut - provides(:windows_shortcut) { true } + provides(:windows_shortcut) do true end description "Use the windows_shortcut resource to create shortcut files on Windows." introduced "14.0" diff --git a/lib/chef/resource/windows_task.rb b/lib/chef/resource/windows_task.rb index 95de6b37c2..920d3e300f 100644 --- a/lib/chef/resource/windows_task.rb +++ b/lib/chef/resource/windows_task.rb @@ -23,7 +23,7 @@ class Chef class Resource class WindowsTask < Chef::Resource resource_name :windows_task - provides(:windows_task) { true } + provides(:windows_task) do true end description "Use the windows_task resource to create, delete or run a Windows scheduled task. Requires Windows Server 2008 or later due to API usage." introduced "13.0" @@ -196,7 +196,7 @@ class Chef # returns true if frequency_modifer has values First, second, third, fourth, last, lastday def frequency_modifier_includes_days_of_weeks?(frequency_modifier) frequency_modifier = frequency_modifier.to_s.split(",") - frequency_modifier.map! { |value| value.strip.upcase } + frequency_modifier.map! do |value| value.strip.upcase end (frequency_modifier - VALID_WEEKS).empty? end @@ -300,7 +300,7 @@ class Chef # Following error will be raise if day is set as 1-31 and frequency is selected as :weekly since those values are valid with only frequency :monthly raise ArgumentError, "day values 1-31 or last is only valid with frequency :monthly" if frequency == :weekly else - days.map! { |day| day.to_s.strip.downcase } + days.map! do |day| day.to_s.strip.downcase end unless (days - VALID_WEEK_DAYS).empty? raise ArgumentError, "day property invalid. Only valid values are: #{VALID_WEEK_DAYS.map(&:upcase).join(", ")}. Multiple values must be separated by a comma." end @@ -313,7 +313,7 @@ class Chef if months.is_a?(String) months = months.split(",") - months.map! { |month| month.strip.upcase } + months.map! do |month| month.strip.upcase end unless (months - VALID_MONTHS).empty? raise ArgumentError, "months property invalid. Only valid values are: #{VALID_MONTHS.join(", ")}. Multiple values must be separated by a comma." end @@ -322,7 +322,7 @@ class Chef # This method returns true if day has values from 1-31 which is a days of moths and used with frequency :monthly def days_includes_days_of_months?(days) - days.map! { |day| day.to_s.strip.downcase } + days.map! do |day| day.to_s.strip.downcase end (days - VALID_DAYS_OF_MONTH).empty? end diff --git a/lib/chef/resource/yum_repository.rb b/lib/chef/resource/yum_repository.rb index 05639842af..de6e51cc7c 100644 --- a/lib/chef/resource/yum_repository.rb +++ b/lib/chef/resource/yum_repository.rb @@ -22,7 +22,7 @@ class Chef class Resource class YumRepository < Chef::Resource resource_name :yum_repository - provides(:yum_repository) { true } + provides(:yum_repository) do true end description "Use the yum_repository resource to manage a Yum repository configuration"\ " file located at /etc/yum.repos.d/repositoryid.repo on the local machine."\ diff --git a/lib/chef/resource/zypper_repository.rb b/lib/chef/resource/zypper_repository.rb index 447660e9ac..8c35065b58 100644 --- a/lib/chef/resource/zypper_repository.rb +++ b/lib/chef/resource/zypper_repository.rb @@ -22,8 +22,8 @@ class Chef class Resource class ZypperRepository < Chef::Resource resource_name :zypper_repository - provides(:zypper_repository) { true } - provides(:zypper_repo) { true } + provides(:zypper_repository) do true end + provides(:zypper_repo) do true end description "Use the zypper_repository resource to create Zypper package repositories on SUSE Enterprise Linux and openSUSE systems. This resource maintains full compatibility with the zypper_repository resource in the existing zypper cookbook." introduced "13.3" diff --git a/lib/chef/resource_reporter.rb b/lib/chef/resource_reporter.rb index bbb4fa2e83..1979448b13 100644 --- a/lib/chef/resource_reporter.rb +++ b/lib/chef/resource_reporter.rb @@ -193,9 +193,9 @@ class Chef def prepare_run_data run_data = {} run_data["action"] = "end" - run_data["resources"] = updated_resources.map do |action_record| + run_data["resources"] = updated_resources.map { |action_record| for_json(action_record) - end + } run_data["status"] = @status run_data["run_list"] = Chef::JSONCompat.to_json(@run_status.node.run_list) run_data["total_res_count"] = total_res_count.to_s diff --git a/lib/chef/run_list.rb b/lib/chef/run_list.rb index 1108b5d2c1..f2949579c3 100644 --- a/lib/chef/run_list.rb +++ b/lib/chef/run_list.rb @@ -77,7 +77,7 @@ class Chef other_run_list_items = other.dup - other_run_list_items.map! { |item| coerce_to_run_list_item(item) } + other_run_list_items.map! do |item| coerce_to_run_list_item(item) end other_run_list_items == @run_list_items end end @@ -133,7 +133,7 @@ class Chef end def remove(item) - @run_list_items.delete_if { |i| i == item } + @run_list_items.delete_if do |i| i == item end self end alias :delete :remove diff --git a/lib/chef/run_list/versioned_recipe_list.rb b/lib/chef/run_list/versioned_recipe_list.rb index 6083dae953..cf222bf710 100644 --- a/lib/chef/run_list/versioned_recipe_list.rb +++ b/lib/chef/run_list/versioned_recipe_list.rb @@ -89,7 +89,7 @@ class Chef # # @return [Array] Array of strings with fully-qualified and unexpanded recipe names def with_duplicate_names - map do |recipe_name| + map { |recipe_name| if recipe_name.end_with?("::default") [ recipe_name.sub(/::default$/, ""), recipe_name ] elsif recipe_name.include?("::") @@ -97,7 +97,7 @@ class Chef else [ recipe_name, "#{recipe_name}::default" ] end - end.flatten + }.flatten end end end diff --git a/lib/chef/runner.rb b/lib/chef/runner.rb index a0ae61fe4c..d31f3ca0f1 100644 --- a/lib/chef/runner.rb +++ b/lib/chef/runner.rb @@ -94,7 +94,7 @@ class Chef # Execute each resource. run_context.resource_collection.execute_each_resource do |resource| begin - Array(resource.action).each { |action| run_action(resource, action) } + Array(resource.action).each do |action| run_action(resource, action) end ensure resource.executed_by_runner = true end diff --git a/lib/chef/search/query.rb b/lib/chef/search/query.rb index 5a9c1f6d41..a97e2cb799 100644 --- a/lib/chef/search/query.rb +++ b/lib/chef/search/query.rb @@ -78,7 +78,7 @@ class Chef response = call_rest_service(type, query: query, **args_h) if block - response["rows"].each { |row| yield(row) if row } + response["rows"].each do |row| yield(row) if row end # # args_h[:rows] and args_h[:start] are the page size and # start position requested of the search index backing the diff --git a/lib/chef/shell/ext.rb b/lib/chef/shell/ext.rb index 843126b4f2..c1210e52a6 100644 --- a/lib/chef/shell/ext.rb +++ b/lib/chef/shell/ext.rb @@ -329,13 +329,13 @@ module Shell filename += object.id end - edited_data = Tempfile.open([filename, ".js"]) do |tempfile| + edited_data = Tempfile.open([filename, ".js"]) { |tempfile| tempfile.sync = true tempfile.puts Chef::JSONCompat.to_json(object) system("#{Shell.editor} #{tempfile.path}") tempfile.rewind tempfile.read - end + } Chef::JSONCompat.from_json(edited_data) end diff --git a/lib/chef/util/backup.rb b/lib/chef/util/backup.rb index 08da52e3b2..5c2201a8f4 100644 --- a/lib/chef/util/backup.rb +++ b/lib/chef/util/backup.rb @@ -81,9 +81,9 @@ class Chef def unsorted_backup_files # If you replace this with Dir[], you will probably break Windows. fn = Regexp.escape(::File.basename(path)) - Dir.entries(::File.dirname(backup_path)).select do |f| + Dir.entries(::File.dirname(backup_path)).select { |f| !!(f =~ /\A#{fn}.chef-[0-9.]*\B/) - end.map { |f| ::File.join(::File.dirname(backup_path), f) } + }.map { |f| ::File.join(::File.dirname(backup_path), f) } end def sorted_backup_files diff --git a/lib/chef/util/dsc/resource_store.rb b/lib/chef/util/dsc/resource_store.rb index d064a397c3..723695f3de 100644 --- a/lib/chef/util/dsc/resource_store.rb +++ b/lib/chef/util/dsc/resource_store.rb @@ -52,9 +52,9 @@ class Chef private def add_resource(new_r) - count = resources.count do |r| + count = resources.count { |r| r["ResourceType"].casecmp(new_r["ResourceType"]) == 0 - end + } if count == 0 resources << new_r end @@ -71,14 +71,14 @@ class Chef end def find_resources(name, module_name, rs) - found = rs.find_all do |r| + found = rs.find_all { |r| name_matches = r["Name"].casecmp(name) == 0 if name_matches module_name.nil? || (r["Module"] && r["Module"]["Name"].casecmp(module_name) == 0) else false end - end + } end # Returns a list of dsc resources diff --git a/lib/chef/util/powershell/cmdlet.rb b/lib/chef/util/powershell/cmdlet.rb index 75cf489e9e..21eea7ca2f 100644 --- a/lib/chef/util/powershell/cmdlet.rb +++ b/lib/chef/util/powershell/cmdlet.rb @@ -115,7 +115,7 @@ class Chef end def command_switches_string(switches) - command_switches = switches.map do |switch_name, switch_value| + command_switches = switches.map { |switch_name, switch_value| if switch_name.class != Symbol raise ArgumentError, "Invalid type `#{switch_name} `for PowerShell switch '#{switch_name}'. The switch must be specified as a Symbol'" end @@ -140,7 +140,7 @@ class Chef end switch_present ? ["-#{switch_name.to_s.downcase}", switch_argument].join(" ").strip : "" - end + } command_switches.join(" ") end diff --git a/lib/chef/util/threaded_job_queue.rb b/lib/chef/util/threaded_job_queue.rb index 6b13bf99a3..ed3cbe4788 100644 --- a/lib/chef/util/threaded_job_queue.rb +++ b/lib/chef/util/threaded_job_queue.rb @@ -45,15 +45,15 @@ class Chef end def process(concurrency = 10) - workers = (1..concurrency).map do + workers = (1..concurrency).map { Thread.new do loop do fn = @queue.pop fn.arity == 1 ? fn.call(@lock) : fn.call end end - end - workers.each { |worker| self << Thread.method(:exit) } + } + workers.each do |worker| self << Thread.method(:exit) end workers.each(&:join) end end diff --git a/lib/chef/win32/registry.rb b/lib/chef/win32/registry.rb index 90bc35143a..1efcd19021 100644 --- a/lib/chef/win32/registry.rb +++ b/lib/chef/win32/registry.rb @@ -55,9 +55,9 @@ class Chef def get_values(key_path) hive, key = get_hive_and_key(key_path) key_exists!(key_path) - values = hive.open(key, ::Win32::Registry::KEY_READ | registry_system_architecture) do |reg| + values = hive.open(key, ::Win32::Registry::KEY_READ | registry_system_architecture) { |reg| reg.map { |name, type, data| { name: name, type: get_name_from_type(type), data: data } } - end + } end def set_value(key_path, value) diff --git a/lib/chef/win32/security/acl.rb b/lib/chef/win32/security/acl.rb index ec963fb522..957cc6738b 100644 --- a/lib/chef/win32/security/acl.rb +++ b/lib/chef/win32/security/acl.rb @@ -37,7 +37,7 @@ class Chef aces_size = aces.inject(0) { |sum, ace| sum + ace.size } acl_size = align_dword(Chef::ReservedNames::Win32::API::Security::ACLStruct.size + aces_size) # What the heck is 94??? acl = Chef::ReservedNames::Win32::Security.initialize_acl(acl_size) - aces.each { |ace| Chef::ReservedNames::Win32::Security.add_ace(acl, ace) } + aces.each do |ace| Chef::ReservedNames::Win32::Security.add_ace(acl, ace) end acl end diff --git a/lib/chef/win32/security/sid.rb b/lib/chef/win32/security/sid.rb index 9643a80c67..73bb35d2fd 100644 --- a/lib/chef/win32/security/sid.rb +++ b/lib/chef/win32/security/sid.rb @@ -248,16 +248,16 @@ class Chef SERVICE_ACCOUNT_USERS = [self.LocalSystem, self.NtLocal, - self.NtNetwork].flat_map do |user_type| + self.NtNetwork].flat_map { |user_type| [user_type.account_simple_name.upcase, user_type.account_name.upcase] - end.freeze + }.freeze BUILT_IN_GROUPS = [self.BuiltinAdministrators, - self.BuiltinUsers, self.Guests].flat_map do |user_type| + self.BuiltinUsers, self.Guests].flat_map { |user_type| [user_type.account_simple_name.upcase, user_type.account_name.upcase] - end.freeze + }.freeze SYSTEM_USER = SERVICE_ACCOUNT_USERS + BUILT_IN_GROUPS diff --git a/omnibus_overrides.rb b/omnibus_overrides.rb index 96342de8db..f4429b2ac5 100644 --- a/omnibus_overrides.rb +++ b/omnibus_overrides.rb @@ -30,4 +30,4 @@ override "openssl", version: "1.0.2s" # definition. This pin will ensure that ohai and chef-client commands use the # same (released) version of ohai. gemfile_lock = File.join(File.expand_path(File.dirname(__FILE__)), "Gemfile.lock") -override "ohai", version: "#{::File.readlines(gemfile_lock).find { |l| l =~ /^\s+ohai \((\d+\.\d+\.\d+)\)/ }; "v" + $1}" # rubocop: disable Layout/SpaceInsideStringInterpolation +override "ohai", version: "#{::File.readlines(gemfile_lock).find do |l| l =~ /^\s+ohai \((\d+\.\d+\.\d+)\)/ end; "v" + $1}" # rubocop: disable Layout/SpaceInsideStringInterpolation diff --git a/spec/functional/dsl/reboot_pending_spec.rb b/spec/functional/dsl/reboot_pending_spec.rb index 89701802b3..1bd1ce3328 100644 --- a/spec/functional/dsl/reboot_pending_spec.rb +++ b/spec/functional/dsl/reboot_pending_spec.rb @@ -36,9 +36,9 @@ describe Chef::DSL::RebootPending, :windows_only do let(:reg_key) { nil } let(:original_set) { false } - before(:all) { @any_flag = {} } + before(:all) do @any_flag = {} end - after { @any_flag[reg_key] = original_set } + after do @any_flag[reg_key] = original_set end describe 'HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations' do let(:reg_key) { 'HKLM\SYSTEM\CurrentControlSet\Control\Session Manager' } diff --git a/spec/functional/event_loggers/windows_eventlog_spec.rb b/spec/functional/event_loggers/windows_eventlog_spec.rb index ca15d3e38d..311fc691a2 100644 --- a/spec/functional/event_loggers/windows_eventlog_spec.rb +++ b/spec/functional/event_loggers/windows_eventlog_spec.rb @@ -48,37 +48,37 @@ describe Chef::EventLoggers::WindowsEventLogger, :windows_only do it "writes run_start event with event_id 10000 and contains version" do logger.run_start(version, run_status) - expect(event_log.read(flags, offset).any? do |e| + expect(event_log.read(flags, offset).any? { |e| e.source == Chef::Dist::PRODUCT && e.event_id == 10000 && e.string_inserts[0].include?(version) - end ).to be_truthy + } ).to be_truthy end it "writes run_started event with event_id 10001 and contains the run_id" do logger.run_started(run_status) - expect(event_log.read(flags, offset).any? do |e| + expect(event_log.read(flags, offset).any? { |e| e.source == Chef::Dist::PRODUCT && e.event_id == 10001 && e.string_inserts[0].include?(run_id) - end ).to be_truthy + } ).to be_truthy end it "writes run_completed event with event_id 10002 and contains the run_id and elapsed time" do logger.run_started(run_status) logger.run_completed(node) - expect(event_log.read(flags, offset).any? do |e| + expect(event_log.read(flags, offset).any? { |e| e.source == Chef::Dist::PRODUCT && e.event_id == 10002 && e.string_inserts[0].include?(run_id) && e.string_inserts[1].include?(elapsed_time.to_s) - end).to be_truthy + }).to be_truthy end it "writes run_failed event with event_id 10003 and contains the run_id, elapsed time, and exception info" do logger.run_started(run_status) logger.run_failed(mock_exception) - expect(event_log.read(flags, offset).any? do |e| + expect(event_log.read(flags, offset).any? { |e| e.source == Chef::Dist::PRODUCT && e.event_id == 10003 && e.string_inserts[0].include?(run_id) && e.string_inserts[1].include?(elapsed_time.to_s) && @@ -86,13 +86,13 @@ describe Chef::EventLoggers::WindowsEventLogger, :windows_only do e.string_inserts[3].include?(mock_exception.message) && e.string_inserts[4].include?(mock_exception.backtrace[0]) && e.string_inserts[4].include?(mock_exception.backtrace[1]) - end).to be_truthy + }).to be_truthy end it "writes run_failed event with event_id 10003 even when run_status is not set" do logger.run_failed(mock_exception) - expect(event_log.read(flags, offset).any? do |e| + expect(event_log.read(flags, offset).any? { |e| e.source == Chef::Dist::PRODUCT && e.event_id == 10003 && e.string_inserts[0].include?("UNKNOWN") && e.string_inserts[1].include?("UNKNOWN") && @@ -100,7 +100,7 @@ describe Chef::EventLoggers::WindowsEventLogger, :windows_only do e.string_inserts[3].include?(mock_exception.message) && e.string_inserts[4].include?(mock_exception.backtrace[0]) && e.string_inserts[4].include?(mock_exception.backtrace[1]) - end).to be_truthy + }).to be_truthy end end diff --git a/spec/functional/file_content_management/deploy_strategies_spec.rb b/spec/functional/file_content_management/deploy_strategies_spec.rb index 07991aa8bd..75d2422454 100644 --- a/spec/functional/file_content_management/deploy_strategies_spec.rb +++ b/spec/functional/file_content_management/deploy_strategies_spec.rb @@ -72,9 +72,9 @@ shared_examples_for "a content deploy strategy" do end let(:parent_inheritable_aces) do - inheritable_aces = parent_security_descriptor.dacl.select do |ace| + inheritable_aces = parent_security_descriptor.dacl.select { |ace| ace_inherits?(ace) - end + } end it "touches the file to create it (Windows)", :windows_only do @@ -91,9 +91,9 @@ shared_examples_for "a content deploy strategy" do # On certain windows systems like 2003 and Azure VMs there are some default # ACEs that are not inherited from parents. So filter out the parents before # comparing the aces - self_aces = security_descriptor.dacl.select do |ace| + self_aces = security_descriptor.dacl.select { |ace| ace_inherits?(ace) - end + } self_aces.each_with_index do |ace, index| expect(ace.mask).to eq(parent_aces[index].mask) @@ -109,7 +109,7 @@ shared_examples_for "a content deploy strategy" do let(:staging_file_path) do path = File.join(staging_dir, "cp-deploy-strategy-staging-file.txt") - File.open(path, "w+", 0600) { |f| f.print(staging_file_content) } + File.open(path, "w+", 0600) do |f| f.print(staging_file_content) end path end diff --git a/spec/functional/http/simple_spec.rb b/spec/functional/http/simple_spec.rb index 313fed064b..1ef809abfa 100644 --- a/spec/functional/http/simple_spec.rb +++ b/spec/functional/http/simple_spec.rb @@ -118,9 +118,9 @@ describe Chef::HTTP::Simple do end it "Logs the request and response and bodies for 400 response" do - expect do + expect { http_client.get("http://localhost:9000/bad_request") - end.to raise_error(Net::HTTPClientException) + }.to raise_error(Net::HTTPClientException) expect(@debug_log).to match(/400/) expect(@debug_log).to match(/HTTP Request Header Data/) expect(@debug_log).to match(/HTTP Status and Header Data/) @@ -131,9 +131,9 @@ describe Chef::HTTP::Simple do end it "Logs the request and response and bodies for 400 POST response" do - expect do + expect { http_client.post("http://localhost:9000/bad_request", "hithere") - end.to raise_error(Net::HTTPClientException) + }.to raise_error(Net::HTTPClientException) expect(@debug_log).to match(/400/) expect(@debug_log).to match(/HTTP Request Header Data/) expect(@debug_log).to match(/HTTP Status and Header Data/) diff --git a/spec/functional/knife/cookbook_delete_spec.rb b/spec/functional/knife/cookbook_delete_spec.rb index 7438ef9841..9b1ac93794 100644 --- a/spec/functional/knife/cookbook_delete_spec.rb +++ b/spec/functional/knife/cookbook_delete_spec.rb @@ -70,7 +70,7 @@ describe Chef::Knife::CookbookDelete do allow(knife.ui).to receive(:stdout).and_return(stdout) cb100_deleted = false - api.delete("/cookbooks/obsolete-cookbook/1.0.0", 200) { cb100_deleted = true; "[\"true\"]" } + api.delete("/cookbooks/obsolete-cookbook/1.0.0", 200) do cb100_deleted = true; "[\"true\"]" end knife.run @@ -86,7 +86,7 @@ describe Chef::Knife::CookbookDelete do allow(knife.ui).to receive(:stdout).and_return(stdout) cb100_deleted = false - api.delete("/cookbooks/obsolete-cookbook/1.0.0?purge=true", 200) { cb100_deleted = true; "[\"true\"]" } + api.delete("/cookbooks/obsolete-cookbook/1.0.0?purge=true", 200) do cb100_deleted = true; "[\"true\"]" end knife.run @@ -111,9 +111,9 @@ describe Chef::Knife::CookbookDelete do knife.config[:all] = true knife.config[:yes] = true cb100_deleted = cb110_deleted = cb120_deleted = nil - api.delete("/cookbooks/obsolete-cookbook/1.0.0", 200) { cb100_deleted = true; "[\"true\"]" } - api.delete("/cookbooks/obsolete-cookbook/1.1.0", 200) { cb110_deleted = true; "[\"true\"]" } - api.delete("/cookbooks/obsolete-cookbook/1.2.0", 200) { cb120_deleted = true; "[\"true\"]" } + api.delete("/cookbooks/obsolete-cookbook/1.0.0", 200) do cb100_deleted = true; "[\"true\"]" end + api.delete("/cookbooks/obsolete-cookbook/1.1.0", 200) do cb110_deleted = true; "[\"true\"]" end + api.delete("/cookbooks/obsolete-cookbook/1.2.0", 200) do cb120_deleted = true; "[\"true\"]" end knife.run expect(cb100_deleted).to be_truthy @@ -123,7 +123,7 @@ describe Chef::Knife::CookbookDelete do it "asks which version to delete and deletes that when not given the -a flag" do cb100_deleted = cb110_deleted = cb120_deleted = nil - api.delete("/cookbooks/obsolete-cookbook/1.0.0", 200) { cb100_deleted = true; "[\"true\"]" } + api.delete("/cookbooks/obsolete-cookbook/1.0.0", 200) do cb100_deleted = true; "[\"true\"]" end stdin, stdout = StringIO.new, StringIO.new allow(knife.ui).to receive(:stdin).and_return(stdin) allow(knife.ui).to receive(:stdout).and_return(stdout) @@ -136,9 +136,9 @@ describe Chef::Knife::CookbookDelete do it "deletes all versions of the cookbook when not given the -a flag and the user chooses to delete all" do cb100_deleted = cb110_deleted = cb120_deleted = nil - api.delete("/cookbooks/obsolete-cookbook/1.0.0", 200) { cb100_deleted = true; "[\"true\"]" } - api.delete("/cookbooks/obsolete-cookbook/1.1.0", 200) { cb110_deleted = true; "[\"true\"]" } - api.delete("/cookbooks/obsolete-cookbook/1.2.0", 200) { cb120_deleted = true; "[\"true\"]" } + api.delete("/cookbooks/obsolete-cookbook/1.0.0", 200) do cb100_deleted = true; "[\"true\"]" end + api.delete("/cookbooks/obsolete-cookbook/1.1.0", 200) do cb110_deleted = true; "[\"true\"]" end + api.delete("/cookbooks/obsolete-cookbook/1.2.0", 200) do cb120_deleted = true; "[\"true\"]" end stdin, stdout = StringIO.new("4\n"), StringIO.new allow(knife.ui).to receive(:stdin).and_return(stdin) diff --git a/spec/functional/mixin/from_file_spec.rb b/spec/functional/mixin/from_file_spec.rb index d8519b4185..8d3b7162c6 100644 --- a/spec/functional/mixin/from_file_spec.rb +++ b/spec/functional/mixin/from_file_spec.rb @@ -70,9 +70,9 @@ describe Chef::Mixin::FromFile do it "should fail on invalid data" do datum = TestData.new - expect do + expect { datum.from_file(INVALID_DATA) - end.to raise_error(NoMethodError) + }.to raise_error(NoMethodError) end it "should fail on nonexistant data" do diff --git a/spec/functional/notifications_spec.rb b/spec/functional/notifications_spec.rb index 87afbd8359..3d2c4c7026 100644 --- a/spec/functional/notifications_spec.rb +++ b/spec/functional/notifications_spec.rb @@ -32,15 +32,15 @@ describe "Notifications" do end it "should subscribe from one resource to another" do - log_resource = recipe.declare_resource(:log, "subscribed-log") do + log_resource = recipe.declare_resource(:log, "subscribed-log") { message "This is a log message" action :nothing subscribes :write, "package[vim]", :immediately - end + } - package_resource = recipe.declare_resource(:package, "vim") do + package_resource = recipe.declare_resource(:package, "vim") { action :install - end + } expect(log_resource).to receive(:run_action).with(:nothing, nil, nil).and_call_original @@ -53,15 +53,15 @@ describe "Notifications" do end it "should notify from one resource to another immediately" do - log_resource = recipe.declare_resource(:log, "log") do + log_resource = recipe.declare_resource(:log, "log") { message "This is a log message" action :write notifies :install, "package[vim]", :immediately - end + } - package_resource = recipe.declare_resource(:package, "vim") do + package_resource = recipe.declare_resource(:package, "vim") { action :nothing - end + } expect(log_resource).to receive(:run_action).with(:write, nil, nil).and_call_original update_action(log_resource) @@ -74,16 +74,16 @@ describe "Notifications" do end it "should notify from one resource to another before" do - log_resource = recipe.declare_resource(:log, "log") do + log_resource = recipe.declare_resource(:log, "log") { message "This is a log message" action :write notifies :install, "package[vim]", :before - end + } update_action(log_resource, 2) - package_resource = recipe.declare_resource(:package, "vim") do + package_resource = recipe.declare_resource(:package, "vim") { action :nothing - end + } actions = [] [ log_resource, package_resource ].each do |resource| @@ -110,15 +110,15 @@ describe "Notifications" do end it "should not notify from one resource to another before if the resource is not updated" do - log_resource = recipe.declare_resource(:log, "log") do + log_resource = recipe.declare_resource(:log, "log") { message "This is a log message" action :write notifies :install, "package[vim]", :before - end + } - package_resource = recipe.declare_resource(:package, "vim") do + package_resource = recipe.declare_resource(:package, "vim") { action :nothing - end + } actions = [] [ log_resource, package_resource ].each do |resource| @@ -144,15 +144,15 @@ describe "Notifications" do end it "should notify from one resource to another delayed" do - log_resource = recipe.declare_resource(:log, "log") do + log_resource = recipe.declare_resource(:log, "log") { message "This is a log message" action :write notifies :install, "package[vim]", :delayed - end + } - package_resource = recipe.declare_resource(:package, "vim") do + package_resource = recipe.declare_resource(:package, "vim") { action :nothing - end + } expect(log_resource).to receive(:run_action).with(:write, nil, nil).and_call_original update_action(log_resource) @@ -169,21 +169,21 @@ describe "Notifications" do it "subscribes to a resource defined in a ruby block" do r = recipe t = self - ruby_block = recipe.declare_resource(:ruby_block, "rblock") do + ruby_block = recipe.declare_resource(:ruby_block, "rblock") { block do - log_resource = r.declare_resource(:log, "log") do + log_resource = r.declare_resource(:log, "log") { message "This is a log message" action :write - end + } t.expect(log_resource).to t.receive(:run_action).with(:write, nil, nil).and_call_original t.update_action(log_resource) end - end + } - package_resource = recipe.declare_resource(:package, "vim") do + package_resource = recipe.declare_resource(:package, "vim") { action :nothing subscribes :install, "log[log]", :delayed - end + } # RubyBlock needs to be able to run for our lazy examples to work - and it alone cannot affect the system expect(ruby_block).to receive(:provider_for_action).and_call_original @@ -198,21 +198,21 @@ describe "Notifications" do it "notifies from inside a ruby_block to a resource defined outside" do r = recipe t = self - ruby_block = recipe.declare_resource(:ruby_block, "rblock") do + ruby_block = recipe.declare_resource(:ruby_block, "rblock") { block do - log_resource = r.declare_resource(:log, "log") do + log_resource = r.declare_resource(:log, "log") { message "This is a log message" action :write notifies :install, "package[vim]", :immediately - end + } t.expect(log_resource).to t.receive(:run_action).with(:write, nil, nil).and_call_original t.update_action(log_resource) end - end + } - package_resource = recipe.declare_resource(:package, "vim") do + package_resource = recipe.declare_resource(:package, "vim") { action :nothing - end + } # RubyBlock needs to be able to run for our lazy examples to work - and it alone cannot affect the system expect(ruby_block).to receive(:provider_for_action).and_call_original diff --git a/spec/functional/provider/remote_file/cache_control_data_spec.rb b/spec/functional/provider/remote_file/cache_control_data_spec.rb index c56787e7e5..a5d938418e 100755 --- a/spec/functional/provider/remote_file/cache_control_data_spec.rb +++ b/spec/functional/provider/remote_file/cache_control_data_spec.rb @@ -81,9 +81,9 @@ describe Chef::Provider::RemoteFile::CacheControlData do let(:uri) { uri_exceeds_file_system_limit } it "writes data to the cache" do - expect do + expect { cache_control_data.save - end.not_to raise_error + }.not_to raise_error end it "writes the data to the cache and the same data can be read back" do diff --git a/spec/functional/provider/whyrun_safe_ruby_block_spec.rb b/spec/functional/provider/whyrun_safe_ruby_block_spec.rb index 1bb36f2cf6..409b084186 100644 --- a/spec/functional/provider/whyrun_safe_ruby_block_spec.rb +++ b/spec/functional/provider/whyrun_safe_ruby_block_spec.rb @@ -38,12 +38,12 @@ describe Chef::Resource::WhyrunSafeRubyBlock do describe "when testing the resource" do let(:new_resource) do r = Chef::Resource::WhyrunSafeRubyBlock.new("reload all", run_context) - r.block { $evil_global_evil_laugh = :mwahahaha } + r.block do $evil_global_evil_laugh = :mwahahaha end r end it "updates the evil laugh, even in why-run mode" do - Array(new_resource.action).each { |action| new_resource.run_action(action) } + Array(new_resource.action).each do |action| new_resource.run_action(action) end expect($evil_global_evil_laugh).to eq(:mwahahaha) expect(new_resource).to be_updated end diff --git a/spec/functional/resource/apt_package_spec.rb b/spec/functional/resource/apt_package_spec.rb index ad4378b83a..6145ea598d 100644 --- a/spec/functional/resource/apt_package_spec.rb +++ b/spec/functional/resource/apt_package_spec.rb @@ -187,9 +187,9 @@ describe Chef::Resource::AptPackage, metadata do end it "raises a reasonable error for action :install" do - expect do + expect { package_resource.run_action(:install) - end.to raise_error(Mixlib::ShellOut::ShellCommandFailed) + }.to raise_error(Mixlib::ShellOut::ShellCommandFailed) end end diff --git a/spec/functional/resource/chocolatey_package_spec.rb b/spec/functional/resource/chocolatey_package_spec.rb index c5590b2d88..eccea739e6 100644 --- a/spec/functional/resource/chocolatey_package_spec.rb +++ b/spec/functional/resource/chocolatey_package_spec.rb @@ -33,7 +33,7 @@ describe Chef::Resource::ChocolateyPackage, :windows_only, :choco_installed do end context "installing a package" do - after { remove_package } + after do remove_package end it "installs the latest version" do subject.run_action(:install) @@ -78,7 +78,7 @@ describe Chef::Resource::ChocolateyPackage, :windows_only, :choco_installed do end context "upgrading a package" do - after { remove_package } + after do remove_package end it "upgrades to a specific version" do subject.version "1.0" diff --git a/spec/functional/resource/cron_spec.rb b/spec/functional/resource/cron_spec.rb index 16b0d2645c..e5bc166958 100644 --- a/spec/functional/resource/cron_spec.rb +++ b/spec/functional/resource/cron_spec.rb @@ -86,7 +86,7 @@ describe Chef::Resource::Cron, :requires_root, :unix_only do end it "should create exactly one crontab entry" do - 5.times { new_resource.run_action(:create) } + 5.times do new_resource.run_action(:create) end cron_should_exists(new_resource.name, new_resource.command) end end diff --git a/spec/functional/resource/dsc_resource_spec.rb b/spec/functional/resource/dsc_resource_spec.rb index 8f5ba5fd9e..58b915f802 100644 --- a/spec/functional/resource/dsc_resource_spec.rb +++ b/spec/functional/resource/dsc_resource_spec.rb @@ -67,9 +67,9 @@ describe Chef::Resource::DscResource, :windows_powershell_dsc_only do it "converges the resource if it is not converged" do new_resource.run_action(:run) - contents = File.open(tmp_file_name, "rb:bom|UTF-16LE") do |f| + contents = File.open(tmp_file_name, "rb:bom|UTF-16LE") { |f| f.read.encode("UTF-8") - end + } expect(contents).to eq(test_text) expect(new_resource).to be_updated end diff --git a/spec/functional/resource/execute_spec.rb b/spec/functional/resource/execute_spec.rb index 3e57795f73..bec056fed2 100644 --- a/spec/functional/resource/execute_spec.rb +++ b/spec/functional/resource/execute_spec.rb @@ -29,7 +29,7 @@ describe Chef::Resource::Execute do describe "when guard is ruby block" do it "guard can still run" do - resource.only_if { true } + resource.only_if do true end resource.run_action(:run) expect(resource).to be_updated_by_last_action end diff --git a/spec/functional/resource/file_spec.rb b/spec/functional/resource/file_spec.rb index 291311f3e2..197e8c1469 100644 --- a/spec/functional/resource/file_spec.rb +++ b/spec/functional/resource/file_spec.rb @@ -140,7 +140,7 @@ describe Chef::Resource::File do context "and the target file exists and has the correct content" do before(:each) do - File.open(path, "w") { |f| f.print expected_content } + File.open(path, "w") do |f| f.print expected_content end @expected_checksum = sha256_checksum(path) diff --git a/spec/functional/resource/git_spec.rb b/spec/functional/resource/git_spec.rb index e978041038..a10bcad2e3 100644 --- a/spec/functional/resource/git_spec.rb +++ b/spec/functional/resource/git_spec.rb @@ -76,7 +76,7 @@ describe Chef::Resource::Git, requires_git: true do Chef::Log.level = :warn # silence git command live streams @old_file_cache_path = Chef::Config[:file_cache_path] shell_out!("git clone \"#{git_bundle_repo}\" example", cwd: origin_repo_dir) - File.open("#{origin_repo}/.git/config", "a+") { |f| f.print(git_user_config) } + File.open("#{origin_repo}/.git/config", "a+") do |f| f.print(git_user_config) end Chef::Config[:file_cache_path] = file_cache_path end diff --git a/spec/functional/resource/link_spec.rb b/spec/functional/resource/link_spec.rb index 4593dc1971..996047e342 100644 --- a/spec/functional/resource/link_spec.rb +++ b/spec/functional/resource/link_spec.rb @@ -281,7 +281,7 @@ describe Chef::Resource::Link do # Writing to one hardlinked file should cause both # to have the new value. expect(IO.read(to)).to eq(IO.read(target_file)) - File.open(to, "w") { |file| file.write("wowzers") } + File.open(to, "w") do |file| file.write("wowzers") end expect(IO.read(target_file)).to eq("wowzers") end it "marks the resource updated" do @@ -306,7 +306,7 @@ describe Chef::Resource::Link do # Writing to one hardlinked file should cause both # to have the new value. expect(IO.read(to)).to eq(IO.read(target_file)) - File.open(to, "w") { |file| file.write("wowzers") } + File.open(to, "w") do |file| file.write("wowzers") end expect(IO.read(target_file)).to eq("wowzers") end it "does not mark the resource updated" do @@ -355,7 +355,7 @@ describe Chef::Resource::Link do before(:each) do resource.owner(test_user) @other_target = File.join(test_file_dir, make_tmpname("other_spec")) - File.open(@other_target, "w") { |file| file.write("eek") } + File.open(@other_target, "w") do |file| file.write("eek") end symlink(@other_target, target_file) chown(target_file, test_user) expect(symlink?(target_file)).to be_truthy @@ -465,7 +465,7 @@ describe Chef::Resource::Link do context "to a file that exists" do before(:each) do @other_target = File.join(test_file_dir, make_tmpname("other_spec")) - File.open(@other_target, "w") { |file| file.write("eek") } + File.open(@other_target, "w") do |file| file.write("eek") end symlink(@other_target, to) expect(symlink?(to)).to be_truthy expect(readlink(to)).to eq(canonicalize(@other_target)) @@ -646,7 +646,7 @@ describe Chef::Resource::Link do context "to a real file" do before(:each) do @other_target = File.join(test_file_dir, make_tmpname("other_spec")) - File.open(@other_target, "w") { |file| file.write("eek") } + File.open(@other_target, "w") do |file| file.write("eek") end symlink(@other_target, to) expect(symlink?(to)).to be_truthy expect(readlink(to)).to eq(canonicalize(@other_target)) diff --git a/spec/functional/resource/msu_package_spec.rb b/spec/functional/resource/msu_package_spec.rb index d6811d99e7..8f28def693 100644 --- a/spec/functional/resource/msu_package_spec.rb +++ b/spec/functional/resource/msu_package_spec.rb @@ -40,7 +40,7 @@ describe Chef::Resource::MsuPackage, :win2012r2_only do end context "installing package" do - after { remove_package } + after do remove_package end it "installs the package successfully" do subject.run_action(:install) diff --git a/spec/functional/resource/powershell_script_spec.rb b/spec/functional/resource/powershell_script_spec.rb index 74ece0d33c..39c614ab91 100644 --- a/spec/functional/resource/powershell_script_spec.rb +++ b/spec/functional/resource/powershell_script_spec.rb @@ -255,7 +255,7 @@ describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do it "raises an error when given a block and a guard_interpreter" do resource.guard_interpreter :sh - resource.only_if { true } + resource.only_if do true end expect { resource.should_skip?(:run) }.to raise_error(ArgumentError, /guard_interpreter does not support blocks/) end diff --git a/spec/functional/resource/reboot_spec.rb b/spec/functional/resource/reboot_spec.rb index 5489dc1c72..5b8752f06f 100644 --- a/spec/functional/resource/reboot_spec.rb +++ b/spec/functional/resource/reboot_spec.rb @@ -80,9 +80,9 @@ describe Chef::Resource::Reboot do it "should have modified the run context correctly" do # this doesn't actually test the flow of Chef::Client#do_run, unfortunately. - expect do + expect { resource.run_action(:reboot_now) - end.to throw_symbol(:end_client_run_early) + }.to throw_symbol(:end_client_run_early) test_reboot_action(resource) end diff --git a/spec/functional/resource/remote_directory_spec.rb b/spec/functional/resource/remote_directory_spec.rb index c25e51cf2a..58b2ed70ec 100644 --- a/spec/functional/resource/remote_directory_spec.rb +++ b/spec/functional/resource/remote_directory_spec.rb @@ -136,8 +136,8 @@ describe Chef::Resource::RemoteDirectory do FileUtils.mkdir_p(File.join(path, "remotesubdir")) modified_file = File.join(path, "remote_dir_file1.txt") modified_subdir_file = File.join(path, "remotesubdir", "remote_subdir_file1.txt") - File.open(modified_file, "a") { |f| f.puts "santa is real" } - File.open(modified_subdir_file, "a") { |f| f.puts "so is rudolph" } + File.open(modified_file, "a") do |f| f.puts "santa is real" end + File.open(modified_subdir_file, "a") do |f| f.puts "so is rudolph" end modified_file_checksum = sha256_checksum(modified_file) modified_subdir_file_checksum = sha256_checksum(modified_subdir_file) diff --git a/spec/functional/resource/windows_certificate_spec.rb b/spec/functional/resource/windows_certificate_spec.rb index 9b79de6a77..fa14c5b59b 100644 --- a/spec/functional/resource/windows_certificate_spec.rb +++ b/spec/functional/resource/windows_certificate_spec.rb @@ -93,7 +93,7 @@ describe Chef::Resource::WindowsCertificate, :windows_only, :appveyor_only do end end - after { cleanup(store) } + after do cleanup(store) end subject(:win_certificate) do new_resource.store_name = store @@ -453,7 +453,7 @@ describe Chef::Resource::WindowsCertificate, :windows_only, :appveyor_only do win_certificate.source = cer_path win_certificate.run_action(:create) end - before { win_certificate.source = tests_thumbprint } + before do win_certificate.source = tests_thumbprint end it "Initial check if certificate is present" do expect(no_of_certificates).to eq(1) end diff --git a/spec/functional/resource/windows_package_spec.rb b/spec/functional/resource/windows_package_spec.rb index bc508dc526..faad96e9e1 100644 --- a/spec/functional/resource/windows_package_spec.rb +++ b/spec/functional/resource/windows_package_spec.rb @@ -70,7 +70,7 @@ describe Chef::Resource::WindowsPackage, :windows_only, :volatile do subject { Chef::Resource::WindowsPackage.new(pkg_name, run_context) } context "multiple versions and a version given to remove" do - before { subject.version("8.0.56336") } + before do subject.version("8.0.56336") end it "removes specified version" do subject.run_action(:remove) @@ -121,7 +121,7 @@ describe Chef::Resource::WindowsPackage, :windows_only, :volatile do end describe "package version and installer type" do - after { subject.run_action(:remove) } + after do subject.run_action(:remove) end context "null soft" do let(:pkg_name) { "Ultra Defragmenter" } diff --git a/spec/functional/resource/windows_path_spec.rb b/spec/functional/resource/windows_path_spec.rb index 912abe6b24..1d08d6113c 100644 --- a/spec/functional/resource/windows_path_spec.rb +++ b/spec/functional/resource/windows_path_spec.rb @@ -35,7 +35,7 @@ describe Chef::Resource::WindowsPath, :windows_only do end describe "adding path" do - after { remove_path } + after do remove_path end it "appends the user given path in the Environment variable Path" do subject.run_action(:add) @@ -44,7 +44,7 @@ describe Chef::Resource::WindowsPath, :windows_only do end describe "removing path" do - before { add_path } + before do add_path end it "removes the user given path from the Environment variable Path" do subject.run_action(:remove) diff --git a/spec/functional/resource/windows_service_spec.rb b/spec/functional/resource/windows_service_spec.rb index 999b235df1..9d5459caac 100644 --- a/spec/functional/resource/windows_service_spec.rb +++ b/spec/functional/resource/windows_service_spec.rb @@ -59,7 +59,7 @@ describe Chef::Resource::WindowsService, :windows_only, :system_windows_service_ let(:service_resource) do r = Chef::Resource::WindowsService.new(service_params[:service_name], run_context) - %i{run_as_user run_as_password}.each { |prop| r.send(prop, service_params[prop]) } + %i{run_as_user run_as_password}.each do |prop| r.send(prop, service_params[prop]) end r end diff --git a/spec/functional/resource/windows_task_spec.rb b/spec/functional/resource/windows_task_spec.rb index fa51ad3f8a..3365d37a34 100644 --- a/spec/functional/resource/windows_task_spec.rb +++ b/spec/functional/resource/windows_task_spec.rb @@ -32,7 +32,7 @@ describe Chef::Resource::WindowsTask, :windows_only do end describe "action :create" do - after { delete_task } + after do delete_task end context "when command is with arguments" do subject do new_resource = Chef::Resource::WindowsTask.new(task_name, run_context) @@ -1340,7 +1340,7 @@ describe Chef::Resource::WindowsTask, :windows_only do context "task_name with parent folder" do describe "task_name with path '\\foo\\chef-client-functional-test' " do let(:task_name) { "\\foo\\chef-client-functional-test" } - after { delete_task } + after do delete_task end subject do new_resource = Chef::Resource::WindowsTask.new(task_name, run_context) new_resource.command task_name @@ -1366,7 +1366,7 @@ describe Chef::Resource::WindowsTask, :windows_only do describe "task_name with path '\\foo\\bar\\chef-client-functional-test' " do let(:task_name) { "\\foo\\bar\\chef-client-functional-test" } - after { delete_task } + after do delete_task end subject do new_resource = Chef::Resource::WindowsTask.new(task_name, run_context) new_resource.command task_name @@ -1392,7 +1392,7 @@ describe Chef::Resource::WindowsTask, :windows_only do end describe "priority" do - after { delete_task } + after do delete_task end subject do new_resource = Chef::Resource::WindowsTask.new(task_name, run_context) new_resource.command task_name @@ -1494,7 +1494,7 @@ describe Chef::Resource::WindowsTask, :windows_only do end describe "Examples of idempotent checks for each frequency" do - after { delete_task } + after do delete_task end context "For frequency :once" do subject do new_resource = Chef::Resource::WindowsTask.new(task_name, run_context) @@ -1853,7 +1853,7 @@ describe Chef::Resource::WindowsTask, :windows_only do end describe "action :run" do - after { delete_task } + after do delete_task end subject do new_resource = Chef::Resource::WindowsTask.new(task_name, run_context) @@ -1873,7 +1873,7 @@ describe Chef::Resource::WindowsTask, :windows_only do end describe "action :end", :volatile do - after { delete_task } + after do delete_task end subject do new_resource = Chef::Resource::WindowsTask.new(task_name, run_context) @@ -1894,7 +1894,7 @@ describe Chef::Resource::WindowsTask, :windows_only do describe "action :enable" do let(:task_name) { "chef-client-functional-test-enable" } - after { delete_task } + after do delete_task end subject do new_resource = Chef::Resource::WindowsTask.new(task_name, run_context) @@ -1917,7 +1917,7 @@ describe Chef::Resource::WindowsTask, :windows_only do describe "action :disable" do let(:task_name) { "chef-client-functional-test-disable" } - after { delete_task } + after do delete_task end subject do new_resource = Chef::Resource::WindowsTask.new(task_name, run_context) @@ -1936,7 +1936,7 @@ describe Chef::Resource::WindowsTask, :windows_only do end describe "action :change" do - after { delete_task } + after do delete_task end subject do new_resource = Chef::Resource::WindowsTask.new(task_name, run_context) new_resource.command task_name diff --git a/spec/functional/resource/zypper_package_spec.rb b/spec/functional/resource/zypper_package_spec.rb index c95c3575ca..f7067aad81 100644 --- a/spec/functional/resource/zypper_package_spec.rb +++ b/spec/functional/resource/zypper_package_spec.rb @@ -64,7 +64,7 @@ describe Chef::Resource::ZypperPackage, :requires_root, :suse_only do end context "installing a package" do - after { remove_package } + after do remove_package end it "installs the latest version" do zypper_package.run_action(:install) expect(zypper_package.updated_by_last_action?).to be true diff --git a/spec/functional/run_lock_spec.rb b/spec/functional/run_lock_spec.rb index d9a8bd2d0e..d368d837cf 100644 --- a/spec/functional/run_lock_spec.rb +++ b/spec/functional/run_lock_spec.rb @@ -34,8 +34,8 @@ describe Chef::RunLock do let(:lockfile) { "#{random_temp_root}/this/long/path/does/not/exist/chef-client-running.pid" } # make sure to start with a clean slate. - before(:each) { log_event("rm -rf before"); FileUtils.rm_r(random_temp_root) if File.exist?(random_temp_root) } - after(:each) { log_event("rm -rf after"); FileUtils.rm_r(random_temp_root) if File.exist?(random_temp_root) } + before(:each) do log_event("rm -rf before"); FileUtils.rm_r(random_temp_root) if File.exist?(random_temp_root) end + after(:each) do log_event("rm -rf after"); FileUtils.rm_r(random_temp_root) if File.exist?(random_temp_root) end def log_event(message, time = Time.now.strftime("%H:%M:%S.%L")) events << [ message, time ] @@ -85,7 +85,7 @@ describe Chef::RunLock do context "when the lockfile does not already exist" do context "when a client creates the lockfile but has not yet acquired the lock" do - before { p1.run_to("created lock") } + before do p1.run_to("created lock") end shared_context "second client gets the lock" do it "the lockfile is created" do log_event("lockfile exists? #{File.exist?(lockfile)}") @@ -106,7 +106,7 @@ describe Chef::RunLock do end context "and a second client gets the lock" do - before { p2.run_to("acquired lock") } + before do p2.run_to("acquired lock") end it "the first client does not get the lock until the second finishes" do p1.run_to("acquired lock") do p2.run_to_completion @@ -128,13 +128,13 @@ describe Chef::RunLock do end context "and the second client has created the lockfile but not yet acquired the lock" do - before { p2.run_to("created lock") } + before do p2.run_to("created lock") end include_context "second client gets the lock" end end context "when a client acquires the lock but has not yet saved the pid" do - before { p1.run_to("acquired lock") } + before do p1.run_to("acquired lock") end it "the lockfile is created" do log_event("lockfile exists? #{File.exist?(lockfile)}") @@ -182,7 +182,7 @@ describe Chef::RunLock do end context "when a client acquires the lock and saves the pid" do - before { p1.run_to("saved pid") } + before do p1.run_to("saved pid") end it "the lockfile is created" do expect(File.exist?(lockfile)).to be_truthy @@ -229,7 +229,7 @@ describe Chef::RunLock do end context "when a client acquires a lock and exits normally" do - before { p1.run_to_completion } + before do p1.run_to_completion end it "the lockfile remains" do expect(File.exist?(lockfile)).to be_truthy @@ -258,20 +258,20 @@ describe Chef::RunLock do run_lock = Chef::RunLock.new(lockfile) from_tests, to_fork = IO.pipe from_fork, to_tests = IO.pipe - p1 = fork do + p1 = fork { expect(run_lock.test).to eq(true) to_tests.puts "lock acquired" # Wait for the test to tell us we can exit before exiting from_tests.readline exit! 0 - end + } wait_on_lock(from_fork) - p2 = fork do + p2 = fork { expect(run_lock.test).to eq(false) exit! 0 - end + } pid, exit_status = Process.waitpid2(p2) expect(exit_status).to eq(0) @@ -284,13 +284,13 @@ describe Chef::RunLock do run_lock = Chef::RunLock.new(lockfile) from_tests, to_fork = IO.pipe from_fork, to_tests = IO.pipe - p1 = fork do + p1 = fork { run_lock.acquire to_tests.puts "lock acquired" # Wait for the test to tell us we can exit before exiting from_tests.readline exit! 0 - end + } wait_on_lock(from_fork) expect(run_lock.test).to eq(false) @@ -437,7 +437,7 @@ describe Chef::RunLock do def start example.log_event("#{name}.start") - @pid = fork do + @pid = fork { begin Timeout.timeout(CLIENT_PROCESS_TIMEOUT) do run_lock = TestRunLock.new(example.lockfile) @@ -453,7 +453,7 @@ describe Chef::RunLock do fire_event($!.message.lines.join(" // ")) raise end - end + } example.log_event("#{name}.start forked (pid #{pid})") end diff --git a/spec/functional/shell_spec.rb b/spec/functional/shell_spec.rb index dd0455fc9e..b68fef023a 100644 --- a/spec/functional/shell_spec.rb +++ b/spec/functional/shell_spec.rb @@ -105,11 +105,11 @@ describe Shell do end it "sets the log_level from the command line" do - output, exitstatus = run_chef_shell_with("-lfatal") do |out, keyboard| + output, exitstatus = run_chef_shell_with("-lfatal") { |out, keyboard| show_log_level_code = %q[puts "===#{Chef::Log.level}==="] keyboard.puts(show_log_level_code) read_until(out, show_log_level_code) - end + } expect(output).to include("===fatal===") expect(exitstatus).to eq(0) end @@ -122,22 +122,22 @@ describe Shell do end it "should be able to use the API" do - output, exitstatus = run_chef_shell_with("-s") do |out, keyboard| + output, exitstatus = run_chef_shell_with("-s") { |out, keyboard| simple_api_get = "api.get('data')" keyboard.puts(simple_api_get) read_until(out, simple_api_get) - end + } expect(output).to include("{}") expect(exitstatus).to eq(0) end end it "sets the override_runlist from the command line" do - output, exitstatus = run_chef_shell_with("-o 'override::foo,override::bar'") do |out, keyboard| + output, exitstatus = run_chef_shell_with("-o 'override::foo,override::bar'") { |out, keyboard| show_recipes_code = %q[puts "#{node["recipes"].inspect}"] keyboard.puts(show_recipes_code) read_until(out, show_recipes_code) - end + } expect(output).to include(%q{["override::foo", "override::bar"]}) expect(exitstatus).to eq(0) end diff --git a/spec/functional/tiny_server_spec.rb b/spec/functional/tiny_server_spec.rb index 1ec56bd490..eb6483a859 100644 --- a/spec/functional/tiny_server_spec.rb +++ b/spec/functional/tiny_server_spec.rb @@ -44,7 +44,7 @@ describe TinyServer::API do it "creates a route for a request with a block" do block_called = false - @api.get("/bar/baz", 200) { block_called = true; "hello barbaz" } + @api.get("/bar/baz", 200) do block_called = true; "hello barbaz" end response = @api.call("REQUEST_METHOD" => "GET", "REQUEST_URI" => "http://localhost:1974/bar/baz") expect(response).to eq([200, { "Content-Type" => "application/json" }, [ "hello barbaz" ]]) expect(block_called).to be_truthy diff --git a/spec/functional/win32/security_spec.rb b/spec/functional/win32/security_spec.rb index a72088a079..c38d1d9571 100644 --- a/spec/functional/win32/security_spec.rb +++ b/spec/functional/win32/security_spec.rb @@ -51,9 +51,9 @@ describe "Chef::Win32::Security", :windows_only do end it "has_admin_privileges? returns false" do - has_admin_privileges = with_user_context(user, password, domain, :local) do + has_admin_privileges = with_user_context(user, password, domain, :local) { Chef::ReservedNames::Win32::Security.has_admin_privileges? - end + } expect(has_admin_privileges).to eq(false) end end diff --git a/spec/functional/win32/versions_spec.rb b/spec/functional/win32/versions_spec.rb index 19bd0e3875..2fee52449f 100644 --- a/spec/functional/win32/versions_spec.rb +++ b/spec/functional/win32/versions_spec.rb @@ -59,7 +59,7 @@ describe "Chef::ReservedNames::Win32::Version", :windows_only do context "Win32 version object" do it "should have have one method for each marketing version" do versions = 0 - for_each_windows_version { versions += 1 } + for_each_windows_version do versions += 1 end expect(versions).to be > 0 expect(versions).to eq(Chef::ReservedNames::Win32::Version::WIN_VERSIONS.length) end diff --git a/spec/integration/client/client_spec.rb b/spec/integration/client/client_spec.rb index 68cfd015ab..a6930e8231 100644 --- a/spec/integration/client/client_spec.rb +++ b/spec/integration/client/client_spec.rb @@ -48,7 +48,7 @@ describe "chef-client" do let(:chef_solo) { "bundle exec #{Chef::Dist::SOLOEXEC} --legacy-mode --minimal-ohai" } when_the_repository "has a cookbook with a no-op recipe" do - before { file "cookbooks/x/recipes/default.rb", "" } + before do file "cookbooks/x/recipes/default.rb", "" end it "should complete with success" do file "config/client.rb", <<~EOM @@ -93,7 +93,7 @@ describe "chef-client" do end context "and a config file under .chef/knife.rb" do - before { file ".chef/knife.rb", "xxx.xxx" } + before do file ".chef/knife.rb", "xxx.xxx" end it "should load .chef/knife.rb when -z is specified" do result = shell_out("#{chef_client} -z -o 'x::default'", cwd: path_to("")) diff --git a/spec/integration/client/exit_code_spec.rb b/spec/integration/client/exit_code_spec.rb index 37999ab431..18f44a3e34 100644 --- a/spec/integration/client/exit_code_spec.rb +++ b/spec/integration/client/exit_code_spec.rb @@ -57,7 +57,7 @@ describe "chef-client" do context "with a recipe" do context "which throws an error" do - before { file "cookbooks/x/recipes/default.rb", "raise 'BOOM'" } + before do file "cookbooks/x/recipes/default.rb", "raise 'BOOM'" end it "exits with GENERIC_FAILURE, 1" do setup_client_rb @@ -66,7 +66,7 @@ describe "chef-client" do end context "with a recipe which calls Chef::Application.fatal with a non-RFC exit code" do - before { file "cookbooks/x/recipes/default.rb", "Chef::Application.fatal!('BOOM', 123)" } + before do file "cookbooks/x/recipes/default.rb", "Chef::Application.fatal!('BOOM', 123)" end it "exits with the GENERIC_FAILURE exit code, 1" do setup_client_rb @@ -75,7 +75,7 @@ describe "chef-client" do end context "with a recipe which calls Chef::Application.exit with a non-RFC exit code" do - before { file "cookbooks/x/recipes/default.rb", "Chef::Application.exit!('BOOM', 231)" } + before do file "cookbooks/x/recipes/default.rb", "Chef::Application.exit!('BOOM', 231)" end it "exits with the GENERIC_FAILURE exit code, 1" do setup_client_rb diff --git a/spec/integration/knife/chef_repo_path_spec.rb b/spec/integration/knife/chef_repo_path_spec.rb index 919741f930..852438d4db 100644 --- a/spec/integration/knife/chef_repo_path_spec.rb +++ b/spec/integration/knife/chef_repo_path_spec.rb @@ -178,21 +178,21 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is at the top level" do - before { cwd "." } + before do cwd "." end it "knife list --local -Rfp fails" do knife("list --local -Rfp").should_fail(error_rel_path_outside_repo) end end context "when cwd is inside the data_bags directory" do - before { cwd "data_bags" } + before do cwd "data_bags" end it "knife list --local -Rfp fails" do knife("list --local -Rfp").should_fail(error_rel_path_outside_repo) end end context "when cwd is inside chef_repo2" do - before { cwd "chef_repo2" } + before do cwd "chef_repo2" end it "knife list --local -Rfp lists everything" do knife("list --local -Rfp").should_succeed <<~EOM clients/ @@ -216,7 +216,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside data_bags2" do - before { cwd "data_bags2" } + before do cwd "data_bags2" end it "knife list --local -Rfp lists data bags" do knife("list --local -Rfp").should_succeed <<~EOM bag2/ @@ -237,7 +237,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is at the top level" do - before { cwd "." } + before do cwd "." end it "knife list --local -Rfp lists everything" do knife("list --local -Rfp").should_succeed <<~EOM clients/ @@ -261,21 +261,21 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside the data_bags directory" do - before { cwd "data_bags" } + before do cwd "data_bags" end it "knife list --local -Rfp fails" do knife("list --local -Rfp").should_fail(error_rel_path_outside_repo) end end context "when cwd is inside chef_repo2" do - before { cwd "chef_repo2" } + before do cwd "chef_repo2" end it "knife list -Rfp fails" do knife("list --local -Rfp").should_fail(error_rel_path_outside_repo) end end context "when cwd is inside data_bags2" do - before { cwd "data_bags2" } + before do cwd "data_bags2" end it "knife list --local -Rfp lists data bags" do knife("list --local -Rfp").should_succeed <<~EOM bag2/ @@ -294,21 +294,21 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is at the top level" do - before { cwd "." } + before do cwd "." end it "knife list --local -Rfp fails" do knife("list --local -Rfp").should_fail(error_rel_path_outside_repo) end end context "when cwd is inside the data_bags directory" do - before { cwd "data_bags" } + before do cwd "data_bags" end it "knife list --local -Rfp fails" do knife("list --local -Rfp").should_fail(error_rel_path_outside_repo) end end context "when cwd is inside chef_repo2" do - before { cwd "chef_repo2" } + before do cwd "chef_repo2" end it "knife list --local -Rfp lists everything" do knife("list --local -Rfp").should_succeed <<~EOM clients/ @@ -332,7 +332,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside chef_repo2/data_bags" do - before { cwd "chef_repo2/data_bags" } + before do cwd "chef_repo2/data_bags" end it "knife list --local -Rfp lists data bags" do knife("list --local -Rfp").should_succeed <<~EOM bag3/ @@ -514,14 +514,14 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is at the top level" do - before { cwd "." } + before do cwd "." end it "knife list --local -Rfp fails" do knife("list --local -Rfp").should_fail(error_rel_path_outside_repo) end end context "when cwd is inside the data_bags directory" do - before { cwd "data_bags" } + before do cwd "data_bags" end it "knife list --local -Rfp lists data bags" do knife("list --local -Rfp").should_succeed <<~EOM bag/ @@ -533,7 +533,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside chef_repo2" do - before { cwd "chef_repo2" } + before do cwd "chef_repo2" end it "knife list --local -Rfp lists everything" do knife("list --local -Rfp").should_succeed <<~EOM clients/ @@ -566,7 +566,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside data_bags2" do - before { cwd "data_bags2" } + before do cwd "data_bags2" end it "knife list --local -Rfp lists data bags" do knife("list --local -Rfp").should_succeed <<~EOM bag/ @@ -590,7 +590,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is at the top level" do - before { cwd "." } + before do cwd "." end it "knife list --local -Rfp lists everything" do knife("list --local -Rfp").should_succeed <<~EOM clients/ @@ -623,7 +623,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside the data_bags directory" do - before { cwd "data_bags" } + before do cwd "data_bags" end it "knife list --local -Rfp lists data bags" do knife("list --local -Rfp").should_succeed <<~EOM bag/ @@ -635,7 +635,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside chef_repo2" do - before { cwd "chef_repo2" } + before do cwd "chef_repo2" end it "knife list --local -Rfp lists everything" do knife("list --local -Rfp").should_succeed <<~EOM clients/ @@ -668,7 +668,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside chef_repo2/data_bags" do - before { cwd "chef_repo2/data_bags" } + before do cwd "chef_repo2/data_bags" end it "knife list --local -Rfp lists data bags" do knife("list --local -Rfp").should_succeed <<~EOM bag/ @@ -690,21 +690,21 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is at the top level" do - before { cwd "." } + before do cwd "." end it "knife list --local -Rfp fails" do knife("list --local -Rfp").should_fail(error_rel_path_outside_repo) end end context "when cwd is inside the data_bags directory" do - before { cwd "data_bags" } + before do cwd "data_bags" end it "knife list --local -Rfp fails" do knife("list --local -Rfp").should_fail(error_rel_path_outside_repo) end end context "when cwd is inside chef_repo2" do - before { cwd "chef_repo2" } + before do cwd "chef_repo2" end it "knife list --local -Rfp lists everything" do knife("list --local -Rfp").should_succeed <<~EOM clients/ @@ -728,7 +728,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside chef_repo2/data_bags" do - before { cwd "chef_repo2/data_bags" } + before do cwd "chef_repo2/data_bags" end it "knife list --local -Rfp lists data bags" do knife("list --local -Rfp").should_succeed <<~EOM bag3/ @@ -751,7 +751,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is at the top level" do - before { cwd "." } + before do cwd "." end it "knife list --local -Rfp lists everything" do knife("list --local -Rfp").should_succeed <<~EOM clients/ @@ -784,7 +784,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside the data_bags directory" do - before { cwd "data_bags" } + before do cwd "data_bags" end it "knife list --local -Rfp lists data bags" do knife("list --local -Rfp").should_succeed <<~EOM bag/ @@ -796,7 +796,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside chef_repo2" do - before { cwd "chef_repo2" } + before do cwd "chef_repo2" end it "knife list --local -Rfp lists everything" do knife("list --local -Rfp").should_succeed <<~EOM clients/ @@ -829,7 +829,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside chef_repo2/data_bags" do - before { cwd "chef_repo2/data_bags" } + before do cwd "chef_repo2/data_bags" end it "knife list --local -Rfp lists data bags" do knife("list --local -Rfp").should_succeed <<~EOM bag/ @@ -851,14 +851,14 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is at the top level" do - before { cwd "." } + before do cwd "." end it "knife list --local -Rfp fails" do knife("list --local -Rfp").should_fail(error_rel_path_outside_repo) end end context "when cwd is inside the data_bags directory" do - before { cwd "data_bags" } + before do cwd "data_bags" end it "knife list --local -Rfp lists data bags" do knife("list --local -Rfp").should_succeed <<~EOM bag/ @@ -868,7 +868,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside chef_repo2" do - before { cwd "chef_repo2" } + before do cwd "chef_repo2" end it "knife list --local -Rfp lists everything" do knife("list --local -Rfp").should_succeed <<~EOM clients/ @@ -892,7 +892,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside chef_repo2/data_bags" do - before { cwd "chef_repo2/data_bags" } + before do cwd "chef_repo2/data_bags" end it "knife list --local -Rfp fails" do knife("list --local -Rfp").should_fail(error_rel_path_outside_repo) end @@ -926,7 +926,7 @@ describe "chef_repo_path tests", :workstation do end context "when cwd is inside the data_bags directory" do - before { cwd "data_bags" } + before do cwd "data_bags" end it "knife list --local -Rfp lists data bags" do knife("list --local -Rfp").should_succeed <<~EOM bag/ diff --git a/spec/integration/knife/chef_repository_file_system_spec.rb b/spec/integration/knife/chef_repository_file_system_spec.rb index 6e9c4611e2..04584e1fb4 100644 --- a/spec/integration/knife/chef_repository_file_system_spec.rb +++ b/spec/integration/knife/chef_repository_file_system_spec.rb @@ -42,7 +42,7 @@ describe "General chef_repo file system checks", :workstation do end when_the_repository "has an empty data_bags directory" do - before { directory "data_bags" } + before do directory "data_bags" end it "knife list --local / returns it" do knife("list --local /").should_succeed "/data_bags\n" @@ -50,7 +50,7 @@ describe "General chef_repo file system checks", :workstation do end when_the_repository "has an empty cookbook directory" do - before { directory "cookbooks/cookbook1" } + before do directory "cookbooks/cookbook1" end it "knife list --local -Rfp / does not return it" do knife("list --local -Rfp /").should_succeed(<<~EOM, stderr: "WARN: Cookbook 'cookbook1' is empty or entirely chefignored at #{Chef::Config.chef_repo_path}/cookbooks/cookbook1\n") @@ -60,7 +60,7 @@ describe "General chef_repo file system checks", :workstation do end when_the_repository "has only empty cookbook subdirectories" do - before { directory "cookbooks/cookbook1/recipes" } + before do directory "cookbooks/cookbook1/recipes" end it "knife list --local -Rfp / does not return it" do knife("list --local -Rfp /").should_succeed(<<~EOM, stderr: "WARN: Cookbook 'cookbook1' is empty or entirely chefignored at #{Chef::Config.chef_repo_path}/cookbooks/cookbook1\n") @@ -87,7 +87,7 @@ describe "General chef_repo file system checks", :workstation do end when_the_repository "has only empty cookbook sub-sub-directories" do - before { directory "cookbooks/cookbook1/templates/default" } + before do directory "cookbooks/cookbook1/templates/default" end it "knife list --local -Rfp / does not return it" do knife("list --local -Rfp /").should_succeed(<<~EOM, stderr: "WARN: Cookbook 'cookbook1' is empty or entirely chefignored at #{Chef::Config.chef_repo_path}/cookbooks/cookbook1\n") @@ -159,7 +159,7 @@ describe "General chef_repo file system checks", :workstation do end when_the_repository "has a file in cookbooks/" do - before { file "cookbooks/file", "" } + before do file "cookbooks/file", "" end it "does not show up in list -Rfp" do knife("list --local -Rfp /").should_succeed <<~EOM /cookbooks/ @@ -168,7 +168,7 @@ describe "General chef_repo file system checks", :workstation do end when_the_repository "has a file in data_bags/" do - before { file "data_bags/file", "" } + before do file "data_bags/file", "" end it "does not show up in list -Rfp" do knife("list --local -Rfp /").should_succeed <<~EOM /data_bags/ diff --git a/spec/integration/knife/chefignore_spec.rb b/spec/integration/knife/chefignore_spec.rb index b92fb1f485..b022f1a842 100644 --- a/spec/integration/knife/chefignore_spec.rb +++ b/spec/integration/knife/chefignore_spec.rb @@ -84,7 +84,7 @@ describe "chefignore tests", :workstation do end context "and has a chefignore with filenames" do - before { file "cookbooks/chefignore", "x.json\n" } + before do file "cookbooks/chefignore", "x.json\n" end it "matching files and directories get ignored in all cookbooks" do knife("list --local -Rfp /").should_succeed <<~EOM diff --git a/spec/integration/knife/client_create_spec.rb b/spec/integration/knife/client_create_spec.rb index 505358923b..2a5420cc46 100644 --- a/spec/integration/knife/client_create_spec.rb +++ b/spec/integration/knife/client_create_spec.rb @@ -57,7 +57,7 @@ describe "knife client create", :workstation do it "reads the public key from a file" do Dir.mktmpdir do |tgt| key = OpenSSL::PKey::RSA.generate(1024) - File.open("#{tgt}/public.pem", "w") { |pub| pub.write(key.public_key.to_pem) } + File.open("#{tgt}/public.pem", "w") do |pub| pub.write(key.public_key.to_pem) end knife("client create -p #{tgt}/public.pem bah").should_succeed stderr: out end end diff --git a/spec/integration/knife/client_key_create_spec.rb b/spec/integration/knife/client_key_create_spec.rb index 7ccec8bffd..dc3fbd236d 100644 --- a/spec/integration/knife/client_key_create_spec.rb +++ b/spec/integration/knife/client_key_create_spec.rb @@ -56,7 +56,7 @@ describe "knife client key create", :workstation do it "reads the public key from a file" do Dir.mktmpdir do |tgt| key = OpenSSL::PKey::RSA.generate(1024) - File.open("#{tgt}/public.pem", "w") { |pub| pub.write(key.public_key.to_pem) } + File.open("#{tgt}/public.pem", "w") do |pub| pub.write(key.public_key.to_pem) end knife("client key create -p #{tgt}/public.pem -k new bah").should_succeed stderr: /^#{out}/ end end diff --git a/spec/integration/knife/common_options_spec.rb b/spec/integration/knife/common_options_spec.rb index 5eac571a85..d92c51955b 100644 --- a/spec/integration/knife/common_options_spec.rb +++ b/spec/integration/knife/common_options_spec.rb @@ -31,7 +31,7 @@ describe "knife common options", :workstation do let(:local_listen_warning) { /\Awarn:.*local.*listen.*$/im } when_the_repository "has a node" do - before { file "nodes/x.json", {} } + before do file "nodes/x.json", {} end context "When chef_zero.enabled is true" do before(:each) do @@ -48,7 +48,7 @@ describe "knife common options", :workstation do end context "And chef_zero.port is 9999" do - before(:each) { Chef::Config.chef_zero.port = 9999 } + before(:each) do Chef::Config.chef_zero.port = 9999 end it "knife raw /nodes/x should retrieve the node" do knife("raw --listen /nodes/x").should_succeed( /"name": "x"/, stderr: local_listen_warning ) @@ -58,7 +58,7 @@ describe "knife common options", :workstation do # 0.0.0.0 is not a valid address to bind to on windows. context "And chef_zero.host is 0.0.0.0", :unix_only do - before(:each) { Chef::Config.chef_zero.host = "0.0.0.0" } + before(:each) do Chef::Config.chef_zero.host = "0.0.0.0" end it "knife raw /nodes/x should retrieve the role" do knife("raw --listen /nodes/x").should_succeed( /"name": "x"/, stderr: local_listen_warning ) diff --git a/spec/integration/knife/config_get_profile_spec.rb b/spec/integration/knife/config_get_profile_spec.rb index e97b24b869..214413f548 100644 --- a/spec/integration/knife/config_get_profile_spec.rb +++ b/spec/integration/knife/config_get_profile_spec.rb @@ -41,7 +41,7 @@ describe "knife config get-profile", :workstation do old_wd = Dir.pwd ChefConfig::PathHelper.per_tool_home_environment = "KNIFE_HOME" # Clear these out because they are cached permanently. - ChefConfig::PathHelper.class_exec { remove_class_variable(:@@home_dir) } + ChefConfig::PathHelper.class_exec do remove_class_variable(:@@home_dir) end Chef::Knife::ConfigGetProfile.reset_config_loader! begin ex.run @@ -88,7 +88,7 @@ describe "knife config get-profile", :workstation do end context "with a context file" do - before { file(".chef/context", "development\n") } + before do file(".chef/context", "development\n") end it { is_expected.to eq "development\n" } end diff --git a/spec/integration/knife/config_get_spec.rb b/spec/integration/knife/config_get_spec.rb index 98fefd729f..d2e1461a2a 100644 --- a/spec/integration/knife/config_get_spec.rb +++ b/spec/integration/knife/config_get_spec.rb @@ -45,7 +45,7 @@ describe "knife config get", :workstation do old_wd = Dir.pwd ChefConfig::PathHelper.per_tool_home_environment = "KNIFE_HOME" # Clear these out because they are cached permanently. - ChefConfig::PathHelper.class_exec { remove_class_variable(:@@home_dir) } + ChefConfig::PathHelper.class_exec do remove_class_variable(:@@home_dir) end Chef::Knife::ConfigGet.reset_config_loader! begin ex.run @@ -69,14 +69,14 @@ describe "knife config get", :workstation do end context "with a global knife.rb" do - before { file(".chef/knife.rb", "node_name 'one'\n") } + before do file(".chef/knife.rb", "node_name 'one'\n") end it { is_expected.to match(%r{^Loading from configuration file .*/#{File.basename(path_to("."))}/.chef/knife.rb$}) } it { is_expected.to match(/^node_name:\s+one$/) } end context "with a repo knife.rb" do - before { file("repo/.chef/knife.rb", "node_name 'two'\n") } + before do file("repo/.chef/knife.rb", "node_name 'two'\n") end it { is_expected.to match(%r{^Loading from configuration file .*/#{File.basename(path_to("."))}/repo/.chef/knife.rb$}) } it { is_expected.to match(/^node_name:\s+two$/) } @@ -93,7 +93,7 @@ describe "knife config get", :workstation do end context "with a credentials file" do - before { file(".chef/credentials", "[default]\nclient_name = \"three\"\n") } + before do file(".chef/credentials", "[default]\nclient_name = \"three\"\n") end it { is_expected.to match(%r{^Loading from credentials file .*/#{File.basename(path_to("."))}/.chef/credentials$}) } it { is_expected.to match(/^node_name:\s+three$/) } @@ -134,49 +134,49 @@ describe "knife config get", :workstation do context "with single argument" do let(:cmd_args) { %w{node_name} } - before { file(".chef/credentials", "[default]\nclient_name = \"three\"\n") } + before do file(".chef/credentials", "[default]\nclient_name = \"three\"\n") end it { is_expected.to match(/^node_name:\s+three\Z/) } end context "with two arguments" do let(:cmd_args) { %w{node_name client_key} } - before { file(".chef/credentials", "[default]\nclient_name = \"three\"\nclient_key = \"three.pem\"") } + before do file(".chef/credentials", "[default]\nclient_name = \"three\"\nclient_key = \"three.pem\"") end it { is_expected.to match(%r{^client_key:\s+\S*/.chef/three.pem\nnode_name:\s+three\Z}) } end context "with a dotted argument" do let(:cmd_args) { %w{knife.ssh_user} } - before { file(".chef/credentials", "[default]\nclient_name = \"three\"\n[default.knife]\nssh_user = \"foo\"\n") } + before do file(".chef/credentials", "[default]\nclient_name = \"three\"\n[default.knife]\nssh_user = \"foo\"\n") end it { is_expected.to match(/^knife.ssh_user:\s+foo\Z/) } end context "with regex argument" do let(:cmd_args) { %w{/name/} } - before { file(".chef/credentials", "[default]\nclient_name = \"three\"\n") } + before do file(".chef/credentials", "[default]\nclient_name = \"three\"\n") end it { is_expected.to match(/^node_name:\s+three\Z/) } end context "with --all" do let(:cmd_args) { %w{-a /key_contents/} } - before { file(".chef/credentials", "[default]\nclient_name = \"three\"\n") } + before do file(".chef/credentials", "[default]\nclient_name = \"three\"\n") end it { is_expected.to match(/^client_key_contents:\s+\nvalidation_key_contents:\s+\Z/) } end context "with --raw" do let(:cmd_args) { %w{-r node_name} } - before { file(".chef/credentials", "[default]\nclient_name = \"three\"\n") } + before do file(".chef/credentials", "[default]\nclient_name = \"three\"\n") end it { is_expected.to eq("three\n") } end context "with --format=json" do let(:cmd_args) { %w{--format=json node_name} } - before { file(".chef/credentials", "[default]\nclient_name = \"three\"\n") } + before do file(".chef/credentials", "[default]\nclient_name = \"three\"\n") end it { expect(JSON.parse(subject)).to eq({ "node_name" => "three" }) } end diff --git a/spec/integration/knife/config_list_profiles_spec.rb b/spec/integration/knife/config_list_profiles_spec.rb index 044b50b5be..3f7dd33c9c 100644 --- a/spec/integration/knife/config_list_profiles_spec.rb +++ b/spec/integration/knife/config_list_profiles_spec.rb @@ -37,7 +37,7 @@ describe "knife config list-profiles", :workstation do old_home = ENV["HOME"] old_wd = Dir.pwd # Clear these out because they are cached permanently. - ChefConfig::PathHelper.class_exec { remove_class_variable(:@@home_dir) } + ChefConfig::PathHelper.class_exec do remove_class_variable(:@@home_dir) end Chef::Knife::ConfigListProfiles.reset_config_loader! begin ex.run @@ -67,13 +67,13 @@ describe "knife config list-profiles", :workstation do end context "with an empty credentials file" do - before { file(".chef/credentials", "") } + before do file(".chef/credentials", "") end subject { knife_list_profiles.stderr } it { is_expected.to eq "FATAL: No profiles found, #{path_to(".chef/credentials")} does not exist or is empty\n" } end context "with a simple default profile" do - before { file(".chef/credentials", <<~EOH) } + before do file(".chef/credentials", <<~EOH) end [default] client_name = "testuser" client_key = "testkey.pem" @@ -87,7 +87,7 @@ describe "knife config list-profiles", :workstation do end context "with multiple profiles" do - before { file(".chef/credentials", <<~EOH) } + before do file(".chef/credentials", <<~EOH) end [default] client_name = "testuser" client_key = "testkey.pem" @@ -114,7 +114,7 @@ describe "knife config list-profiles", :workstation do context "with a non-default active profile" do let(:cmd_args) { %w{--profile prod} } - before { file(".chef/credentials", <<~EOH) } + before do file(".chef/credentials", <<~EOH) end [default] client_name = "testuser" client_key = "testkey.pem" @@ -140,7 +140,7 @@ describe "knife config list-profiles", :workstation do end context "with a minimal profile" do - before { file(".chef/credentials", <<~EOH) } + before do file(".chef/credentials", <<~EOH) end [default] chef_server_url = "https://example.com/organizations/testorg" EOH @@ -149,7 +149,7 @@ describe "knife config list-profiles", :workstation do context "with -i" do let(:cmd_args) { %w{-i} } - before { file(".chef/credentials", <<~EOH) } + before do file(".chef/credentials", <<~EOH) end [default] chef_server_url = "https://example.com/organizations/testorg" EOH @@ -162,7 +162,7 @@ describe "knife config list-profiles", :workstation do context "with --format=json" do let(:cmd_args) { %w{--format=json node_name} } - before { file(".chef/credentials", <<~EOH) } + before do file(".chef/credentials", <<~EOH) end [default] client_name = "testuser" client_key = "testkey.pem" diff --git a/spec/integration/knife/config_use_profile_spec.rb b/spec/integration/knife/config_use_profile_spec.rb index a021dbbe6f..4c52d1c4bd 100644 --- a/spec/integration/knife/config_use_profile_spec.rb +++ b/spec/integration/knife/config_use_profile_spec.rb @@ -42,7 +42,7 @@ describe "knife config use-profile", :workstation do old_wd = Dir.pwd ChefConfig::PathHelper.per_tool_home_environment = "KNIFE_HOME" # Clear these out because they are cached permanently. - ChefConfig::PathHelper.class_exec { remove_class_variable(:@@home_dir) } + ChefConfig::PathHelper.class_exec do remove_class_variable(:@@home_dir) end Chef::Knife::ConfigUseProfile.reset_config_loader! begin ex.run @@ -80,7 +80,7 @@ describe "knife config use-profile", :workstation do context "with $CHEF_HOME" do let(:cmd_args) { %w{staging} } - before { ENV["CHEF_HOME"] = path_to("chefhome"); file("chefhome/tmp", "") } + before do ENV["CHEF_HOME"] = path_to("chefhome"); file("chefhome/tmp", "") end it do is_expected.to eq "Set default profile to staging\n" expect(File.read(path_to("chefhome/.chef/context"))).to eq "staging\n" @@ -90,7 +90,7 @@ describe "knife config use-profile", :workstation do context "with $KNIFE_HOME" do let(:cmd_args) { %w{development} } - before { ENV["KNIFE_HOME"] = path_to("knifehome"); file("knifehome/tmp", "") } + before do ENV["KNIFE_HOME"] = path_to("knifehome"); file("knifehome/tmp", "") end it do is_expected.to eq "Set default profile to development\n" expect(File.read(path_to("knifehome/.chef/context"))).to eq "development\n" diff --git a/spec/integration/knife/delete_spec.rb b/spec/integration/knife/delete_spec.rb index fd5853dfef..440be05878 100644 --- a/spec/integration/knife/delete_spec.rb +++ b/spec/integration/knife/delete_spec.rb @@ -641,7 +641,7 @@ describe "knife delete", :workstation do end context "and cwd is at the top level" do - before { cwd "." } + before do cwd "." end it "knife delete fails" do knife("delete").should_fail "FATAL: You must specify at least one argument. If you want to delete everything in this directory, run \"knife delete --recurse .\"\n", stdout: /USAGE/ knife("list -Rf /").should_succeed <<~EOM @@ -854,7 +854,7 @@ describe "knife delete", :workstation do end context "and cwd is at the top level" do - before { cwd "." } + before do cwd "." end it "knife delete fails" do knife("delete").should_fail "FATAL: You must specify at least one argument. If you want to delete everything in this directory, run \"knife delete --recurse .\"\n", stdout: /USAGE/ knife("list -Rf /").should_succeed <<~EOM @@ -928,7 +928,7 @@ describe "knife delete", :workstation do end when_the_chef_server "has a later version for the cookbook, and no current version" do - before { cookbook "x", "1.0.1", { "onlyin1.0.1.rb" => "hi" } } + before do cookbook "x", "1.0.1", { "onlyin1.0.1.rb" => "hi" } end it "knife delete --both /cookbooks/x deletes the server and client version of the cookbook" do knife("delete --both -r /cookbooks/x").should_succeed "Deleted /cookbooks/x\n" @@ -938,7 +938,7 @@ describe "knife delete", :workstation do end when_the_chef_server "has an earlier version for the cookbook, and no current version" do - before { cookbook "x", "0.9.9", { "onlyin0.9.9.rb" => "hi" } } + before do cookbook "x", "0.9.9", { "onlyin0.9.9.rb" => "hi" } end it "knife delete --both /cookbooks/x deletes the server and client version of the cookbook" do knife("delete --both -r /cookbooks/x").should_succeed "Deleted /cookbooks/x\n" diff --git a/spec/integration/knife/deps_spec.rb b/spec/integration/knife/deps_spec.rb index 4dfccf38de..0c0e441966 100644 --- a/spec/integration/knife/deps_spec.rb +++ b/spec/integration/knife/deps_spec.rb @@ -25,7 +25,7 @@ describe "knife deps", :workstation do context "local" do when_the_repository "has a role with no run_list" do - before { file "roles/starring.json", {} } + before do file "roles/starring.json", {} end it "knife deps reports no dependencies" do knife("deps /roles/starring.json").should_succeed "/roles/starring.json\n" end @@ -70,7 +70,7 @@ describe "knife deps", :workstation do end when_the_repository "has a node with no environment or run_list" do - before { file "nodes/mort.json", {} } + before do file "nodes/mort.json", {} end it "knife deps reports just the node" do knife("deps /nodes/mort.json").should_succeed "/nodes/mort.json\n" end @@ -123,13 +123,13 @@ depends "kettle"' end end when_the_repository "has a data bag" do - before { file "data_bags/bag/item.json", {} } + before do file "data_bags/bag/item.json", {} end it "knife deps reports just the data bag" do knife("deps /data_bags/bag/item.json").should_succeed "/data_bags/bag/item.json\n" end end when_the_repository "has an environment" do - before { file "environments/desert.json", {} } + before do file "environments/desert.json", {} end it "knife deps reports just the environment" do knife("deps /environments/desert.json").should_succeed "/environments/desert.json\n" end @@ -344,13 +344,13 @@ depends "foo"' end end when_the_repository "has a data bag" do - before { file "data_bags/bag/item.json", "" } + before do file "data_bags/bag/item.json", "" end it "knife deps /data_bags/bag shows no dependencies" do knife("deps /data_bags/bag").should_succeed("/data_bags/bag\n") end end when_the_repository "has a cookbook" do - before { file "cookbooks/blah/metadata.rb", 'name "blah"' } + before do file "cookbooks/blah/metadata.rb", 'name "blah"' end it "knife deps on a cookbook file shows no dependencies" do knife("deps /cookbooks/blah/metadata.rb").should_succeed( "/cookbooks/blah/metadata.rb\n" @@ -364,7 +364,7 @@ depends "foo"' include_context "default config options" when_the_chef_server "has a role with no run_list" do - before { role "starring", {} } + before do role "starring", {} end it "knife deps reports no dependencies" do knife("deps --remote /roles/starring.json").should_succeed "/roles/starring.json\n" end @@ -405,7 +405,7 @@ depends "foo"' end when_the_chef_server "has a node with no environment or run_list" do - before { node "mort", {} } + before do node "mort", {} end it "knife deps reports just the node" do knife("deps --remote /nodes/mort.json").should_succeed "/nodes/mort.json\n" end @@ -454,13 +454,13 @@ depends "kettle"', "recipes" => { "default.rb" => "" } } end end when_the_chef_server "has a data bag" do - before { data_bag "bag", { "item" => {} } } + before do data_bag "bag", { "item" => {} } end it "knife deps reports just the data bag" do knife("deps --remote /data_bags/bag/item.json").should_succeed "/data_bags/bag/item.json\n" end end when_the_chef_server "has an environment" do - before { environment "desert", {} } + before do environment "desert", {} end it "knife deps reports just the environment" do knife("deps --remote /environments/desert.json").should_succeed "/environments/desert.json\n" end @@ -678,7 +678,7 @@ depends "self"' } end end when_the_chef_server "has a data bag" do - before { data_bag "bag", { "item" => {} } } + before do data_bag "bag", { "item" => {} } end it "knife deps /data_bags/bag shows no dependencies" do knife("deps --remote /data_bags/bag").should_succeed("/data_bags/bag\n") end diff --git a/spec/integration/knife/diff_spec.rb b/spec/integration/knife/diff_spec.rb index 87cbd1559d..944666ccc7 100644 --- a/spec/integration/knife/diff_spec.rb +++ b/spec/integration/knife/diff_spec.rb @@ -134,7 +134,7 @@ describe "knife diff", :workstation do end context "when cwd is the data_bags directory" do - before { cwd "data_bags" } + before do cwd "data_bags" end it "knife diff reports different data bags" do knife("diff --name-status").should_succeed <<~EOM A\tx/z.json @@ -240,13 +240,13 @@ describe "knife diff", :workstation do end when_the_chef_server "has an empty environment" do - before { environment "x", {} } + before do environment "x", {} end it "knife diff returns no differences" do knife("diff /environments/x.json").should_succeed "" end end when_the_chef_server "has an environment with a different value" do - before { environment "x", { "description" => "hi" } } + before do environment "x", { "description" => "hi" } end it "knife diff reports the difference" do knife("diff /environments/x.json").should_succeed(/ { @@ -305,9 +305,9 @@ describe "knife diff", :workstation do end when_the_chef_server "has an environment" do - before { environment "x", {} } + before do environment "x", {} end when_the_repository "has an environment with bad JSON" do - before { file "environments/x.json", "{" } + before do file "environments/x.json", "{" end it "knife diff reports an error and does a textual diff" do error_text = "WARN: Parse error reading #{path_to("environments/x.json")} as JSON: parse error: premature EOF" error_match = Regexp.new(Regexp.escape(error_text)) @@ -430,7 +430,7 @@ describe "knife diff", :workstation do end context "when cwd is the data_bags directory" do - before { cwd "data_bags" } + before do cwd "data_bags" end it "knife diff reports different data bags" do knife("diff --name-status").should_succeed <<~EOM A\tx/z.json @@ -524,15 +524,15 @@ describe "knife diff", :workstation do context "json diff tests" do when_the_repository "has an empty environment file" do - before { file "environments/x.json", {} } + before do file "environments/x.json", {} end when_the_chef_server "has an empty environment" do - before { environment "x", {} } + before do environment "x", {} end it "knife diff returns no differences" do knife("diff /environments/x.json").should_succeed "" end end when_the_chef_server "has an environment with a different value" do - before { environment "x", { "description" => "hi" } } + before do environment "x", { "description" => "hi" } end it "knife diff reports the difference" do knife("diff /environments/x.json").should_succeed(/ { @@ -559,7 +559,7 @@ describe "knife diff", :workstation do end end when_the_chef_server "has an environment with no value" do - before { environment "x", {} } + before do environment "x", {} end it "knife diff reports the difference" do knife("diff /environments/x.json").should_succeed(/ { @@ -588,9 +588,9 @@ describe "knife diff", :workstation do end when_the_chef_server "has an environment" do - before { environment "x", {} } + before do environment "x", {} end when_the_repository "has an environment with bad JSON" do - before { file "environments/x.json", "{" } + before do file "environments/x.json", "{" end it "knife diff reports an error and does a textual diff" do error_text = "WARN: Parse error reading #{path_to("environments/x.json")} as JSON: parse error: premature EOF" error_match = Regexp.new(Regexp.escape(error_text)) diff --git a/spec/integration/knife/list_spec.rb b/spec/integration/knife/list_spec.rb index 830dd0e428..fb62c69ec7 100644 --- a/spec/integration/knife/list_spec.rb +++ b/spec/integration/knife/list_spec.rb @@ -314,7 +314,7 @@ describe "knife list", :workstation do context "symlink tests" do when_the_repository "is empty" do context "when cwd is at the top of the repository" do - before { cwd "." } + before do cwd "." end it "knife list -Rfp returns everything" do knife("list -Rfp").should_succeed <<~EOM @@ -357,9 +357,9 @@ describe "knife list", :workstation do end when_the_repository "has a cookbooks directory" do - before { directory "cookbooks" } + before do directory "cookbooks" end context "when cwd is in cookbooks/" do - before { cwd "cookbooks" } + before do cwd "cookbooks" end it "knife list -Rfp / returns everything" do knife("list -Rfp /").should_succeed <<~EOM @@ -451,10 +451,10 @@ describe "knife list", :workstation do end when_the_repository "has a cookbooks/cookbook2 directory" do - before { directory "cookbooks/cookbook2" } + before do directory "cookbooks/cookbook2" end context "when cwd is in cookbooks/cookbook2" do - before { cwd "cookbooks/cookbook2" } + before do cwd "cookbooks/cookbook2" end it "knife list -Rfp returns cookbooks" do knife("list -Rfp").should_succeed <<~EOM @@ -473,7 +473,7 @@ describe "knife list", :workstation do end context "when cwd is in cookbooks/" do - before { cwd "cookbooks" } + before do cwd "cookbooks" end it "knife list -Rfp returns cookbooks" do knife("list -Rfp").should_succeed <<~EOM @@ -488,7 +488,7 @@ describe "knife list", :workstation do end context "when cwd is in symlinked/" do - before { cwd "symlinked" } + before do cwd "symlinked" end it "knife list -Rfp returns cookbooks" do knife("list -Rfp").should_succeed <<~EOM @@ -510,7 +510,7 @@ describe "knife list", :workstation do end context "when cwd is in real_cookbooks/" do - before { cwd "real_cookbooks" } + before do cwd "real_cookbooks" end it "knife list -Rfp returns cookbooks" do knife("list -Rfp").should_succeed <<~EOM @@ -525,7 +525,7 @@ describe "knife list", :workstation do end context "when cwd is in cookbooks/" do - before { cwd "cookbooks" } + before do cwd "cookbooks" end it "knife list -Rfp returns cookbooks" do knife("list -Rfp").should_succeed <<~EOM diff --git a/spec/integration/knife/redirection_spec.rb b/spec/integration/knife/redirection_spec.rb index 5e5ef27b9a..7bf7b772cd 100644 --- a/spec/integration/knife/redirection_spec.rb +++ b/spec/integration/knife/redirection_spec.rb @@ -27,7 +27,7 @@ describe "redirection", :workstation do include_context "default config options" when_the_chef_server "has a role" do - before { role "x", {} } + before do role "x", {} end context "and another server redirects to it with 302" do before :each do diff --git a/spec/integration/knife/show_spec.rb b/spec/integration/knife/show_spec.rb index dd83475b8c..a237603ceb 100644 --- a/spec/integration/knife/show_spec.rb +++ b/spec/integration/knife/show_spec.rb @@ -156,7 +156,7 @@ describe "knife show", :workstation do end when_the_repository "has an environment with bad JSON" do - before { file "environments/x.json", "{" } + before do file "environments/x.json", "{" end it "knife show succeeds" do knife("show --local /environments/x.json").should_succeed <<~EOM /environments/x.json: diff --git a/spec/integration/recipes/lwrp_inline_resources_spec.rb b/spec/integration/recipes/lwrp_inline_resources_spec.rb index b96fa1d67d..e732da9f69 100644 --- a/spec/integration/recipes/lwrp_inline_resources_spec.rb +++ b/spec/integration/recipes/lwrp_inline_resources_spec.rb @@ -37,9 +37,9 @@ describe "LWRPs with inline resources" do it "this is totally a bug, but for backcompat purposes, it adds the resources to the main resource collection and does not get marked updated" do r = nil - expect_recipe do + expect_recipe { r = lwrp_inline_resources_test "hi" - end.to have_updated("ruby_block[run a]", :run) + }.to have_updated("ruby_block[run a]", :run) expect(r.ran_a).to eq "ran a" end end @@ -58,7 +58,7 @@ describe "LWRPs with inline resources" do end end - after { File.delete(LwrpShadowedPropertyTest::PATH) if File.exists?(LwrpShadowedPropertyTest::PATH) } + after do File.delete(LwrpShadowedPropertyTest::PATH) if File.exists?(LwrpShadowedPropertyTest::PATH) end # https://github.com/chef/chef/issues/4334 it "does not warn spuriously" do @@ -101,11 +101,11 @@ describe "LWRPs with inline resources" do it "resources declared in b are executed immediately inline" do r = nil - expect_recipe do + expect_recipe { r = lwrp_inline_resources_test2 "hi" do action :b end - end.to have_updated("lwrp_inline_resources_test2[hi]", :b) + }.to have_updated("lwrp_inline_resources_test2[hi]", :b) .and have_updated("ruby_block[run a]", :run) .and have_updated("ruby_block[run b]", :run) expect(r.ran_b).to eq "ran b: ran_a value was \"ran a\"" diff --git a/spec/integration/recipes/noop_resource_spec.rb b/spec/integration/recipes/noop_resource_spec.rb index db6b668553..2f2c6e7ae4 100644 --- a/spec/integration/recipes/noop_resource_spec.rb +++ b/spec/integration/recipes/noop_resource_spec.rb @@ -13,11 +13,11 @@ describe "Resources with a no-op provider" do end it "does not blow up a run with a noop'd resource" do - recipe = converge do + recipe = converge { hi_there "blah" do action :update end - end + } expect(recipe.logged_warnings).to eq "" end end diff --git a/spec/integration/recipes/provider_choice.rb b/spec/integration/recipes/provider_choice.rb index dea58230db..3f9e87eb77 100644 --- a/spec/integration/recipes/provider_choice.rb +++ b/spec/integration/recipes/provider_choice.rb @@ -25,9 +25,9 @@ describe "Recipe DSL methods" do end it "provider_thingy 'blah' runs the provider and warns" do - recipe = converge do + recipe = converge { provider_thingy("blah") {} - end + } expect(recipe.logged_warnings).to match /hello from Chef::Provider::ProviderThingy/ expect(recipe.logged_warnings).to match /you must use 'provides' to provide DSL/i end diff --git a/spec/integration/recipes/recipe_dsl_spec.rb b/spec/integration/recipes/recipe_dsl_spec.rb index 766752ac13..75670722a4 100644 --- a/spec/integration/recipes/recipe_dsl_spec.rb +++ b/spec/integration/recipes/recipe_dsl_spec.rb @@ -8,8 +8,8 @@ describe "Recipe DSL methods" do attr_accessor :current_index end - before(:all) { Namer.current_index = 1 } - before { Namer.current_index += 1 } + before(:all) do Namer.current_index = 1 end + before do Namer.current_index += 1 end context "with resource 'base_thingy' declared as BaseThingy" do before(:each) do @@ -50,18 +50,18 @@ describe "Recipe DSL methods" do end it "creates base_thingy when you call base_thingy in a recipe" do - recipe = converge do + recipe = converge { base_thingy("blah") {} - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_name).to eq "blah" expect(BaseThingy.created_resource).to eq BaseThingy end it "errors when you call base_thingy do ... end in a recipe" do - expect_converge do + expect_converge { base_thingy { ; } - end.to raise_error(Chef::Exceptions::ValidationFailed) + }.to raise_error(Chef::Exceptions::ValidationFailed) end context "nameless resources" do @@ -75,9 +75,9 @@ describe "Recipe DSL methods" do end it "does not error when not given a name" do - recipe = converge do + recipe = converge { nameless_thingy {} - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_name).to eq "" expect(BaseThingy.created_resource).to eq NamelessThingy @@ -98,9 +98,9 @@ describe "Recipe DSL methods" do end it "bar_thingy does not work" do - expect_converge do + expect_converge { bar_thingy("blah") {} - end.to raise_error(NoMethodError) + }.to raise_error(NoMethodError) end end @@ -114,9 +114,9 @@ describe "Recipe DSL methods" do end it "no_name_thingy does not work" do - expect_converge do + expect_converge { no_name_thingy("blah") {} - end.to raise_error(NoMethodError) + }.to raise_error(NoMethodError) end end @@ -130,15 +130,15 @@ describe "Recipe DSL methods" do end it "another_no_name_thingy does not work" do - expect_converge do + expect_converge { another_no_name_thingy("blah") {} - end.to raise_error(NoMethodError) + }.to raise_error(NoMethodError) end it "another_thingy_name works" do - recipe = converge do + recipe = converge { another_thingy_name("blah") {} - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq(AnotherNoNameThingy) end @@ -155,21 +155,21 @@ describe "Recipe DSL methods" do end it "another_no_name_thingy does not work" do - expect_converge do + expect_converge { another_no_name_thingy2("blah") {} - end.to raise_error(NoMethodError) + }.to raise_error(NoMethodError) end it "another_thingy_name2 does not work" do - expect_converge do + expect_converge { another_thingy_name2("blah") {} - end.to raise_error(NoMethodError) + }.to raise_error(NoMethodError) end it "yet_another_thingy_name3 works" do - recipe = converge do + recipe = converge { another_thingy_name3("blah") {} - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq(AnotherNoNameThingy2) end @@ -187,19 +187,19 @@ describe "Recipe DSL methods" do end it "and os = linux, another_no_name_thingy3 does not work" do - expect_converge do + expect_converge { # TODO this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "linux" another_no_name_thingy3("blah") {} - end.to raise_error(Chef::Exceptions::NoSuchResourceType) + }.to raise_error(Chef::Exceptions::NoSuchResourceType) end it "and os = blarghle, another_no_name_thingy3 works" do - recipe = converge do + recipe = converge { # TODO this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "blarghle" another_no_name_thingy3("blah") {} - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy3) end @@ -217,29 +217,29 @@ describe "Recipe DSL methods" do end it "and os = linux, another_no_name_thingy4 does not work" do - expect_converge do + expect_converge { # TODO this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "linux" another_no_name_thingy4("blah") {} - end.to raise_error(Chef::Exceptions::NoSuchResourceType) + }.to raise_error(Chef::Exceptions::NoSuchResourceType) end it "and os = blarghle, another_no_name_thingy4 works" do - recipe = converge do + recipe = converge { # TODO this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "blarghle" another_no_name_thingy4("blah") {} - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy4) end it "and platform_family = foo, another_no_name_thingy4 works" do - recipe = converge do + recipe = converge { # TODO this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:platform_family] = "foo" another_no_name_thingy4("blah") {} - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy4) end @@ -256,27 +256,27 @@ describe "Recipe DSL methods" do end it "and os = linux, another_no_name_thingy5 does not work" do - expect_converge do + expect_converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "linux" another_no_name_thingy5("blah") {} - end.to raise_error(Chef::Exceptions::NoSuchResourceType) + }.to raise_error(Chef::Exceptions::NoSuchResourceType) end it "and os = blarghle, another_no_name_thingy5 works" do - recipe = converge do + recipe = converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "blarghle" another_no_name_thingy5("blah") {} - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy5) end it "the new resource name can be used in a recipe" do - recipe = converge do + recipe = converge { another_thingy_name_for_another_no_name_thingy5("blah") {} - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy5) end @@ -293,27 +293,27 @@ describe "Recipe DSL methods" do end it "and os = linux, another_no_name_thingy6 does not work" do - expect_converge do + expect_converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "linux" another_no_name_thingy6("blah") {} - end.to raise_error(Chef::Exceptions::NoSuchResourceType) + }.to raise_error(Chef::Exceptions::NoSuchResourceType) end it "and os = blarghle, another_no_name_thingy6 works" do - recipe = converge do + recipe = converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "blarghle" another_no_name_thingy6("blah") {} - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy6) end it "the new resource name can be used in a recipe" do - recipe = converge do + recipe = converge { another_thingy_name_for_another_no_name_thingy6("blah") {} - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy6) end @@ -330,29 +330,29 @@ describe "Recipe DSL methods" do end it "and os = linux, another_thingy_name_for_another_no_name_thingy7 does not work" do - expect_converge do + expect_converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "linux" another_thingy_name_for_another_no_name_thingy7("blah") {} - end.to raise_error(Chef::Exceptions::NoSuchResourceType) + }.to raise_error(Chef::Exceptions::NoSuchResourceType) end it "and os = blarghle, another_thingy_name_for_another_no_name_thingy7 works" do - recipe = converge do + recipe = converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "blarghle" another_thingy_name_for_another_no_name_thingy7("blah") {} - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy7) end it "the old resource name does not work" do - expect_converge do + expect_converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "linux" another_no_name_thingy_7("blah") {} - end.to raise_error(NoMethodError) + }.to raise_error(NoMethodError) end end @@ -368,29 +368,29 @@ describe "Recipe DSL methods" do end it "and os = linux, another_thingy_name_for_another_no_name_thingy8 does not work" do - expect_converge do + expect_converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "linux" another_thingy_name_for_another_no_name_thingy8("blah") {} - end.to raise_error(Chef::Exceptions::NoSuchResourceType) + }.to raise_error(Chef::Exceptions::NoSuchResourceType) end it "and os = blarghle, another_thingy_name_for_another_no_name_thingy8 works" do - recipe = converge do + recipe = converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "blarghle" another_thingy_name_for_another_no_name_thingy8("blah") {} - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy8) end it "the old resource name does not work" do - expect_converge do + expect_converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "linux" another_thingy_name8("blah") {} - end.to raise_error(NoMethodError) + }.to raise_error(NoMethodError) end end end @@ -407,15 +407,15 @@ describe "Recipe DSL methods" do end it "my_supplier does not work in a recipe" do - expect_converge do + expect_converge { my_supplier("blah") {} - end.to raise_error(NoMethodError) + }.to raise_error(NoMethodError) end it "hemlock works in a recipe" do - expect_recipe do + expect_recipe { hemlock("blah") {} - end.to emit_no_warnings_or_errors + }.to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::MySupplier end end @@ -430,9 +430,9 @@ describe "Recipe DSL methods" do end it "thingy3 works in a recipe" do - expect_recipe do + expect_recipe { thingy3("blah") {} - end.to emit_no_warnings_or_errors + }.to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy3 end @@ -446,16 +446,16 @@ describe "Recipe DSL methods" do end it "thingy3 works in a recipe and yields Thingy4 (the last one)" do - recipe = converge do + recipe = converge { thingy3("blah") {} - end + } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy4 end it "thingy4 does not work in a recipe" do - expect_converge do + expect_converge { thingy4("blah") {} - end.to raise_error(NoMethodError) + }.to raise_error(NoMethodError) end it "resource_matching_short_name returns Thingy4" do @@ -477,9 +477,9 @@ describe "Recipe DSL methods" do end it "thingy5 works in a recipe" do - expect_recipe do + expect_recipe { thingy5("blah") {} - end.to emit_no_warnings_or_errors + }.to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy5 end @@ -494,16 +494,16 @@ describe "Recipe DSL methods" do end it "thingy6 works in a recipe and yields Thingy6" do - recipe = converge do + recipe = converge { thingy6("blah") {} - end + } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy6 end it "thingy5 works in a recipe and yields Foo::Thingy6 (the last one)" do - recipe = converge do + recipe = converge { thingy5("blah") {} - end + } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy6 end @@ -521,9 +521,9 @@ describe "Recipe DSL methods" do end it "thingy5reverse works in a recipe and yields AThingy5 (the alphabetical one)" do - recipe = converge do + recipe = converge { thingy5reverse("blah") {} - end + } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::AThingy5 end end @@ -540,9 +540,9 @@ describe "Recipe DSL methods" do end it "thingy5_2 works in a recipe and yields the ZRecipeDSLSpaceNamespace one (the last one)" do - recipe = converge do + recipe = converge { thingy5_2("blah") {} - end + } expect(BaseThingy.created_resource).to eq ZRecipeDSLSpecNamespace::Thingy5 end end @@ -559,9 +559,9 @@ describe "Recipe DSL methods" do end it "thingy5_2reverse works in a recipe and yields the ARecipeDSLSpaceNamespace one (the alphabetical one)" do - recipe = converge do + recipe = converge { thingy5_2reverse("blah") {} - end + } expect(BaseThingy.created_resource).to eq ARecipeDSLSpecNamespace::Thingy5 end end @@ -577,9 +577,9 @@ describe "Recipe DSL methods" do end it "thingy3 works in a recipe" do - expect_recipe do + expect_recipe { thingy3("blah") {} - end.to emit_no_warnings_or_errors + }.to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy3 end @@ -593,16 +593,16 @@ describe "Recipe DSL methods" do end it "thingy3 works in a recipe and yields Thingy4 (the last one)" do - recipe = converge do + recipe = converge { thingy3("blah") {} - end + } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy4 end it "thingy4 does not work in a recipe" do - expect_converge do + expect_converge { thingy4("blah") {} - end.to raise_error(NoMethodError) + }.to raise_error(NoMethodError) end it "resource_matching_short_name returns Thingy4" do @@ -620,16 +620,16 @@ describe "Recipe DSL methods" do end it "thingy3 works in a recipe and yields Thingy4 (the last one)" do - recipe = converge do + recipe = converge { thingy3("blah") {} - end + } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy4 end it "thingy4 does not work in a recipe" do - expect_converge do + expect_converge { thingy4("blah") {} - end.to raise_error(NoMethodError) + }.to raise_error(NoMethodError) end it "resource_matching_short_name returns Thingy4" do @@ -660,16 +660,16 @@ describe "Recipe DSL methods" do end it "thingy7 works in a recipe and yields Thingy7" do - recipe = converge do + recipe = converge { thingy7("blah") {} - end + } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy7 end it "thingy8 works in a recipe and yields Thingy7 (last)" do - recipe = converge do + recipe = converge { thingy8("blah") {} - end + } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy8 end @@ -691,23 +691,23 @@ describe "Recipe DSL methods" do end it "thingy12 works in a recipe and yields Thingy12" do - expect_recipe do + expect_recipe { thingy12("blah") {} - end.to emit_no_warnings_or_errors + }.to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy12 end it "twizzle works in a recipe and yields Thingy12" do - expect_recipe do + expect_recipe { twizzle("blah") {} - end.to emit_no_warnings_or_errors + }.to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy12 end it "twizzle2 works in a recipe and yields Thingy12" do - expect_recipe do + expect_recipe { twizzle2("blah") {} - end.to emit_no_warnings_or_errors + }.to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy12 end end @@ -750,11 +750,11 @@ describe "Recipe DSL methods" do it "A run with platform 'x' reports that my_super_thingy is not supported" do r = Cheffish::ChefRun.new(chef_config) r.client.run_context.node.automatic["platform"] = "x" - expect do + expect { r.compile_recipe do my_super_thingy("blah") {} end - end.to raise_error(Chef::Exceptions::NoSuchResourceType) + }.to raise_error(Chef::Exceptions::NoSuchResourceType) end end @@ -804,7 +804,7 @@ describe "Recipe DSL methods" do result.resource_name two_classes_one_dsl result end - before { resource_class } # pull on it so it gets defined before the recipe runs + before do resource_class end # pull on it so it gets defined before the recipe runs context "and another resource named 'A' with resource_name :two_classes_one_dsl" do let(:resource_class_a) do @@ -820,13 +820,13 @@ describe "Recipe DSL methods" do result.resource_name two_classes_one_dsl result end - before { resource_class_a } # pull on it so it gets defined before the recipe runs + before do resource_class_a end # pull on it so it gets defined before the recipe runs it "two_classes_one_dsl resolves to A (alphabetically earliest)" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { instance_eval("#{temp_two_classes_one_dsl} 'blah'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq resource_class_a end @@ -850,13 +850,13 @@ describe "Recipe DSL methods" do result.resource_name two_classes_one_dsl result end - before { resource_class_z } # pull on it so it gets defined before the recipe runs + before do resource_class_z end # pull on it so it gets defined before the recipe runs it "two_classes_one_dsl resolves to Z (last)" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { instance_eval("#{temp_two_classes_one_dsl} 'blah'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq resource_class_z end @@ -872,9 +872,9 @@ describe "Recipe DSL methods" do it "two_classes_one_dsl resolves to Z (respects the priority array)" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { instance_eval("#{temp_two_classes_one_dsl} 'blah'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq resource_class_z end @@ -890,9 +890,9 @@ describe "Recipe DSL methods" do it "two_classes_one_dsl resolves to B (picks the next thing in the priority array)" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { instance_eval("#{temp_two_classes_one_dsl} 'blah'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq resource_class end @@ -911,9 +911,9 @@ describe "Recipe DSL methods" do it "two_classes_one_dsl resolves to Z (respects the most recent priority array)" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { instance_eval("#{temp_two_classes_one_dsl} 'blah'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq resource_class_z end @@ -929,9 +929,9 @@ describe "Recipe DSL methods" do it "two_classes_one_dsl resolves to B (picks the first match from the other priority array)" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { instance_eval("#{temp_two_classes_one_dsl} 'blah'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq resource_class end @@ -954,9 +954,9 @@ describe "Recipe DSL methods" do it "two_classes_one_dsl resolves to B (picks the first match outside the priority array)" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { instance_eval("#{temp_two_classes_one_dsl} 'blah'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq resource_class end @@ -987,7 +987,7 @@ describe "Recipe DSL methods" do result.provides two_classes_one_dsl result end - before { provider_class } # pull on it so it gets defined before the recipe runs + before do provider_class end # pull on it so it gets defined before the recipe runs context "and another provider named 'A'" do let(:provider_class_a) do @@ -1003,25 +1003,25 @@ describe "Recipe DSL methods" do result end context "which provides :two_classes_one_dsl" do - before { provider_class_a.provides two_classes_one_dsl } + before do provider_class_a.provides two_classes_one_dsl end it "two_classes_one_dsl resolves to A (alphabetically earliest)" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { instance_eval("#{temp_two_classes_one_dsl} 'blah'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_provider).to eq provider_class_a end end context "which provides(:two_classes_one_dsl) { false }" do - before { provider_class_a.provides(two_classes_one_dsl) { false } } + before do provider_class_a.provides(two_classes_one_dsl) { false } end it "two_classes_one_dsl resolves to B (since A declined)" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { instance_eval("#{temp_two_classes_one_dsl} 'blah'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_provider).to eq provider_class end @@ -1041,28 +1041,28 @@ describe "Recipe DSL methods" do end result end - before { provider_class_z } # pull on it so it gets defined before the recipe runs + before do provider_class_z end # pull on it so it gets defined before the recipe runs context "which provides :two_classes_one_dsl" do - before { provider_class_z.provides two_classes_one_dsl } + before do provider_class_z.provides two_classes_one_dsl end it "two_classes_one_dsl resolves to Z (last)" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { instance_eval("#{temp_two_classes_one_dsl} 'blah'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_provider).to eq provider_class_z end context "with a priority array [ Z, B ]" do - before { Chef.set_provider_priority_array two_classes_one_dsl, [ provider_class_z, provider_class ] } + before do Chef.set_provider_priority_array two_classes_one_dsl, [ provider_class_z, provider_class ] end it "two_classes_one_dsl resolves to Z (respects the priority map)" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { instance_eval("#{temp_two_classes_one_dsl} 'blah'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_provider).to eq provider_class_z end @@ -1070,30 +1070,30 @@ describe "Recipe DSL methods" do end context "which provides(:two_classes_one_dsl) { false }" do - before { provider_class_z.provides(two_classes_one_dsl) { false } } + before do provider_class_z.provides(two_classes_one_dsl) { false } end context "with a priority array [ Z, B ]" do - before { Chef.set_provider_priority_array two_classes_one_dsl, [ provider_class_z, provider_class ] } + before do Chef.set_provider_priority_array two_classes_one_dsl, [ provider_class_z, provider_class ] end it "two_classes_one_dsl resolves to B (the next one in the priority map)" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { instance_eval("#{temp_two_classes_one_dsl} 'blah'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_provider).to eq provider_class end end context "with priority arrays [ B ] and [ Z ]" do - before { Chef.set_provider_priority_array two_classes_one_dsl, [ provider_class_z ] } - before { Chef.set_provider_priority_array two_classes_one_dsl, [ provider_class ] } + before do Chef.set_provider_priority_array two_classes_one_dsl, [ provider_class_z ] end + before do Chef.set_provider_priority_array two_classes_one_dsl, [ provider_class ] end it "two_classes_one_dsl resolves to B (the one in the next priority map)" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { instance_eval("#{temp_two_classes_one_dsl} 'blah'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_provider).to eq provider_class end @@ -1117,26 +1117,26 @@ describe "Recipe DSL methods" do result.provides two_classes_one_dsl, os: "blarghle" result end - before { resource_class_blarghle } # pull on it so it gets defined before the recipe runs + before do resource_class_blarghle end # pull on it so it gets defined before the recipe runs it "on os = blarghle, two_classes_one_dsl resolves to Blarghle" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "blarghle" instance_eval("#{temp_two_classes_one_dsl} 'blah' do; end") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq resource_class_blarghle end it "on os = linux, two_classes_one_dsl resolves to B" do temp_two_classes_one_dsl = two_classes_one_dsl - recipe = converge do + recipe = converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = "linux" instance_eval("#{temp_two_classes_one_dsl} 'blah' do; end") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq resource_class end @@ -1174,9 +1174,9 @@ describe "Recipe DSL methods" do it "my_resource returns the resource and calls provides?, but does not emit a warning" do dsl_name = my_resource - recipe = converge do + recipe = converge { instance_eval("#{dsl_name} 'foo'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq resource_class expect(resource_class.called_provides).to be_truthy @@ -1216,9 +1216,9 @@ describe "Recipe DSL methods" do it "my_resource runs the provider and does not emit a warning" do temp_my_resource = my_resource - recipe = converge do + recipe = converge { instance_eval("#{temp_my_resource} 'foo'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_provider).to eq provider_class end @@ -1246,9 +1246,9 @@ describe "Recipe DSL methods" do it "my_resource runs the first provider" do temp_my_resource = my_resource - recipe = converge do + recipe = converge { instance_eval("#{temp_my_resource} 'foo'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_provider).to eq provider_class end @@ -1263,9 +1263,9 @@ describe "Recipe DSL methods" do # TODO no warning? ick it "my_resource runs the provider anyway" do temp_my_resource = my_resource - recipe = converge do + recipe = converge { instance_eval("#{temp_my_resource} 'foo'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_provider).to eq provider_class end @@ -1291,13 +1291,13 @@ describe "Recipe DSL methods" do end end end - before { provider_class2 } # make sure the provider class shows up + before do provider_class2 end # make sure the provider class shows up it "my_resource runs the other provider" do temp_my_resource = my_resource - recipe = converge do + recipe = converge { instance_eval("#{temp_my_resource} 'foo'") - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_provider).to eq provider_class2 end @@ -1317,17 +1317,17 @@ describe "Recipe DSL methods" do end it "utf-8 dsl names work" do - recipe = converge do + recipe = converge { Straße("blah") {} - end + } expect(recipe.logged_warnings).to eq "" expect(BaseThingy.created_resource).to eq(UTF8Thingy) end end end - before(:all) { Namer.current_index = 0 } - before { Namer.current_index += 1 } + before(:all) do Namer.current_index = 0 end + before do Namer.current_index += 1 end context "with an LWRP that declares actions" do let(:resource_class) do diff --git a/spec/integration/recipes/resource_action_spec.rb b/spec/integration/recipes/resource_action_spec.rb index c8da9196ca..f2f9936f9b 100644 --- a/spec/integration/recipes/resource_action_spec.rb +++ b/spec/integration/recipes/resource_action_spec.rb @@ -103,14 +103,14 @@ module ResourceActionSpec end it "the action cannot access private methods" do - expect do + expect { converge(<<-EOM, __FILE__, __LINE__ + 1) #{resource_dsl} "hi" do foo "foo!" action :access_private_method end EOM - end.to raise_error(NameError) + }.to raise_error(NameError) expect(ActionJackson.ran_action).to eq :access_private_method end @@ -249,7 +249,7 @@ module ResourceActionSpec end it "Can retrieve ancestors of action class without crashing" do - converge { action_jackson "hi" } + converge do action_jackson "hi" end expect { ActionJackson.action_class.ancestors.join(",") }.not_to raise_error end @@ -371,9 +371,9 @@ module ResourceActionSpec context "With a resource with a UTF-8 action" do it "Running the action works" do - expect_recipe do + expect_recipe { weird_action_jackson "hi" - end.to be_up_to_date + }.to be_up_to_date expect(WeirdActionJackson.action_was).to eq :Straße end end @@ -398,11 +398,11 @@ module ResourceActionSpec end it "Setting group to nil in an action does not emit a warning about it being defined in two places" do - expect_recipe do + expect_recipe { resource_action_spec_set_group_to_nil "hi" do action :set_group_to_nil end - end.to emit_no_warnings_or_errors + }.to emit_no_warnings_or_errors end end @@ -444,9 +444,9 @@ module ResourceActionSpec it "the methods are available to the action" do r = nil - expect_recipe do + expect_recipe { r = declares_action_class_methods "hi" - end.to emit_no_warnings_or_errors + }.to emit_no_warnings_or_errors expect(r.x).to eq(4) end @@ -467,9 +467,9 @@ module ResourceActionSpec it "the methods are available to the action" do r = nil - expect_recipe do + expect_recipe { r = declares_action_class_methods_too "hi" - end.to emit_no_warnings_or_errors + }.to emit_no_warnings_or_errors expect(r.x).to eq(8) end end @@ -492,9 +492,9 @@ module ResourceActionSpec it "the methods are available to the action" do r = nil - expect_recipe do + expect_recipe { r = declares_action_class_methods_too "hi" - end.to emit_no_warnings_or_errors + }.to emit_no_warnings_or_errors expect(r.x).to eq(8) end end diff --git a/spec/integration/recipes/resource_converge_if_changed_spec.rb b/spec/integration/recipes/resource_converge_if_changed_spec.rb index 605cb2c941..2cb3b5fc3a 100644 --- a/spec/integration/recipes/resource_converge_if_changed_spec.rb +++ b/spec/integration/recipes/resource_converge_if_changed_spec.rb @@ -13,9 +13,9 @@ describe "Resource::ActionClass#converge_if_changed" do attr_writer :incrementing_value end - before(:all) { Namer.current_index = 1 } - before { Namer.current_index += 1 } - before { Namer.incrementing_value = 0 } + before(:all) do Namer.current_index = 1 end + before do Namer.current_index += 1 end + before do Namer.incrementing_value = 0 end context "when the resource has identity, state, control, and sensitive properties" do let(:resource_name) { :"converge_if_changed_dsl#{Namer.current_index}" } diff --git a/spec/integration/recipes/resource_load_spec.rb b/spec/integration/recipes/resource_load_spec.rb index 79df1d6478..860f4b0080 100644 --- a/spec/integration/recipes/resource_load_spec.rb +++ b/spec/integration/recipes/resource_load_spec.rb @@ -13,9 +13,9 @@ describe "Resource.load_current_value" do attr_writer :incrementing_value end - before(:all) { Namer.current_index = 1 } - before { Namer.current_index += 1 } - before { Namer.incrementing_value = 0 } + before(:all) do Namer.current_index = 1 end + before do Namer.current_index += 1 end + before do Namer.incrementing_value = 0 end let(:resource_name) { :"load_current_value_dsl#{Namer.current_index}" } let(:resource_class) do @@ -40,7 +40,7 @@ describe "Resource.load_current_value" do end # Pull on resource_class to initialize it - before { resource_class } + before do resource_class end context "with a resource with load_current_value" do before :each do @@ -57,9 +57,9 @@ describe "Resource.load_current_value" do e = self r = nil converge do - r = public_send(e.resource_name, "blah") do + r = public_send(e.resource_name, "blah") { x "desired" - end + } end r end @@ -131,15 +131,15 @@ describe "Resource.load_current_value" do end # Pull on subresource_class to initialize it - before { subresource_class } + before do subresource_class end let(:subresource) do e = self r = nil converge do - r = public_send(e.subresource_name, "blah") do + r = public_send(e.subresource_name, "blah") { x "desired" - end + } end r end diff --git a/spec/integration/solo/solo_spec.rb b/spec/integration/solo/solo_spec.rb index 451943e225..f19cc682c4 100644 --- a/spec/integration/solo/solo_spec.rb +++ b/spec/integration/solo/solo_spec.rb @@ -180,7 +180,7 @@ describe Chef::Dist::SOLOEXEC do EOM # We have a timeout protection here so that if due to some bug # run_lock gets stuck we can discover it. - expect do + expect { Timeout.timeout(120) do chef_dir = File.join(File.dirname(__FILE__), "..", "..", "..") @@ -200,7 +200,7 @@ describe Chef::Dist::SOLOEXEC do threads.each(&:join) end - end.not_to raise_error + }.not_to raise_error # Unfortunately file / directory helpers in integration tests # are implemented using before(:each) so we need to do all below diff --git a/spec/scripts/ssl-serve.rb b/spec/scripts/ssl-serve.rb index e9f645416c..fc5f273af0 100644 --- a/spec/scripts/ssl-serve.rb +++ b/spec/scripts/ssl-serve.rb @@ -42,6 +42,6 @@ webrick_opts = DEFAULT_OPTIONS.merge(server_opts) pp webrick_opts: webrick_opts server = WEBrick::HTTPServer.new(webrick_opts) -trap("INT") { server.shutdown } +trap("INT") do server.shutdown end server.start diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 5ab97a8320..4d42cd29e2 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -53,7 +53,7 @@ require "chef/knife" Dir["lib/chef/knife/**/*.rb"] .map { |f| f.gsub("lib/", "") } .map { |f| f.gsub(/\.rb$/, "") } - .each { |f| require f } + .each do |f| require f end require "chef/resource_resolver" require "chef/provider_resolver" @@ -95,7 +95,7 @@ Dir["spec/support/**/*.rb"] .reject { |f| f =~ %r{^spec/support/pedant} } .map { |f| f.gsub(/.rb$/, "") } .map { |f| f.gsub(%r{spec/}, "") } - .each { |f| require f } + .each do |f| require f end OHAI_SYSTEM = Ohai::System.new OHAI_SYSTEM.all_plugins(["platform", "hostname", "languages/powershell"]) @@ -271,11 +271,11 @@ RSpec.configure do |config| if Process.euid == 0 && Process.uid == 0 config.after(:each) do if Process.uid != 0 - RSpec.configure { |c| c.fail_fast = true } + RSpec.configure do |c| c.fail_fast = true end raise "rspec was invoked as root, but the last test dropped real uid to #{Process.uid}" end if Process.euid != 0 - RSpec.configure { |c| c.fail_fast = true } + RSpec.configure do |c| c.fail_fast = true end raise "rspec was invoked as root, but the last test dropped effective uid to #{Process.euid}" end end diff --git a/spec/stress/win32/security_spec.rb b/spec/stress/win32/security_spec.rb index 8929a2ff74..0f9da86a9b 100644 --- a/spec/stress/win32/security_spec.rb +++ b/spec/stress/win32/security_spec.rb @@ -49,21 +49,21 @@ describe "Chef::ReservedNames::Win32::Security", :windows_only do end it "should not leak when retrieving and reading the ACE from a file", :volatile do - expect do + expect { sids = Chef::ReservedNames::Win32::Security::SecurableObject.new(@monkeyfoo).security_descriptor.dacl.select(&:sid) GC.start - end.not_to leak_memory(warmup: 50, iterations: 100) + }.not_to leak_memory(warmup: 50, iterations: 100) end it "should not leak when creating a new ACL and setting it on a file", :volatile do securable_object = Security::SecurableObject.new(@monkeyfoo) - expect do + expect { securable_object.dacl = Chef::ReservedNames::Win32::Security::ACL.create([ Chef::ReservedNames::Win32::Security::ACE.access_allowed(Chef::ReservedNames::Win32::Security::SID.Everyone, Chef::ReservedNames::Win32::API::Security::GENERIC_READ), Chef::ReservedNames::Win32::Security::ACE.access_denied(Chef::ReservedNames::Win32::Security::SID.from_account("Users"), Chef::ReservedNames::Win32::API::Security::GENERIC_ALL), ]) GC.start - end.not_to leak_memory(warmup: 50, iterations: 100) + }.not_to leak_memory(warmup: 50, iterations: 100) end end diff --git a/spec/support/shared/functional/file_resource.rb b/spec/support/shared/functional/file_resource.rb index 114971641d..bb6a68e946 100644 --- a/spec/support/shared/functional/file_resource.rb +++ b/spec/support/shared/functional/file_resource.rb @@ -149,7 +149,7 @@ shared_examples_for "a file with the wrong content" do end context "when set" do - before { resource.sensitive(true) } + before do resource.sensitive(true) end it "should be set on the resource" do expect(resource.sensitive).to(be_truthy) @@ -917,7 +917,7 @@ shared_examples_for "a configured file resource" do context "when the target file has the wrong content" do before(:each) do - File.open(path, "wb") { |f| f.print "This is so wrong!!!" } + File.open(path, "wb") do |f| f.print "This is so wrong!!!" end now = Time.now.to_i File.utime(now - 9000, now - 9000, path) @@ -944,7 +944,7 @@ shared_examples_for "a configured file resource" do context "when the target file has the correct content" do before(:each) do - File.open(path, "wb") { |f| f.print expected_content } + File.open(path, "wb") do |f| f.print expected_content end now = Time.now.to_i File.utime(now - 9000, now - 9000, path) @@ -981,7 +981,7 @@ shared_examples_for "a configured file resource" do end before do - File.open(path, "wb") { |f| f.print expected_content } + File.open(path, "wb") do |f| f.print expected_content end now = Time.now.to_i File.utime(now - 9000, now - 9000, path) diff --git a/spec/support/shared/integration/integration_helper.rb b/spec/support/shared/integration/integration_helper.rb index 6c0eca98be..42f63e7c05 100644 --- a/spec/support/shared/integration/integration_helper.rb +++ b/spec/support/shared/integration/integration_helper.rb @@ -142,13 +142,13 @@ module IntegrationSupport # Versioned cookbooks RSpec.shared_context "with versioned cookbooks", versioned_cookbooks: true do - before(:each) { Chef::Config[:versioned_cookbooks] = true } + before(:each) do Chef::Config[:versioned_cookbooks] = true end after(:each) { Chef::Config.delete(:versioned_cookbooks) } end RSpec.shared_context "without versioned cookbooks", versioned_cookbooks: false do # Just make sure this goes back to default - before(:each) { Chef::Config[:versioned_cookbooks] = false } + before(:each) do Chef::Config[:versioned_cookbooks] = false end after(:each) { Chef::Config.delete(:versioned_cookbooks) } end diff --git a/spec/support/shared/unit/file_system_support.rb b/spec/support/shared/unit/file_system_support.rb index 957479f149..0ecbff1eda 100644 --- a/spec/support/shared/unit/file_system_support.rb +++ b/spec/support/shared/unit/file_system_support.rb @@ -64,7 +64,7 @@ module FileSystemSupport def list_should_yield_paths(fs, pattern_str, *expected_paths) result_paths = [] - Chef::ChefFS::FileSystem.list(fs, pattern(pattern_str)).each { |result| result_paths << result.path } + Chef::ChefFS::FileSystem.list(fs, pattern(pattern_str)).each do |result| result_paths << result.path end expect(result_paths).to match_array(expected_paths) end end diff --git a/spec/support/shared/unit/provider/file.rb b/spec/support/shared/unit/provider/file.rb index 2771a371d4..820b4bb887 100644 --- a/spec/support/shared/unit/provider/file.rb +++ b/spec/support/shared/unit/provider/file.rb @@ -415,7 +415,7 @@ shared_examples_for Chef::Provider::File do context "define_resource_requirements" do context "when the enclosing directory does not exist" do - before { setup_missing_enclosing_directory } + before do setup_missing_enclosing_directory end %i{create create_if_missing touch}.each do |action| context "action #{action}" do @@ -433,7 +433,7 @@ shared_examples_for Chef::Provider::File do end context "when the file exists but is not deletable" do - before { setup_unwritable_file } + before do setup_unwritable_file end it "action delete raises InsufficientPermissions" do expect { provider.run_action(:delete) }.to raise_error(Chef::Exceptions::InsufficientPermissions) @@ -458,7 +458,7 @@ shared_examples_for Chef::Provider::File do end context "do_validate_content" do - before { setup_normal_file } + before do setup_normal_file end let(:tempfile) do t = double("Tempfile", path: "/tmp/foo-bar-baz", closed?: true) @@ -492,7 +492,7 @@ shared_examples_for Chef::Provider::File do context "do_create_file" do context "when the file exists" do - before { setup_normal_file } + before do setup_normal_file end it "should not create the file" do provider.load_current_resource expect(provider.deployment_strategy).not_to receive(:create).with(resource_path) @@ -501,7 +501,7 @@ shared_examples_for Chef::Provider::File do end end context "when the file does not exist" do - before { setup_missing_file } + before do setup_missing_file end it "should create the file" do provider.load_current_resource expect(provider.deployment_strategy).to receive(:create).with(resource_path) @@ -540,7 +540,7 @@ shared_examples_for Chef::Provider::File do expect(provider.deployment_strategy).to receive(:deploy).with(tempfile_path, normalized_path) end context "when the file was created" do - before { expect(provider).to receive(:needs_creating?).at_least(:once).and_return(true) } + before do expect(provider).to receive(:needs_creating?).at_least(:once).and_return(true) end it "does not backup the file" do expect(provider).not_to receive(:do_backup) provider.send(:do_contents_changes) @@ -693,8 +693,8 @@ shared_examples_for Chef::Provider::File do end context "in why run mode" do - before { Chef::Config[:why_run] = true } - after { Chef::Config[:why_run] = false } + before do Chef::Config[:why_run] = true end + after do Chef::Config[:why_run] = false end it "does not modify new_resource" do setup_missing_file @@ -708,7 +708,7 @@ shared_examples_for Chef::Provider::File do context "when the file exists" do context "when the file is writable" do context "when the file is not a symlink" do - before { setup_normal_file } + before do setup_normal_file end it "should backup and delete the file and be updated by the last action" do expect(provider).to receive(:do_backup).at_least(:once).and_return(true) expect(File).to receive(:delete).with(resource_path).and_return(true) @@ -717,7 +717,7 @@ shared_examples_for Chef::Provider::File do end end context "when the file is a symlink" do - before { setup_symlink } + before do setup_symlink end it "should not backup the symlink" do expect(provider).not_to receive(:do_backup) expect(File).to receive(:delete).with(resource_path).and_return(true) @@ -727,7 +727,7 @@ shared_examples_for Chef::Provider::File do end end context "when the file is not writable" do - before { setup_unwritable_file } + before do setup_unwritable_file end it "should not try to backup or delete the file, and should not be updated by last action" do expect(provider).not_to receive(:do_backup) expect(File).not_to receive(:delete) @@ -738,7 +738,7 @@ shared_examples_for Chef::Provider::File do end context "when the file does not exist" do - before { setup_missing_file } + before do setup_missing_file end it "should not try to backup or delete the file, and should not be updated by last action" do expect(provider).not_to receive(:do_backup) @@ -751,7 +751,7 @@ shared_examples_for Chef::Provider::File do context "action touch" do context "when the file does not exist" do - before { setup_missing_file } + before do setup_missing_file end it "should update the atime/mtime on action_touch" do expect(File).to receive(:utime).once expect(provider).to receive(:action_create) @@ -760,7 +760,7 @@ shared_examples_for Chef::Provider::File do end end context "when the file exists" do - before { setup_normal_file } + before do setup_normal_file end it "should update the atime/mtime on action_touch" do expect(File).to receive(:utime).once expect(provider).to receive(:action_create) @@ -772,7 +772,7 @@ shared_examples_for Chef::Provider::File do context "action create_if_missing" do context "when the file does not exist" do - before { setup_missing_file } + before do setup_missing_file end it "should call action_create" do expect(provider).to receive(:action_create) provider.run_action(:create_if_missing) @@ -780,7 +780,7 @@ shared_examples_for Chef::Provider::File do end context "when the file exists" do - before { setup_normal_file } + before do setup_normal_file end it "should not call action_create" do expect(provider).not_to receive(:action_create) provider.run_action(:create_if_missing) diff --git a/spec/support/shared/unit/windows_script_resource.rb b/spec/support/shared/unit/windows_script_resource.rb index 29238a3917..48974b2387 100644 --- a/spec/support/shared/unit/windows_script_resource.rb +++ b/spec/support/shared/unit/windows_script_resource.rb @@ -57,13 +57,13 @@ shared_examples_for "a Windows script resource" do describe "when the guard is given a ruby block" do it "should evaluate the guard if the guard_interpreter is set to its default value" do - @resource.only_if { true } + @resource.only_if do true end expect(@resource.should_skip?(:run)).to eq(nil) end it "should raise an exception if the guard_interpreter is overridden from its default value" do @resource.guard_interpreter :bash - @resource.only_if { true } + @resource.only_if do true end expect { @resource.should_skip?(:run) }.to raise_error(ArgumentError) end end diff --git a/spec/unit/application/client_spec.rb b/spec/unit/application/client_spec.rb index 0773fc70fd..316dbea17c 100644 --- a/spec/unit/application/client_spec.rb +++ b/spec/unit/application/client_spec.rb @@ -392,10 +392,10 @@ Enable .* interval runs by setting `:client_fork = true` in your config file or end it "sleeps for the amount of time passed" do - pid = fork do + pid = fork { expect(@app).to receive(:interval_sleep).with(wait_secs) @app.run_application - end + } _pid, result = Process.waitpid2(pid) expect(result.exitstatus).to eq 0 @@ -523,18 +523,18 @@ describe Chef::Application::Client, "run_application", :unix_only do end it "should exit hard with exitstatus 3", :volatile do - pid = fork do + pid = fork { @app.run_application - end + } Process.kill("TERM", pid) _pid, result = Process.waitpid2(pid) expect(result.exitstatus).to eq(3) end it "should allow child to finish converging" do - pid = fork do + pid = fork { @app.run_application - end + } expect(@pipe[0].gets).to eq("started\n") Process.kill("TERM", pid) Process.wait(pid) @@ -551,9 +551,9 @@ describe Chef::Application::Client, "run_application", :unix_only do end it "should exit gracefully when sent during converge" do - pid = fork do + pid = fork { @app.run_application - end + } expect(@pipe[0].gets).to eq("started\n") Process.kill("TERM", pid) _pid, result = Process.waitpid2(pid) @@ -563,10 +563,10 @@ describe Chef::Application::Client, "run_application", :unix_only do end it "should exit hard when sent before converge" do - pid = fork do + pid = fork { sleep 3 @app.run_application - end + } Process.kill("TERM", pid) _pid, result = Process.waitpid2(pid) expect(result.exitstatus).to eq(3) @@ -585,9 +585,9 @@ describe Chef::Application::Client, "run_application", :unix_only do it "shouldn't sleep when sent USR1" do allow(@app).to receive(:interval_sleep).and_return true allow(@app).to receive(:interval_sleep).with(0).and_call_original - pid = fork do + pid = fork { @app.run_application - end + } _pid, result = Process.waitpid2(pid) expect(result.exitstatus).to eq(0) end diff --git a/spec/unit/chef_class_spec.rb b/spec/unit/chef_class_spec.rb index d862273f52..b0f08e260a 100644 --- a/spec/unit/chef_class_spec.rb +++ b/spec/unit/chef_class_spec.rb @@ -99,18 +99,18 @@ describe "Chef class" do end it "raise error if unknown event type is passed" do - expect do + expect { Chef.event_handler do on :yolo do end end - end.to raise_error(Chef::Exceptions::InvalidEventType) + }.to raise_error(Chef::Exceptions::InvalidEventType) end end describe "Deprecation system" do context "with treat_deprecation_warnings_as_errors false" do - before { Chef::Config[:treat_deprecation_warnings_as_errors] = false } + before do Chef::Config[:treat_deprecation_warnings_as_errors] = false end it "displays a simple deprecation warning" do expect(Chef::Log).to receive(:warn).with(%r{spec/unit/chef_class_spec\.rb.*?I'm a little teapot.*?Please see}m) @@ -229,7 +229,7 @@ describe "Chef class" do context "with treat_deprecation_warnings_as_errors true" do # This is already turned on globally for Chef's unit tests, but just for clarity do it here too. - before { Chef::Config[:treat_deprecation_warnings_as_errors] = true } + before do Chef::Config[:treat_deprecation_warnings_as_errors] = true end it "displays a simple deprecation error" do expect(Chef::Log).to receive(:error).with(%r{spec/unit/chef_class_spec\.rb.*?I'm a little teapot.*?Please see}m) diff --git a/spec/unit/chef_fs/file_system/operation_failed_error_spec.rb b/spec/unit/chef_fs/file_system/operation_failed_error_spec.rb index 661994337b..2bda2b75c9 100644 --- a/spec/unit/chef_fs/file_system/operation_failed_error_spec.rb +++ b/spec/unit/chef_fs/file_system/operation_failed_error_spec.rb @@ -30,17 +30,17 @@ describe Chef::ChefFS::FileSystem::OperationFailedError do allow(@response).to receive(:code).and_return("400") allow(@response).to receive(:body).and_return(response_body) exception = Net::HTTPClientException.new("(exception) unauthorized", @response) - expect do + expect { raise Chef::ChefFS::FileSystem::OperationFailedError.new(:write, self, exception), error_message - end.to raise_error(Chef::ChefFS::FileSystem::OperationFailedError, "#{error_message} cause: #{response_body}") + }.to raise_error(Chef::ChefFS::FileSystem::OperationFailedError, "#{error_message} cause: #{response_body}") end end context "does not have a cause attribute" do it "does not include error cause" do - expect do + expect { raise Chef::ChefFS::FileSystem::OperationFailedError.new(:write, self), error_message - end.to raise_error(Chef::ChefFS::FileSystem::OperationFailedError, error_message) + }.to raise_error(Chef::ChefFS::FileSystem::OperationFailedError, error_message) end end end diff --git a/spec/unit/chef_fs/parallelizer.rb b/spec/unit/chef_fs/parallelizer.rb index d43e48b7bc..541ce2593e 100644 --- a/spec/unit/chef_fs/parallelizer.rb +++ b/spec/unit/chef_fs/parallelizer.rb @@ -35,29 +35,29 @@ describe Chef::ChefFS::Parallelizer do context "With :ordered => false (unordered output)" do it "An empty input produces an empty output" do - expect(parallelize([], ordered: false) do + expect(parallelize([], ordered: false) { sleep 10 - end.to_a).to eql([]) + }.to_a).to eql([]) expect(elapsed_time).to be < 0.1 end it "10 sleep(0.2)s complete within 0.5 seconds" do - expect(parallelize(1.upto(10), ordered: false) do |i| + expect(parallelize(1.upto(10), ordered: false) { |i| sleep 0.2 "x" - end.to_a).to eq(%w{x x x x x x x x x x}) + }.to_a).to eq(%w{x x x x x x x x x x}) expect(elapsed_time).to be < 0.5 end it "The output comes as soon as it is available" do - enum = parallelize([0.5, 0.3, 0.1], ordered: false) do |val| + enum = parallelize([0.5, 0.3, 0.1], ordered: false) { |val| sleep val val - end - expect(enum.map do |value| + } + expect(enum.map { |value| expect(elapsed_time).to be < value + 0.1 value - end).to eq([ 0.1, 0.3, 0.5 ]) + }).to eq([ 0.1, 0.3, 0.5 ]) end it "An exception in input is passed through but does NOT stop processing" do @@ -73,7 +73,7 @@ describe Chef::ChefFS::Parallelizer do it "Exceptions in output are raised after all processing is done" do processed = 0 - enum = parallelize([1, 2, "x", 3], ordered: false) do |x| + enum = parallelize([1, 2, "x", 3], ordered: false) { |x| if x == "x" sleep 0.1 raise "hi" @@ -81,7 +81,7 @@ describe Chef::ChefFS::Parallelizer do sleep 0.2 processed += 1 x - end + } results = [] expect { enum.each { |value| results << value } }.to raise_error "hi" expect(results.sort).to eq([ 1, 2, 3 ]) @@ -91,7 +91,7 @@ describe Chef::ChefFS::Parallelizer do it "Exceptions with :stop_on_exception are raised after all processing is done" do processed = 0 - parallelized = parallelize([0.3, 0.3, "x", 0.3, 0.3, 0.3, 0.3, 0.3], ordered: false, stop_on_exception: true) do |x| + parallelized = parallelize([0.3, 0.3, "x", 0.3, 0.3, 0.3, 0.3, 0.3], ordered: false, stop_on_exception: true) { |x| if x == "x" sleep(0.1) raise "hi" @@ -99,7 +99,7 @@ describe Chef::ChefFS::Parallelizer do sleep(x) processed += 1 x - end + } expect { parallelized.to_a }.to raise_error "hi" expect(processed).to eq(4) end @@ -107,25 +107,25 @@ describe Chef::ChefFS::Parallelizer do context "With :ordered => true (ordered output)" do it "An empty input produces an empty output" do - expect(parallelize([]) do + expect(parallelize([]) { sleep 10 - end.to_a).to eql([]) + }.to_a).to eql([]) expect(elapsed_time).to be < 0.1 end it "10 sleep(0.2)s complete within 0.5 seconds" do - expect(parallelize(1.upto(10), ordered: true) do |i| + expect(parallelize(1.upto(10), ordered: true) { |i| sleep 0.2 "x" - end.to_a).to eq(%w{x x x x x x x x x x}) + }.to_a).to eq(%w{x x x x x x x x x x}) expect(elapsed_time).to be < 0.5 end it "Output comes in the order of the input" do - enum = parallelize([0.5, 0.3, 0.1]) do |val| + enum = parallelize([0.5, 0.3, 0.1]) { |val| sleep val val - end.enum_for(:each_with_index) + }.enum_for(:each_with_index) expect(enum.next).to eq([ 0.5, 0 ]) expect(enum.next).to eq([ 0.3, 1 ]) expect(enum.next).to eq([ 0.1, 2 ]) @@ -145,7 +145,7 @@ describe Chef::ChefFS::Parallelizer do it "Exceptions in output are raised in the correct sequence and running processes do NOT stop processing" do processed = 0 - enum = parallelize([1, 2, "x", 3]) do |x| + enum = parallelize([1, 2, "x", 3]) { |x| if x == "x" sleep(0.1) raise "hi" @@ -153,7 +153,7 @@ describe Chef::ChefFS::Parallelizer do sleep(0.2) processed += 1 x - end + } results = [] expect { enum.each { |value| results << value } }.to raise_error "hi" expect(results).to eq([ 1, 2 ]) @@ -163,7 +163,7 @@ describe Chef::ChefFS::Parallelizer do it "Exceptions with :stop_on_exception are raised after all processing is done" do processed = 0 - parallelized = parallelize([0.3, 0.3, "x", 0.3, 0.3, 0.3, 0.3, 0.3], ordered: false, stop_on_exception: true) do |x| + parallelized = parallelize([0.3, 0.3, "x", 0.3, 0.3, 0.3, 0.3, 0.3], ordered: false, stop_on_exception: true) { |x| if x == "x" sleep(0.1) raise "hi" @@ -171,7 +171,7 @@ describe Chef::ChefFS::Parallelizer do sleep(x) processed += 1 x - end + } expect { parallelized.to_a }.to raise_error "hi" expect(processed).to eq(4) end @@ -187,10 +187,10 @@ describe Chef::ChefFS::Parallelizer do sleep 0.1 end enum = parallelize(input) { |x| x } - expect(enum.map do |value| + expect(enum.map { |value| expect(elapsed_time).to be < (value + 1) * 0.1 value - end).to eq([ 1, 2, 3 ]) + }).to eq([ 1, 2, 3 ]) end end @@ -205,11 +205,11 @@ describe Chef::ChefFS::Parallelizer do started = false @occupying_job_finished = occupying_job_finished = [ false ] @thread = Thread.new do - parallelizer.parallelize([0], main_thread_processing: false) do |x| + parallelizer.parallelize([0], main_thread_processing: false) { |x| started = true sleep(0.3) occupying_job_finished[0] = true - end.wait + }.wait end sleep(0.01) until started end @@ -219,18 +219,18 @@ describe Chef::ChefFS::Parallelizer do end it "parallelize with :main_thread_processing = true does not block" do - expect(parallelizer.parallelize([1]) do |x| + expect(parallelizer.parallelize([1]) { |x| sleep(0.1) x - end.to_a).to eq([ 1 ]) + }.to_a).to eq([ 1 ]) expect(elapsed_time).to be < 0.2 end it "parallelize with :main_thread_processing = false waits for the job to finish" do - expect(parallelizer.parallelize([1], main_thread_processing: false) do |x| + expect(parallelizer.parallelize([1], main_thread_processing: false) { |x| sleep(0.1) x + 1 - end.to_a).to eq([ 2 ]) + }.to_a).to eq([ 2 ]) expect(elapsed_time).to be > 0.3 end @@ -264,11 +264,11 @@ describe Chef::ChefFS::Parallelizer do it ".count does not process anything" do outputs_processed = 0 input_mapper = TestEnumerable.new(1, 2, 3, 4, 5, 6) - enum = parallelizer.parallelize(input_mapper) do |x| + enum = parallelizer.parallelize(input_mapper) { |x| outputs_processed += 1 sleep(0.05) # Just enough to yield and get other inputs in the queue x - end + } expect(enum.count).to eq(6) expect(outputs_processed).to eq(0) expect(input_mapper.num_processed).to eq(6) @@ -277,10 +277,10 @@ describe Chef::ChefFS::Parallelizer do it ".count with arguments works normally" do outputs_processed = 0 input_mapper = TestEnumerable.new(1, 1, 1, 1, 2, 2, 2, 3, 3, 4) - enum = parallelizer.parallelize(input_mapper) do |x| + enum = parallelizer.parallelize(input_mapper) { |x| outputs_processed += 1 x - end + } expect(enum.count { |x| x > 1 }).to eq(6) expect(enum.count(2)).to eq(3) expect(outputs_processed).to eq(20) @@ -290,11 +290,11 @@ describe Chef::ChefFS::Parallelizer do it ".first does not enumerate anything other than the first result(s)" do outputs_processed = 0 input_mapper = TestEnumerable.new(1, 2, 3, 4, 5, 6) - enum = parallelizer.parallelize(input_mapper) do |x| + enum = parallelizer.parallelize(input_mapper) { |x| outputs_processed += 1 sleep(0.05) # Just enough to yield and get other inputs in the queue x - end + } expect(enum.first).to eq(1) expect(enum.first(2)).to eq([1, 2]) expect(outputs_processed).to eq(3) @@ -304,11 +304,11 @@ describe Chef::ChefFS::Parallelizer do it ".take does not enumerate anything other than the first result(s)" do outputs_processed = 0 input_mapper = TestEnumerable.new(1, 2, 3, 4, 5, 6) - enum = parallelizer.parallelize(input_mapper) do |x| + enum = parallelizer.parallelize(input_mapper) { |x| outputs_processed += 1 sleep(0.05) # Just enough to yield and get other inputs in the queue x - end + } expect(enum.take(2)).to eq([1, 2]) expect(outputs_processed).to eq(2) expect(input_mapper.num_processed).to eq(2) @@ -317,11 +317,11 @@ describe Chef::ChefFS::Parallelizer do it ".drop does not process anything other than the last result(s)" do outputs_processed = 0 input_mapper = TestEnumerable.new(1, 2, 3, 4, 5, 6) - enum = parallelizer.parallelize(input_mapper) do |x| + enum = parallelizer.parallelize(input_mapper) { |x| outputs_processed += 1 sleep(0.05) # Just enough to yield and get other inputs in the queue x - end + } expect(enum.drop(2)).to eq([3, 4, 5, 6]) expect(outputs_processed).to eq(4) expect(input_mapper.num_processed).to eq(6) @@ -331,11 +331,11 @@ describe Chef::ChefFS::Parallelizer do it ".lazy.take does not enumerate anything other than the first result(s)" do outputs_processed = 0 input_mapper = TestEnumerable.new(1, 2, 3, 4, 5, 6) - enum = parallelizer.parallelize(input_mapper) do |x| + enum = parallelizer.parallelize(input_mapper) { |x| outputs_processed += 1 sleep(0.05) # Just enough to yield and get other inputs in the queue x - end + } expect(enum.lazy.take(2).to_a).to eq([1, 2]) expect(outputs_processed).to eq(2) expect(input_mapper.num_processed).to eq(2) @@ -344,11 +344,11 @@ describe Chef::ChefFS::Parallelizer do it ".drop does not process anything other than the last result(s)" do outputs_processed = 0 input_mapper = TestEnumerable.new(1, 2, 3, 4, 5, 6) - enum = parallelizer.parallelize(input_mapper) do |x| + enum = parallelizer.parallelize(input_mapper) { |x| outputs_processed += 1 sleep(0.05) # Just enough to yield and get other inputs in the queue x - end + } expect(enum.lazy.drop(2).to_a).to eq([3, 4, 5, 6]) expect(outputs_processed).to eq(4) expect(input_mapper.num_processed).to eq(6) @@ -357,11 +357,11 @@ describe Chef::ChefFS::Parallelizer do it "lazy enumerable is actually lazy" do outputs_processed = 0 input_mapper = TestEnumerable.new(1, 2, 3, 4, 5, 6) - enum = parallelizer.parallelize(input_mapper) do |x| + enum = parallelizer.parallelize(input_mapper) { |x| outputs_processed += 1 sleep(0.05) # Just enough to yield and get other inputs in the queue x - end + } enum.lazy.take(2) enum.lazy.drop(2) sleep(0.1) @@ -375,10 +375,10 @@ describe Chef::ChefFS::Parallelizer do it ".map twice on the same parallel enumerable returns the correct results and re-processes the input" do outputs_processed = 0 input_mapper = TestEnumerable.new(1, 2, 3) - enum = parallelizer.parallelize(input_mapper) do |x| + enum = parallelizer.parallelize(input_mapper) { |x| outputs_processed += 1 x - end + } expect(enum.map { |x| x }).to eq([1, 2, 3]) expect(enum.map { |x| x }).to eq([1, 2, 3]) expect(outputs_processed).to eq(6) @@ -388,10 +388,10 @@ describe Chef::ChefFS::Parallelizer do it ".first and then .map on the same parallel enumerable returns the correct results and re-processes the input" do outputs_processed = 0 input_mapper = TestEnumerable.new(1, 2, 3) - enum = parallelizer.parallelize(input_mapper) do |x| + enum = parallelizer.parallelize(input_mapper) { |x| outputs_processed += 1 x - end + } expect(enum.first).to eq(1) expect(enum.map { |x| x }).to eq([1, 2, 3]) expect(outputs_processed).to be >= 4 @@ -402,10 +402,10 @@ describe Chef::ChefFS::Parallelizer do enum = parallelizer.parallelize([1, 2, 3]) { |x| x } a = enum.enum_for(:each) a.next - expect do + expect { b = enum.enum_for(:each) b.next - end.to raise_error + }.to raise_error end end end @@ -436,13 +436,13 @@ describe Chef::ChefFS::Parallelizer do end it "does not have contention issues with large numbers of jobs and inputs with ordering off" do - parallelizers = 0.upto(99).map do + parallelizers = 0.upto(99).map { parallelizer.parallelize(1.upto(500)) { |x| x + 1 } - end + } outputs = [] - threads = 0.upto(99).map do |i| + threads = 0.upto(99).map { |i| Thread.new { outputs[i] = parallelizers[i].to_a } - end + } threads.each(&:join) outputs.each { |output| expect(output.sort).to eq(2.upto(501).to_a) } end diff --git a/spec/unit/client_spec.rb b/spec/unit/client_spec.rb index 5182717af8..eae1b6a400 100644 --- a/spec/unit/client_spec.rb +++ b/spec/unit/client_spec.rb @@ -733,9 +733,9 @@ describe Chef::Client do context "when any directory of cookbook_path contains no cookbook" do it "raises CookbookNotFound error" do - expect do + expect { client.send(:assert_cookbook_path_not_empty, nil) - end.to raise_error(Chef::Exceptions::CookbookNotFound, 'None of the cookbook paths set in Chef::Config[:cookbook_path], ["/path/to/invalid/cookbook_path"], contain any cookbooks') + }.to raise_error(Chef::Exceptions::CookbookNotFound, 'None of the cookbook paths set in Chef::Config[:cookbook_path], ["/path/to/invalid/cookbook_path"], contain any cookbooks') end end end diff --git a/spec/unit/cookbook/syntax_check_spec.rb b/spec/unit/cookbook/syntax_check_spec.rb index a24fa3ab2a..18b2227bee 100644 --- a/spec/unit/cookbook/syntax_check_spec.rb +++ b/spec/unit/cookbook/syntax_check_spec.rb @@ -208,7 +208,7 @@ describe Chef::Cookbook::SyntaxCheck do describe "and the files have been syntax checked previously" do before do - syntax_check.untested_ruby_files.each { |f| syntax_check.validated(f) } + syntax_check.untested_ruby_files.each do |f| syntax_check.validated(f) end syntax_check.untested_template_files.each { |f| syntax_check.validated(f) } end diff --git a/spec/unit/cookbook_loader_spec.rb b/spec/unit/cookbook_loader_spec.rb index c747f14dd0..c6bcb60d57 100644 --- a/spec/unit/cookbook_loader_spec.rb +++ b/spec/unit/cookbook_loader_spec.rb @@ -40,7 +40,7 @@ describe Chef::CookbookLoader do cookbook_paths |= Dir[File.join(repo_path, "*")] end - cookbook_paths.delete_if { |path| File.basename(path) == "chefignore" } + cookbook_paths.delete_if do |path| File.basename(path) == "chefignore" end cookbook_paths.each do |cookbook_path| expect(Chef::Cookbook::CookbookVersionLoader).to receive(:new) @@ -112,30 +112,30 @@ describe Chef::CookbookLoader do end it "should load different attribute files from deeper paths" do - expect(full_paths_for_part(:openldap, "attributes").detect do |f| + expect(full_paths_for_part(:openldap, "attributes").detect { |f| f =~ %r{cookbooks/openldap/attributes/smokey.rb} - end).not_to eql(nil) + }).not_to eql(nil) end it "should load definition files from deeper paths" do - expect(full_paths_for_part(:openldap, "definitions").detect do |f| + expect(full_paths_for_part(:openldap, "definitions").detect { |f| f =~ %r{cookbooks/openldap/definitions/server.rb} - end).not_to eql(nil) + }).not_to eql(nil) end it "should load recipe files from deeper paths" do - expect(full_paths_for_part(:openldap, "recipes").detect do |f| + expect(full_paths_for_part(:openldap, "recipes").detect { |f| f =~ %r{cookbooks/openldap/recipes/one.rb} - end).not_to eql(nil) + }).not_to eql(nil) end it "should find files that start with a ." do - expect(full_paths_for_part(:openldap, "files").detect do |f| + expect(full_paths_for_part(:openldap, "files").detect { |f| f =~ /\.dotfile$/ - end).to match(/\.dotfile$/) - expect(full_paths_for_part(:openldap, "files").detect do |f| + }).to match(/\.dotfile$/) + expect(full_paths_for_part(:openldap, "files").detect { |f| f =~ %r{\.ssh/id_rsa$} - end).to match(%r{\.ssh/id_rsa$}) + }).to match(%r{\.ssh/id_rsa$}) end it "should load the metadata for the cookbook" do diff --git a/spec/unit/cookbook_uploader_spec.rb b/spec/unit/cookbook_uploader_spec.rb index 2adecfaa82..6dc2f6563b 100644 --- a/spec/unit/cookbook_uploader_spec.rb +++ b/spec/unit/cookbook_uploader_spec.rb @@ -77,10 +77,10 @@ describe Chef::CookbookUploader do end let(:sandbox_response) do - sandbox_checksums = cksums_not_on_remote.inject({}) do |cksum_map, cksum| + sandbox_checksums = cksums_not_on_remote.inject({}) { |cksum_map, cksum| cksum_map[cksum] = { "needs_upload" => true, "url" => url_for(cksum) } cksum_map - end + } { "checksums" => sandbox_checksums, "uri" => sandbox_commit_uri } end diff --git a/spec/unit/cookbook_version_file_specificity_spec.rb b/spec/unit/cookbook_version_file_specificity_spec.rb index 4d0c8c62f1..b562eb53c2 100644 --- a/spec/unit/cookbook_version_file_specificity_spec.rb +++ b/spec/unit/cookbook_version_file_specificity_spec.rb @@ -338,24 +338,24 @@ describe Chef::CookbookVersion, "file specificity" do it "should raise a FileNotFound exception without match" do node = Chef::Node.new - expect do + expect { @cookbook.preferred_manifest_record(node, :files, "doesn't_exist.rb") - end.to raise_error(Chef::Exceptions::FileNotFound) + }.to raise_error(Chef::Exceptions::FileNotFound) end it "should raise a FileNotFound exception consistently without match" do node = Chef::Node.new - expect do + expect { @cookbook.preferred_manifest_record(node, :files, "doesn't_exist.rb") - end.to raise_error(Chef::Exceptions::FileNotFound) + }.to raise_error(Chef::Exceptions::FileNotFound) - expect do + expect { @cookbook.preferred_manifest_record(node, :files, "doesn't_exist.rb") - end.to raise_error(Chef::Exceptions::FileNotFound) + }.to raise_error(Chef::Exceptions::FileNotFound) - expect do + expect { @cookbook.preferred_manifest_record(node, :files, "doesn't_exist.rb") - end.to raise_error(Chef::Exceptions::FileNotFound) + }.to raise_error(Chef::Exceptions::FileNotFound) end describe "when fetching the contents of a directory by file specificity" do diff --git a/spec/unit/data_bag_spec.rb b/spec/unit/data_bag_spec.rb index 4b0ba42172..80d901bdb7 100644 --- a/spec/unit/data_bag_spec.rb +++ b/spec/unit/data_bag_spec.rb @@ -241,9 +241,9 @@ describe Chef::DataBag do it "should raise an error if the configured data_bag_path is invalid" do file_dir_stub(@paths.first, false) - expect do + expect { Chef::DataBag.load("foo") - end.to raise_error Chef::Exceptions::InvalidDataBagPath, "Data bag path '/var/chef/data_bags' is invalid" + }.to raise_error Chef::Exceptions::InvalidDataBagPath, "Data bag path '/var/chef/data_bags' is invalid" end end diff --git a/spec/unit/decorator/lazy_array_spec.rb b/spec/unit/decorator/lazy_array_spec.rb index 0c5c2eeee0..61465c027f 100644 --- a/spec/unit/decorator/lazy_array_spec.rb +++ b/spec/unit/decorator/lazy_array_spec.rb @@ -51,7 +51,7 @@ describe Chef::Decorator::LazyArray do it "if we loop over the elements and do nothing then its not lazy" do # we don't know how many elements there are unless we evaluate the proc - decorator.each { |i| } + decorator.each do |i| end expect(@foo).to equal(1) expect(@bar).to equal(2) end diff --git a/spec/unit/dsl/declare_resource_spec.rb b/spec/unit/dsl/declare_resource_spec.rb index ead0be2967..80b9ffae5f 100644 --- a/spec/unit/dsl/declare_resource_spec.rb +++ b/spec/unit/dsl/declare_resource_spec.rb @@ -59,36 +59,36 @@ describe Chef::ResourceCollection do describe "#edit_resource!" do it "raises if nothing is found" do - expect do + expect { recipe.edit_resource!(:zen_master, "monkey") do something true end - end.to raise_error(Chef::Exceptions::ResourceNotFound) + }.to raise_error(Chef::Exceptions::ResourceNotFound) end it "raises if nothing is found and no block is given" do - expect do + expect { recipe.edit_resource!(:zen_master, "monkey") - end.to raise_error(Chef::Exceptions::ResourceNotFound) + }.to raise_error(Chef::Exceptions::ResourceNotFound) end it "edits the resource if it finds one" do - resource = recipe.declare_resource(:zen_master, "monkey") do + resource = recipe.declare_resource(:zen_master, "monkey") { something false - end + } expect( - recipe.edit_resource!(:zen_master, "monkey") do + recipe.edit_resource!(:zen_master, "monkey") { something true - end + } ).to eql(resource) expect(run_context.resource_collection.all_resources.size).to eql(1) expect(run_context.resource_collection.first.something).to be true end it "acts like find_resource! if not given a block and the resource exists" do - resource = recipe.declare_resource(:zen_master, "monkey") do + resource = recipe.declare_resource(:zen_master, "monkey") { something false - end + } expect( recipe.edit_resource!(:zen_master, "monkey") ).to eql(resource) @@ -99,9 +99,9 @@ describe Chef::ResourceCollection do describe "#edit_resource" do it "inserts a resource if nothing is found" do - resource = recipe.edit_resource(:zen_master, "monkey") do + resource = recipe.edit_resource(:zen_master, "monkey") { something true - end + } expect(run_context.resource_collection.all_resources.size).to eql(1) expect(run_context.resource_collection.first).to eql(resource) expect(run_context.resource_collection.first.something).to be true @@ -114,22 +114,22 @@ describe Chef::ResourceCollection do end it "edits the resource if it finds one" do - resource = recipe.declare_resource(:zen_master, "monkey") do + resource = recipe.declare_resource(:zen_master, "monkey") { something false - end + } expect( - recipe.edit_resource(:zen_master, "monkey") do + recipe.edit_resource(:zen_master, "monkey") { something true - end + } ).to eql(resource) expect(run_context.resource_collection.all_resources.size).to eql(1) expect(run_context.resource_collection.first.something).to be true end it "acts like find_resource if not given a block and the resource exists" do - resource = recipe.declare_resource(:zen_master, "monkey") do + resource = recipe.declare_resource(:zen_master, "monkey") { something false - end + } expect( recipe.edit_resource(:zen_master, "monkey") ).to eql(resource) @@ -140,26 +140,26 @@ describe Chef::ResourceCollection do describe "#find_resource!" do it "raises if nothing is found" do - expect do + expect { recipe.find_resource!(:zen_master, "monkey") - end.to raise_error(Chef::Exceptions::ResourceNotFound) + }.to raise_error(Chef::Exceptions::ResourceNotFound) end it "raises if given a block" do - resource = recipe.declare_resource(:zen_master, "monkey") do + resource = recipe.declare_resource(:zen_master, "monkey") { something false - end - expect do + } + expect { recipe.find_resource!(:zen_master, "monkey") do something false end - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "returns the resource if it finds one" do - resource = recipe.declare_resource(:zen_master, "monkey") do + resource = recipe.declare_resource(:zen_master, "monkey") { something false - end + } expect( recipe.find_resource!(:zen_master, "monkey") ).to eql(resource) @@ -175,9 +175,9 @@ describe Chef::ResourceCollection do end it "returns the resource if it finds one" do - resource = recipe.declare_resource(:zen_master, "monkey") do + resource = recipe.declare_resource(:zen_master, "monkey") { something false - end + } expect( recipe.find_resource(:zen_master, "monkey") ).to eql(resource) @@ -188,22 +188,22 @@ describe Chef::ResourceCollection do describe "#find_resource with block" do it "inserts a resource if nothing is found" do - resource = recipe.find_resource(:zen_master, "monkey") do + resource = recipe.find_resource(:zen_master, "monkey") { something true - end + } expect(run_context.resource_collection.all_resources.size).to eql(1) expect(run_context.resource_collection.first).to eql(resource) expect(run_context.resource_collection.first.something).to be true end it "returns the resource if it finds one" do - resource = recipe.declare_resource(:zen_master, "monkey") do + resource = recipe.declare_resource(:zen_master, "monkey") { something false - end + } expect( - recipe.find_resource(:zen_master, "monkey") do + recipe.find_resource(:zen_master, "monkey") { something true - end + } ).to eql(resource) expect(run_context.resource_collection.all_resources.size).to eql(1) expect(run_context.resource_collection.first.something).to be false @@ -218,9 +218,9 @@ describe Chef::ResourceCollection do end it "deletes and returns the resource if it finds one" do - resource = recipe.declare_resource(:zen_master, "monkey") do + resource = recipe.declare_resource(:zen_master, "monkey") { something false - end + } expect( recipe.delete_resource(:zen_master, "monkey") ).to eql(resource) @@ -230,15 +230,15 @@ describe Chef::ResourceCollection do describe "#delete_resource!" do it "raises if nothing is found" do - expect do + expect { recipe.delete_resource!(:zen_master, "monkey") - end.to raise_error(Chef::Exceptions::ResourceNotFound) + }.to raise_error(Chef::Exceptions::ResourceNotFound) end it "deletes and returns the resource if it finds one" do - resource = recipe.declare_resource(:zen_master, "monkey") do + resource = recipe.declare_resource(:zen_master, "monkey") { something false - end + } expect( recipe.delete_resource!(:zen_master, "monkey") ).to eql(resource) @@ -300,15 +300,15 @@ describe Chef::ResourceCollection do end it "our tests have correct separation" do - child_resource = child_recipe.declare_resource(:zen_master, "child") do + child_resource = child_recipe.declare_resource(:zen_master, "child") { something false - end - parent_resource = parent_recipe.declare_resource(:zen_master, "parent") do + } + parent_resource = parent_recipe.declare_resource(:zen_master, "parent") { something false - end - root_resource = recipe.declare_resource(:zen_master, "root") do + } + root_resource = recipe.declare_resource(:zen_master, "root") { something false - end + } expect(run_context.resource_collection.first).to eql(root_resource) expect(run_context.resource_collection.first.to_s).to eql("zen_master[root]") expect(run_context.resource_collection.all_resources.size).to eql(1) @@ -364,9 +364,9 @@ describe Chef::ResourceCollection do it "with_run_context returns the return value of the block" do child_recipe.instance_eval do - ret = with_run_context(:root) do + ret = with_run_context(:root) { "return value" - end + } raise "failed" unless ret == "return value" end end diff --git a/spec/unit/environment_spec.rb b/spec/unit/environment_spec.rb index 42906ef772..c62774dbbe 100644 --- a/spec/unit/environment_spec.rb +++ b/spec/unit/environment_spec.rb @@ -296,9 +296,9 @@ describe Chef::Environment do end it "should raise an exception" do - expect do + expect { Chef::Environment.validate_cookbook_version("= 1.2.3.4") - end.to raise_error Chef::Exceptions::IllegalVersionConstraint, + }.to raise_error Chef::Exceptions::IllegalVersionConstraint, /Environment cookbook version constraints not allowed in .*/ end end @@ -452,9 +452,9 @@ describe Chef::Environment do it "should raise an error if the configured environment_path is invalid" do expect(File).to receive(:directory?).with(Chef::Config[:environment_path]).and_return(false) - expect do + expect { Chef::Environment.load("foo") - end.to raise_error Chef::Exceptions::InvalidEnvironmentPath, "Environment path '/var/chef/environments' is invalid" + }.to raise_error Chef::Exceptions::InvalidEnvironmentPath, "Environment path '/var/chef/environments' is invalid" end it "should raise an error if the file does not exist" do @@ -462,9 +462,9 @@ describe Chef::Environment do expect(File).to receive(:exists?).with(File.join(Chef::Config[:environment_path], "foo.json")).and_return(false) expect(File).to receive(:exists?).with(File.join(Chef::Config[:environment_path], "foo.rb")).and_return(false) - expect do + expect { Chef::Environment.load("foo") - end.to raise_error Chef::Exceptions::EnvironmentNotFound, "Environment 'foo' could not be loaded from disk" + }.to raise_error Chef::Exceptions::EnvironmentNotFound, "Environment 'foo' could not be loaded from disk" end end end diff --git a/spec/unit/event_dispatch/dsl_spec.rb b/spec/unit/event_dispatch/dsl_spec.rb index 009242f4fb..2896ce4610 100644 --- a/spec/unit/event_dispatch/dsl_spec.rb +++ b/spec/unit/event_dispatch/dsl_spec.rb @@ -35,18 +35,18 @@ describe Chef::EventDispatch::DSL do subject { described_class.new("test") } it "set handler name" do - subject.on(:run_started) {} + subject.on(:run_started) do end expect(events.subscribers.first.name).to eq("test") end it "raise error when invalid event type is supplied" do - expect do + expect { subject.on(:foo_bar) {} - end.to raise_error(Chef::Exceptions::InvalidEventType) + }.to raise_error(Chef::Exceptions::InvalidEventType) end it "register user hooks against valid event type" do - subject.on(:run_failed) { "testhook" } + subject.on(:run_failed) do "testhook" end expect(events.subscribers.first.run_failed).to eq("testhook") end @@ -61,7 +61,7 @@ describe Chef::EventDispatch::DSL do end end resource = Chef::Resource::RubyBlock.new("foo", run_context) - resource.block {} + resource.block do end resource.run_action(:run) expect(calls).to eq(%i{started updated}) end @@ -76,7 +76,7 @@ describe Chef::EventDispatch::DSL do end end resource = Chef::Resource::RubyBlock.new("foo", run_context) - resource.block {} + resource.block do end resource.run_action(:run) expect(events.subscribers.first.instance_variable_get(:@ivar)).to eq([1, 2]) end diff --git a/spec/unit/file_cache_spec.rb b/spec/unit/file_cache_spec.rb index 388b0e746a..60a0ff2c80 100644 --- a/spec/unit/file_cache_spec.rb +++ b/spec/unit/file_cache_spec.rb @@ -57,7 +57,7 @@ describe Chef::FileCache do describe "when loading cached files" do it "finds and reads the cached file" do FileUtils.mkdir_p(File.join(@file_cache_path, "whiz")) - File.open(File.join(@file_cache_path, "whiz", "bang"), "w") { |f| f.print("borkborkbork") } + File.open(File.join(@file_cache_path, "whiz", "bang"), "w") do |f| f.print("borkborkbork") end expect(Chef::FileCache.load("whiz/bang")).to eq("borkborkbork") end diff --git a/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb b/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb index 7add65150a..7de11a4c75 100644 --- a/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb +++ b/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb @@ -47,7 +47,7 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do describe "when explaining an error converging a resource" do before do - @resource = package("non-existing-package") do + @resource = package("non-existing-package") { only_if do true @@ -55,7 +55,7 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do not_if("/bin/false") action :upgrade - end + } @trace = [ "/var/chef/cache/cookbooks/syntax-err/recipes/default.rb:14:in `from_file'", @@ -89,9 +89,9 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do @context = Chef::Mixin::Template::TemplateContext.new({}) @context[:chef] = "cool" - @resource = template("/tmp/foo.txt") do + @resource = template("/tmp/foo.txt") { mode "0644" - end + } @error = begin @context.render_template_from_string("foo\nbar\nbaz\n<%= this_is_not_defined %>\nquin\nqunx\ndunno") diff --git a/spec/unit/http/ssl_policies_spec.rb b/spec/unit/http/ssl_policies_spec.rb index b67ecc84de..49b55a18e4 100644 --- a/spec/unit/http/ssl_policies_spec.rb +++ b/spec/unit/http/ssl_policies_spec.rb @@ -85,7 +85,7 @@ describe "HTTP SSL Policy" do end describe "when configured with a client certificate" do - before { @url = URI.parse("https://chef.example.com:4443/") } + before do @url = URI.parse("https://chef.example.com:4443/") end it "raises ConfigurationError if the certificate file doesn't exist" do Chef::Config[:ssl_client_cert] = "/dev/null/nothing_here" diff --git a/spec/unit/json_compat_spec.rb b/spec/unit/json_compat_spec.rb index 38c2c60b2e..1218f2e20d 100644 --- a/spec/unit/json_compat_spec.rb +++ b/spec/unit/json_compat_spec.rb @@ -20,7 +20,7 @@ require File.expand_path("../../spec_helper", __FILE__) require "chef/json_compat" describe Chef::JSONCompat do - before { Chef::Config[:treat_deprecation_warnings_as_errors] = false } + before do Chef::Config[:treat_deprecation_warnings_as_errors] = false end describe "#parse with JSON containing comments" do let(:json) { %Q{{\n/* comment */\n// comment 2\n"json_class": "Chef::Role"}} } @@ -57,9 +57,9 @@ describe Chef::JSONCompat do end it "should has 'test' as a 252 nested value" do - v = 252.times.inject(hash) do |memo, _| + v = 252.times.inject(hash) { |memo, _| memo["key"] - end + } expect(v).to eq("test") end end diff --git a/spec/unit/knife/bootstrap_spec.rb b/spec/unit/knife/bootstrap_spec.rb index 5f4be8dfa2..bc54bdfe7b 100644 --- a/spec/unit/knife/bootstrap_spec.rb +++ b/spec/unit/knife/bootstrap_spec.rb @@ -321,7 +321,7 @@ describe Chef::Knife::Bootstrap do context "with bootstrap_attribute options" do let(:jsonfile) do file = Tempfile.new (["node", ".json"]) - File.open(file.path, "w") { |f| f.puts '{"foo":{"bar":"baz"}}' } + File.open(file.path, "w") do |f| f.puts '{"foo":{"bar":"baz"}}' end file end diff --git a/spec/unit/knife/configure_client_spec.rb b/spec/unit/knife/configure_client_spec.rb index be76250e7c..2f1df09e46 100644 --- a/spec/unit/knife/configure_client_spec.rb +++ b/spec/unit/knife/configure_client_spec.rb @@ -33,9 +33,9 @@ describe Chef::Knife::ConfigureClient do it "should print usage and exit when a directory is not provided" do expect(@knife).to receive(:show_usage) expect(@knife.ui).to receive(:fatal).with(/must provide the directory/) - expect do + expect { @knife.run - end.to raise_error SystemExit + }.to raise_error SystemExit end describe "when specifing a directory" do diff --git a/spec/unit/knife/cookbook_upload_spec.rb b/spec/unit/knife/cookbook_upload_spec.rb index 9c371c4140..e4af9a5b4f 100644 --- a/spec/unit/knife/cookbook_upload_spec.rb +++ b/spec/unit/knife/cookbook_upload_spec.rb @@ -158,11 +158,11 @@ describe Chef::Knife::CookbookUpload do knife.config[:depends] = true allow(knife).to receive(:cookbook_names).and_return(%w{test_cookbook1 test_cookbook2 test_cookbook3}) expect(knife).to receive(:upload).exactly(3).times - expect do + expect { Timeout.timeout(5) do knife.run end - end.not_to raise_error + }.not_to raise_error end end diff --git a/spec/unit/knife/core/node_editor_spec.rb b/spec/unit/knife/core/node_editor_spec.rb index 493de3c5b1..5ddc2d0067 100644 --- a/spec/unit/knife/core/node_editor_spec.rb +++ b/spec/unit/knife/core/node_editor_spec.rb @@ -44,10 +44,10 @@ describe Chef::Knife::NodeEditor do describe "#view" do it "returns a Hash with only the name, chef_environment, normal, " + "policy_name, policy_group, and run_list properties" do - expected = node_data.select do |key,| + expected = node_data.select { |key,| %w{ name chef_environment normal policy_name policy_group run_list }.include?(key) - end + } expect(subject.view).to eq(expected) end diff --git a/spec/unit/knife/core/ui_spec.rb b/spec/unit/knife/core/ui_spec.rb index e5f19a4837..245411f524 100644 --- a/spec/unit/knife/core/ui_spec.rb +++ b/spec/unit/knife/core/ui_spec.rb @@ -541,9 +541,9 @@ describe Chef::Knife::UI do shared_examples_for "confirm with negative answer" do it "confirm should exit 3" do - expect do + expect { run_confirm - end.to raise_error(SystemExit) { |e| expect(e.status).to eq(3) } + }.to raise_error(SystemExit) { |e| expect(e.status).to eq(3) } end it "confirm_without_exit should return false" do diff --git a/spec/unit/knife/node_bulk_delete_spec.rb b/spec/unit/knife/node_bulk_delete_spec.rb index db9e2caab1..5b7054a6b3 100644 --- a/spec/unit/knife/node_bulk_delete_spec.rb +++ b/spec/unit/knife/node_bulk_delete_spec.rb @@ -36,10 +36,10 @@ describe Chef::Knife::NodeBulkDelete do describe "when creating the list of nodes" do it "fetches the node list" do - expected = @nodes.inject({}) do |inflatedish, (name, uri)| + expected = @nodes.inject({}) { |inflatedish, (name, uri)| inflatedish[name] = Chef::Node.new.tap { |n| n.name(name) } inflatedish - end + } expect(Chef::Node).to receive(:list).and_return(@nodes) # I hate not having == defined for anything :( actual = @knife.all_nodes @@ -50,13 +50,13 @@ describe Chef::Knife::NodeBulkDelete do describe "run" do before do - @inflatedish_list = @nodes.keys.inject({}) do |nodes_by_name, name| + @inflatedish_list = @nodes.keys.inject({}) { |nodes_by_name, name| node = Chef::Node.new node.name(name) allow(node).to receive(:destroy).and_return(true) nodes_by_name[name] = node nodes_by_name - end + } allow(@knife).to receive(:all_nodes).and_return(@inflatedish_list) end diff --git a/spec/unit/lwrp_spec.rb b/spec/unit/lwrp_spec.rb index def981801e..b84f611a15 100644 --- a/spec/unit/lwrp_spec.rb +++ b/spec/unit/lwrp_spec.rb @@ -229,9 +229,9 @@ describe "LWRP" do end it "allows to user to user the resource_name" do - expect do + expect { klass.resource_name(:foo) - end.to_not raise_error + }.to_not raise_error end it "returns the set value for the resource" do diff --git a/spec/unit/mixin/openssl_helper_spec.rb b/spec/unit/mixin/openssl_helper_spec.rb index a6a6fb0e71..d68fcb71eb 100644 --- a/spec/unit/mixin/openssl_helper_spec.rb +++ b/spec/unit/mixin/openssl_helper_spec.rb @@ -32,9 +32,9 @@ describe Chef::Mixin::OpenSSLHelper do describe "#get_key_filename" do context "When the input is not a string" do it "Throws a TypeError" do - expect do + expect { instance.get_key_filename(33) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end @@ -89,11 +89,11 @@ describe Chef::Mixin::OpenSSLHelper do context "When the dhparam.pem file does exist, but does not contain a valid dhparam key" do it "Throws an OpenSSL::PKey::DHError exception" do - expect do + expect { @dhparam_file.puts("I_am_not_a_key_I_am_a_free_man") @dhparam_file.close instance.dhparam_pem_valid?(@dhparam_file.path) - end.to raise_error(::OpenSSL::PKey::DHError) + }.to raise_error(::OpenSSL::PKey::DHError) end end @@ -225,17 +225,17 @@ describe Chef::Mixin::OpenSSLHelper do describe "#gen_dhparam" do context "When given an invalid key length" do it "Throws an ArgumentError" do - expect do + expect { instance.gen_dhparam(2046, 2) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end end context "When given an invalid generator id" do it "Throws a TypeError" do - expect do + expect { instance.gen_dhparam(2048, "bob") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end @@ -249,9 +249,9 @@ describe Chef::Mixin::OpenSSLHelper do describe "#gen_rsa_priv_key" do context "When given an invalid key length" do it "Throws an ArgumentError" do - expect do + expect { instance.gen_rsa_priv_key(4093) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end end @@ -269,33 +269,33 @@ describe Chef::Mixin::OpenSSLHelper do context "When given anything other than an RSA key object to encrypt" do it "Raises a TypeError" do - expect do + expect { instance.encrypt_rsa_key("abcd", "efgh", "des3") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When given anything other than a string as the passphrase" do it "Raises a TypeError" do - expect do + expect { instance.encrypt_rsa_key(@rsa_key, 1234, "des3") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When given anything other than a string as the cipher" do it "Raises a TypeError" do - expect do + expect { instance.encrypt_rsa_key(@rsa_key, "1234", 1234) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When given an invalid cipher string" do it "Raises an ArgumentError" do - expect do + expect { instance.encrypt_rsa_key(@rsa_key, "1234", "des3_bogus") - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end end @@ -311,15 +311,15 @@ describe Chef::Mixin::OpenSSLHelper do describe "#gen_ec_priv_key" do context "When given an invalid curve" do it "Raises a TypeError" do - expect do + expect { instance.gen_ec_priv_key(2048) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end it "Throws an ArgumentError" do - expect do + expect { instance.gen_ec_priv_key("primeFromTheFuture") - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end end @@ -337,33 +337,33 @@ describe Chef::Mixin::OpenSSLHelper do context "When given anything other than an EC key object to encrypt" do it "Raises a TypeError" do - expect do + expect { instance.encrypt_ec_key("abcd", "efgh", "des3") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When given anything other than a string as the passphrase" do it "Raises a TypeError" do - expect do + expect { instance.encrypt_ec_key(@ec_key, 1234, "des3") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When given anything other than a string as the cipher" do it "Raises a TypeError" do - expect do + expect { instance.encrypt_ec_key(@ec_key, "1234", 1234) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When given an invalid cipher string" do it "Raises an ArgumentError" do - expect do + expect { instance.encrypt_ec_key(@ec_key, "1234", "des3_bogus") - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end end @@ -385,17 +385,17 @@ describe Chef::Mixin::OpenSSLHelper do context "When given anything other than an RSA/EC key object" do it "Raises a TypeError" do - expect do + expect { instance.gen_x509_request(@subject, "abc") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When given anything other than an X509 Name object" do it "Raises a TypeError" do - expect do + expect { instance.gen_x509_request("abc", @key) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end @@ -419,35 +419,35 @@ describe Chef::Mixin::OpenSSLHelper do describe "#gen_x509_extensions" do context "When given anything other than an Ruby Hash object" do it "Raises a TypeError" do - expect do + expect { instance.gen_x509_extensions("abc") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When a misformatted ruby Hash is given" do it "Raises a TypeError" do - expect do + expect { instance.gen_x509_extensions("pouet" => "plop") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end it "Raises a ArgumentError" do - expect do + expect { instance.gen_x509_extensions("pouet" => { "values" => [ "keyCertSign" ], "wrong_key" => true }) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "Raises a TypeError" do - expect do + expect { instance.gen_x509_extensions("keyUsage" => { "values" => "keyCertSign", "critical" => true }) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end it "Raises a TypeError" do - expect do + expect { instance.gen_x509_extensions("keyUsage" => { "values" => [ "keyCertSign" ], "critical" => "yes" }) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end @@ -496,33 +496,33 @@ describe Chef::Mixin::OpenSSLHelper do context "When the request given is anything other then a Ruby OpenSSL::X509::Request" do it "Raises a TypeError" do - expect do + expect { @instance.gen_x509_cert("abc", @x509_extension, @info_without_issuer, @rsa_key) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When the extension given is anything other then a Ruby Array" do it "Raises a TypeError" do - expect do + expect { @instance.gen_x509_cert(@rsa_request, "abc", @info_without_issuer, @rsa_key) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When the info given is anything other then a Ruby Hash" do it "Raises a TypeError" do - expect do + expect { @instance.gen_x509_cert(@rsa_request, @x509_extension, "abc", @rsa_key) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When the key given is anything other then a Ruby OpenSSL::Pkey::EC or OpenSSL::Pkey::RSA object" do it "Raises a TypeError" do - expect do + expect { @instance.gen_x509_cert(@rsa_request, @x509_extension, @info_without_issuer, "abc") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end @@ -550,9 +550,9 @@ describe Chef::Mixin::OpenSSLHelper do context "When the CRL given is anything other then a Ruby OpenSSL::X509::CRL object" do it "Raises a TypeError" do - expect do + expect { instance.get_next_crl_number("abc") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end @@ -572,17 +572,17 @@ describe Chef::Mixin::OpenSSLHelper do context "When the CRL given is anything other then a Ruby OpenSSL::X509::CRL object" do it "Raises a TypeError" do - expect do + expect { instance.serial_revoked?("abc", "C7BCB6602A2E4251EF4E2827A228CB52BC0CEA2F") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When the serial given is anything other then a Ruby String or Integer object" do it "Raises a TypeError" do - expect do + expect { instance.serial_revoked?(@crl, []) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end @@ -621,37 +621,37 @@ describe Chef::Mixin::OpenSSLHelper do context "When the CA private key given is anything other then a Ruby OpenSSL::PKey::EC object or a OpenSSL::PKey::RSA object" do it "Raises a TypeError" do - expect do + expect { instance.gen_x509_crl("abc", @info) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When the info given is anything other then a Ruby Hash" do it "Raises a TypeError" do - expect do + expect { instance.gen_x509_crl(@ca_key, "abc") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When a misformatted info Ruby Hash is given" do it "Raises a ArgumentError" do - expect do + expect { instance.gen_x509_crl(@ca_key, "abc" => "def", "validity" => 8) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "Raises a TypeError" do - expect do + expect { instance.gen_x509_crl(@ca_key, "issuer" => "abc", "validity" => 8) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end it "Raises a TypeError" do - expect do + expect { instance.gen_x509_crl(@ca_key, "issuer" => @ca_cert, "validity" => "abc") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end @@ -693,45 +693,45 @@ describe Chef::Mixin::OpenSSLHelper do context "When the CRL given is anything other then a Ruby OpenSSL::X509::CRL object" do it "Raises a TypeError" do - expect do + expect { instance.renew_x509_crl("abc", @ca_key, @info) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When the CA private key given is anything other then a Ruby OpenSSL::PKey::EC object or a OpenSSL::PKey::RSA object" do it "Raises a TypeError" do - expect do + expect { instance.renew_x509_crl(@crl, "abc", @info) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When the info given is anything other then a Ruby Hash" do it "Raises a TypeError" do - expect do + expect { instance.renew_x509_crl(@crl, @ca_key, "abc") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When a misformatted info Ruby Hash is given" do it "Raises a ArgumentError" do - expect do + expect { instance.renew_x509_crl(@crl, @ca_key, "abc" => "def", "validity" => 8) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "Raises a TypeError" do - expect do + expect { instance.renew_x509_crl(@crl, @ca_key, "issuer" => "abc", "validity" => 8) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end it "Raises a TypeError" do - expect do + expect { instance.renew_x509_crl(@crl, @ca_key, "issuer" => @ca_cert, "validity" => "abc") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end @@ -775,73 +775,73 @@ describe Chef::Mixin::OpenSSLHelper do context "When the revoke_info given is anything other then a Ruby Hash" do it "Raises a TypeError" do - expect do + expect { instance.revoke_x509_crl("abc", @crl, @ca_key, @info) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When the CRL given is anything other then a Ruby OpenSSL::X509::CRL object" do it "Raises a TypeError" do - expect do + expect { instance.revoke_x509_crl(@revoke_info, "abc", @ca_key, @info) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When the CA private key given is anything other then a Ruby OpenSSL::PKey::EC object or a OpenSSL::PKey::RSA object" do it "Raises a TypeError" do - expect do + expect { instance.revoke_x509_crl(@revoke_info, @crl, "abc", @info) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When the info given is anything other then a Ruby Hash" do it "Raises a TypeError" do - expect do + expect { instance.revoke_x509_crl(@revoke_info, @crl, @ca_key, "abc") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When a misformatted revoke_info Ruby Hash is given" do it "Raises a ArgumentError" do - expect do + expect { instance.revoke_x509_crl({ "abc" => "def", "ghi" => "jkl" }, @crl, @ca_key, @info) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "Raises a TypeError" do - expect do + expect { instance.revoke_x509_crl({ "serial" => [], "reason" => 0 }, @crl, @ca_key, @info) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end it "Raises a TypeError" do - expect do + expect { instance.revoke_x509_crl({ "serial" => 1, "reason" => "abc" }, @crl, @ca_key, @info) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end context "When a misformatted info Ruby Hash is given" do it "Raises a ArgumentError" do - expect do + expect { instance.revoke_x509_crl(@revoke_info, @crl, @ca_key, "abc" => "def", "validity" => 8) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "Raises a TypeError" do - expect do + expect { instance.revoke_x509_crl(@revoke_info, @crl, @ca_key, "issuer" => "abc", "validity" => 8) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end it "Raises a TypeError" do - expect do + expect { instance.revoke_x509_crl(@revoke_info, @crl, @ca_key, "issuer" => @ca_cert, "validity" => "abc") - end.to raise_error(TypeError) + }.to raise_error(TypeError) end end diff --git a/spec/unit/mixin/params_validate_spec.rb b/spec/unit/mixin/params_validate_spec.rb index 489742cb7d..3e7a5969f1 100644 --- a/spec/unit/mixin/params_validate_spec.rb +++ b/spec/unit/mixin/params_validate_spec.rb @@ -56,7 +56,7 @@ describe Chef::Mixin::ParamsValidate do end it "should allow you to check what kind_of? thing an argument is with kind_of" do - expect do + expect { @vo.validate( { one: "string" }, { @@ -65,9 +65,9 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.not_to raise_error + }.not_to raise_error - expect do + expect { @vo.validate( { one: "string" }, { @@ -76,11 +76,11 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should allow you to specify an argument is required with required" do - expect do + expect { @vo.validate( { one: "string" }, { @@ -89,9 +89,9 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.not_to raise_error + }.not_to raise_error - expect do + expect { @vo.validate( { two: "string" }, { @@ -100,9 +100,9 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) - expect do + expect { @vo.validate( { two: "string" }, { @@ -111,11 +111,11 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.not_to raise_error + }.not_to raise_error end it "should allow you to specify whether an object has a method with respond_to" do - expect do + expect { @vo.validate( { one: @vo }, { @@ -124,9 +124,9 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.not_to raise_error + }.not_to raise_error - expect do + expect { @vo.validate( { one: @vo }, { @@ -135,11 +135,11 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should allow you to specify whether an object has all the given methods with respond_to and an array" do - expect do + expect { @vo.validate( { one: @vo }, { @@ -148,9 +148,9 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.not_to raise_error + }.not_to raise_error - expect do + expect { @vo.validate( { one: @vo }, { @@ -159,7 +159,7 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should let you set a default value with default => value" do @@ -173,7 +173,7 @@ describe Chef::Mixin::ParamsValidate do end it "should let you check regular expressions" do - expect do + expect { @vo.validate( { one: "is good" }, { @@ -182,9 +182,9 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.not_to raise_error + }.not_to raise_error - expect do + expect { @vo.validate( { one: "is good" }, { @@ -193,11 +193,11 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should let you specify your own callbacks" do - expect do + expect { @vo.validate( { one: "is good" }, { @@ -210,9 +210,9 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.not_to raise_error + }.not_to raise_error - expect do + expect { @vo.validate( { one: "is bad" }, { @@ -225,12 +225,12 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should let you combine checks" do args = { one: "is good", two: "is bad" } - expect do + expect { @vo.validate( args, { @@ -252,9 +252,9 @@ describe Chef::Mixin::ParamsValidate do three: { default: "neato mosquito" }, } ) - end.not_to raise_error + }.not_to raise_error expect(args[:three]).to eq("neato mosquito") - expect do + expect { @vo.validate( args, { @@ -276,11 +276,11 @@ describe Chef::Mixin::ParamsValidate do three: { default: "neato mosquito" }, } ) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should raise an ArgumentError if the validation map has an unknown check" do - expect do + expect { @vo.validate( { one: "two" }, { @@ -289,17 +289,17 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should accept keys that are strings in the options" do - expect do + expect { @vo.validate({ "one" => "two" }, { one: { regex: /^two$/ } }) - end.not_to raise_error + }.not_to raise_error end it "should allow an array to kind_of" do - expect do + expect { @vo.validate( { one: "string" }, { @@ -308,8 +308,8 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.not_to raise_error - expect do + }.not_to raise_error + expect { @vo.validate( { one: ["string"] }, { @@ -318,8 +318,8 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.not_to raise_error - expect do + }.not_to raise_error + expect { @vo.validate( { one: {} }, { @@ -328,29 +328,29 @@ describe Chef::Mixin::ParamsValidate do }, } ) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "asserts that a value returns false from a predicate method" do - expect do + expect { @vo.validate({ not_blank: "should pass" }, { not_blank: { cannot_be: %i{nil empty} } }) - end.not_to raise_error - expect do + }.not_to raise_error + expect { @vo.validate({ not_blank: "" }, { not_blank: { cannot_be: %i{nil empty} } }) - end.to raise_error(Chef::Exceptions::ValidationFailed) + }.to raise_error(Chef::Exceptions::ValidationFailed) end it "allows a custom validation message" do - expect do + expect { @vo.validate({ not_blank: "should pass" }, { not_blank: { cannot_be: %i{nil empty}, validation_message: "my validation message" } }) - end.not_to raise_error - expect do + }.not_to raise_error + expect { @vo.validate({ not_blank: "" }, { not_blank: { cannot_be: %i{nil empty}, validation_message: "my validation message" } }) - end.to raise_error(Chef::Exceptions::ValidationFailed, "my validation message") + }.to raise_error(Chef::Exceptions::ValidationFailed, "my validation message") end it "should set and return a value, then return the same value" do @@ -366,15 +366,15 @@ describe Chef::Mixin::ParamsValidate do end it "should raise an ArgumentError when argument is nil and required is true" do - expect do + expect { @vo.set_or_return(:test, nil, { required: true }) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should not raise an error when argument is nil and required is false" do - expect do + expect { @vo.set_or_return(:test, nil, { required: false }) - end.not_to raise_error + }.not_to raise_error end it "should set and return @name, then return @name for foo when argument is nil" do @@ -391,9 +391,9 @@ describe Chef::Mixin::ParamsValidate do it "should raise an error when delayed evaluated attribute is not valid" do value = Chef::DelayedEvaluator.new { "test" } @vo.set_or_return(:test, value, { kind_of: Numeric }) - expect do + expect { @vo.set_or_return(:test, nil, { kind_of: Numeric }) - end.to raise_error(Chef::Exceptions::ValidationFailed) + }.to raise_error(Chef::Exceptions::ValidationFailed) end it "should create DelayedEvaluator instance when #lazy is used" do diff --git a/spec/unit/node/vivid_mash_spec.rb b/spec/unit/node/vivid_mash_spec.rb index 575d8c3321..93fc919fa1 100644 --- a/spec/unit/node/vivid_mash_spec.rb +++ b/spec/unit/node/vivid_mash_spec.rb @@ -226,7 +226,7 @@ describe Chef::Node::VividMash do it "writes with a block" do expect(root).to receive(:reset_cache).at_least(:once).with("one") - vivid.write("one", "five") { "six" } + vivid.write("one", "five") do "six" end expect(vivid["one"]["five"]).to eql("six") end end @@ -282,7 +282,7 @@ describe Chef::Node::VividMash do it "writes with a block" do expect(root).to receive(:reset_cache).at_least(:once).with("one") - vivid.write!("one", "five") { "six" } + vivid.write!("one", "five") do "six" end expect(vivid["one"]["five"]).to eql("six") end end @@ -406,14 +406,14 @@ describe Chef::Node::AttrArray do context "#collect!" do it "converts Hashes" do - array.collect! { |x| { "zero" => "zero2" } } + array.collect! do |x| { "zero" => "zero2" } end expect(array[1].class).to eql(Chef::Node::VividMash) end end context "#map!" do it "converts Hashes" do - array.map! { |x| { "zero" => "zero2" } } + array.map! do |x| { "zero" => "zero2" } end expect(array[1].class).to eql(Chef::Node::VividMash) end end diff --git a/spec/unit/policy_builder/policyfile_spec.rb b/spec/unit/policy_builder/policyfile_spec.rb index d08a9f5b33..760eef3194 100644 --- a/spec/unit/policy_builder/policyfile_spec.rb +++ b/spec/unit/policy_builder/policyfile_spec.rb @@ -151,7 +151,7 @@ describe Chef::PolicyBuilder::Policyfile do end context "chef-solo" do - before { Chef::Config[:solo_legacy_mode] = true } + before do Chef::Config[:solo_legacy_mode] = true end it "errors on create" do expect { initialize_pb }.to raise_error(err_namespace::UnsupportedFeature) @@ -175,7 +175,7 @@ describe Chef::PolicyBuilder::Policyfile do end context "when an environment is configured" do - before { Chef::Config[:environment] = "blurch" } + before do Chef::Config[:environment] = "blurch" end it "errors when an environment is configured" do expect { initialize_pb }.to raise_error(err_namespace::UnsupportedFeature) diff --git a/spec/unit/property/validation_spec.rb b/spec/unit/property/validation_spec.rb index dab2be8000..240555a783 100644 --- a/spec/unit/property/validation_spec.rb +++ b/spec/unit/property/validation_spec.rb @@ -84,7 +84,7 @@ describe "Chef::Resource.property validation" do end success_values.each do |v| it "value #{v.inspect} is valid" do - resource.instance_eval { @x = "default" } + resource.instance_eval do @x = "default" end expect(resource.x v).to eq v expect(resource.x).to eq v end @@ -92,7 +92,7 @@ describe "Chef::Resource.property validation" do failure_values.each do |v| it "value #{v.inspect} is invalid" do expect { resource.x v }.to raise_error Chef::Exceptions::ValidationFailed - resource.instance_eval { @x = "default" } + resource.instance_eval do @x = "default" end expect { resource.x v }.to raise_error Chef::Exceptions::ValidationFailed end end @@ -102,7 +102,7 @@ describe "Chef::Resource.property validation" do end unless tags.include?(:nillable) it "changing x to nil does a set" do - resource.instance_eval { @x = "default" } + resource.instance_eval do @x = "default" end expect(resource.x nil).to eq nil expect(resource.x).to eq nil end @@ -115,7 +115,7 @@ describe "Chef::Resource.property validation" do expect(resource.x).to be_nil end it "changing x to nil does a set" do - resource.instance_eval { @x = "default" } + resource.instance_eval do @x = "default" end expect(resource.x nil).to eq nil expect(resource.x).to eq nil end @@ -123,7 +123,7 @@ describe "Chef::Resource.property validation" do elsif tags.include?(:nillable) with_property ":x, #{validation}, nillable: true" do it "changing x to nil with nillable true overwrites defaults and just works" do - resource.instance_eval { @x = "default" } + resource.instance_eval do @x = "default" end expect { resource.x nil }.not_to raise_error expect(resource.x nil).to eq nil expect(resource.x).to eq nil diff --git a/spec/unit/property_spec.rb b/spec/unit/property_spec.rb index 1fcbb77e8e..c24b442d1a 100644 --- a/spec/unit/property_spec.rb +++ b/spec/unit/property_spec.rb @@ -493,7 +493,7 @@ describe "Chef::Resource.property" do expect(resource.state_for_resource_reporter).to eq({}) end it "when x is set to nil, it returns nil" do - resource.instance_eval { @x = nil } + resource.instance_eval do @x = nil end expect(resource.x).to be_nil end @@ -1083,18 +1083,18 @@ describe "Chef::Resource.property" do context "property_type" do it "property_types validate their defaults" do - expect do + expect { module ::PropertySpecPropertyTypes include Chef::Mixin::Properties property_type(is: %i{a b}, default: :c) end - end.to raise_error(Chef::Exceptions::ValidationFailed) - expect do + }.to raise_error(Chef::Exceptions::ValidationFailed) + expect { module ::PropertySpecPropertyTypes include Chef::Mixin::Properties property_type(is: %i{a b}, default: :b) end - end.not_to raise_error + }.not_to raise_error end context "With property_type ABType (is: [:a, :b]) and CDType (is: [:c, :d])" do @@ -1161,7 +1161,7 @@ describe "Chef::Resource.property" do with_property ":real, Integer" do it "should set the real property and emit a deprecation message" do expect(Chef).to receive(:deprecated).with(:property, "we don't like the deprecated property no more") - resource_class.class_eval { deprecated_property_alias :deprecated, :real, "we don't like the deprecated property no more" } + resource_class.class_eval do deprecated_property_alias :deprecated, :real, "we don't like the deprecated property no more" end resource.deprecated 10 expect(resource.real).to eq 10 end diff --git a/spec/unit/provider/cron/unix_spec.rb b/spec/unit/provider/cron/unix_spec.rb index c8ef82e37a..3bff44f2de 100644 --- a/spec/unit/provider/cron/unix_spec.rb +++ b/spec/unit/provider/cron/unix_spec.rb @@ -96,9 +96,9 @@ describe Chef::Provider::Cron::Unix do let (:exitstatus) { 2 } it "should raise an exception if another error occurs" do - expect do + expect { provider.send(:read_crontab) - end.to raise_error(Chef::Exceptions::Cron, "Error determining state of #{new_resource.name}, exit: 2") + }.to raise_error(Chef::Exceptions::Cron, "Error determining state of #{new_resource.name}, exit: 2") end it "logs the crontab output to debug" do @@ -135,9 +135,9 @@ describe Chef::Provider::Cron::Unix do context "when writing the crontab fails" do let(:exitstatus) { 1 } it "should raise an exception if the command returns non-zero" do - expect do + expect { provider.send(:write_crontab, "Foo") - end.to raise_error(Chef::Exceptions::Cron, /Error updating state of #{new_resource.name}, exit: 1/) + }.to raise_error(Chef::Exceptions::Cron, /Error updating state of #{new_resource.name}, exit: 1/) end end end diff --git a/spec/unit/provider/cron_spec.rb b/spec/unit/provider/cron_spec.rb index 4cd8a140af..c3a2409d82 100644 --- a/spec/unit/provider/cron_spec.rb +++ b/spec/unit/provider/cron_spec.rb @@ -194,9 +194,9 @@ describe Chef::Provider::Cron do # Chef Name: foo[bar] (baz) 21 */4 * * * some_prog 1234567 CRONTAB - expect do + expect { @provider.load_current_resource - end.not_to raise_error + }.not_to raise_error end end @@ -799,9 +799,9 @@ describe Chef::Provider::Cron do it "should throw an error" do @new_resource.shell "/bash" @new_resource.environment "SHELL" => "/bash" - expect do + expect { @provider.run_action(:create) - end.to raise_error(Chef::Exceptions::Cron, /cronhole some stuff: the 'SHELL' property is set and environment property also contains the 'SHELL' variable. Remove the variable from the environment property./) + }.to raise_error(Chef::Exceptions::Cron, /cronhole some stuff: the 'SHELL' property is set and environment property also contains the 'SHELL' variable. Remove the variable from the environment property./) end end @@ -1034,9 +1034,9 @@ describe Chef::Provider::Cron do it "should raise an exception if the command returns non-zero" do @status = double("Status", exitstatus: 1) allow(@provider).to receive(:shell_out!).and_raise(Mixlib::ShellOut::ShellCommandFailed) - expect do + expect { @provider.send(:write_crontab, "Foo") - end.to raise_error(Chef::Exceptions::Cron) + }.to raise_error(Chef::Exceptions::Cron) end end diff --git a/spec/unit/provider/directory_spec.rb b/spec/unit/provider/directory_spec.rb index 4672db7d8d..18b7108209 100644 --- a/spec/unit/provider/directory_spec.rb +++ b/spec/unit/provider/directory_spec.rb @@ -150,8 +150,8 @@ describe Chef::Provider::Directory do end context "in why run mode" do - before { Chef::Config[:why_run] = true } - after { Chef::Config[:why_run] = false } + before do Chef::Config[:why_run] = true end + after do Chef::Config[:why_run] = false end it "does not modify new_resource" do expect(directory).not_to receive(:load_resource_attributes_from_file).with(new_resource) diff --git a/spec/unit/provider/dsc_script_spec.rb b/spec/unit/provider/dsc_script_spec.rb index a1115150e8..138c55c3c8 100644 --- a/spec/unit/provider/dsc_script_spec.rb +++ b/spec/unit/provider/dsc_script_spec.rb @@ -156,16 +156,16 @@ describe Chef::Provider::DscScript do it "raises an exception for powershell version '#{version}'" do node.automatic[:languages][:powershell][:version] = version - expect do + expect { provider.run_action(:run) - end.to raise_error(Chef::Exceptions::ProviderNotFound) + }.to raise_error(Chef::Exceptions::ProviderNotFound) end end it "raises an exception if PowerShell is not present" do - expect do + expect { provider.run_action(:run) - end.to raise_error(Chef::Exceptions::ProviderNotFound) + }.to raise_error(Chef::Exceptions::ProviderNotFound) end end diff --git a/spec/unit/provider/execute_spec.rb b/spec/unit/provider/execute_spec.rb index 11eb70e396..c4f7c2c254 100644 --- a/spec/unit/provider/execute_spec.rb +++ b/spec/unit/provider/execute_spec.rb @@ -159,9 +159,9 @@ describe Chef::Provider::Execute do opts.delete(:live_stream) new_resource.sensitive true expect(provider).to receive(:shell_out!).and_raise(Mixlib::ShellOut::ShellCommandFailed) - expect do + expect { provider.run_action(:run) - end.to raise_error(Mixlib::ShellOut::ShellCommandFailed, /suppressed for sensitive resource/) + }.to raise_error(Mixlib::ShellOut::ShellCommandFailed, /suppressed for sensitive resource/) end describe "streaming output" do diff --git a/spec/unit/provider/git_spec.rb b/spec/unit/provider/git_spec.rb index 9a6ae31397..50a337ec8a 100644 --- a/spec/unit/provider/git_spec.rb +++ b/spec/unit/provider/git_spec.rb @@ -294,7 +294,7 @@ describe Chef::Provider::Git do end context "with a timeout set" do let (:seconds) { 10 } - before { @resource.timeout(seconds) } + before do @resource.timeout(seconds) end it "clones a repo with amended git options" do expect(@provider).to receive(:shell_out!).with(expected_cmd, default_options.merge(timeout: seconds)) @provider.clone @@ -314,7 +314,7 @@ describe Chef::Provider::Git do before do @resource.environment(override_home) end - before { @resource.environment(override_home) } + before do @resource.environment(override_home) end it "clones a repo with amended git options with specific home" do expect(@provider).to receive(:shell_out!).with(expected_cmd, overrided_options) @provider.clone @@ -350,7 +350,7 @@ describe Chef::Provider::Git do before do @resource.environment(override_home) end - before { @resource.environment(override_home) } + before do @resource.environment(override_home) end it "clones a repo with amended git options with specific home" do expect(@provider).to receive(:shell_out!).with(expected_cmd, hash_including(overrided_options)) @provider.clone diff --git a/spec/unit/provider/group/groupadd_spec.rb b/spec/unit/provider/group/groupadd_spec.rb index 79586eac71..0b25c40017 100644 --- a/spec/unit/provider/group/groupadd_spec.rb +++ b/spec/unit/provider/group/groupadd_spec.rb @@ -85,7 +85,7 @@ describe Chef::Provider::Group::Groupadd do end context "on Solaris" do - before { node.automatic["platform"] = "solaris2" } + before do node.automatic["platform"] = "solaris2" end it "should not set groupadd -r if system is true" do new_resource.system(true) expect(provider.groupadd_options).to eql([]) diff --git a/spec/unit/provider/group_spec.rb b/spec/unit/provider/group_spec.rb index d7fdfb299c..18597659c7 100644 --- a/spec/unit/provider/group_spec.rb +++ b/spec/unit/provider/group_spec.rb @@ -119,7 +119,7 @@ describe Chef::Provider::User do end it "should return true if the append is true and excluded_members include an existing user" do - @new_resource.members.each { |m| @new_resource.excluded_members << m } + @new_resource.members.each do |m| @new_resource.excluded_members << m end @new_resource.members.clear @new_resource.append(true) expect(@provider.compare_group).to be_truthy diff --git a/spec/unit/provider/http_request_spec.rb b/spec/unit/provider/http_request_spec.rb index 8b5ae02b3c..47d270d5e1 100644 --- a/spec/unit/provider/http_request_spec.rb +++ b/spec/unit/provider/http_request_spec.rb @@ -52,7 +52,7 @@ describe Chef::Provider::HttpRequest do describe "action_get" do it "should inflate a message block at runtime" do - @new_resource.message { "return" } + @new_resource.message do "return" end expect(@http).to receive(:get).with("http://www.opscode.com/", {}) @provider.run_action(:get) expect(@new_resource).to be_updated @@ -88,7 +88,7 @@ describe Chef::Provider::HttpRequest do end it "should inflate a message block at runtime" do - @new_resource.message { "return" } + @new_resource.message do "return" end expect(@http).to receive(:post).with("http://www.opscode.com/", "return", {}) @provider.run_action(:post) expect(@new_resource).to be_updated @@ -111,7 +111,7 @@ describe Chef::Provider::HttpRequest do end it "should inflate a message block at runtime" do - @new_resource.message { "return" } + @new_resource.message do "return" end expect(@http).to receive(:head).with("http://www.opscode.com/", {}).and_return(nil) @provider.run_action(:head) expect(@new_resource).to be_updated diff --git a/spec/unit/provider/launchd_spec.rb b/spec/unit/provider/launchd_spec.rb index 53b56b4960..e5e3435450 100644 --- a/spec/unit/provider/launchd_spec.rb +++ b/spec/unit/provider/launchd_spec.rb @@ -138,12 +138,12 @@ describe Chef::Provider::Launchd do describe "start_calendar_interval is passed" do it "should allow array of Hashes" do - allowed = (1..2).collect do |num| + allowed = (1..2).collect { |num| { "Hour" => 10 + num, "Weekday" => num, } - end + } new_resource.program "/Library/scripts/call_mom.sh" new_resource.time_out 300 new_resource.start_calendar_interval allowed @@ -171,17 +171,17 @@ describe Chef::Provider::Launchd do it "should not allow invalid ShowCalendarInterval keys" do new_resource.program "/Library/scripts/call_mom.sh" new_resource.time_out 300 - expect do + expect { new_resource.start_calendar_interval "Hourly" => 1 - end.to raise_error(/Hourly are invalid/) + }.to raise_error(/Hourly are invalid/) end it "should not allow non-integer values" do new_resource.program "/Library/scripts/call_mom.sh" new_resource.time_out 300 - expect do + expect { new_resource.start_calendar_interval "Weekday" => "1-2" - end.to raise_error(/Invalid value.*\(1-2\)/) + }.to raise_error(/Invalid value.*\(1-2\)/) end end diff --git a/spec/unit/provider/package/rubygems_spec.rb b/spec/unit/provider/package/rubygems_spec.rb index 1bafefe5e8..dde9efc2a6 100644 --- a/spec/unit/provider/package/rubygems_spec.rb +++ b/spec/unit/provider/package/rubygems_spec.rb @@ -33,7 +33,7 @@ class RspecVersionString def self.rspec_version_string @rspec_version_string ||= begin stubs = Gem::Specification.send(:installed_stubs, Gem::Specification.dirs, "rspec-core-*.gemspec") - stubs.select! { |stub| stub.name == "rspec-core" && Gem::Dependency.new("rspec-core", ">= 0").requirement.satisfied_by?(stub.version) } + stubs.select! do |stub| stub.name == "rspec-core" && Gem::Dependency.new("rspec-core", ">= 0").requirement.satisfied_by?(stub.version) end stubs.max_by(&:version).version.to_s end end diff --git a/spec/unit/provider/package/windows/exe_spec.rb b/spec/unit/provider/package/windows/exe_spec.rb index 6fa1747b03..67365660fb 100644 --- a/spec/unit/provider/package/windows/exe_spec.rb +++ b/spec/unit/provider/package/windows/exe_spec.rb @@ -87,7 +87,7 @@ describe Chef::Provider::Package::Windows::Exe do end describe "package_version" do - before { new_resource.version(nil) } + before do new_resource.version(nil) end context "source file does not exist" do before do diff --git a/spec/unit/provider/package/windows/msi_spec.rb b/spec/unit/provider/package/windows/msi_spec.rb index d2902e1bb1..f162ae678c 100644 --- a/spec/unit/provider/package/windows/msi_spec.rb +++ b/spec/unit/provider/package/windows/msi_spec.rb @@ -147,7 +147,7 @@ describe Chef::Provider::Package::Windows::MSI do end context "custom options includes /Q" do - before { new_resource.options("/Q") } + before do new_resource.options("/Q") end it "does not duplicate quiet switch" do expect(provider).to receive(:shell_out!).with(%r{msiexec /x {guid} /Q}, kind_of(Hash)) @@ -156,7 +156,7 @@ describe Chef::Provider::Package::Windows::MSI do end context "custom options includes /qn" do - before { new_resource.options("/qn") } + before do new_resource.options("/qn") end it "does not duplicate quiet switch" do expect(provider).to receive(:shell_out!).with(%r{msiexec /x {guid} /qn}, kind_of(Hash)) diff --git a/spec/unit/provider/package/windows_spec.rb b/spec/unit/provider/package/windows_spec.rb index 2fafb3bd0e..0549048d2b 100644 --- a/spec/unit/provider/package/windows_spec.rb +++ b/spec/unit/provider/package/windows_spec.rb @@ -225,7 +225,7 @@ describe Chef::Provider::Package::Windows, :windows_only do end context "uninstall entries is empty" do - before { allow(Chef::Provider::Package::Windows::RegistryUninstallEntry).to receive(:find_entries).and_return([]) } + before do allow(Chef::Provider::Package::Windows::RegistryUninstallEntry).to receive(:find_entries).and_return([]) end it "returns nil" do expect(provider.installer_type).to eql(nil) @@ -326,7 +326,7 @@ describe Chef::Provider::Package::Windows, :windows_only do end context "no version given or discovered but package is installed" do - before { allow(provider).to receive(:current_version_array).and_return(["5.5.5"]) } + before do allow(provider).to receive(:current_version_array).and_return(["5.5.5"]) end it "does not install" do expect(provider).not_to receive(:install_package) @@ -335,7 +335,7 @@ describe Chef::Provider::Package::Windows, :windows_only do end context "a version is given and none is installed" do - before { new_resource.version("5.5.5") } + before do new_resource.version("5.5.5") end it "installs given version" do expect(provider).to receive(:install_package).with("blah", "5.5.5") diff --git a/spec/unit/provider/remote_directory_spec.rb b/spec/unit/provider/remote_directory_spec.rb index f9559d8827..c4648ec064 100644 --- a/spec/unit/provider/remote_directory_spec.rb +++ b/spec/unit/provider/remote_directory_spec.rb @@ -125,7 +125,7 @@ describe Chef::Provider::RemoteDirectory do @resource.path(@destination_dir) end - after { FileUtils.rm_rf(@destination_dir) } + after do FileUtils.rm_rf(@destination_dir) end # CHEF-3552 it "creates the toplevel directory without error " do @@ -149,8 +149,8 @@ describe Chef::Provider::RemoteDirectory do @resource.overwrite(true) @provider.run_action(:create) - File.open(@destination_dir + "/remote_dir_file1.txt", "a") { |f| f.puts "blah blah blah" } - File.open(@destination_dir + "/remotesubdir/remote_subdir_file1.txt", "a") { |f| f.puts "blah blah blah" } + File.open(@destination_dir + "/remote_dir_file1.txt", "a") do |f| f.puts "blah blah blah" end + File.open(@destination_dir + "/remotesubdir/remote_subdir_file1.txt", "a") do |f| f.puts "blah blah blah" end file1md5 = Digest::MD5.hexdigest(File.read(@destination_dir + "/remote_dir_file1.txt")) subdirfile1md5 = Digest::MD5.hexdigest(File.read(@destination_dir + "/remotesubdir/remote_subdir_file1.txt")) @@ -162,7 +162,7 @@ describe Chef::Provider::RemoteDirectory do end describe "with purging enabled" do - before { @resource.purge(true) } + before do @resource.purge(true) end it "removes existing files if purge is true" do @provider.run_action(:create) @@ -217,13 +217,13 @@ describe Chef::Provider::RemoteDirectory do end describe "with overwrite disabled" do - before { @resource.purge(false) } - before { @resource.overwrite(false) } + before do @resource.purge(false) end + before do @resource.overwrite(false) end it "leaves modifications alone" do @provider.run_action(:create) - ::File.open(@destination_dir + "/remote_dir_file1.txt", "a") { |f| f.puts "blah blah blah" } - ::File.open(@destination_dir + "/remotesubdir/remote_subdir_file1.txt", "a") { |f| f.puts "blah blah blah" } + ::File.open(@destination_dir + "/remote_dir_file1.txt", "a") do |f| f.puts "blah blah blah" end + ::File.open(@destination_dir + "/remotesubdir/remote_subdir_file1.txt", "a") do |f| f.puts "blah blah blah" end file1md5 = Digest::MD5.hexdigest(::File.read(@destination_dir + "/remote_dir_file1.txt")) subdirfile1md5 = Digest::MD5.hexdigest(::File.read(@destination_dir + "/remotesubdir/remote_subdir_file1.txt")) @provider.run_action(:create) diff --git a/spec/unit/provider/ruby_block_spec.rb b/spec/unit/provider/ruby_block_spec.rb index b49aef9243..35fa0b8a26 100644 --- a/spec/unit/provider/ruby_block_spec.rb +++ b/spec/unit/provider/ruby_block_spec.rb @@ -25,7 +25,7 @@ describe Chef::Provider::RubyBlock, "initialize" do @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @new_resource = Chef::Resource::RubyBlock.new("bloc party") - @new_resource.block { $evil_global_evil_laugh = :mwahahaha } + @new_resource.block do $evil_global_evil_laugh = :mwahahaha end @provider = Chef::Provider::RubyBlock.new(@new_resource, @run_context) end diff --git a/spec/unit/provider/service/debian_service_spec.rb b/spec/unit/provider/service/debian_service_spec.rb index 5f89605b2e..3119cd0bf5 100644 --- a/spec/unit/provider/service/debian_service_spec.rb +++ b/spec/unit/provider/service/debian_service_spec.rb @@ -50,9 +50,9 @@ describe Chef::Provider::Service::Debian do expect(File).to receive(:exists?).with("/usr/sbin/update-rc.d") .and_return(false) @provider.define_resource_requirements - expect do + expect { @provider.process_resource_requirements - end.to raise_error(Chef::Exceptions::Service) + }.to raise_error(Chef::Exceptions::Service) end context "when update-rc.d shows init linked to rc*.d/" do diff --git a/spec/unit/provider/service/gentoo_service_spec.rb b/spec/unit/provider/service/gentoo_service_spec.rb index bc3d0b5c04..b0e956cfaf 100644 --- a/spec/unit/provider/service/gentoo_service_spec.rb +++ b/spec/unit/provider/service/gentoo_service_spec.rb @@ -124,7 +124,7 @@ describe Chef::Provider::Service::Gentoo do end describe "action_methods" do - before(:each) { allow(@provider).to receive(:load_current_resource).and_return(@current_resource) } + before(:each) do allow(@provider).to receive(:load_current_resource).and_return(@current_resource) end describe Chef::Provider::Service::Gentoo, "enable_service" do it "should call rc-update add *service* default" do diff --git a/spec/unit/provider/user/aix_spec.rb b/spec/unit/provider/user/aix_spec.rb index f8b5b8a324..4aab195cd2 100644 --- a/spec/unit/provider/user/aix_spec.rb +++ b/spec/unit/provider/user/aix_spec.rb @@ -58,7 +58,7 @@ describe Chef::Provider::User::Aix do describe "#create_user" do context "with a system user" do - before { new_resource.system(true) } + before do new_resource.system(true) end it "should add the user to the system group" do expect(provider).to receive(:shell_out_compacted!).with("useradd", "-g", "system", "adam") provider.create_user diff --git a/spec/unit/provider/user/solaris_spec.rb b/spec/unit/provider/user/solaris_spec.rb index 11c8656a5c..aae4a686f1 100644 --- a/spec/unit/provider/user/solaris_spec.rb +++ b/spec/unit/provider/user/solaris_spec.rb @@ -81,7 +81,7 @@ describe Chef::Provider::User::Solaris do describe "#create_user" do context "with a system user" do - before { new_resource.system(true) } + before do new_resource.system(true) end it "should not pass -r" do expect(provider).to receive(:shell_out_compacted!).with( "useradd", "adam") provider.create_user @@ -89,7 +89,7 @@ describe Chef::Provider::User::Solaris do end context "with manage_home" do - before { new_resource.manage_home(true) } + before do new_resource.manage_home(true) end it "should not pass -r" do expect(provider).to receive(:shell_out_compacted!).with( "useradd", "-m", "adam") provider.create_user diff --git a/spec/unit/provider/whyrun_safe_ruby_block_spec.rb b/spec/unit/provider/whyrun_safe_ruby_block_spec.rb index 29d49ff90b..3fbc940cbe 100644 --- a/spec/unit/provider/whyrun_safe_ruby_block_spec.rb +++ b/spec/unit/provider/whyrun_safe_ruby_block_spec.rb @@ -25,7 +25,7 @@ describe Chef::Provider::WhyrunSafeRubyBlock, "initialize" do @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @new_resource = Chef::Resource::WhyrunSafeRubyBlock.new("bloc party") - @new_resource.block { $evil_global_evil_laugh = :mwahahaha } + @new_resource.block do $evil_global_evil_laugh = :mwahahaha end @provider = Chef::Provider::WhyrunSafeRubyBlock.new(@new_resource, @run_context) end diff --git a/spec/unit/provider_resolver_spec.rb b/spec/unit/provider_resolver_spec.rb index 94e0d6074b..358030e75a 100644 --- a/spec/unit/provider_resolver_spec.rb +++ b/spec/unit/provider_resolver_spec.rb @@ -91,10 +91,10 @@ describe Chef::ProviderResolver do let(:platform_family) { platform_family } let(:platform_version) { platform_version } - define_singleton_method(:os) { os } - define_singleton_method(:platform) { platform } - define_singleton_method(:platform_family) { platform_family } - define_singleton_method(:platform_version) { platform_version } + define_singleton_method(:os) do os end + define_singleton_method(:platform) do platform end + define_singleton_method(:platform_family) do platform_family end + define_singleton_method(:platform_version) do platform_version end instance_eval(&block) end diff --git a/spec/unit/recipe_spec.rb b/spec/unit/recipe_spec.rb index f2ec175243..9d14216cb1 100644 --- a/spec/unit/recipe_spec.rb +++ b/spec/unit/recipe_spec.rb @@ -47,27 +47,27 @@ describe Chef::Recipe do describe "method_missing" do describe "resources" do it "should load a two word (zen_master) resource" do - expect do + expect { recipe.zen_master "monkey" do peace true end - end.not_to raise_error + }.not_to raise_error end it "should load a one word (cat) resource" do - expect do + expect { recipe.cat "loulou" do pretty_kitty true end - end.not_to raise_error + }.not_to raise_error end it "should load a four word (one_two_three_four) resource" do - expect do + expect { recipe.one_two_three_four "numbers" do i_can_count true end - end.not_to raise_error + }.not_to raise_error end it "should throw an error if you access a resource that we can't find" do @@ -75,9 +75,9 @@ describe Chef::Recipe do end it "should allow regular errors (not NameErrors) to pass unchanged" do - expect do + expect { recipe.cat("felix") { raise ArgumentError, "You Suck" } - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should add our zen_master to the collection" do @@ -299,18 +299,18 @@ describe Chef::Recipe do describe "when attempting to create a resource of an invalid type" do it "gives a sane error message when using method_missing" do - expect do + expect { recipe.no_such_resource("foo") - end.to raise_error(NoMethodError, /undefined method `no_such_resource' for cookbook: hjk, recipe: test :Chef::Recipe/) + }.to raise_error(NoMethodError, /undefined method `no_such_resource' for cookbook: hjk, recipe: test :Chef::Recipe/) end it "gives a sane error message when using method_missing 'bare'" do - expect do + expect { recipe.instance_eval do # Giving an argument will change this from NameError to NoMethodError no_such_resource end - end.to raise_error(NameError, /undefined local variable or method `no_such_resource' for cookbook: hjk, recipe: test :Chef::Recipe/) + }.to raise_error(NameError, /undefined local variable or method `no_such_resource' for cookbook: hjk, recipe: test :Chef::Recipe/) end it "gives a sane error message when using build_resource" do @@ -326,11 +326,11 @@ describe Chef::Recipe do describe "when creating a resource that contains an error in the attributes block" do it "does not obfuscate the error source" do - expect do + expect { recipe.zen_master("klopp") do this_method_doesnt_exist end - end.to raise_error(NoMethodError, "undefined method `this_method_doesnt_exist' for Chef::Resource::ZenMaster") + }.to raise_error(NoMethodError, "undefined method `this_method_doesnt_exist' for Chef::Resource::ZenMaster") end diff --git a/spec/unit/resource/dsc_resource_spec.rb b/spec/unit/resource/dsc_resource_spec.rb index e0beb309ab..661f9fa3c2 100644 --- a/spec/unit/resource/dsc_resource_spec.rb +++ b/spec/unit/resource/dsc_resource_spec.rb @@ -77,9 +77,9 @@ describe Chef::Resource::DscResource do end it "raises a TypeError if property_name is not a symbol" do - expect do + expect { dsc_test_resource.property("Foo", dsc_test_property_value) - end.to raise_error(TypeError) + }.to raise_error(TypeError) end context "when using DelayedEvaluators" do diff --git a/spec/unit/resource/file/verification_spec.rb b/spec/unit/resource/file/verification_spec.rb index 57c58249eb..cb60c9d917 100644 --- a/spec/unit/resource/file/verification_spec.rb +++ b/spec/unit/resource/file/verification_spec.rb @@ -88,16 +88,16 @@ describe Chef::Resource::File::Verification do it "raises an error when \%{file} is used" do test_command = platform_specific_verify_command("file") - expect do + expect { Chef::Resource::File::Verification.new(parent_resource, test_command, {}).verify(temp_path) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "does not raise an error when \%{file} is not used" do test_command = platform_specific_verify_command("path") - expect do + expect { Chef::Resource::File::Verification.new(parent_resource, test_command, {}).verify(temp_path) - end.to_not raise_error + }.to_not raise_error end it "substitutes \%{path} with the path" do diff --git a/spec/unit/resource/remote_file_spec.rb b/spec/unit/resource/remote_file_spec.rb index 39d34d9a96..ae7f38af83 100644 --- a/spec/unit/resource/remote_file_spec.rb +++ b/spec/unit/resource/remote_file_spec.rb @@ -99,15 +99,15 @@ describe Chef::Resource::RemoteFile do end it "only accept a single argument if a delayed evalutor is used" do - expect do + expect { resource.source("http://opscode.com/", Chef::DelayedEvaluator.new { "http://opscode.com/" }) - end.to raise_error(Chef::Exceptions::InvalidRemoteFileURI) + }.to raise_error(Chef::Exceptions::InvalidRemoteFileURI) end it "only accept a single array item if a delayed evalutor is used" do - expect do + expect { resource.source(["http://opscode.com/", Chef::DelayedEvaluator.new { "http://opscode.com/" }]) - end.to raise_error(Chef::Exceptions::InvalidRemoteFileURI) + }.to raise_error(Chef::Exceptions::InvalidRemoteFileURI) end it "does not accept a non-URI as the source" do @@ -115,10 +115,10 @@ describe Chef::Resource::RemoteFile do end it "does not accept a non-URI as the source when read from a delayed evaluator" do - expect do + expect { resource.source(Chef::DelayedEvaluator.new { "not-a-uri" }) resource.source - end.to raise_error(Chef::Exceptions::InvalidRemoteFileURI) + }.to raise_error(Chef::Exceptions::InvalidRemoteFileURI) end it "raises an exception when source is an empty array" do diff --git a/spec/unit/resource/rhsm_errata_level_spec.rb b/spec/unit/resource/rhsm_errata_level_spec.rb index 8d0de18f98..eb67f3278e 100644 --- a/spec/unit/resource/rhsm_errata_level_spec.rb +++ b/spec/unit/resource/rhsm_errata_level_spec.rb @@ -43,8 +43,8 @@ describe Chef::Resource::RhsmErrataLevel do end it "raises an exception if invalid errata_level is passed" do - expect do + expect { resource.errata_level "FOO" - end.to raise_error(Chef::Exceptions::ValidationFailed) + }.to raise_error(Chef::Exceptions::ValidationFailed) end end diff --git a/spec/unit/resource/ruby_block_spec.rb b/spec/unit/resource/ruby_block_spec.rb index fb5a8815c7..ff01ddb802 100644 --- a/spec/unit/resource/ruby_block_spec.rb +++ b/spec/unit/resource/ruby_block_spec.rb @@ -41,9 +41,9 @@ describe Chef::Resource::RubyBlock do end it "accepts a ruby block/proc/.. for the 'block' parameter" do - expect(resource.block do + expect(resource.block { "foo" - end.call).to eql("foo") + }.call).to eql("foo") end describe "when it has been initialized with block code" do diff --git a/spec/unit/resource/scm_spec.rb b/spec/unit/resource/scm_spec.rb index 5478309a86..ad6f7cdcb2 100644 --- a/spec/unit/resource/scm_spec.rb +++ b/spec/unit/resource/scm_spec.rb @@ -133,7 +133,7 @@ describe Chef::Resource::Scm do describe "when it has a timeout property" do let(:ten_seconds) { 10 } - before { resource.timeout(ten_seconds) } + before do resource.timeout(ten_seconds) end it "stores this timeout" do expect(resource.timeout).to eq(ten_seconds) end @@ -165,7 +165,7 @@ describe Chef::Resource::Scm do describe "when it has a environment property" do let(:test_environment) { { "CHEF_ENV" => "/tmp" } } - before { resource.environment(test_environment) } + before do resource.environment(test_environment) end it "stores this environment" do expect(resource.environment).to eq(test_environment) end diff --git a/spec/unit/resource/service_spec.rb b/spec/unit/resource/service_spec.rb index be88d82f3b..cfebb70898 100644 --- a/spec/unit/resource/service_spec.rb +++ b/spec/unit/resource/service_spec.rb @@ -61,9 +61,9 @@ describe Chef::Resource::Service do end it "does not accept a regexp for the service pattern" do - expect do + expect { resource.pattern /.*/ - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "accepts a String for the user property" do @@ -88,9 +88,9 @@ describe Chef::Resource::Service do end it "does not accept a regexp for the init_command property" do - expect do + expect { resource.init_command /.*/ - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "accepts an array for options property" do @@ -109,9 +109,9 @@ describe Chef::Resource::Service do end it "does not accept a boolean for options property" do - expect do + expect { resource.options true - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end %w{restart_command start_command stop_command status_command reload_command}.each do |prop| diff --git a/spec/unit/resource/template_spec.rb b/spec/unit/resource/template_spec.rb index 2f8e234c85..dfabe38efb 100644 --- a/spec/unit/resource/template_spec.rb +++ b/spec/unit/resource/template_spec.rb @@ -129,19 +129,19 @@ describe Chef::Resource::Template do end it "collects helper method bodies as blocks" do - resource.helper(:example_1) { "example_1" } - resource.helper(:example_2) { "example_2" } + resource.helper(:example_1) do "example_1" end + resource.helper(:example_2) do "example_2" end expect(resource.inline_helper_blocks[:example_1].call).to eq("example_1") expect(resource.inline_helper_blocks[:example_2].call).to eq("example_2") end it "compiles helper methods into a module" do - resource.helper(:example_1) { "example_1" } - resource.helper(:example_2) { "example_2" } + resource.helper(:example_1) do "example_1" end + resource.helper(:example_2) do "example_2" end modules = resource.helper_modules expect(modules.size).to eq(1) o = Object.new - modules.each { |m| o.extend(m) } + modules.each do |m| o.extend(m) end expect(o.example_1).to eq("example_1") expect(o.example_2).to eq("example_2") end @@ -150,7 +150,7 @@ describe Chef::Resource::Template do resource.helper(:shout, &:upcase) modules = resource.helper_modules o = Object.new - modules.each { |m| o.extend(m) } + modules.each do |m| o.extend(m) end expect(o.shout("shout")).to eq("SHOUT") end @@ -181,7 +181,7 @@ describe Chef::Resource::Template do modules = resource.helper_modules expect(modules.size).to eq(1) o = Object.new - modules.each { |m| o.extend(m) } + modules.each do |m| o.extend(m) end expect(o.example_1).to eq("example_1") end @@ -209,11 +209,11 @@ describe Chef::Resource::Template do "inline_module" end end - resource.helper(:inline_method) { "inline_method" } + resource.helper(:inline_method) do "inline_method" end expect(resource.helper_modules.size).to eq(3) o = Object.new - resource.helper_modules.each { |m| o.extend(m) } + resource.helper_modules.each do |m| o.extend(m) end expect(o.static_example).to eq("static_example") expect(o.inline_module).to eq("inline_module") expect(o.inline_method).to eq("inline_method") diff --git a/spec/unit/resource/windows_task_spec.rb b/spec/unit/resource/windows_task_spec.rb index d08849d4be..4817a8aa4b 100644 --- a/spec/unit/resource/windows_task_spec.rb +++ b/spec/unit/resource/windows_task_spec.rb @@ -79,7 +79,7 @@ describe Chef::Resource::WindowsTask, :windows_only do end context "for an interactive task" do - before { resource.interactive_enabled true } + before do resource.interactive_enabled true end it "does not require a password" do expect { resource.after_created }.to_not raise_error end @@ -94,7 +94,7 @@ describe Chef::Resource::WindowsTask, :windows_only do end context "for a non-interactive task" do - before { resource.interactive_enabled false } + before do resource.interactive_enabled false end it "does not require a password" do expect { resource.after_created }.to_not raise_error end @@ -115,7 +115,7 @@ describe Chef::Resource::WindowsTask, :windows_only do resource.user "bob" end context "for an interactive task" do - before { resource.interactive_enabled true } + before do resource.interactive_enabled true end it "does not require a password" do expect { resource.after_created }.to_not raise_error end @@ -126,7 +126,7 @@ describe Chef::Resource::WindowsTask, :windows_only do end context "for a non-interactive task" do - before { resource.interactive_enabled false } + before do resource.interactive_enabled false end it "require a password" do expect { resource.after_created }.to raise_error(ArgumentError, %q{Please provide a password or check if this task needs to be interactive! Valid passwordless users are: 'SYSTEM', 'NT AUTHORITY\SYSTEM', 'LOCAL SERVICE', 'NT AUTHORITY\LOCAL SERVICE', 'NETWORK SERVICE', 'NT AUTHORITY\NETWORK SERVICE', 'ADMINISTRATORS', 'BUILTIN\ADMINISTRATORS', 'USERS', 'BUILTIN\USERS', 'GUESTS', 'BUILTIN\GUESTS'}) end diff --git a/spec/unit/resource_collection_spec.rb b/spec/unit/resource_collection_spec.rb index 60f17b6934..44dad6599b 100644 --- a/spec/unit/resource_collection_spec.rb +++ b/spec/unit/resource_collection_spec.rb @@ -98,11 +98,11 @@ describe Chef::ResourceCollection do it "should allow you to iterate over every resource in the collection" do load_up_resources results = [] - expect do + expect { rc.each do |r| results << r.name end - end.not_to raise_error + }.not_to raise_error results.each_index do |i| case i when 0 @@ -120,11 +120,11 @@ describe Chef::ResourceCollection do it "should allow you to iterate over every resource by index" do load_up_resources results = [] - expect do + expect { rc.each_index do |i| results << rc[i].name end - end.not_to raise_error + }.not_to raise_error results.each_index do |i| case i when 0 @@ -270,15 +270,15 @@ describe Chef::ResourceCollection do end it "rejects a malformed query string" do - expect do + expect { rc.validate_lookup_spec!("resource_type[missing-end-bracket") - end.to raise_error(Chef::Exceptions::InvalidResourceSpecification) + }.to raise_error(Chef::Exceptions::InvalidResourceSpecification) end it "rejects an argument that is not a String, Hash, or Chef::Resource" do - expect do + expect { rc.validate_lookup_spec!(Object.new) - end.to raise_error(Chef::Exceptions::InvalidResourceSpecification) + }.to raise_error(Chef::Exceptions::InvalidResourceSpecification) end end diff --git a/spec/unit/resource_definition_spec.rb b/spec/unit/resource_definition_spec.rb index a1c59eaaca..2a45dd6725 100644 --- a/spec/unit/resource_definition_spec.rb +++ b/spec/unit/resource_definition_spec.rb @@ -53,26 +53,26 @@ describe Chef::ResourceDefinition do end it "should accept a new definition with a symbol for a name" do - expect do + expect { defn.define :smoke do end - end.not_to raise_error - expect do + }.not_to raise_error + expect { defn.define "george washington" do end - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) expect(defn.name).to eql(:smoke) end it "should accept a new definition with a hash" do - expect do + expect { defn.define :smoke, cigar: "cuban", cigarette: "marlboro" do end - end.not_to raise_error + }.not_to raise_error end it "should expose the prototype hash params in the params hash" do - defn.define(:smoke, cigar: "cuban", cigarette: "marlboro") {} + defn.define(:smoke, cigar: "cuban", cigarette: "marlboro") do end expect(defn.params[:cigar]).to eql("cuban") expect(defn.params[:cigarette]).to eql("marlboro") end @@ -91,16 +91,16 @@ describe Chef::ResourceDefinition do end it "should raise an exception if prototype_params is not a hash" do - expect do + expect { defn.define :monkey, [] do end - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should raise an exception if define is called without a block" do - expect do + expect { defn.define :monkey - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should load a description from a file" do diff --git a/spec/unit/resource_reporter_spec.rb b/spec/unit/resource_reporter_spec.rb index 1d7fd7fc79..2876c9ec29 100644 --- a/spec/unit/resource_reporter_spec.rb +++ b/spec/unit/resource_reporter_spec.rb @@ -716,9 +716,9 @@ describe Chef::ResourceReporter do it "fails the run and prints an message about the error" do expect(Chef::Log).to receive(:error).with(/500/) - expect do + expect { resource_reporter.run_started(run_status) - end.to raise_error(Net::HTTPClientException) + }.to raise_error(Net::HTTPClientException) end end @@ -801,9 +801,9 @@ describe Chef::ResourceReporter do it "should raise if an unkwown error happens" do allow(rest_client).to receive(:raw_request).and_raise(Exception.new) - expect do + expect { resource_reporter.post_reporting_data - end.to raise_error(Exception) + }.to raise_error(Exception) end end end diff --git a/spec/unit/resource_spec.rb b/spec/unit/resource_spec.rb index 6745dd448d..6a618079f3 100644 --- a/spec/unit/resource_spec.rb +++ b/spec/unit/resource_spec.rb @@ -242,9 +242,9 @@ describe Chef::Resource do it "should raise an exception if told to act in other than :delay or :immediate(ly)" do run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") - expect do + expect { resource.notifies :reload, run_context.resource_collection.find(zen_master: "coffee"), :someday - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should allow multiple notified resources appear in the actions hash" do @@ -673,7 +673,7 @@ describe Chef::Resource do it "runs runs an only_if when one is given" do snitch_variable = nil - resource.only_if { snitch_variable = true } + resource.only_if do snitch_variable = true end expect(resource.only_if.first.positivity).to eq(:only_if) # Chef::Mixin::Command.should_receive(:only_if).with(true, {}).and_return(false) resource.run_action(:purr) @@ -682,8 +682,8 @@ describe Chef::Resource do it "runs multiple only_if conditionals" do snitch_var1, snitch_var2 = nil, nil - resource.only_if { snitch_var1 = 1 } - resource.only_if { snitch_var2 = 2 } + resource.only_if do snitch_var1 = 1 end + resource.only_if do snitch_var2 = 2 end resource.run_action(:purr) expect(snitch_var1).to eq(1) expect(snitch_var2).to eq(2) @@ -704,7 +704,7 @@ describe Chef::Resource do it "runs not_if as a block when it is a ruby block" do expect_any_instance_of(Chef::Resource::Conditional).to receive(:evaluate_block).at_least(1).times - resource.not_if { puts "foo" } + resource.not_if do puts "foo" end resource.run_action(:purr) end @@ -721,8 +721,8 @@ describe Chef::Resource do it "accepts multiple not_if conditionals" do snitch_var1, snitch_var2 = true, true - resource.not_if { snitch_var1 = nil } - resource.not_if { snitch_var2 = false } + resource.not_if do snitch_var1 = nil end + resource.not_if do snitch_var2 = false end resource.run_action(:purr) expect(snitch_var1).to be_nil expect(snitch_var2).to be_falsey @@ -766,62 +766,62 @@ describe Chef::Resource do end it "should return false when only_if is met" do - resource.only_if { true } + resource.only_if do true end expect(resource.should_skip?(:purr)).to be_falsey end it "should return true when only_if is not met" do - resource.only_if { false } + resource.only_if do false end expect(resource.should_skip?(:purr)).to be_truthy end it "should return true when not_if is met" do - resource.not_if { true } + resource.not_if do true end expect(resource.should_skip?(:purr)).to be_truthy end it "should return false when not_if is not met" do - resource.not_if { false } + resource.not_if do false end expect(resource.should_skip?(:purr)).to be_falsey end it "should return true when only_if is met but also not_if is met" do - resource.only_if { true } - resource.not_if { true } + resource.only_if do true end + resource.not_if do true end expect(resource.should_skip?(:purr)).to be_truthy end it "should return false when only_if is met and also not_if is not met" do - resource.only_if { true } - resource.not_if { false } + resource.only_if do true end + resource.not_if do false end expect(resource.should_skip?(:purr)).to be_falsey end it "should return true when one of multiple only_if's is not met" do - resource.only_if { true } - resource.only_if { false } - resource.only_if { true } + resource.only_if do true end + resource.only_if do false end + resource.only_if do true end expect(resource.should_skip?(:purr)).to be_truthy end it "should return true when one of multiple not_if's is met" do - resource.not_if { false } - resource.not_if { true } - resource.not_if { false } + resource.not_if do false end + resource.not_if do true end + resource.not_if do false end expect(resource.should_skip?(:purr)).to be_truthy end it "should return false when all of multiple only_if's are met" do - resource.only_if { true } - resource.only_if { true } - resource.only_if { true } + resource.only_if do true end + resource.only_if do true end + resource.only_if do true end expect(resource.should_skip?(:purr)).to be_falsey end it "should return false when all of multiple not_if's are not met" do - resource.not_if { false } - resource.not_if { false } - resource.not_if { false } + resource.not_if do false end + resource.not_if do false end + resource.not_if do false end expect(resource.should_skip?(:purr)).to be_falsey end @@ -830,8 +830,8 @@ describe Chef::Resource do end it "should return true when action is :nothing ignoring only_if/not_if conditionals" do - resource.only_if { true } - resource.not_if { false } + resource.only_if do true end + resource.not_if do false end expect(resource.should_skip?(:nothing)).to be_truthy end @@ -857,8 +857,8 @@ describe Chef::Resource do it "should not run only_if/not_if conditionals (CHEF-972)" do snitch_var1 = 0 - resource1.only_if { snitch_var1 = 1 } - resource1.not_if { snitch_var1 = 2 } + resource1.only_if do snitch_var1 = 1 end + resource1.not_if do snitch_var1 = 2 end resource1.run_action(:nothing) expect(snitch_var1).to eq(0) end @@ -869,8 +869,8 @@ describe Chef::Resource do Chef::Provider::SnakeOil.provides :cat - resource1.only_if { snitch_var1 = 1 } - resource1.not_if { snitch_var2 = 2 } + resource1.only_if do snitch_var1 = 1 end + resource1.not_if do snitch_var2 = 2 end resource2 = Chef::Resource::Cat.new("coffee", run_context) resource2.notifies :purr, resource1 resource2.action = :purr @@ -1021,9 +1021,9 @@ describe Chef::Resource do describe "with a syntax error in the resource spec" do it "raises an exception immmediately" do - expect do + expect { resource.notifies(:run, "typo[missing-closing-bracket") - end.to raise_error(Chef::Exceptions::InvalidResourceSpecification) + }.to raise_error(Chef::Exceptions::InvalidResourceSpecification) end end end @@ -1108,27 +1108,27 @@ describe Chef::Resource do end context "with a symbol action" do - before { resource.action(:one) } + before do resource.action(:one) end it { is_expected.to eq [:one] } end context "with a string action" do - before { resource.action("two") } + before do resource.action("two") end it { is_expected.to eq [:two] } end context "with an array action" do - before { resource.action(%i{two one}) } + before do resource.action(%i{two one}) end it { is_expected.to eq %i{two one} } end context "with an assignment" do - before { resource.action = :one } + before do resource.action = :one end it { is_expected.to eq [:one] } end context "with an array assignment" do - before { resource.action = %i{two one} } + before do resource.action = %i{two one} end it { is_expected.to eq %i{two one} } end diff --git a/spec/unit/run_context_spec.rb b/spec/unit/run_context_spec.rb index 0d66b1f66d..49fc92b6d0 100644 --- a/spec/unit/run_context_spec.rb +++ b/spec/unit/run_context_spec.rb @@ -136,16 +136,16 @@ describe Chef::RunContext do it "raises an error when attempting to include_recipe from a cookbook not reachable by run list or dependencies" do expect(node).to receive(:loaded_recipe).with(:ancient, "aliens") - expect do + expect { run_context.include_recipe("ancient::aliens") # In CHEF-5120, this becomes a Chef::Exceptions::MissingCookbookDependency error: - end.to raise_error(Chef::Exceptions::CookbookNotFound) + }.to raise_error(Chef::Exceptions::CookbookNotFound) end it "raises an error on a recipe with a leading :: with no current_cookbook" do - expect do + expect { run_context.include_recipe("::aliens") - end.to raise_error(RuntimeError) + }.to raise_error(RuntimeError) end end @@ -165,9 +165,9 @@ describe Chef::RunContext do end it "errors when querying for a template in a not-available cookbook" do - expect do + expect { run_context.has_template_in_cookbook?("no-such-cookbook", "foo.erb") - end.to raise_error(Chef::Exceptions::CookbookNotFound) + }.to raise_error(Chef::Exceptions::CookbookNotFound) end it "queries whether a given cookbook has a specific cookbook_file" do @@ -176,9 +176,9 @@ describe Chef::RunContext do end it "errors when querying for a cookbook_file in a not-available cookbook" do - expect do + expect { run_context.has_cookbook_file_in_cookbook?("no-such-cookbook", "foo.txt") - end.to raise_error(Chef::Exceptions::CookbookNotFound) + }.to raise_error(Chef::Exceptions::CookbookNotFound) end end diff --git a/spec/unit/run_list/versioned_recipe_list_spec.rb b/spec/unit/run_list/versioned_recipe_list_spec.rb index e116ffc130..de0109e83c 100644 --- a/spec/unit/run_list/versioned_recipe_list_spec.rb +++ b/spec/unit/run_list/versioned_recipe_list_spec.rb @@ -33,7 +33,7 @@ describe Chef::RunList::VersionedRecipeList do let(:recipes) { [] } before do - recipes.each { |r| list << r } + recipes.each do |r| list << r end versioned_recipes.each { |r| list.add_recipe r[:name], r[:version] } end diff --git a/spec/unit/run_list_spec.rb b/spec/unit/run_list_spec.rb index 5dc877ad9a..9d42a3dabf 100644 --- a/spec/unit/run_list_spec.rb +++ b/spec/unit/run_list_spec.rb @@ -134,7 +134,7 @@ describe Chef::RunList do @run_list << "foo" @run_list << "bar" seen = [] - @run_list.each { |r| seen << r } + @run_list.each do |r| seen << r end expect(seen).to be_include("recipe[foo]") expect(seen).to be_include("recipe[bar]") end @@ -143,7 +143,7 @@ describe Chef::RunList do describe "each_index" do it "should yield each members index to your block" do to_add = [ "recipe[foo]", "recipe[bar]", "recipe[baz]" ] - to_add.each { |i| @run_list << i } + to_add.each do |i| @run_list << i end @run_list.each_index { |i| expect(@run_list[i]).to eq(to_add[i]) } end end @@ -160,7 +160,7 @@ describe Chef::RunList do @run_list << "chromeo" list = %w{camp chairs snakes clowns} @run_list.reset!(list) - list.each { |i| expect(@run_list).to be_include(i) } + list.each do |i| expect(@run_list).to be_include(i) end expect(@run_list.include?("chromeo")).to eq(false) end end diff --git a/spec/unit/runner_spec.rb b/spec/unit/runner_spec.rb index ffb0cd523f..cd2f656cf7 100644 --- a/spec/unit/runner_spec.rb +++ b/spec/unit/runner_spec.rb @@ -359,10 +359,10 @@ describe Chef::Runner do first_resource.action = :buy only_if_called_times = 0 - first_resource.only_if { only_if_called_times += 1; true } + first_resource.only_if do only_if_called_times += 1; true end not_if_called_times = 0 - first_resource.not_if { not_if_called_times += 1; false } + first_resource.not_if do not_if_called_times += 1; false end second_resource = Chef::Resource::Cat.new("carmel", run_context) run_context.resource_collection << second_resource @@ -387,7 +387,7 @@ describe Chef::Runner do end second_resource = Chef::Resource::RubyBlock.new("myblock", run_context) run_context.resource_collection << second_resource - second_resource.block { lazy_resources.call } + second_resource.block do lazy_resources.call end runner.converge diff --git a/spec/unit/search/query_spec.rb b/spec/unit/search/query_spec.rb index 83f988911c..d9693573b1 100644 --- a/spec/unit/search/query_spec.rb +++ b/spec/unit/search/query_spec.rb @@ -207,13 +207,13 @@ describe Chef::Search::Query do it "calls a block for each object in the response" do @call_me = double("blocky") - response["rows"].each { |r| expect(@call_me).to receive(:do).with(Chef::Node.from_hash(r)) } + response["rows"].each do |r| expect(@call_me).to receive(:do).with(Chef::Node.from_hash(r)) end query.search(:node) { |r| @call_me.do(r) } end it "pages through the responses" do @call_me = double("blocky") - response["rows"].each { |r| expect(@call_me).to receive(:do).with(Chef::Node.from_hash(r)) } + response["rows"].each do |r| expect(@call_me).to receive(:do).with(Chef::Node.from_hash(r)) end query.search(:node, "*:*", start: 0, rows: 4) { |r| @call_me.do(r) } end diff --git a/spec/unit/util/dsc/configuration_generator_spec.rb b/spec/unit/util/dsc/configuration_generator_spec.rb index faf554326d..a128808ac4 100644 --- a/spec/unit/util/dsc/configuration_generator_spec.rb +++ b/spec/unit/util/dsc/configuration_generator_spec.rb @@ -40,9 +40,9 @@ describe Chef::Util::DSC::ConfigurationGenerator do %w{! @ # $ % ^ & * & * ( ) - = + \{ \} . ? < > \\ /}.each do |sym| it "raises an Argument error if it configuration name contains #{sym}" do - expect do + expect { conf_man.send(:validate_configuration_name!, "Hello#{sym}") - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end end end @@ -57,15 +57,15 @@ describe Chef::Util::DSC::ConfigurationGenerator do end it "should raise an ArgumentError if you try to override outputpath" do - expect do + expect { conf_man.send(:get_merged_configuration_flags!, { "outputpath" => "a" }, "hello") - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should be case insensitive for switches that are not allowed" do - expect do + expect { conf_man.send(:get_merged_configuration_flags!, { "OutputPath" => "a" }, "hello") - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should be case insensitive to switches that are allowed" do @@ -83,15 +83,15 @@ describe Chef::Util::DSC::ConfigurationGenerator do end it "should raise an ArgumentError if you try to override outputpath" do - expect do + expect { conf_man.send(:get_merged_configuration_flags!, { outputpath: "a" }, "hello") - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should be case insensitive for switches that are not allowed" do - expect do + expect { conf_man.send(:get_merged_configuration_flags!, { OutputPath: "a" }, "hello") - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should be case insensitive to switches that are allowed" do diff --git a/spec/unit/util/powershell/cmdlet_spec.rb b/spec/unit/util/powershell/cmdlet_spec.rb index 144e363979..6969eb3df5 100644 --- a/spec/unit/util/powershell/cmdlet_spec.rb +++ b/spec/unit/util/powershell/cmdlet_spec.rb @@ -40,9 +40,9 @@ describe Chef::Util::Powershell::Cmdlet do %w{! @ # $ % ^ & * & * ( ) - = + \{ \} . ? < > \\ /}.each do |sym| it "raises an Argument error if it configuration name contains #{sym}" do - expect do + expect { @cmdlet.send(:validate_switch_name!, "Hello#{sym}") - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end end end @@ -68,15 +68,15 @@ describe Chef::Util::Powershell::Cmdlet do describe "#command_switches_string" do it "raises an ArgumentError if the key is not a symbol" do - expect do + expect { @cmdlet.send(:command_switches_string, { "foo" => "bar" }) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "does not allow invalid switch names" do - expect do + expect { @cmdlet.send(:command_switches_string, { foo!: "bar" }) - end.to raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "ignores switches with a false value" do diff --git a/spec/unit/util/threaded_job_queue_spec.rb b/spec/unit/util/threaded_job_queue_spec.rb index 48a34bce31..4134843f44 100644 --- a/spec/unit/util/threaded_job_queue_spec.rb +++ b/spec/unit/util/threaded_job_queue_spec.rb @@ -26,7 +26,7 @@ describe Chef::Util::ThreadedJobQueue do expect(job).to receive(:arity).at_least(:once).and_return(1) expect(job).to receive(:call).exactly(5).times.with(an_instance_of(Mutex)) - 5.times { queue << job } + 5.times do queue << job end queue.process end @@ -35,7 +35,7 @@ describe Chef::Util::ThreadedJobQueue do expect(job).to receive(:arity).at_least(:once).and_return(0) expect(job).to receive(:call).exactly(5).times.with(no_args) - 5.times { queue << job } + 5.times do queue << job end queue.process end diff --git a/spec/unit/version_class_spec.rb b/spec/unit/version_class_spec.rb index c6848491ee..81925478de 100644 --- a/spec/unit/version_class_spec.rb +++ b/spec/unit/version_class_spec.rb @@ -102,17 +102,17 @@ describe Chef::Version do end it "should sort an array of versions" do - a = %w{0.0.0 0.0.1 0.1.0 0.1.1 1.0.0 1.1.0 1.1.1}.map do |s| + a = %w{0.0.0 0.0.1 0.1.0 0.1.1 1.0.0 1.1.0 1.1.1}.map { |s| Chef::Version.new(s) - end + } got = a.sort.map(&:to_s) expect(got).to eq(%w{0.0.0 0.0.1 0.1.0 0.1.1 1.0.0 1.1.0 1.1.1}) end it "should sort an array of versions, part 2" do - a = %w{9.8.7 1.0.0 1.2.3 4.4.6 4.5.6 0.8.6 4.5.5 5.9.8 3.5.7}.map do |s| + a = %w{9.8.7 1.0.0 1.2.3 4.4.6 4.5.6 0.8.6 4.5.5 5.9.8 3.5.7}.map { |s| Chef::Version.new(s) - end + } got = a.sort.map(&:to_s) expect(got).to eq(%w{0.8.6 1.0.0 1.2.3 3.5.7 4.4.6 4.5.5 4.5.6 5.9.8 9.8.7}) end diff --git a/tasks/docs.rb b/tasks/docs.rb index af35e77701..37f3d17c5e 100755 --- a/tasks/docs.rb +++ b/tasks/docs.rb @@ -83,7 +83,7 @@ namespace :docs_site do # which needs to be "true" and "false" # @return String def friendly_types_list(arr) - fixed_arr = Array(arr).map do |x| + fixed_arr = Array(arr).map { |x| case x when "TrueClass" "true" @@ -92,7 +92,7 @@ namespace :docs_site do else x end - end + } fixed_arr.compact.join(", ") end |