From 938c37c2dd5bff3b888540ae1ae4d2e51b3208d8 Mon Sep 17 00:00:00 2001 From: Lamont Granquist Date: Thu, 4 Feb 2016 08:35:04 -0800 Subject: whitespace fixes 5533 Style/SpaceInsideHashLiteralBraces 2619 Style/SpaceAroundOperators 2288 Style/EmptyLinesAroundBlockBody 2012 Style/SpaceInsideBlockBraces 1444 Style/AlignHash 1395 Style/SpaceAfterComma 1382 Style/SpaceAroundEqualsInParameterDefault 800 Style/EmptyLinesAroundClassBody 396 Style/IndentationConsistency 354 Style/ExtraSpacing 310 Style/SpaceBeforeBlockBraces 309 Style/EmptyLines 304 Style/TrailingWhitespace 241 Style/MultilineOperationIndentation 230 Style/TrailingBlankLines 219 Style/EmptyLinesAroundModuleBody 212 Style/IndentHash 147 Style/IndentationWidth 120 Style/EmptyLineBetweenDefs 107 Style/SpaceAroundBlockParameters 63 Style/EmptyLinesAroundMethodBody 29 Style/EmptyLinesAroundAccessModifier 1 Style/RescueEnsureAlignment --- .../inspec/chef_windows_service_spec.rb | 8 +- bin/knife | 1 - chef-config/Rakefile | 1 - chef-config/chef-config.gemspec | 2 +- chef-config/lib/chef-config.rb | 1 - chef-config/lib/chef-config/config.rb | 11 +- chef-config/lib/chef-config/exceptions.rb | 2 - chef-config/lib/chef-config/logger.rb | 6 - chef-config/lib/chef-config/package_task.rb | 6 +- chef-config/lib/chef-config/path_helper.rb | 24 +- chef-config/lib/chef-config/windows.rb | 3 - .../lib/chef-config/workstation_config_loader.rb | 11 +- chef-config/spec/unit/config_spec.rb | 37 +- chef-config/spec/unit/path_helper_spec.rb | 14 +- .../spec/unit/workstation_config_loader_spec.rb | 29 - chef.gemspec | 2 +- ext/win32-eventlog/Rakefile | 3 +- kitchen-tests/cookbooks/audit_test/metadata.rb | 1 - .../webapp/serverspec/localhost/default_spec.rb | 2 - lib/chef/api_client.rb | 24 +- lib/chef/api_client/registration.rb | 3 +- lib/chef/api_client_v1.rb | 24 +- lib/chef/application.rb | 6 +- lib/chef/application/apply.rb | 9 +- lib/chef/application/client.rb | 15 +- lib/chef/application/knife.rb | 8 +- lib/chef/application/solo.rb | 12 +- lib/chef/application/windows_service.rb | 17 +- lib/chef/application/windows_service_manager.rb | 5 +- lib/chef/audit/audit_event_proxy.rb | 13 +- lib/chef/audit/audit_reporter.rb | 5 +- lib/chef/audit/control_group_data.rb | 41 +- lib/chef/audit/logger.rb | 2 +- lib/chef/audit/runner.rb | 3 +- lib/chef/chef_class.rb | 6 +- lib/chef/chef_fs/chef_fs_data_store.rb | 21 +- lib/chef/chef_fs/command_line.rb | 1 - lib/chef/chef_fs/config.rb | 10 +- lib/chef/chef_fs/data_handler/acl_data_handler.rb | 12 +- .../chef_fs/data_handler/container_data_handler.rb | 6 +- .../chef_fs/data_handler/cookbook_data_handler.rb | 22 +- .../data_handler/data_bag_item_data_handler.rb | 4 +- lib/chef/chef_fs/data_handler/data_handler_base.rb | 9 +- .../data_handler/environment_data_handler.rb | 16 +- lib/chef/chef_fs/data_handler/node_data_handler.rb | 20 +- .../data_handler/organization_data_handler.rb | 12 +- .../data_handler/policy_group_data_handler.rb | 2 - lib/chef/chef_fs/data_handler/role_data_handler.rb | 18 +- lib/chef/chef_fs/data_handler/user_data_handler.rb | 20 +- lib/chef/chef_fs/file_pattern.rb | 18 +- lib/chef/chef_fs/file_system.rb | 6 +- .../chef_server/cookbook_artifacts_dir.rb | 1 - .../file_system/chef_server/cookbook_dir.rb | 6 +- .../file_system/chef_server/cookbooks_dir.rb | 1 - .../chef_server/organization_invites_entry.rb | 2 +- .../file_system/chef_server/policies_dir.rb | 1 - .../chef_server/policy_revision_entry.rb | 3 +- .../file_system/chef_server/rest_list_dir.rb | 1 - .../file_system/chef_server/rest_list_entry.rb | 5 +- .../chef_server/versioned_cookbooks_dir.rb | 1 - lib/chef/chef_fs/file_system/memory/memory_file.rb | 1 + .../chef_repository_file_system_cookbooks_dir.rb | 2 +- .../chef_repository_file_system_root_dir.rb | 3 +- ...epository_file_system_versioned_cookbook_dir.rb | 2 +- .../file_system/repository/file_system_entry.rb | 8 +- lib/chef/chef_fs/knife.rb | 2 +- lib/chef/chef_fs/parallelizer.rb | 2 +- .../chef_fs/parallelizer/flatten_enumerable.rb | 2 +- .../chef_fs/parallelizer/parallel_enumerable.rb | 2 +- lib/chef/chef_fs/path_utils.rb | 7 +- lib/chef/client.rb | 14 +- lib/chef/config.rb | 2 - lib/chef/config_fetcher.rb | 1 - lib/chef/constants.rb | 1 + lib/chef/cookbook/chefignore.rb | 4 +- lib/chef/cookbook/cookbook_collection.rb | 5 +- lib/chef/cookbook/cookbook_version_loader.rb | 3 +- lib/chef/cookbook/file_system_file_vendor.rb | 2 - lib/chef/cookbook/file_vendor.rb | 3 - lib/chef/cookbook/metadata.rb | 104 ++- lib/chef/cookbook/remote_file_vendor.rb | 4 +- lib/chef/cookbook/synchronizer.rb | 8 +- lib/chef/cookbook/syntax_check.rb | 12 +- lib/chef/cookbook_loader.rb | 8 +- lib/chef/cookbook_manifest.rb | 35 +- lib/chef/cookbook_site_streaming_uploader.rb | 18 +- lib/chef/cookbook_uploader.rb | 11 +- lib/chef/cookbook_version.rb | 24 +- lib/chef/daemon.rb | 4 +- lib/chef/data_bag.rb | 10 +- lib/chef/data_bag_item.rb | 16 +- lib/chef/deprecation/provider/cookbook_file.rb | 4 - lib/chef/deprecation/provider/file.rb | 16 +- lib/chef/deprecation/provider/remote_directory.rb | 4 +- lib/chef/deprecation/provider/remote_file.rb | 5 +- lib/chef/deprecation/provider/template.rb | 3 - lib/chef/deprecation/warnings.rb | 2 - lib/chef/digester.rb | 1 - lib/chef/dsl/audit.rb | 10 +- lib/chef/dsl/chef_provisioning.rb | 2 +- lib/chef/dsl/cheffish.rb | 2 +- lib/chef/dsl/data_query.rb | 6 +- lib/chef/dsl/declare_resource.rb | 7 +- lib/chef/dsl/definitions.rb | 3 +- lib/chef/dsl/include_attribute.rb | 4 - lib/chef/dsl/include_recipe.rb | 2 - lib/chef/dsl/platform_introspection.rb | 17 +- lib/chef/dsl/powershell.rb | 2 +- lib/chef/dsl/reboot_pending.rb | 14 +- lib/chef/dsl/recipe.rb | 2 - lib/chef/dsl/registry_helper.rb | 6 +- lib/chef/dsl/resources.rb | 5 +- lib/chef/encrypted_data_bag_item.rb | 3 +- lib/chef/encrypted_data_bag_item/assertions.rb | 6 +- .../encrypted_data_bag_item/check_encrypted.rb | 2 - lib/chef/encrypted_data_bag_item/decryptor.rb | 7 - .../encrypted_data_bag_item_assertions.rb | 4 - lib/chef/encrypted_data_bag_item/encryptor.rb | 11 +- lib/chef/environment.rb | 26 +- lib/chef/event_dispatch/base.rb | 8 +- lib/chef/event_dispatch/dispatcher.rb | 4 +- lib/chef/event_dispatch/dsl.rb | 1 + lib/chef/event_loggers/windows_eventlog.rb | 1 - lib/chef/exceptions.rb | 14 +- lib/chef/file_access_control.rb | 3 - lib/chef/file_cache.rb | 7 +- lib/chef/file_content_management/content_base.rb | 1 - lib/chef/file_content_management/deploy.rb | 1 - lib/chef/file_content_management/deploy/mv_unix.rb | 1 - .../file_content_management/deploy/mv_windows.rb | 3 - lib/chef/file_content_management/tempfile.rb | 4 +- lib/chef/formatters/base.rb | 8 +- lib/chef/formatters/doc.rb | 9 +- lib/chef/formatters/error_descriptor.rb | 4 +- lib/chef/formatters/error_inspectors.rb | 1 - .../error_inspectors/api_error_formatting.rb | 26 +- .../error_inspectors/compile_error_inspector.rb | 20 +- .../cookbook_resolve_error_inspector.rb | 9 +- .../cookbook_sync_error_inspector.rb | 5 +- .../error_inspectors/node_load_error_inspector.rb | 19 +- .../registration_error_inspector.rb | 34 +- .../error_inspectors/resource_failure_inspector.rb | 14 +- .../run_list_expansion_error_inspector.rb | 20 +- lib/chef/formatters/error_mapper.rb | 1 - lib/chef/formatters/indentable_output_stream.rb | 1 - lib/chef/formatters/minimal.rb | 11 +- .../guard_interpreter/default_guard_interpreter.rb | 1 - .../resource_guard_interpreter.rb | 9 +- lib/chef/handler.rb | 2 - lib/chef/handler/error_report.rb | 2 - lib/chef/handler/json_file.rb | 5 +- lib/chef/http.rb | 33 +- lib/chef/http/auth_credentials.rb | 9 +- lib/chef/http/authenticator.rb | 9 +- lib/chef/http/basic_client.rb | 18 +- lib/chef/http/cookie_manager.rb | 7 +- lib/chef/http/decompressor.rb | 8 +- lib/chef/http/http_request.rb | 9 +- lib/chef/http/json_input.rb | 9 +- lib/chef/http/json_output.rb | 7 +- lib/chef/http/json_to_model_output.rb | 3 +- lib/chef/http/remote_request_id.rb | 8 +- lib/chef/http/simple.rb | 3 - lib/chef/http/simple_json.rb | 3 - lib/chef/http/socketless_chef_zero_client.rb | 11 +- lib/chef/http/ssl_policies.rb | 5 - lib/chef/http/validate_content_length.rb | 6 +- lib/chef/json_compat.rb | 4 +- lib/chef/key.rb | 37 +- lib/chef/knife.rb | 15 +- lib/chef/knife/bootstrap.rb | 13 +- lib/chef/knife/bootstrap/chef_vault_handler.rb | 4 +- lib/chef/knife/bootstrap/client_builder.rb | 1 - lib/chef/knife/client_bulk_delete.rb | 1 - lib/chef/knife/client_create.rb | 1 - lib/chef/knife/client_delete.rb | 2 - lib/chef/knife/client_edit.rb | 1 - lib/chef/knife/client_key_create.rb | 2 +- lib/chef/knife/client_key_delete.rb | 2 +- lib/chef/knife/client_key_edit.rb | 3 +- lib/chef/knife/client_key_list.rb | 2 +- lib/chef/knife/client_key_show.rb | 2 +- lib/chef/knife/client_list.rb | 1 - lib/chef/knife/client_reregister.rb | 1 - lib/chef/knife/client_show.rb | 2 - lib/chef/knife/configure.rb | 4 +- lib/chef/knife/configure_client.rb | 1 - lib/chef/knife/cookbook_bulk_delete.rb | 4 +- lib/chef/knife/cookbook_create.rb | 14 +- lib/chef/knife/cookbook_delete.rb | 4 +- lib/chef/knife/cookbook_download.rb | 3 - lib/chef/knife/cookbook_list.rb | 1 - lib/chef/knife/cookbook_metadata.rb | 2 - lib/chef/knife/cookbook_metadata_from_file.rb | 2 - lib/chef/knife/cookbook_show.rb | 5 - lib/chef/knife/cookbook_site_download.rb | 2 +- lib/chef/knife/cookbook_site_install.rb | 3 +- lib/chef/knife/cookbook_site_list.rb | 9 +- lib/chef/knife/cookbook_site_search.rb | 8 +- lib/chef/knife/cookbook_site_share.rb | 11 +- lib/chef/knife/cookbook_site_show.rb | 8 +- lib/chef/knife/cookbook_site_unshare.rb | 2 - lib/chef/knife/cookbook_site_vendor.rb | 2 - lib/chef/knife/cookbook_test.rb | 3 - lib/chef/knife/cookbook_upload.rb | 10 +- lib/chef/knife/core/bootstrap_context.rb | 2 - lib/chef/knife/core/cookbook_scm_repo.rb | 7 +- lib/chef/knife/core/custom_manifest_loader.rb | 1 - lib/chef/knife/core/gem_glob_loader.rb | 6 +- lib/chef/knife/core/generic_presenter.rb | 18 +- lib/chef/knife/core/hashed_command_loader.rb | 2 +- lib/chef/knife/core/node_editor.rb | 1 - lib/chef/knife/core/node_presenter.rb | 10 +- lib/chef/knife/core/object_loader.rb | 2 - lib/chef/knife/core/status_presenter.rb | 7 +- lib/chef/knife/core/subcommand_loader.rb | 5 +- lib/chef/knife/core/text_formatter.rb | 5 +- lib/chef/knife/core/ui.rb | 12 +- lib/chef/knife/data_bag_delete.rb | 3 - lib/chef/knife/data_bag_edit.rb | 3 - lib/chef/knife/data_bag_from_file.rb | 1 + lib/chef/knife/data_bag_list.rb | 5 - lib/chef/knife/data_bag_secret_options.rb | 1 - lib/chef/knife/data_bag_show.rb | 1 - lib/chef/knife/delete.rb | 1 - lib/chef/knife/deps.rb | 6 +- lib/chef/knife/diff.rb | 1 - lib/chef/knife/download.rb | 1 - lib/chef/knife/edit.rb | 1 - lib/chef/knife/environment_compare.rb | 34 +- lib/chef/knife/environment_create.rb | 1 - lib/chef/knife/environment_delete.rb | 1 - lib/chef/knife/environment_edit.rb | 1 - lib/chef/knife/environment_from_file.rb | 2 - lib/chef/knife/environment_list.rb | 1 - lib/chef/knife/environment_show.rb | 1 - lib/chef/knife/exec.rb | 2 - lib/chef/knife/help.rb | 5 +- lib/chef/knife/index_rebuild.rb | 3 - lib/chef/knife/key_create.rb | 3 +- lib/chef/knife/key_delete.rb | 1 - lib/chef/knife/key_edit.rb | 3 +- lib/chef/knife/key_list.rb | 4 +- lib/chef/knife/key_show.rb | 1 - lib/chef/knife/node_bulk_delete.rb | 10 +- lib/chef/knife/node_create.rb | 4 - lib/chef/knife/node_delete.rb | 3 - lib/chef/knife/node_edit.rb | 5 - lib/chef/knife/node_environment_set.rb | 4 +- lib/chef/knife/node_from_file.rb | 8 +- lib/chef/knife/node_list.rb | 4 - lib/chef/knife/node_run_list_add.rb | 4 +- lib/chef/knife/node_run_list_remove.rb | 2 - lib/chef/knife/node_run_list_set.rb | 2 - lib/chef/knife/node_show.rb | 2 - lib/chef/knife/osc_user_create.rb | 1 - lib/chef/knife/osc_user_delete.rb | 2 - lib/chef/knife/osc_user_edit.rb | 1 - lib/chef/knife/osc_user_list.rb | 1 - lib/chef/knife/osc_user_reregister.rb | 1 - lib/chef/knife/osc_user_show.rb | 2 - lib/chef/knife/raw.rb | 3 +- lib/chef/knife/recipe_list.rb | 2 - lib/chef/knife/rehash.rb | 4 +- lib/chef/knife/role_bulk_delete.rb | 6 - lib/chef/knife/role_create.rb | 3 - lib/chef/knife/role_delete.rb | 3 - lib/chef/knife/role_edit.rb | 4 - lib/chef/knife/role_env_run_list_add.rb | 6 +- lib/chef/knife/role_env_run_list_clear.rb | 2 - lib/chef/knife/role_env_run_list_remove.rb | 18 +- lib/chef/knife/role_env_run_list_replace.rb | 4 +- lib/chef/knife/role_env_run_list_set.rb | 2 - lib/chef/knife/role_from_file.rb | 7 - lib/chef/knife/role_list.rb | 2 - lib/chef/knife/role_run_list_add.rb | 6 +- lib/chef/knife/role_run_list_clear.rb | 2 - lib/chef/knife/role_run_list_remove.rb | 18 +- lib/chef/knife/role_run_list_replace.rb | 4 +- lib/chef/knife/role_run_list_set.rb | 2 - lib/chef/knife/role_show.rb | 5 - lib/chef/knife/search.rb | 6 +- lib/chef/knife/serve.rb | 1 - lib/chef/knife/ssh.rb | 16 +- lib/chef/knife/ssl_check.rb | 4 +- lib/chef/knife/ssl_fetch.rb | 8 +- lib/chef/knife/status.rb | 11 +- lib/chef/knife/tag_create.rb | 1 - lib/chef/knife/tag_delete.rb | 1 - lib/chef/knife/tag_list.rb | 1 - lib/chef/knife/upload.rb | 1 - lib/chef/knife/user_create.rb | 5 +- lib/chef/knife/user_delete.rb | 4 +- lib/chef/knife/user_edit.rb | 4 +- lib/chef/knife/user_key_create.rb | 2 +- lib/chef/knife/user_key_delete.rb | 2 +- lib/chef/knife/user_key_edit.rb | 3 +- lib/chef/knife/user_key_list.rb | 2 +- lib/chef/knife/user_key_show.rb | 2 +- lib/chef/knife/user_list.rb | 2 - lib/chef/knife/user_reregister.rb | 4 +- lib/chef/knife/user_show.rb | 4 +- lib/chef/knife/xargs.rb | 4 +- lib/chef/local_mode.rb | 3 +- lib/chef/log.rb | 3 +- lib/chef/log/syslog.rb | 3 +- lib/chef/log/winevt.rb | 3 +- lib/chef/mash.rb | 8 +- lib/chef/mixin/api_version_request_handling.rb | 1 - lib/chef/mixin/checksum.rb | 2 - lib/chef/mixin/command.rb | 10 +- lib/chef/mixin/command/unix.rb | 9 +- lib/chef/mixin/command/windows.rb | 6 +- lib/chef/mixin/convert_to_class_name.rb | 9 +- lib/chef/mixin/create_path.rb | 2 - lib/chef/mixin/deep_merge.rb | 2 - lib/chef/mixin/deprecation.rb | 48 +- lib/chef/mixin/descendants_tracker.rb | 3 +- .../mixin/enforce_ownership_and_permissions.rb | 2 - lib/chef/mixin/file_class.rb | 1 - lib/chef/mixin/from_file.rb | 2 - lib/chef/mixin/get_source_from_package.rb | 1 - lib/chef/mixin/homebrew_user.rb | 1 - lib/chef/mixin/language.rb | 3 - lib/chef/mixin/language_include_attribute.rb | 3 - lib/chef/mixin/language_include_recipe.rb | 3 - lib/chef/mixin/params_validate.rb | 7 +- lib/chef/mixin/path_sanity.rb | 4 +- lib/chef/mixin/powershell_type_coercions.rb | 19 +- lib/chef/mixin/properties.rb | 10 +- lib/chef/mixin/provides.rb | 2 +- lib/chef/mixin/proxified_socket.rb | 2 - lib/chef/mixin/securable.rb | 34 +- lib/chef/mixin/shell_out.rb | 1 - lib/chef/mixin/template.rb | 11 +- lib/chef/mixin/unformatter.rb | 2 - lib/chef/mixin/uris.rb | 2 - lib/chef/mixin/why_run.rb | 7 +- lib/chef/mixin/wide_string.rb | 2 - lib/chef/mixin/windows_architecture_helper.rb | 3 - lib/chef/mixin/windows_env_helper.rb | 1 - lib/chef/mixin/xml_escape.rb | 12 +- lib/chef/mixins.rb | 1 - lib/chef/monkey_patches/net-ssh-multi.rb | 7 +- lib/chef/monkey_patches/net_http.rb | 4 +- lib/chef/monkey_patches/webrick-utils.rb | 4 +- lib/chef/monkey_patches/win32/registry.rb | 5 +- lib/chef/monologger.rb | 6 - lib/chef/node.rb | 34 +- lib/chef/node/attribute.rb | 562 ++++++++------- lib/chef/node/attribute_collections.rb | 12 +- lib/chef/node/immutable_collections.rb | 7 +- lib/chef/node_map.rb | 15 +- lib/chef/null_logger.rb | 5 +- lib/chef/org.rb | 19 +- lib/chef/platform.rb | 2 - lib/chef/platform/provider_mapping.rb | 44 +- lib/chef/platform/query_helpers.rb | 3 - lib/chef/platform/rebooter.rb | 3 +- lib/chef/platform/service_helpers.rb | 2 +- lib/chef/policy_builder.rb | 2 - lib/chef/policy_builder/dynamic.rb | 9 +- lib/chef/policy_builder/expand_node_object.rb | 7 +- lib/chef/policy_builder/policyfile.rb | 8 +- lib/chef/property.rb | 21 +- lib/chef/provider.rb | 5 +- lib/chef/provider/apt_update.rb | 2 +- lib/chef/provider/batch.rb | 2 - lib/chef/provider/breakpoint.rb | 2 - lib/chef/provider/cookbook_file.rb | 2 - lib/chef/provider/cookbook_file/content.rb | 1 - lib/chef/provider/cron.rb | 6 +- lib/chef/provider/cron/aix.rb | 1 - lib/chef/provider/cron/unix.rb | 1 - lib/chef/provider/deploy.rb | 12 +- lib/chef/provider/deploy/revision.rb | 5 +- lib/chef/provider/directory.rb | 2 - lib/chef/provider/dsc_resource.rb | 6 +- lib/chef/provider/dsc_script.rb | 7 +- lib/chef/provider/env.rb | 18 +- lib/chef/provider/env/windows.rb | 1 - lib/chef/provider/erl_call.rb | 1 - lib/chef/provider/execute.rb | 6 +- lib/chef/provider/file.rb | 6 +- lib/chef/provider/git.rb | 30 +- lib/chef/provider/group.rb | 3 +- lib/chef/provider/group/aix.rb | 3 +- lib/chef/provider/group/dscl.rb | 11 +- lib/chef/provider/group/groupadd.rb | 4 +- lib/chef/provider/group/groupmod.rb | 3 +- lib/chef/provider/group/pw.rb | 1 - lib/chef/provider/group/suse.rb | 1 - lib/chef/provider/group/usermod.rb | 2 - lib/chef/provider/group/windows.rb | 3 +- lib/chef/provider/http_request.rb | 15 +- lib/chef/provider/ifconfig.rb | 3 +- lib/chef/provider/ifconfig/aix.rb | 4 +- lib/chef/provider/ifconfig/debian.rb | 3 +- lib/chef/provider/ifconfig/redhat.rb | 1 - lib/chef/provider/link.rb | 5 +- lib/chef/provider/log.rb | 8 - lib/chef/provider/lwrp_base.rb | 2 - lib/chef/provider/mdadm.rb | 4 +- lib/chef/provider/mount/aix.rb | 7 +- lib/chef/provider/mount/mount.rb | 10 +- lib/chef/provider/mount/solaris.rb | 2 +- lib/chef/provider/mount/windows.rb | 2 - lib/chef/provider/osx_profile.rb | 14 +- lib/chef/provider/package.rb | 7 +- lib/chef/provider/package/aix.rb | 8 +- lib/chef/provider/package/apt.rb | 2 - lib/chef/provider/package/chocolatey.rb | 12 +- lib/chef/provider/package/dpkg.rb | 9 +- lib/chef/provider/package/easy_install.rb | 18 +- lib/chef/provider/package/freebsd/base.rb | 6 +- lib/chef/provider/package/freebsd/pkg.rb | 5 +- lib/chef/provider/package/freebsd/pkgng.rb | 4 +- lib/chef/provider/package/freebsd/port.rb | 4 +- lib/chef/provider/package/homebrew.rb | 2 - lib/chef/provider/package/ips.rb | 1 - lib/chef/provider/package/macports.rb | 2 +- lib/chef/provider/package/openbsd.rb | 8 +- lib/chef/provider/package/pacman.rb | 7 +- lib/chef/provider/package/paludis.rb | 4 +- lib/chef/provider/package/portage.rb | 11 +- lib/chef/provider/package/rpm.rb | 1 - lib/chef/provider/package/rubygems.rb | 35 +- lib/chef/provider/package/smartos.rb | 5 +- lib/chef/provider/package/solaris.rb | 2 - lib/chef/provider/package/windows.rb | 5 +- lib/chef/provider/package/windows/msi.rb | 12 +- .../package/windows/registry_uninstall_entry.rb | 1 - lib/chef/provider/package/yum.rb | 58 +- lib/chef/provider/package/zypper.rb | 4 +- lib/chef/provider/powershell_script.rb | 8 +- lib/chef/provider/registry_key.rb | 10 +- lib/chef/provider/remote_directory.rb | 5 +- lib/chef/provider/remote_file.rb | 1 - .../provider/remote_file/cache_control_data.rb | 5 +- lib/chef/provider/remote_file/content.rb | 2 - lib/chef/provider/remote_file/fetcher.rb | 2 - lib/chef/provider/remote_file/ftp.rb | 2 - lib/chef/provider/remote_file/http.rb | 5 +- lib/chef/provider/remote_file/local_file.rb | 4 +- lib/chef/provider/remote_file/network_file.rb | 2 - lib/chef/provider/resource_update.rb | 3 - lib/chef/provider/route.rb | 366 +++++----- lib/chef/provider/ruby_block.rb | 1 - lib/chef/provider/script.rb | 1 - lib/chef/provider/service.rb | 16 +- lib/chef/provider/service/aix.rb | 2 +- lib/chef/provider/service/aixinit.rb | 10 +- lib/chef/provider/service/arch.rb | 8 +- lib/chef/provider/service/debian.rb | 18 +- lib/chef/provider/service/freebsd.rb | 3 +- lib/chef/provider/service/gentoo.rb | 1 - lib/chef/provider/service/init.rb | 1 - lib/chef/provider/service/insserv.rb | 1 - lib/chef/provider/service/invokercd.rb | 1 - lib/chef/provider/service/macosx.rb | 3 +- lib/chef/provider/service/openbsd.rb | 4 +- lib/chef/provider/service/redhat.rb | 3 +- lib/chef/provider/service/simple.rb | 4 +- lib/chef/provider/service/solaris.rb | 3 +- lib/chef/provider/service/systemd.rb | 2 - lib/chef/provider/service/upstart.rb | 6 +- lib/chef/provider/service/windows.rb | 5 +- lib/chef/provider/subversion.rb | 13 +- lib/chef/provider/template.rb | 1 - lib/chef/provider/template/content.rb | 2 - lib/chef/provider/template_finder.rb | 3 +- lib/chef/provider/user.rb | 3 +- lib/chef/provider/user/aix.rb | 4 +- lib/chef/provider/user/dscl.rb | 37 +- lib/chef/provider/user/pw.rb | 2 +- lib/chef/provider/user/useradd.rb | 3 +- lib/chef/provider/user/windows.rb | 10 +- lib/chef/provider/windows_script.rb | 3 +- lib/chef/provider_resolver.rb | 1 - lib/chef/recipe.rb | 3 - lib/chef/reserved_names.rb | 1 - lib/chef/resource.rb | 62 +- lib/chef/resource/action_class.rb | 2 +- lib/chef/resource/apt_package.rb | 1 - lib/chef/resource/bash.rb | 4 +- lib/chef/resource/batch.rb | 4 +- lib/chef/resource/breakpoint.rb | 4 +- lib/chef/resource/chef_gem.rb | 6 +- lib/chef/resource/chocolatey_package.rb | 3 +- lib/chef/resource/conditional.rb | 8 +- .../resource/conditional_action_not_nothing.rb | 2 - lib/chef/resource/cookbook_file.rb | 7 +- lib/chef/resource/cron.rb | 35 +- lib/chef/resource/csh.rb | 4 +- lib/chef/resource/deploy.rb | 85 ++- lib/chef/resource/deploy_revision.rb | 2 - lib/chef/resource/directory.rb | 8 +- lib/chef/resource/dsc_resource.rb | 11 +- lib/chef/resource/dsc_script.rb | 22 +- lib/chef/resource/easy_install_package.rb | 1 - lib/chef/resource/env.rb | 9 +- lib/chef/resource/erl_call.rb | 14 +- lib/chef/resource/execute.rb | 26 +- lib/chef/resource/file.rb | 2 +- lib/chef/resource/file/verification.rb | 7 +- lib/chef/resource/gem_package.rb | 1 - lib/chef/resource/git.rb | 5 +- lib/chef/resource/group.rb | 18 +- lib/chef/resource/homebrew_package.rb | 1 - lib/chef/resource/http_request.rb | 10 +- lib/chef/resource/ifconfig.rb | 28 +- lib/chef/resource/ksh.rb | 4 +- lib/chef/resource/link.rb | 13 +- lib/chef/resource/log.rb | 8 +- lib/chef/resource/lwrp_base.rb | 3 - lib/chef/resource/macosx_service.rb | 8 +- lib/chef/resource/mdadm.rb | 19 +- lib/chef/resource/mount.rb | 32 +- lib/chef/resource/ohai.rb | 7 +- lib/chef/resource/osx_profile.rb | 11 +- lib/chef/resource/package.rb | 1 - lib/chef/resource/perl.rb | 3 +- lib/chef/resource/portage_package.rb | 3 +- lib/chef/resource/powershell_script.rb | 6 +- lib/chef/resource/python.rb | 3 +- lib/chef/resource/reboot.rb | 6 +- lib/chef/resource/registry_key.rb | 13 +- lib/chef/resource/remote_directory.rb | 20 +- lib/chef/resource/remote_file.rb | 19 +- lib/chef/resource/resource_notification.rb | 2 - lib/chef/resource/route.rb | 24 +- lib/chef/resource/rpm_package.rb | 1 - lib/chef/resource/ruby.rb | 2 +- lib/chef/resource/ruby_block.rb | 4 +- lib/chef/resource/scm.rb | 37 +- lib/chef/resource/script.rb | 11 +- lib/chef/resource/service.rb | 33 +- lib/chef/resource/subversion.rb | 4 +- lib/chef/resource/template.rb | 17 +- lib/chef/resource/user.rb | 29 +- lib/chef/resource/windows_package.rb | 2 +- lib/chef/resource/windows_script.rb | 2 +- lib/chef/resource/windows_service.rb | 9 +- lib/chef/resource/yum_package.rb | 1 - lib/chef/resource_builder.rb | 1 - lib/chef/resource_collection.rb | 7 +- .../resource_collection_serialization.rb | 6 +- lib/chef/resource_collection/resource_list.rb | 1 - lib/chef/resource_collection/resource_set.rb | 5 +- lib/chef/resource_collection/stepable_iterator.rb | 8 +- lib/chef/resource_definition.rb | 5 +- lib/chef/resource_definition_list.rb | 2 +- lib/chef/resource_reporter.rb | 14 +- lib/chef/resource_resolver.rb | 1 - lib/chef/rest.rb | 15 +- lib/chef/role.rb | 25 +- lib/chef/run_context.rb | 9 +- lib/chef/run_context/cookbook_compiler.rb | 10 +- lib/chef/run_list.rb | 11 +- lib/chef/run_list/run_list_expansion.rb | 33 +- lib/chef/run_list/run_list_item.rb | 4 +- lib/chef/run_list/versioned_recipe_list.rb | 5 +- lib/chef/run_lock.rb | 5 +- lib/chef/run_status.rb | 4 +- lib/chef/runner.rb | 8 +- lib/chef/scan_access_control.rb | 1 - lib/chef/search/query.rb | 12 +- lib/chef/server_api.rb | 3 +- lib/chef/shell.rb | 11 +- lib/chef/shell/ext.rb | 61 +- lib/chef/shell/model_wrapper.rb | 11 +- lib/chef/shell/shell_session.rb | 18 +- lib/chef/shell_out.rb | 3 +- lib/chef/tasks/chef_repo.rake | 1 - lib/chef/user.rb | 27 +- lib/chef/user_v1.rb | 38 +- lib/chef/util/backup.rb | 4 +- lib/chef/util/diff.rb | 1 - lib/chef/util/dsc/configuration_generator.rb | 8 +- lib/chef/util/dsc/lcm_output_parser.rb | 7 +- lib/chef/util/dsc/local_configuration_manager.rb | 4 +- lib/chef/util/dsc/resource_info.rb | 30 +- lib/chef/util/dsc/resource_store.rb | 140 ++-- lib/chef/util/editor.rb | 1 - lib/chef/util/file_edit.rb | 1 - lib/chef/util/powershell/cmdlet.rb | 228 +++--- lib/chef/util/powershell/cmdlet_result.rb | 66 +- lib/chef/util/selinux.rb | 4 +- lib/chef/util/windows/net_group.rb | 2 - lib/chef/util/windows/net_use.rb | 4 +- lib/chef/util/windows/net_user.rb | 8 +- lib/chef/version/platform.rb | 6 +- lib/chef/version_class.rb | 5 +- lib/chef/version_constraint.rb | 7 +- lib/chef/version_constraint/platform.rb | 1 - lib/chef/whitelist.rb | 4 +- lib/chef/win32/api.rb | 5 +- lib/chef/win32/api/crypto.rb | 8 +- lib/chef/win32/api/error.rb | 13 +- lib/chef/win32/api/file.rb | 20 +- lib/chef/win32/api/installer.rb | 19 +- lib/chef/win32/api/memory.rb | 1 - lib/chef/win32/api/net.rb | 2 - lib/chef/win32/api/process.rb | 1 - lib/chef/win32/api/psapi.rb | 1 - lib/chef/win32/api/registry.rb | 3 +- lib/chef/win32/api/security.rb | 28 +- lib/chef/win32/api/unicode.rb | 1 - lib/chef/win32/crypto.rb | 1 - lib/chef/win32/file.rb | 11 +- lib/chef/win32/file/info.rb | 4 - lib/chef/win32/file/version_info.rb | 4 +- lib/chef/win32/handle.rb | 1 - lib/chef/win32/memory.rb | 1 - lib/chef/win32/net.rb | 10 +- lib/chef/win32/process.rb | 1 - lib/chef/win32/registry.rb | 17 +- lib/chef/win32/security.rb | 11 +- lib/chef/win32/security/ace.rb | 1 - lib/chef/win32/security/acl.rb | 7 +- lib/chef/win32/security/securable_object.rb | 1 - lib/chef/win32/security/security_descriptor.rb | 1 - lib/chef/win32/security/sid.rb | 38 + lib/chef/win32/security/token.rb | 1 - lib/chef/win32/system.rb | 1 - lib/chef/win32/unicode.rb | 4 +- lib/chef/win32/version.rb | 39 +- omnibus/config/projects/chef.rb | 6 +- spec/functional/audit/rspec_formatter_spec.rb | 1 - spec/functional/audit/runner_spec.rb | 8 +- spec/functional/dsl/reboot_pending_spec.rb | 4 +- spec/functional/dsl/registry_helper_spec.rb | 9 +- .../event_loggers/windows_eventlog_spec.rb | 7 +- .../deploy_strategies_spec.rb | 15 +- spec/functional/knife/cookbook_delete_spec.rb | 13 +- spec/functional/knife/exec_spec.rb | 3 +- spec/functional/knife/smoke_test.rb | 3 +- spec/functional/knife/ssh_spec.rb | 4 +- spec/functional/mixin/shell_out_spec.rb | 4 +- spec/functional/notifications_spec.rb | 9 +- .../remote_file/cache_control_data_spec.rb | 17 +- .../provider/whyrun_safe_ruby_block_spec.rb | 2 +- spec/functional/rebooter_spec.rb | 3 - spec/functional/resource/aix_service_spec.rb | 3 - spec/functional/resource/aixinit_service_spec.rb | 25 +- spec/functional/resource/base.rb | 2 - spec/functional/resource/batch_spec.rb | 1 - spec/functional/resource/bff_spec.rb | 2 - .../functional/resource/chocolatey_package_spec.rb | 12 +- spec/functional/resource/cookbook_file_spec.rb | 1 - spec/functional/resource/cron_spec.rb | 4 +- spec/functional/resource/deploy_revision_spec.rb | 33 +- spec/functional/resource/directory_spec.rb | 1 - spec/functional/resource/dpkg_package_spec.rb | 6 +- spec/functional/resource/dsc_resource_spec.rb | 3 +- spec/functional/resource/dsc_script_spec.rb | 58 +- spec/functional/resource/env_spec.rb | 7 +- spec/functional/resource/execute_spec.rb | 6 +- spec/functional/resource/file_spec.rb | 4 +- spec/functional/resource/git_spec.rb | 5 +- spec/functional/resource/group_spec.rb | 20 +- spec/functional/resource/link_spec.rb | 10 +- spec/functional/resource/ohai_spec.rb | 3 +- spec/functional/resource/package_spec.rb | 24 +- spec/functional/resource/powershell_script_spec.rb | 78 +- spec/functional/resource/reboot_spec.rb | 1 - spec/functional/resource/registry_spec.rb | 132 ++-- spec/functional/resource/remote_directory_spec.rb | 9 +- spec/functional/resource/remote_file_spec.rb | 5 +- spec/functional/resource/template_spec.rb | 13 +- spec/functional/resource/user/dscl_spec.rb | 1 - spec/functional/resource/user/useradd_spec.rb | 36 +- spec/functional/resource/windows_package_spec.rb | 8 +- spec/functional/resource/windows_service_spec.rb | 21 +- spec/functional/run_lock_spec.rb | 12 +- spec/functional/shell_spec.rb | 5 +- spec/functional/tiny_server_spec.rb | 13 +- spec/functional/util/powershell/cmdlet_spec.rb | 30 +- spec/functional/version_spec.rb | 1 - spec/functional/win32/crypto_spec.rb | 2 +- spec/functional/win32/registry_spec.rb | 182 +++-- spec/functional/win32/security_spec.rb | 6 +- spec/functional/win32/service_manager_spec.rb | 9 +- spec/functional/win32/versions_spec.rb | 3 +- spec/integration/client/client_spec.rb | 11 +- spec/integration/client/ipv6_spec.rb | 15 +- spec/integration/knife/chef_fs_data_store_spec.rb | 13 +- spec/integration/knife/cookbook_api_ipv6_spec.rb | 7 +- spec/integration/knife/delete_spec.rb | 2 +- spec/integration/knife/diff_spec.rb | 5 +- spec/integration/knife/download_spec.rb | 10 +- spec/integration/knife/raw_spec.rb | 4 +- spec/integration/knife/redirection_spec.rb | 2 +- spec/integration/knife/show_spec.rb | 2 +- spec/integration/knife/upload_spec.rb | 36 +- .../recipes/lwrp_inline_resources_spec.rb | 6 +- spec/integration/recipes/lwrp_spec.rb | 2 - spec/integration/recipes/provider_choice.rb | 1 + spec/integration/recipes/recipe_dsl_spec.rb | 87 +-- spec/integration/recipes/resource_action_spec.rb | 793 +++++++++++---------- .../recipes/resource_converge_if_changed_spec.rb | 4 +- spec/integration/recipes/resource_load_spec.rb | 21 +- spec/integration/solo/solo_spec.rb | 11 +- spec/scripts/ssl-serve.rb | 13 +- spec/spec_helper.rb | 13 +- spec/stress/win32/file_spec.rb | 1 - spec/stress/win32/security_spec.rb | 2 - spec/support/chef_helpers.rb | 1 - spec/support/lib/chef/provider/snakeoil.rb | 1 - spec/support/lib/chef/resource/cat.rb | 5 +- .../lib/chef/resource/one_two_three_four.rb | 3 +- .../support/lib/chef/resource/openldap_includer.rb | 1 - spec/support/lib/chef/resource/zen_follower.rb | 3 +- spec/support/lib/chef/resource/zen_master.rb | 3 +- spec/support/lib/library_load_order.rb | 2 - spec/support/matchers/leak.rb | 5 +- spec/support/mock/constant.rb | 2 +- spec/support/mock/platform.rb | 8 +- spec/support/platform_helpers.rb | 9 +- spec/support/platforms/prof/gc.rb | 3 - spec/support/platforms/prof/win32.rb | 3 - spec/support/shared/context/client.rb | 8 +- spec/support/shared/examples/client.rb | 4 +- spec/support/shared/functional/diff_disabled.rb | 2 +- .../shared/functional/directory_resource.rb | 4 +- spec/support/shared/functional/file_resource.rb | 50 +- spec/support/shared/functional/http.rb | 5 +- .../shared/functional/securable_resource.rb | 9 +- .../securable_resource_with_reporting.rb | 30 +- spec/support/shared/functional/win32_service.rb | 2 - spec/support/shared/functional/windows_script.rb | 6 +- .../shared/integration/integration_helper.rb | 6 +- spec/support/shared/integration/knife_support.rb | 1 - spec/support/shared/matchers/exit_with_code.rb | 3 +- spec/support/shared/shared_examples.rb | 2 - spec/support/shared/unit/api_error_inspector.rb | 11 - spec/support/shared/unit/api_versioning.rb | 7 +- spec/support/shared/unit/execute_resource.rb | 1 - spec/support/shared/unit/knife_shared.rb | 1 - spec/support/shared/unit/mock_shellout.rb | 3 + spec/support/shared/unit/platform_introspector.rb | 16 +- spec/support/shared/unit/provider/file.rb | 37 +- .../unit/provider/useradd_based_user_provider.rb | 42 +- .../unit/resource/static_provider_resolution.rb | 5 +- spec/support/shared/unit/script_resource.rb | 3 +- spec/support/shared/unit/user_and_client_shared.rb | 14 +- .../support/shared/unit/windows_script_resource.rb | 3 - spec/tiny_server.rb | 33 +- spec/unit/api_client/registration_spec.rb | 26 +- spec/unit/api_client_spec.rb | 24 +- spec/unit/api_client_v1_spec.rb | 23 +- spec/unit/application/apply_spec.rb | 4 +- spec/unit/application/client_spec.rb | 11 +- spec/unit/application/knife_spec.rb | 7 +- spec/unit/application/solo_spec.rb | 10 +- spec/unit/application_spec.rb | 6 - spec/unit/audit/audit_event_proxy_spec.rb | 16 +- spec/unit/audit/audit_reporter_spec.rb | 47 +- spec/unit/audit/control_group_data_spec.rb | 46 +- spec/unit/audit/logger_spec.rb | 2 - spec/unit/audit/runner_spec.rb | 7 +- spec/unit/chef_fs/config_spec.rb | 21 +- .../chef_fs/data_handler/group_handler_spec.rb | 4 +- spec/unit/chef_fs/diff_spec.rb | 186 ++--- spec/unit/chef_fs/file_pattern_spec.rb | 1 - spec/unit/chef_fs/file_system_spec.rb | 24 +- spec/unit/chef_fs/parallelizer.rb | 70 +- spec/unit/chef_fs/path_util_spec.rb | 2 +- spec/unit/client_spec.rb | 15 +- spec/unit/config_fetcher_spec.rb | 24 +- spec/unit/config_spec.rb | 2 - spec/unit/cookbook/cookbook_version_loader_spec.rb | 14 - spec/unit/cookbook/file_vendor_spec.rb | 16 +- spec/unit/cookbook/metadata_spec.rb | 76 +- spec/unit/cookbook/synchronizer_spec.rb | 7 +- spec/unit/cookbook/syntax_check_spec.rb | 12 +- spec/unit/cookbook_loader_spec.rb | 12 +- spec/unit/cookbook_manifest_spec.rb | 35 +- spec/unit/cookbook_site_streaming_uploader_spec.rb | 28 +- spec/unit/cookbook_spec.rb | 1 - spec/unit/cookbook_uploader_spec.rb | 21 +- .../unit/cookbook_version_file_specificity_spec.rb | 21 +- spec/unit/cookbook_version_spec.rb | 16 +- spec/unit/daemon_spec.rb | 9 - spec/unit/data_bag_item_spec.rb | 10 +- spec/unit/data_bag_spec.rb | 14 +- spec/unit/deprecation_spec.rb | 2 - spec/unit/digester_spec.rb | 4 - spec/unit/dsl/audit_spec.rb | 7 +- spec/unit/dsl/data_query_spec.rb | 11 +- spec/unit/dsl/platform_introspection_spec.rb | 19 +- spec/unit/dsl/reboot_pending_spec.rb | 19 +- spec/unit/dsl/recipe_spec.rb | 9 - spec/unit/dsl/regsitry_helper_spec.rb | 4 +- spec/unit/dsl/resources_spec.rb | 6 +- .../check_encrypted_spec.rb | 18 +- spec/unit/encrypted_data_bag_item_spec.rb | 43 +- spec/unit/environment_spec.rb | 21 +- spec/unit/event_dispatch/dispatcher_spec.rb | 3 - spec/unit/event_dispatch/dsl_spec.rb | 8 +- spec/unit/exceptions_spec.rb | 11 +- spec/unit/file_cache_spec.rb | 6 +- .../unit/file_content_management/deploy/cp_spec.rb | 6 - .../file_content_management/deploy/mv_unix_spec.rb | 9 - .../deploy/mv_windows_spec.rb | 22 +- spec/unit/formatters/doc_spec.rb | 9 +- .../error_inspectors/api_error_formatting_spec.rb | 8 +- .../compile_error_inspector_spec.rb | 16 +- .../cookbook_resolve_error_inspector_spec.rb | 12 - .../cookbook_sync_error_inspector_spec.rb | 1 - .../node_load_error_inspector_spec.rb | 1 - .../registration_error_inspector_spec.rb | 1 - .../resource_failure_inspector_spec.rb | 8 +- .../run_list_expansion_error_inspector_spec.rb | 11 +- .../resource_guard_interpreter_spec.rb | 8 +- spec/unit/guard_interpreter_spec.rb | 2 +- spec/unit/handler/json_file_spec.rb | 2 - spec/unit/handler_spec.rb | 5 +- spec/unit/http/authenticator_spec.rb | 9 +- spec/unit/http/basic_client_spec.rb | 7 - spec/unit/http/http_request_spec.rb | 6 - spec/unit/http/json_input_spec.rb | 16 +- spec/unit/http/socketless_chef_zero_client_spec.rb | 18 +- spec/unit/http/ssl_policies_spec.rb | 17 +- spec/unit/http/validate_content_length_spec.rb | 7 +- spec/unit/http_spec.rb | 25 - spec/unit/json_compat_spec.rb | 4 +- spec/unit/key_spec.rb | 48 +- .../knife/bootstrap/chef_vault_handler_spec.rb | 2 - spec/unit/knife/bootstrap/client_builder_spec.rb | 9 +- spec/unit/knife/bootstrap_spec.rb | 35 +- spec/unit/knife/client_bulk_delete_spec.rb | 6 +- spec/unit/knife/client_create_spec.rb | 3 +- spec/unit/knife/client_delete_spec.rb | 2 +- spec/unit/knife/client_reregister_spec.rb | 1 - spec/unit/knife/client_show_spec.rb | 2 +- spec/unit/knife/configure_client_spec.rb | 6 +- spec/unit/knife/configure_spec.rb | 6 +- spec/unit/knife/cookbook_bulk_delete_spec.rb | 16 +- spec/unit/knife/cookbook_create_spec.rb | 34 +- spec/unit/knife/cookbook_delete_spec.rb | 9 +- spec/unit/knife/cookbook_download_spec.rb | 46 +- spec/unit/knife/cookbook_list_spec.rb | 19 +- .../unit/knife/cookbook_metadata_from_file_spec.rb | 3 +- spec/unit/knife/cookbook_metadata_spec.rb | 22 +- spec/unit/knife/cookbook_show_spec.rb | 10 +- spec/unit/knife/cookbook_site_download_spec.rb | 33 +- spec/unit/knife/cookbook_site_install_spec.rb | 1 - spec/unit/knife/cookbook_site_share_spec.rb | 17 +- spec/unit/knife/cookbook_site_unshare_spec.rb | 4 - spec/unit/knife/cookbook_test_spec.rb | 5 +- spec/unit/knife/cookbook_upload_spec.rb | 25 +- spec/unit/knife/core/bootstrap_context_spec.rb | 45 +- spec/unit/knife/core/cookbook_scm_repo_spec.rb | 13 +- .../unit/knife/core/custom_manifest_loader_spec.rb | 10 +- spec/unit/knife/core/gem_glob_loader_spec.rb | 21 +- spec/unit/knife/core/hashed_command_loader_spec.rb | 4 +- spec/unit/knife/core/node_editor_spec.rb | 6 +- spec/unit/knife/core/object_loader_spec.rb | 2 - spec/unit/knife/core/ui_spec.rb | 34 +- spec/unit/knife/data_bag_create_spec.rb | 11 +- spec/unit/knife/data_bag_edit_spec.rb | 13 +- spec/unit/knife/data_bag_from_file_spec.rb | 12 +- spec/unit/knife/data_bag_secret_options_spec.rb | 7 - spec/unit/knife/data_bag_show_spec.rb | 14 +- spec/unit/knife/environment_compare_spec.rb | 19 +- spec/unit/knife/environment_from_file_spec.rb | 4 +- spec/unit/knife/environment_list_spec.rb | 2 +- spec/unit/knife/index_rebuild_spec.rb | 24 +- spec/unit/knife/key_create_spec.rb | 3 +- spec/unit/knife/key_delete_spec.rb | 7 +- spec/unit/knife/key_edit_spec.rb | 11 +- spec/unit/knife/key_list_spec.rb | 16 +- spec/unit/knife/key_show_spec.rb | 4 +- spec/unit/knife/node_bulk_delete_spec.rb | 10 +- spec/unit/knife/node_delete_spec.rb | 2 +- spec/unit/knife/node_edit_spec.rb | 30 +- spec/unit/knife/node_environment_set_spec.rb | 2 +- spec/unit/knife/node_from_file_spec.rb | 2 +- spec/unit/knife/node_list_spec.rb | 3 +- spec/unit/knife/node_run_list_add_spec.rb | 5 +- spec/unit/knife/node_run_list_remove_spec.rb | 2 +- spec/unit/knife/node_run_list_set_spec.rb | 3 +- spec/unit/knife/node_show_spec.rb | 1 - spec/unit/knife/raw_spec.rb | 2 +- spec/unit/knife/role_bulk_delete_spec.rb | 4 +- spec/unit/knife/role_create_spec.rb | 2 +- spec/unit/knife/role_delete_spec.rb | 2 +- spec/unit/knife/role_edit_spec.rb | 5 +- spec/unit/knife/role_env_run_list_add_spec.rb | 10 +- spec/unit/knife/role_env_run_list_clear_spec.rb | 78 +- spec/unit/knife/role_env_run_list_remove_spec.rb | 94 ++- spec/unit/knife/role_env_run_list_replace_spec.rb | 97 ++- spec/unit/knife/role_env_run_list_set_spec.rb | 13 +- spec/unit/knife/role_from_file_spec.rb | 3 +- spec/unit/knife/role_list_spec.rb | 4 +- spec/unit/knife/role_run_list_add_spec.rb | 10 +- spec/unit/knife/role_run_list_clear_spec.rb | 58 +- spec/unit/knife/role_run_list_remove_spec.rb | 74 +- spec/unit/knife/role_run_list_replace_spec.rb | 83 +-- spec/unit/knife/role_run_list_set_spec.rb | 11 +- spec/unit/knife/role_show_spec.rb | 4 +- spec/unit/knife/ssh_spec.rb | 28 +- spec/unit/knife/ssl_check_spec.rb | 17 +- spec/unit/knife/ssl_fetch_spec.rb | 20 +- spec/unit/knife/status_spec.rb | 6 +- spec/unit/knife/user_create_spec.rb | 8 +- spec/unit/knife/user_delete_spec.rb | 4 +- spec/unit/knife/user_edit_spec.rb | 6 +- spec/unit/knife/user_reregister_spec.rb | 4 +- spec/unit/knife/user_show_spec.rb | 4 +- spec/unit/knife_spec.rb | 33 +- spec/unit/log/winevt_spec.rb | 3 +- spec/unit/lwrp_spec.rb | 14 +- spec/unit/mash_spec.rb | 10 +- .../mixin/api_version_request_handling_spec.rb | 21 +- spec/unit/mixin/checksum_spec.rb | 2 - spec/unit/mixin/command_spec.rb | 19 +- spec/unit/mixin/convert_to_class_name_spec.rb | 1 - spec/unit/mixin/deep_merge_spec.rb | 203 +++--- spec/unit/mixin/deprecation_spec.rb | 1 - .../enforce_ownership_and_permissions_spec.rb | 3 - spec/unit/mixin/homebrew_user_spec.rb | 6 - spec/unit/mixin/params_validate_spec.rb | 77 +- spec/unit/mixin/path_sanity_spec.rb | 13 +- spec/unit/mixin/powershell_out_spec.rb | 4 +- spec/unit/mixin/powershell_type_coercions_spec.rb | 8 +- spec/unit/mixin/proxified_socket_spec.rb | 4 +- spec/unit/mixin/securable_spec.rb | 3 +- spec/unit/mixin/shell_out_spec.rb | 92 ++- spec/unit/mixin/template_spec.rb | 10 +- spec/unit/mixin/unformatter_spec.rb | 3 - spec/unit/mixin/uris_spec.rb | 3 +- .../unit/mixin/windows_architecture_helper_spec.rb | 23 +- spec/unit/monkey_patches/uri_spec.rb | 4 - spec/unit/node/attribute_spec.rb | 354 ++++----- spec/unit/node/immutable_collections_spec.rb | 19 +- spec/unit/node_map_spec.rb | 4 +- spec/unit/node_spec.rb | 121 ++-- spec/unit/org_spec.rb | 14 +- spec/unit/platform/query_helpers_spec.rb | 4 +- spec/unit/platform_spec.rb | 9 +- spec/unit/policy_builder/dynamic_spec.rb | 46 +- .../unit/policy_builder/expand_node_object_spec.rb | 36 +- spec/unit/policy_builder/policyfile_spec.rb | 83 +-- spec/unit/policy_builder_spec.rb | 2 - spec/unit/property/state_spec.rb | 15 +- spec/unit/property/validation_spec.rb | 22 +- spec/unit/property_spec.rb | 11 +- spec/unit/provider/breakpoint_spec.rb | 3 - spec/unit/provider/cookbook_file/content_spec.rb | 3 - spec/unit/provider/cookbook_file_spec.rb | 2 +- spec/unit/provider/cron/unix_spec.rb | 1 - spec/unit/provider/cron_spec.rb | 9 +- spec/unit/provider/deploy/revision_spec.rb | 11 +- spec/unit/provider/deploy/timestamped_spec.rb | 2 - spec/unit/provider/deploy_spec.rb | 43 +- spec/unit/provider/directory_spec.rb | 9 +- spec/unit/provider/dsc_resource_spec.rb | 15 +- spec/unit/provider/dsc_script_spec.rb | 4 +- spec/unit/provider/env/windows_spec.rb | 15 +- spec/unit/provider/env_spec.rb | 7 +- spec/unit/provider/erl_call_spec.rb | 2 - spec/unit/provider/execute_spec.rb | 5 +- spec/unit/provider/file/content_spec.rb | 7 +- spec/unit/provider/file_spec.rb | 4 +- spec/unit/provider/git_spec.rb | 83 +-- spec/unit/provider/group/dscl_spec.rb | 4 +- spec/unit/provider/group/gpasswd_spec.rb | 1 - spec/unit/provider/group/groupadd_spec.rb | 11 +- spec/unit/provider/group/groupmod_spec.rb | 20 +- spec/unit/provider/group/pw_spec.rb | 3 - spec/unit/provider/group/usermod_spec.rb | 1 - spec/unit/provider/group/windows_spec.rb | 1 - spec/unit/provider/group_spec.rb | 26 +- spec/unit/provider/http_request_spec.rb | 4 +- spec/unit/provider/ifconfig/aix_spec.rb | 8 +- spec/unit/provider/ifconfig/debian_spec.rb | 13 +- spec/unit/provider/ifconfig/redhat_spec.rb | 2 - spec/unit/provider/ifconfig_spec.rb | 6 - spec/unit/provider/log_spec.rb | 1 - spec/unit/provider/mdadm_spec.rb | 12 +- spec/unit/provider/mount/aix_spec.rb | 7 +- spec/unit/provider/mount/mount_spec.rb | 15 +- spec/unit/provider/mount/solaris_spec.rb | 7 +- spec/unit/provider/mount/windows_spec.rb | 12 +- spec/unit/provider/mount_spec.rb | 6 +- spec/unit/provider/ohai_spec.rb | 4 +- spec/unit/provider/osx_profile_spec.rb | 171 ++--- spec/unit/provider/package/aix_spec.rb | 8 +- spec/unit/provider/package/apt_spec.rb | 50 +- spec/unit/provider/package/chocolatey_spec.rb | 48 +- spec/unit/provider/package/dpkg_spec.rb | 7 +- spec/unit/provider/package/easy_install_spec.rb | 26 +- spec/unit/provider/package/freebsd/pkg_spec.rb | 11 +- spec/unit/provider/package/freebsd/pkgng_spec.rb | 9 +- spec/unit/provider/package/freebsd/port_spec.rb | 15 +- spec/unit/provider/package/homebrew_spec.rb | 3 +- spec/unit/provider/package/ips_spec.rb | 11 +- spec/unit/provider/package/macports_spec.rb | 2 +- spec/unit/provider/package/openbsd_spec.rb | 27 +- spec/unit/provider/package/pacman_spec.rb | 13 +- spec/unit/provider/package/paludis_spec.rb | 14 +- spec/unit/provider/package/portage_spec.rb | 2 - spec/unit/provider/package/rpm_spec.rb | 38 - spec/unit/provider/package/rubygems_spec.rb | 25 +- spec/unit/provider/package/smartos_spec.rb | 15 +- spec/unit/provider/package/solaris_spec.rb | 6 +- spec/unit/provider/package/windows/exe_spec.rb | 8 +- spec/unit/provider/package/windows/msi_spec.rb | 6 +- spec/unit/provider/package/windows_spec.rb | 11 +- spec/unit/provider/package/yum_spec.rb | 74 +- spec/unit/provider/package/zypper_spec.rb | 23 +- spec/unit/provider/package_spec.rb | 6 - spec/unit/provider/powershell_script_spec.rb | 5 +- spec/unit/provider/registry_key_spec.rb | 1 - spec/unit/provider/remote_directory_spec.rb | 17 +- .../remote_file/cache_control_data_spec.rb | 11 +- spec/unit/provider/remote_file/content_spec.rb | 8 +- spec/unit/provider/remote_file/fetcher_spec.rb | 2 - spec/unit/provider/remote_file/ftp_spec.rb | 11 +- spec/unit/provider/remote_file/http_spec.rb | 32 +- spec/unit/provider/remote_file/local_file_spec.rb | 7 - .../unit/provider/remote_file/network_file_spec.rb | 4 - spec/unit/provider/remote_file_spec.rb | 4 +- spec/unit/provider/route_spec.rb | 7 +- spec/unit/provider/ruby_block_spec.rb | 3 +- spec/unit/provider/script_spec.rb | 3 +- spec/unit/provider/service/aix_service_spec.rb | 1 - spec/unit/provider/service/aixinit_service_spec.rb | 40 +- spec/unit/provider/service/arch_service_spec.rb | 18 +- spec/unit/provider/service/debian_service_spec.rb | 61 +- spec/unit/provider/service/freebsd_service_spec.rb | 15 +- spec/unit/provider/service/gentoo_service_spec.rb | 4 - spec/unit/provider/service/init_service_spec.rb | 16 +- spec/unit/provider/service/insserv_service_spec.rb | 3 +- .../provider/service/invokercd_service_spec.rb | 14 +- spec/unit/provider/service/macosx_spec.rb | 40 +- spec/unit/provider/service/openbsd_service_spec.rb | 8 +- spec/unit/provider/service/redhat_spec.rb | 30 +- spec/unit/provider/service/simple_service_spec.rb | 6 +- .../provider/service/solaris_smf_service_spec.rb | 28 +- spec/unit/provider/service/systemd_service_spec.rb | 3 - spec/unit/provider/service/upstart_service_spec.rb | 6 +- spec/unit/provider/service/windows_spec.rb | 7 +- spec/unit/provider/service_spec.rb | 1 - spec/unit/provider/subversion_spec.rb | 36 +- spec/unit/provider/template/content_spec.rb | 4 +- spec/unit/provider/template_spec.rb | 7 +- spec/unit/provider/user/dscl_spec.rb | 10 +- spec/unit/provider/user/pw_spec.rb | 10 +- spec/unit/provider/user/solaris_spec.rb | 3 - spec/unit/provider/user/useradd_spec.rb | 1 - spec/unit/provider/user/windows_spec.rb | 9 +- spec/unit/provider/user_spec.rb | 8 +- spec/unit/provider/whyrun_safe_ruby_block_spec.rb | 4 +- spec/unit/provider_resolver_spec.rb | 1 - spec/unit/provider_spec.rb | 11 +- spec/unit/recipe_spec.rb | 23 +- spec/unit/resource/apt_package_spec.rb | 1 - spec/unit/resource/apt_update_spec.rb | 1 - spec/unit/resource/bash_spec.rb | 2 - spec/unit/resource/batch_spec.rb | 3 - spec/unit/resource/breakpoint_spec.rb | 2 - spec/unit/resource/chef_gem_spec.rb | 3 - spec/unit/resource/chocolatey_package_spec.rb | 1 - .../conditional_action_not_nothing_spec.rb | 2 - spec/unit/resource/conditional_spec.rb | 4 +- spec/unit/resource/cookbook_file_spec.rb | 29 +- spec/unit/resource/cron_spec.rb | 3 +- spec/unit/resource/csh_spec.rb | 2 - spec/unit/resource/deploy_revision_spec.rb | 4 - spec/unit/resource/deploy_spec.rb | 40 +- spec/unit/resource/directory_spec.rb | 1 - spec/unit/resource/dpkg_package_spec.rb | 2 - spec/unit/resource/dsc_resource_spec.rb | 2 +- spec/unit/resource/dsc_script_spec.rb | 6 +- spec/unit/resource/easy_install_package_spec.rb | 1 - spec/unit/resource/env_spec.rb | 4 +- spec/unit/resource/erl_call_spec.rb | 1 - spec/unit/resource/execute_spec.rb | 1 - spec/unit/resource/file/verification_spec.rb | 10 +- spec/unit/resource/file_spec.rb | 17 +- spec/unit/resource/freebsd_package_spec.rb | 3 - spec/unit/resource/gem_package_spec.rb | 2 - spec/unit/resource/git_spec.rb | 2 - spec/unit/resource/homebrew_package_spec.rb | 2 - spec/unit/resource/http_request_spec.rb | 4 +- spec/unit/resource/ifconfig_spec.rb | 2 - spec/unit/resource/ips_package_spec.rb | 1 - spec/unit/resource/ksh_spec.rb | 2 - spec/unit/resource/link_spec.rb | 3 +- spec/unit/resource/log_spec.rb | 1 - spec/unit/resource/macports_package_spec.rb | 2 - spec/unit/resource/mdadm_spec.rb | 2 - spec/unit/resource/mount_spec.rb | 5 +- spec/unit/resource/ohai_spec.rb | 3 - spec/unit/resource/openbsd_package_spec.rb | 3 - spec/unit/resource/osx_profile_spec.rb | 4 +- spec/unit/resource/package_spec.rb | 6 +- spec/unit/resource/pacman_package_spec.rb | 2 - spec/unit/resource/perl_spec.rb | 2 - spec/unit/resource/portage_package_spec.rb | 1 - spec/unit/resource/powershell_script_spec.rb | 21 +- spec/unit/resource/python_spec.rb | 2 - spec/unit/resource/registry_key_spec.rb | 6 +- spec/unit/resource/remote_directory_spec.rb | 1 - spec/unit/resource/remote_file_spec.rb | 19 +- spec/unit/resource/resource_notification_spec.rb | 32 +- spec/unit/resource/route_spec.rb | 1 - spec/unit/resource/rpm_package_spec.rb | 2 - spec/unit/resource/ruby_block_spec.rb | 1 - spec/unit/resource/ruby_spec.rb | 2 - spec/unit/resource/scm_spec.rb | 11 +- spec/unit/resource/service_spec.rb | 5 +- spec/unit/resource/smartos_package_spec.rb | 2 - spec/unit/resource/solaris_package_spec.rb | 1 - spec/unit/resource/subversion_spec.rb | 1 - spec/unit/resource/template_spec.rb | 13 +- spec/unit/resource/timestamped_deploy_spec.rb | 2 - spec/unit/resource/user_spec.rb | 3 +- spec/unit/resource/yum_package_spec.rb | 2 - .../unit/resource_collection/resource_list_spec.rb | 8 +- spec/unit/resource_collection/resource_set_spec.rb | 14 +- .../resource_collection/stepable_iterator_spec.rb | 12 +- spec/unit/resource_collection_spec.rb | 13 +- spec/unit/resource_definition_spec.rb | 1 - spec/unit/resource_reporter_spec.rb | 70 +- spec/unit/resource_resolver_spec.rb | 1 - spec/unit/resource_spec.rb | 57 +- spec/unit/rest/auth_credentials_spec.rb | 15 +- spec/unit/rest_spec.rb | 103 ++- spec/unit/role_spec.rb | 23 +- spec/unit/run_context/cookbook_compiler_spec.rb | 6 - spec/unit/run_context_spec.rb | 5 +- spec/unit/run_list/run_list_expansion_spec.rb | 19 +- spec/unit/run_list/run_list_item_spec.rb | 12 +- spec/unit/run_list/versioned_recipe_list_spec.rb | 43 +- spec/unit/run_list_spec.rb | 6 - spec/unit/run_lock_spec.rb | 10 +- spec/unit/run_status_spec.rb | 2 - spec/unit/runner_spec.rb | 14 +- spec/unit/scan_access_control_spec.rb | 11 - spec/unit/search/query_spec.rb | 7 +- spec/unit/shell/model_wrapper_spec.rb | 15 +- spec/unit/shell/shell_ext_spec.rb | 8 +- spec/unit/shell/shell_session_spec.rb | 10 +- spec/unit/shell_out_spec.rb | 1 - spec/unit/shell_spec.rb | 16 +- spec/unit/user_spec.rb | 20 +- spec/unit/user_v1_spec.rb | 17 +- spec/unit/util/backup_spec.rb | 5 - spec/unit/util/diff_spec.rb | 21 +- spec/unit/util/dsc/configuration_generator_spec.rb | 36 +- spec/unit/util/dsc/lcm_output_parser_spec.rb | 8 +- .../util/dsc/local_configuration_manager_spec.rb | 10 +- spec/unit/util/dsc/resource_store.rb | 8 +- spec/unit/util/file_edit_spec.rb | 5 +- spec/unit/util/powershell/cmdlet_spec.rb | 16 +- spec/unit/util/powershell/ps_credential_spec.rb | 2 +- spec/unit/util/selinux_spec.rb | 9 +- spec/unit/version/platform_spec.rb | 5 - spec/unit/version_class_spec.rb | 4 +- spec/unit/version_constraint/platform_spec.rb | 4 - spec/unit/version_constraint_spec.rb | 1 - spec/unit/win32/registry_spec.rb | 32 +- tasks/cbgb.rb | 6 +- tasks/external_tests.rb | 4 +- tasks/maintainers.rb | 16 +- tasks/rspec.rb | 3 +- 1170 files changed, 5913 insertions(+), 9030 deletions(-) diff --git a/acceptance/windows-service/test/integration/chef-windows-service/inspec/chef_windows_service_spec.rb b/acceptance/windows-service/test/integration/chef-windows-service/inspec/chef_windows_service_spec.rb index ec90ac083b..a791177362 100644 --- a/acceptance/windows-service/test/integration/chef-windows-service/inspec/chef_windows_service_spec.rb +++ b/acceptance/windows-service/test/integration/chef-windows-service/inspec/chef_windows_service_spec.rb @@ -15,7 +15,7 @@ end describe command("chef-service-manager -a install") do its("exit_status") { should eq 0 } - its(:stdout) { should match /Service 'chef-client' has successfully been installed./} + its(:stdout) { should match /Service 'chef-client' has successfully been installed./ } end describe service("chef-client") do @@ -26,7 +26,7 @@ end describe command("chef-service-manager -a start") do its("exit_status") { should eq 0 } - its(:stdout) { should match /Service 'chef-client' is now 'running'/} + its(:stdout) { should match /Service 'chef-client' is now 'running'/ } end describe service("chef-client") do @@ -37,7 +37,7 @@ end describe command("chef-service-manager -a stop") do its("exit_status") { should eq 0 } - its(:stdout) { should match /Service 'chef-client' is now 'stopped'/} + its(:stdout) { should match /Service 'chef-client' is now 'stopped'/ } end describe service("chef-client") do @@ -48,7 +48,7 @@ end describe command("chef-service-manager -a uninstall") do its("exit_status") { should eq 0 } - its(:stdout) { should match /Service chef-client deleted/} + its(:stdout) { should match /Service chef-client deleted/ } end describe service("chef-client") do diff --git a/bin/knife b/bin/knife index 692ac7b43c..b8983d6d5c 100755 --- a/bin/knife +++ b/bin/knife @@ -23,4 +23,3 @@ $:.unshift(File.expand_path(File.join(File.dirname(__FILE__), "..", "lib"))) require "chef/application/knife" Chef::Application::Knife.new.run - diff --git a/chef-config/Rakefile b/chef-config/Rakefile index ac088852cf..151c2754c3 100644 --- a/chef-config/Rakefile +++ b/chef-config/Rakefile @@ -11,4 +11,3 @@ desc "Run standard specs" RSpec::Core::RakeTask.new(:spec) do |t| t.pattern = FileList["spec/**/*_spec.rb"] end - diff --git a/chef-config/chef-config.gemspec b/chef-config/chef-config.gemspec index 12373ac8fb..f59741629f 100644 --- a/chef-config/chef-config.gemspec +++ b/chef-config/chef-config.gemspec @@ -25,7 +25,7 @@ Gem::Specification.new do |spec| end spec.files = %w{Rakefile LICENSE README.md} + Dir.glob("*.gemspec") + - Dir.glob("{lib,spec}/**/*", File::FNM_DOTMATCH).reject {|f| File.directory?(f) } + Dir.glob("{lib,spec}/**/*", File::FNM_DOTMATCH).reject { |f| File.directory?(f) } spec.bindir = "bin" spec.executables = [] diff --git a/chef-config/lib/chef-config.rb b/chef-config/lib/chef-config.rb index 3c52462ab6..c4bfd30346 100644 --- a/chef-config/lib/chef-config.rb +++ b/chef-config/lib/chef-config.rb @@ -16,5 +16,4 @@ # module ChefConfig - end diff --git a/chef-config/lib/chef-config/config.rb b/chef-config/lib/chef-config/config.rb index 2a9f5e87aa..dd583fb079 100644 --- a/chef-config/lib/chef-config/config.rb +++ b/chef-config/lib/chef-config/config.rb @@ -30,9 +30,7 @@ require "uri" require "openssl" module ChefConfig - class Config - extend Mixlib::Config # Evaluates the given string as config. @@ -57,7 +55,7 @@ module ChefConfig path end - def self.add_formatter(name, file_path=nil) + def self.add_formatter(name, file_path = nil) formatters << [name, file_path] end @@ -115,7 +113,7 @@ module ChefConfig end end elsif configuration[:cookbook_artifact_path] - File.expand_path("..", self.configuration[:cookbook_artifact_path]) + File.expand_path("..", self.configuration[:cookbook_artifact_path]) else cache_path end @@ -141,7 +139,7 @@ module ChefConfig if chef_repo_path.kind_of?(String) PathHelper.join(chef_repo_path, child_path) else - chef_repo_path.uniq.map { |path| PathHelper.join(path, child_path)} + chef_repo_path.uniq.map { |path| PathHelper.join(path, child_path) } end end @@ -367,7 +365,7 @@ module ChefConfig # if the chef_server_url is a path to an organization, aka # 'some_url.../organizations/*' then remove the '/organization/*' by default if self.configuration[:chef_server_url] =~ /\/organizations\/\S*$/ - self.configuration[:chef_server_url].split("/")[0..-3].join("/") + self.configuration[:chef_server_url].split("/")[0..-3].join("/") elsif self.configuration[:chef_server_url] # default to whatever chef_server_url is self.configuration[:chef_server_url] else @@ -449,7 +447,6 @@ module ChefConfig # effect if `policy_document_native_api` is set to `false`. default :deployment_group, nil - # Set these to enable SSL authentication / mutual-authentication # with the server diff --git a/chef-config/lib/chef-config/exceptions.rb b/chef-config/lib/chef-config/exceptions.rb index db10a5f364..03cd6c36ad 100644 --- a/chef-config/lib/chef-config/exceptions.rb +++ b/chef-config/lib/chef-config/exceptions.rb @@ -19,8 +19,6 @@ require "chef-config/windows" require "chef-config/logger" module ChefConfig - class ConfigurationError < ArgumentError; end class InvalidPath < StandardError; end - end diff --git a/chef-config/lib/chef-config/logger.rb b/chef-config/lib/chef-config/logger.rb index d298852c6e..02702f481d 100644 --- a/chef-config/lib/chef-config/logger.rb +++ b/chef-config/lib/chef-config/logger.rb @@ -15,13 +15,10 @@ # limitations under the License. # - module ChefConfig - # Implements enough of Logger's API that we can use it in place of a real # logger for `ChefConfig.logger` class NullLogger - def <<(_msg) end @@ -45,7 +42,6 @@ module ChefConfig def fatal(_progname = nil, &block) end - end @logger = NullLogger.new @@ -58,5 +54,3 @@ module ChefConfig @logger end end - - diff --git a/chef-config/lib/chef-config/package_task.rb b/chef-config/lib/chef-config/package_task.rb index 1eb702965f..d49b3e1dd8 100644 --- a/chef-config/lib/chef-config/package_task.rb +++ b/chef-config/lib/chef-config/package_task.rb @@ -22,7 +22,6 @@ require "rubygems/package_task" module ChefConfig class PackageTask < Rake::TaskLib - # Full path to root of top-level repository. All other files (like VERSION or # lib//version.rb are rooted at this path). attr_accessor :root_path @@ -55,7 +54,7 @@ module ChefConfig # Name of git remote used to push tags during a release. Default is origin. attr_accessor :git_remote - def initialize(root_path=nil, module_name=nil) + def initialize(root_path = nil, module_name = nil) init(root_path, module_name) yield self if block_given? define unless root_path.nil? || module_name.nil? @@ -72,7 +71,7 @@ module ChefConfig end def component_full_paths - component_paths.map { |path| File.expand_path(path, root_path)} + component_paths.map { |path| File.expand_path(path, root_path) } end def version_rb_path @@ -218,5 +217,4 @@ end end end end - end diff --git a/chef-config/lib/chef-config/path_helper.rb b/chef-config/lib/chef-config/path_helper.rb index 28c16cd608..7fc79ba4a9 100644 --- a/chef-config/lib/chef-config/path_helper.rb +++ b/chef-config/lib/chef-config/path_helper.rb @@ -36,7 +36,7 @@ module ChefConfig elsif slash == end_slash - 1 end_slash = slash else - return path[0..slash-1] + return path[0..slash - 1] end end else @@ -110,7 +110,7 @@ module ChefConfig end # Produces a comparable path. - def self.canonical_path(path, add_prefix=true) + def self.canonical_path(path, add_prefix = true) # First remove extra separators and resolve any relative paths abs_path = File.absolute_path(path) @@ -146,7 +146,7 @@ module ChefConfig # http://stackoverflow.com/questions/14127343 def self.escape_glob(*parts) path = cleanpath(join(*parts)) - path.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\"+x } + path.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\" + x } end def self.relative_path_from(from, to) @@ -233,18 +233,19 @@ module ChefConfig def self.is_sip_path?(path, node) if node["platform"] == "mac_os_x" and Gem::Version.new(node["platform_version"]) >= Gem::Version.new("10.11") # todo: parse rootless.conf for this? - sip_paths= [ - "/System", "/bin", "/sbin", "/usr" - ] - sip_paths.each do |sip_path| - ChefConfig.logger.info("This is a SIP path, checking if it in exceptions list.") - return true if path.start_with?(sip_path) - end - false + sip_paths = [ + "/System", "/bin", "/sbin", "/usr" + ] + sip_paths.each do |sip_path| + ChefConfig.logger.info("This is a SIP path, checking if it in exceptions list.") + return true if path.start_with?(sip_path) + end + false else false end end + # Determine if the given path is on the exception list for OS X System Integrity Protection. def self.writable_sip_path?(path) # todo: parse rootless.conf for this? @@ -261,4 +262,3 @@ module ChefConfig end end end - diff --git a/chef-config/lib/chef-config/windows.rb b/chef-config/lib/chef-config/windows.rb index a3d8ffe73a..a5b4a994a0 100644 --- a/chef-config/lib/chef-config/windows.rb +++ b/chef-config/lib/chef-config/windows.rb @@ -16,7 +16,6 @@ # module ChefConfig - def self.windows? if RUBY_PLATFORM =~ /mswin|mingw|windows/ true @@ -24,6 +23,4 @@ module ChefConfig false end end - end - diff --git a/chef-config/lib/chef-config/workstation_config_loader.rb b/chef-config/lib/chef-config/workstation_config_loader.rb index 70028ff798..9ad08889ac 100644 --- a/chef-config/lib/chef-config/workstation_config_loader.rb +++ b/chef-config/lib/chef-config/workstation_config_loader.rb @@ -24,12 +24,11 @@ require "chef-config/windows" module ChefConfig class WorkstationConfigLoader - # Path to a config file requested by user, (e.g., via command line option). Can be nil attr_accessor :explicit_config_file # TODO: initialize this with a logger for Chef and Knife - def initialize(explicit_config_file, logger=nil) + def initialize(explicit_config_file, logger = nil) @explicit_config_file = explicit_config_file @chef_config_dir = nil @config_location = nil @@ -119,7 +118,7 @@ module ChefConfig candidate_configs << File.join(dot_chef_dir, "knife.rb") end - candidate_configs.find do | candidate_config | + candidate_configs.find do |candidate_config| have_config?(candidate_config) end end @@ -151,7 +150,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 { |bt_line| message << " " << bt_line << "\n" } if !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) @@ -159,10 +158,9 @@ module ChefConfig raise ChefConfig::ConfigurationError, message end - 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 { |l, i| config_file_lines << "#{(i + 1).to_s.rjust(3)}: #{l.chomp}" } if line == 1 lines = config_file_lines[0..3] else @@ -174,6 +172,5 @@ module ChefConfig def logger @logger end - end end diff --git a/chef-config/spec/unit/config_spec.rb b/chef-config/spec/unit/config_spec.rb index 2408d3c822..2138ad674b 100644 --- a/chef-config/spec/unit/config_spec.rb +++ b/chef-config/spec/unit/config_spec.rb @@ -48,7 +48,6 @@ RSpec.describe ChefConfig::Config do it "strips the space from the url when setting" do expect(ChefConfig::Config.chef_server_url).to eq("https://junglist.gen.nz") end - end context "when the url is a frozen string" do @@ -105,11 +104,9 @@ RSpec.describe ChefConfig::Config do ChefConfig::Config.add_formatter(:doc, "/var/log/formatter.log") expect(ChefConfig::Config.formatters).to eq([[:doc, "/var/log/formatter.log"]]) end - end [ false, true ].each do |is_windows| - context "On #{is_windows ? 'Windows' : 'Unix'}" do def to_platform(*args) ChefConfig::Config.platform_specific_path(*args) @@ -289,9 +286,7 @@ RSpec.describe ChefConfig::Config do end describe "ChefConfig::Config[:repo_mode]" do - context "when local mode is enabled" do - before { ChefConfig::Config[:local_mode] = true } it "defaults to 'hosted_everything'" do @@ -299,7 +294,6 @@ RSpec.describe ChefConfig::Config do end context "and osc_compat is enabled" do - before { ChefConfig::Config.chef_zero.osc_compat = true } it "defaults to 'everything'" do @@ -309,19 +303,15 @@ RSpec.describe ChefConfig::Config do end context "when local mode is not enabled" do - context "and the chef_server_url is multi-tenant" do - before { ChefConfig::Config[:chef_server_url] = "https://chef.example/organizations/example" } it "defaults to 'hosted_everything'" do expect(ChefConfig::Config[:repo_mode]).to eq("hosted_everything") end - end context "and the chef_server_url is not multi-tenant" do - before { ChefConfig::Config[:chef_server_url] = "https://chef.example/" } it "defaults to 'everything'" do @@ -332,20 +322,16 @@ RSpec.describe ChefConfig::Config do end describe "ChefConfig::Config[:chef_repo_path]" do - context "when cookbook_path is set to a single path" do - before { ChefConfig::Config[:cookbook_path] = "/home/anne/repo/cookbooks" } it "is set to a path one directory up from the cookbook_path" do expected = File.expand_path("/home/anne/repo") expect(ChefConfig::Config[:chef_repo_path]).to eq(expected) end - end context "when cookbook_path is set to multiple paths" do - before do ChefConfig::Config[:cookbook_path] = [ "/home/anne/repo/cookbooks", @@ -357,11 +343,9 @@ RSpec.describe ChefConfig::Config do expected = [ "/home/anne/repo", "/home/anne/other_repo"].map { |p| File.expand_path(p) } expect(ChefConfig::Config[:chef_repo_path]).to eq(expected) end - end context "when cookbook_path is not set but cookbook_artifact_path is set" do - before do ChefConfig::Config[:cookbook_path] = nil ChefConfig::Config[:cookbook_artifact_path] = "/home/roxie/repo/cookbook_artifacts" @@ -371,19 +355,15 @@ RSpec.describe ChefConfig::Config do expected = File.expand_path("/home/roxie/repo") expect(ChefConfig::Config[:chef_repo_path]).to eq(expected) end - end context "when cookbook_path is not set" do - before { ChefConfig::Config[:cookbook_path] = nil } it "is set to the cache_path" do expect(ChefConfig::Config[:chef_repo_path]).to eq(ChefConfig::Config[:cache_path]) end - end - end # On Windows, we'll detect an omnibus build and set this to the @@ -414,9 +394,7 @@ RSpec.describe ChefConfig::Config do end describe "setting the config dir" do - context "when the config file is given with a relative path" do - before do ChefConfig::Config.config_file = "client.rb" end @@ -432,11 +410,9 @@ RSpec.describe ChefConfig::Config do ChefConfig::Config.local_mode = true expect(ChefConfig::Config.cache_path.downcase).to eq(to_platform(File.join(Dir.pwd, "local-mode-cache")).downcase) end - end context "when the config file is /etc/chef/client.rb" do - before do config_location = to_platform("/etc/chef/client.rb").downcase allow(File).to receive(:absolute_path).with(config_location).and_return(config_location) @@ -466,7 +442,6 @@ RSpec.describe ChefConfig::Config do expect(ChefConfig::Config.config_dir).to eq(to_platform("/other/config/dir/")) end end - end context "when the user's home dir is /home/charlie/" do @@ -488,7 +463,6 @@ RSpec.describe ChefConfig::Config do end end end - end if is_windows @@ -537,7 +511,7 @@ RSpec.describe ChefConfig::Config do end describe "ChefConfig::Config[:encrypted_data_bag_secret]" do - let(:db_secret_default_path){ to_platform("/etc/chef/encrypted_data_bag_secret") } + let(:db_secret_default_path) { to_platform("/etc/chef/encrypted_data_bag_secret") } before do allow(File).to receive(:exist?).with(db_secret_default_path).and_return(secret_exists) @@ -795,17 +769,13 @@ RSpec.describe ChefConfig::Config do end describe "allowing chefdk configuration outside of chefdk" do - it "allows arbitrary settings in the chefdk config context" do expect { ChefConfig::Config.chefdk.generator_cookbook("/path") }.to_not raise_error end - end describe "Treating deprecation warnings as errors" do - context "when using our default RSpec configuration" do - it "defaults to treating deprecation warnings as errors" do expect(ChefConfig::Config[:treat_deprecation_warnings_as_errors]).to be(true) end @@ -823,11 +793,9 @@ RSpec.describe ChefConfig::Config do ChefConfig::Config.reset expect(ChefConfig::Config[:treat_deprecation_warnings_as_errors]).to be(true) end - end context "outside of our test environment" do - before do ENV.delete("CHEF_TREAT_DEPRECATION_WARNINGS_AS_ERRORS") ChefConfig::Config.reset @@ -837,8 +805,5 @@ RSpec.describe ChefConfig::Config do expect(ChefConfig::Config[:treat_deprecation_warnings_as_errors]).to be(false) end end - - end - end diff --git a/chef-config/spec/unit/path_helper_spec.rb b/chef-config/spec/unit/path_helper_spec.rb index 0192bbf621..042ed27f7f 100644 --- a/chef-config/spec/unit/path_helper_spec.rb +++ b/chef-config/spec/unit/path_helper_spec.rb @@ -20,12 +20,10 @@ require "chef-config/path_helper" require "spec_helper" RSpec.describe ChefConfig::PathHelper do - let(:path_helper) { described_class } shared_examples_for "common_functionality" do describe "join" do - it "joins starting with '' resolve to absolute paths" do expect(path_helper.join("", "a", "b")).to eq("#{path_helper.path_separator}a#{path_helper.path_separator}b") end @@ -33,7 +31,6 @@ RSpec.describe ChefConfig::PathHelper do it "joins ending with '' add a / to the end" do expect(path_helper.join("a", "b", "")).to eq("a#{path_helper.path_separator}b#{path_helper.path_separator}") end - end describe "dirname" do @@ -56,7 +53,6 @@ RSpec.describe ChefConfig::PathHelper do end context "on windows" do - before(:each) do allow(ChefConfig).to receive(:windows?).and_return(true) end @@ -68,7 +64,6 @@ RSpec.describe ChefConfig::PathHelper do end describe "platform-specific #join behavior" do - it "joins components on Windows when some end with unix separators" do expect(path_helper.join('C:\\foo/', "bar", "baz")).to eq('C:\\foo\\bar\\baz') end @@ -90,10 +85,8 @@ RSpec.describe ChefConfig::PathHelper do expected = "C:#{expected}" expect(path_helper.join('C:\\foo', "bar", "baz")).to eq(expected) end - end - it "cleanpath changes slashes into backslashes and leaves backslashes alone" do expect(path_helper.cleanpath('/a/b\\c/d/')).to eq('\\a\\b\\c\\d') end @@ -101,11 +94,9 @@ RSpec.describe ChefConfig::PathHelper do it "cleanpath does not remove leading double backslash" do expect(path_helper.cleanpath('\\\\a/b\\c/d/')).to eq('\\\\a\\b\\c\\d') end - end context "on unix" do - before(:each) do allow(ChefConfig).to receive(:windows?).and_return(false) end @@ -121,7 +112,6 @@ RSpec.describe ChefConfig::PathHelper do end describe "platform-specific #join behavior" do - it "joins components when some end with separators" do expected = path_helper.cleanpath("/foo/bar/baz") expect(path_helper.join("/foo/", "bar", "baz")).to eq(expected) @@ -136,9 +126,7 @@ RSpec.describe ChefConfig::PathHelper do expected = path_helper.cleanpath("/foo/bar/baz") expect(path_helper.join("/foo", "bar", "baz")).to eq(expected) end - end - end describe "validate_path" do @@ -224,7 +212,7 @@ RSpec.describe ChefConfig::PathHelper do end end - context "not on windows", :unix_only do + context "not on windows", :unix_only do it "returns a canonical path" do expect(path_helper.canonical_path("/etc//apache.d/sites-enabled/../sites-available/default")).to eq("/etc/apache.d/sites-available/default") end diff --git a/chef-config/spec/unit/workstation_config_loader_spec.rb b/chef-config/spec/unit/workstation_config_loader_spec.rb index ecfb27f8eb..bce61573af 100644 --- a/chef-config/spec/unit/workstation_config_loader_spec.rb +++ b/chef-config/spec/unit/workstation_config_loader_spec.rb @@ -24,7 +24,6 @@ require "chef-config/windows" require "chef-config/workstation_config_loader" RSpec.describe ChefConfig::WorkstationConfigLoader do - let(:explicit_config_location) { nil } let(:env) { {} } @@ -48,12 +47,10 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do expect(config_loader.path_exists?("/nope/nope/nope/nope/frab/jab/nab")).to be(false) expect(config_loader.path_exists?(__FILE__)).to be(true) end - end describe "locating the config file" do context "without an explicit config" do - before do allow(config_loader).to receive(:path_exists?).with(an_instance_of(String)).and_return(false) end @@ -64,7 +61,6 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do end context "when HOME is set and contains a knife.rb" do - let(:home) { "/Users/example.user" } before do @@ -77,7 +73,6 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do end context "and has a config.rb" do - before do allow(config_loader).to receive(:path_exists?).with("#{home}/.chef/config.rb").and_return(true) end @@ -87,7 +82,6 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do end context "and/or a parent dir contains a .chef dir" do - let(:env_pwd) { "/path/to/cwd" } before do @@ -107,7 +101,6 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do end context "and the parent dir's .chef dir has a config.rb" do - before do allow(config_loader).to receive(:path_exists?).with("#{env_pwd}/.chef/config.rb").and_return(true) end @@ -117,7 +110,6 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do end context "and/or the current working directory contains a .chef dir" do - let(:cwd) { Dir.pwd } before do @@ -129,7 +121,6 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do end context "and the CWD's .chef dir has a config.rb" do - before do allow(config_loader).to receive(:path_exists?).with("#{cwd}/config.rb").and_return(true) end @@ -138,9 +129,7 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do expect(config_loader.config_location).to eq("#{cwd}/config.rb") end - context "and/or KNIFE_HOME is set" do - let(:knife_home) { "/path/to/knife/home" } before do @@ -153,7 +142,6 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do end context "and KNIFE_HOME contains a config.rb" do - before do env["KNIFE_HOME"] = knife_home allow(config_loader).to receive(:path_exists?).with("#{knife_home}/config.rb").and_return(true) @@ -162,9 +150,7 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do it "prefers a config.rb located in KNIFE_HOME" do expect(config_loader.config_location).to eq("/path/to/knife/home/config.rb") end - end - end end end @@ -196,21 +182,16 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do end context "when given an explicit config to load" do - let(:explicit_config_location) { "/path/to/explicit/config.rb" } it "prefers the explicit config" do expect(config_loader.config_location).to eq(explicit_config_location) end - end end - describe "loading the config file" do - context "when no explicit config is specifed and no implicit config is found" do - before do allow(config_loader).to receive(:path_exists?).with(an_instance_of(String)).and_return(false) end @@ -219,21 +200,17 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do expect(config_loader.config_location).to be(nil) expect(config_loader.load).to be(false) end - end context "when an explicit config is given but it doesn't exist" do - let(:explicit_config_location) { "/nope/nope/nope/frab/jab/nab" } it "raises a configuration error" do expect { config_loader.load }.to raise_error(ChefConfig::ConfigurationError) end - end context "when the config file exists" do - let(:config_content) { "" } # We need to keep a reference to the tempfile because while #close does @@ -252,7 +229,6 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do after { File.unlink(explicit_config_location) if File.exist?(explicit_config_location) } context "and is valid" do - let(:config_content) { "config_file_evaluated(true)" } it "loads the config" do @@ -267,7 +243,6 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do end context "and has a syntax error" do - let(:config_content) { "{{{{{:{{" } it "raises a ConfigurationError" do @@ -276,16 +251,12 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do end context "and raises a ruby exception during evaluation" do - let(:config_content) { ":foo\n:bar\nraise 'oops'\n:baz\n" } it "raises a ConfigurationError" do expect { config_loader.load }.to raise_error(ChefConfig::ConfigurationError) end end - end - end - end diff --git a/chef.gemspec b/chef.gemspec index 168279d99a..2ba0cc7979 100644 --- a/chef.gemspec +++ b/chef.gemspec @@ -54,5 +54,5 @@ Gem::Specification.new do |s| s.executables = %w{ chef-client chef-solo knife chef-shell chef-apply } s.require_paths = %w{ lib lib-backcompat } - s.files = %w{Gemfile Rakefile LICENSE README.md CONTRIBUTING.md} + Dir.glob("{distro,lib,lib-backcompat,tasks,acceptance,spec}/**/*", File::FNM_DOTMATCH).reject {|f| File.directory?(f) } + Dir.glob("*.gemspec") + s.files = %w{Gemfile Rakefile LICENSE README.md CONTRIBUTING.md} + Dir.glob("{distro,lib,lib-backcompat,tasks,acceptance,spec}/**/*", File::FNM_DOTMATCH).reject { |f| File.directory?(f) } + Dir.glob("*.gemspec") end diff --git a/ext/win32-eventlog/Rakefile b/ext/win32-eventlog/Rakefile index 81137b0d8d..4788d73cae 100644 --- a/ext/win32-eventlog/Rakefile +++ b/ext/win32-eventlog/Rakefile @@ -12,7 +12,6 @@ def ensure_present(commands) end end - EVT_MC_FILE = "chef-log.man" EVT_RC_FILE = "chef-log.rc" EVT_RESOURCE_OBJECT = "resource.o" @@ -26,7 +25,7 @@ ensure_present [MC, RC, CC] task :build => [EVT_RESOURCE_OBJECT, EVT_SHARED_OBJECT] task :default => [:build, :register] -file EVT_RC_FILE=> EVT_MC_FILE do +file EVT_RC_FILE => EVT_MC_FILE do sh "#{MC} #{EVT_MC_FILE}" end diff --git a/kitchen-tests/cookbooks/audit_test/metadata.rb b/kitchen-tests/cookbooks/audit_test/metadata.rb index 91cf94c0ff..3fbda5dbe1 100644 --- a/kitchen-tests/cookbooks/audit_test/metadata.rb +++ b/kitchen-tests/cookbooks/audit_test/metadata.rb @@ -5,4 +5,3 @@ license "all_rights" description "Installs/Configures audit_test" long_description "Installs/Configures audit_test" version "0.1.0" - diff --git a/kitchen-tests/test/integration/webapp/serverspec/localhost/default_spec.rb b/kitchen-tests/test/integration/webapp/serverspec/localhost/default_spec.rb index 992e4f7683..91eccaf19f 100644 --- a/kitchen-tests/test/integration/webapp/serverspec/localhost/default_spec.rb +++ b/kitchen-tests/test/integration/webapp/serverspec/localhost/default_spec.rb @@ -5,7 +5,6 @@ require "uri" require "#{ENV['BUSSER_ROOT']}/../kitchen/data/serverspec_helper" describe "webapp::default", :end_to_end => true do - describe "installed packages" do shared_examples_for "a package" do it "is installed" do @@ -60,7 +59,6 @@ describe "webapp::default", :end_to_end => true do let(:service_name) { property[:mysql][:service_name] } end end - end describe "mysql database" do diff --git a/lib/chef/api_client.rb b/lib/chef/api_client.rb index bff5e0b378..a318cffda9 100644 --- a/lib/chef/api_client.rb +++ b/lib/chef/api_client.rb @@ -32,7 +32,6 @@ require "chef/server_api" # Chef::ApiClientV1 until the time before Chef 13. class Chef class ApiClient - include Chef::Mixin::FromFile include Chef::Mixin::ParamsValidate @@ -49,7 +48,7 @@ class Chef # # @params [Optional String] The name must be alpha-numeric plus - and _. # @return [String] The current value of the name. - def name(arg=nil) + def name(arg = nil) set_or_return( :name, arg, @@ -61,7 +60,7 @@ class Chef # # @params [Optional True/False] Should be true or false - default is false. # @return [True/False] The current value - def admin(arg=nil) + def admin(arg = nil) set_or_return( :admin, arg, @@ -73,7 +72,7 @@ class Chef # # @params [Optional String] The string representation of the public key. # @return [String] The current value. - def public_key(arg=nil) + def public_key(arg = nil) set_or_return( :public_key, arg, @@ -86,7 +85,7 @@ class Chef # @params [Boolean] whether or not the client is a validator. If # `nil`, retrieves the already-set value. # @return [Boolean] The current value - def validator(arg=nil) + def validator(arg = nil) set_or_return( :validator, arg, @@ -98,7 +97,7 @@ class Chef # # @params [Optional String] The string representation of the private key. # @return [String] The current value. - def private_key(arg=nil) + def private_key(arg = nil) set_or_return( :private_key, arg, @@ -150,7 +149,7 @@ class Chef end def self.http_api - Chef::ServerAPI.new(Chef::Config[:chef_server_url], {:api_version => "0"}) + Chef::ServerAPI.new(Chef::Config[:chef_server_url], { :api_version => "0" }) end def self.reregister(name) @@ -158,7 +157,7 @@ class Chef api_client.reregister end - def self.list(inflate=false) + def self.list(inflate = false) if inflate response = Hash.new Chef::Search::Query.new.search(:client) do |n| @@ -189,11 +188,11 @@ class Chef # Save this client via the REST API, returns a hash including the private key def save begin - http_api.put("clients/#{name}", { :name => self.name, :admin => self.admin, :validator => self.validator}) + http_api.put("clients/#{name}", { :name => self.name, :admin => self.admin, :validator => self.validator }) rescue Net::HTTPServerException => e # If that fails, go ahead and try and update it if e.response.code == "404" - http_api.post("clients", {:name => self.name, :admin => self.admin, :validator => self.validator }) + http_api.post("clients", { :name => self.name, :admin => self.admin, :validator => self.validator }) else raise e end @@ -222,12 +221,11 @@ class Chef def inspect "Chef::ApiClient name:'#{name}' admin:'#{admin.inspect}' validator:'#{validator}' " + - "public_key:'#{public_key}' private_key:'#{private_key}'" + "public_key:'#{public_key}' private_key:'#{private_key}'" end def http_api - @http_api ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url], {:api_version => "0"}) + @http_api ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url], { :api_version => "0" }) end - end end diff --git a/lib/chef/api_client/registration.rb b/lib/chef/api_client/registration.rb index 98ab1c01c2..cffdf2ef48 100644 --- a/lib/chef/api_client/registration.rb +++ b/lib/chef/api_client/registration.rb @@ -22,7 +22,6 @@ require "chef/exceptions" class Chef class ApiClient - # ==Chef::ApiClient::Registration # Manages the process of creating or updating a Chef::ApiClient on the # server and writing the resulting private key to disk. Registration uses @@ -180,7 +179,7 @@ class Chef end def file_flags - base_flags = File::CREAT|File::TRUNC|File::RDWR + base_flags = File::CREAT | File::TRUNC | File::RDWR # Windows doesn't have symlinks, so it doesn't have NOFOLLOW if defined?(File::NOFOLLOW) && !Chef::Config[:follow_client_key_symlink] base_flags |= File::NOFOLLOW diff --git a/lib/chef/api_client_v1.rb b/lib/chef/api_client_v1.rb index b177ec1284..4dd9b4daa7 100644 --- a/lib/chef/api_client_v1.rb +++ b/lib/chef/api_client_v1.rb @@ -39,12 +39,11 @@ require "chef/api_client" # API V1 before you pull in Chef 13. class Chef class ApiClientV1 - include Chef::Mixin::FromFile include Chef::Mixin::ParamsValidate include Chef::Mixin::ApiVersionRequestHandling - SUPPORTED_API_VERSIONS = [0,1] + SUPPORTED_API_VERSIONS = [0, 1] # Create a new Chef::ApiClientV1 object. def initialize @@ -57,22 +56,22 @@ class Chef end def chef_rest_v0 - @chef_rest_v0 ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url], {:api_version => "0", :inflate_json_class => false}) + @chef_rest_v0 ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url], { :api_version => "0", :inflate_json_class => false }) end def chef_rest_v1 - @chef_rest_v1 ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url], {:api_version => "1", :inflate_json_class => false}) + @chef_rest_v1 ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url], { :api_version => "1", :inflate_json_class => false }) end def self.http_api - Chef::ServerAPI.new(Chef::Config[:chef_server_url], {:api_version => "1", :inflate_json_class => false}) + Chef::ServerAPI.new(Chef::Config[:chef_server_url], { :api_version => "1", :inflate_json_class => false }) end # Gets or sets the client name. # # @params [Optional String] The name must be alpha-numeric plus - and _. # @return [String] The current value of the name. - def name(arg=nil) + def name(arg = nil) set_or_return( :name, arg, @@ -84,7 +83,7 @@ class Chef # # @params [Optional True/False] Should be true or false - default is false. # @return [True/False] The current value - def admin(arg=nil) + def admin(arg = nil) set_or_return( :admin, arg, @@ -96,7 +95,7 @@ class Chef # # @params [Optional String] The string representation of the public key. # @return [String] The current value. - def public_key(arg=nil) + def public_key(arg = nil) set_or_return( :public_key, arg, @@ -109,7 +108,7 @@ class Chef # @params [Boolean] whether or not the client is a validator. If # `nil`, retrieves the already-set value. # @return [Boolean] The current value - def validator(arg=nil) + def validator(arg = nil) set_or_return( :validator, arg, @@ -122,7 +121,7 @@ class Chef # # @params [Optional String] The string representation of the private key. # @return [String] The current value. - def private_key(arg=nil) + def private_key(arg = nil) set_or_return( :private_key, arg, @@ -134,7 +133,7 @@ class Chef # # @params [Optional True/False] Should be true or false - default is false. # @return [True/False] The current value - def create_key(arg=nil) + def create_key(arg = nil) set_or_return( :create_key, arg, @@ -186,7 +185,7 @@ class Chef api_client.reregister end - def self.list(inflate=false) + def self.list(inflate = false) if inflate response = Hash.new Chef::Search::Query.new.search(:client) do |n| @@ -320,6 +319,5 @@ class Chef def to_s "client[#{@name}]" end - end end diff --git a/lib/chef/application.rb b/lib/chef/application.rb index c5a128a179..cd795ae766 100644 --- a/lib/chef/application.rb +++ b/lib/chef/application.rb @@ -154,7 +154,7 @@ class Chef def configure_stdout_logger stdout_logger = MonoLogger.new(STDOUT) stdout_logger.formatter = Chef::Log.logger.formatter - Chef::Log.loggers << stdout_logger + Chef::Log.loggers << stdout_logger end # Based on config and whether or not STDOUT is a tty, should we setup a @@ -232,6 +232,7 @@ class Chef end private + def can_fork? # win32-process gem exposes some form of :fork for Process # class. So we are separately ensuring that the platform we're @@ -297,7 +298,7 @@ class Chef rescue Exception => error Chef::Log.fatal("Configuration error #{error.class}: #{error.message}") filtered_trace = error.backtrace.grep(/#{Regexp.escape(config_file_path)}/) - filtered_trace.each {|line| Chef::Log.fatal(" " + line )} + filtered_trace.each { |line| Chef::Log.fatal(" " + line ) } Chef::Application.fatal!("Aborting due to error in '#{config_file_path}'", 2) end @@ -336,6 +337,5 @@ class Chef Process.exit err end end - end end diff --git a/lib/chef/application/apply.rb b/lib/chef/application/apply.rb index 04dc1dae34..91529d7945 100644 --- a/lib/chef/application/apply.rb +++ b/lib/chef/application/apply.rb @@ -28,7 +28,6 @@ require "chef/providers" require "chef/resources" class Chef::Application::Apply < Chef::Application - banner "Usage: chef-apply [RECIPE_FILE | -e RECIPE_TEXT | -s] [OPTIONS]" option :execute, @@ -82,13 +81,12 @@ class Chef::Application::Apply < Chef::Application :show_options => true, :exit => 0 - option :version, :short => "-v", :long => "--version", :description => "Show chef version", :boolean => true, - :proc => lambda {|v| puts "Chef: #{::Chef::VERSION}"}, + :proc => lambda { |v| puts "Chef: #{::Chef::VERSION}" }, :exit => 0 option :why_run, @@ -187,9 +185,9 @@ class Chef::Application::Apply < Chef::Application Chef::Application.exit! "No recipe file provided", 1 end @recipe_filename = ARGV[0] - @recipe_text,@recipe_fh = read_recipe_file @recipe_filename + @recipe_text, @recipe_fh = read_recipe_file @recipe_filename end - recipe,run_context = get_recipe_and_run_context + recipe, run_context = get_recipe_and_run_context recipe.instance_eval(@recipe_text, @recipe_filename, 1) runner = Chef::Runner.new(run_context) begin @@ -218,5 +216,4 @@ class Chef::Application::Apply < Chef::Application reconfigure run_application end - end diff --git a/lib/chef/application/client.rb b/lib/chef/application/client.rb index ea091276d1..a3cac2782a 100644 --- a/lib/chef/application/client.rb +++ b/lib/chef/application/client.rb @@ -181,7 +181,7 @@ class Chef::Application::Client < Chef::Application :long => "--version", :description => "Show chef version", :boolean => true, - :proc => lambda {|v| puts "Chef: #{::Chef::VERSION}"}, + :proc => lambda { |v| puts "Chef: #{::Chef::VERSION}" }, :exit => 0 option :override_runlist, @@ -402,6 +402,7 @@ class Chef::Application::Client < Chef::Application end private + def interval_run_chef_client if Chef::Config[:daemonize] Chef::Daemon.daemonize("chef-client") @@ -461,16 +462,16 @@ class Chef::Application::Client < Chef::Application def unforked_interval_error_message "Unforked chef-client interval runs are disabled in Chef 12." + - "\nConfiguration settings:" + - "#{"\n interval = #{Chef::Config[:interval]} seconds" if Chef::Config[:interval]}" + - "\nEnable chef-client interval runs by setting `:client_fork = true` in your config file or adding `--fork` to your command line options." + "\nConfiguration settings:" + + "#{"\n interval = #{Chef::Config[:interval]} seconds" if Chef::Config[:interval]}" + + "\nEnable chef-client interval runs by setting `:client_fork = true` in your config file or adding `--fork` to your command line options." end def audit_mode_settings_explanation "\n* To enable audit mode after converge, use command line option `--audit-mode enabled` or set `audit_mode :enabled` in your config file." + - "\n* To disable audit mode, use command line option `--audit-mode disabled` or set `audit_mode :disabled` in your config file." + - "\n* To only run audit mode, use command line option `--audit-mode audit-only` or set `audit_mode :audit_only` in your config file." + - "\nAudit mode is disabled by default." + "\n* To disable audit mode, use command line option `--audit-mode disabled` or set `audit_mode :disabled` in your config file." + + "\n* To only run audit mode, use command line option `--audit-mode audit-only` or set `audit_mode :audit_only` in your config file." + + "\nAudit mode is disabled by default." end def unrecognized_audit_mode(mode) diff --git a/lib/chef/application/knife.rb b/lib/chef/application/knife.rb index bb1e1f7918..6f0752613c 100644 --- a/lib/chef/application/knife.rb +++ b/lib/chef/application/knife.rb @@ -22,7 +22,6 @@ require "ohai/config" require "chef/monkey_patches/net_http.rb" class Chef::Application::Knife < Chef::Application - NO_COMMAND_GIVEN = "You need to pass a sub-command (e.g., knife SUB-COMMAND)\n" banner "Usage: knife sub-command (options)" @@ -38,7 +37,7 @@ class Chef::Application::Knife < Chef::Application :short => "-V", :long => "--verbose", :description => "More verbose output. Use twice for max verbosity", - :proc => Proc.new { verbosity_level += 1}, + :proc => Proc.new { verbosity_level += 1 }, :default => 0 option :color, @@ -131,7 +130,7 @@ class Chef::Application::Knife < Chef::Application :long => "--version", :description => "Show chef version", :boolean => true, - :proc => lambda {|v| puts "Chef: #{::Chef::VERSION}"}, + :proc => lambda { |v| puts "Chef: #{::Chef::VERSION}" }, :exit => 0 option :fips, @@ -191,7 +190,7 @@ class Chef::Application::Knife < Chef::Application ARGV[0] =~ /^(--version|-v)$/ end - def print_help_and_exit(exitcode=1, fatal_message=nil) + def print_help_and_exit(exitcode = 1, fatal_message = nil) Chef::Log.error(fatal_message) if fatal_message begin @@ -204,5 +203,4 @@ class Chef::Application::Knife < Chef::Application Chef::Knife.list_commands exit exitcode end - end diff --git a/lib/chef/application/solo.rb b/lib/chef/application/solo.rb index 54d31a5faa..b704696e1f 100644 --- a/lib/chef/application/solo.rb +++ b/lib/chef/application/solo.rb @@ -27,7 +27,6 @@ require "chef/config_fetcher" require "fileutils" class Chef::Application::Solo < Chef::Application - option :config_file, :short => "-c CONFIG", :long => "--config CONFIG", @@ -145,7 +144,7 @@ class Chef::Application::Solo < Chef::Application :long => "--version", :description => "Show chef version", :boolean => true, - :proc => lambda {|v| puts "Chef: #{::Chef::VERSION}"}, + :proc => lambda { |v| puts "Chef: #{::Chef::VERSION}" }, :exit => 0 option :override_runlist, @@ -211,7 +210,7 @@ class Chef::Application::Solo < Chef::Application Chef::Application.fatal!(unforked_interval_error_message) if !Chef::Config[:client_fork] && Chef::Config[:interval] if Chef::Config[:recipe_url] - cookbooks_path = Array(Chef::Config[:cookbook_path]).detect{|e| e =~ /\/cookbooks\/*$/ } + cookbooks_path = Array(Chef::Config[:cookbook_path]).detect { |e| e =~ /\/cookbooks\/*$/ } recipes_path = File.expand_path(File.join(cookbooks_path, "..")) Chef::Log.debug "Cleanup path #{recipes_path} before extract recipes into it" @@ -254,7 +253,6 @@ class Chef::Application::Solo < Chef::Application end end - private def for_ezra @@ -312,8 +310,8 @@ EOH def unforked_interval_error_message "Unforked chef-client interval runs are disabled in Chef 12." + - "\nConfiguration settings:" + - "#{"\n interval = #{Chef::Config[:interval]} seconds" if Chef::Config[:interval]}" + - "\nEnable chef-client interval runs by setting `:client_fork = true` in your config file or adding `--fork` to your command line options." + "\nConfiguration settings:" + + "#{"\n interval = #{Chef::Config[:interval]} seconds" if Chef::Config[:interval]}" + + "\nEnable chef-client interval runs by setting `:client_fork = true` in your config file or adding `--fork` to your command line options." end end diff --git a/lib/chef/application/windows_service.rb b/lib/chef/application/windows_service.rb index 0032114136..cedfd2c7f4 100644 --- a/lib/chef/application/windows_service.rb +++ b/lib/chef/application/windows_service.rb @@ -187,12 +187,12 @@ class Chef Chef::Log.info "Starting chef-client in a new process" # Pass config params to the new process config_params = " --no-fork" - config_params += " -c #{Chef::Config[:config_file]}" unless Chef::Config[:config_file].nil? + config_params += " -c #{Chef::Config[:config_file]}" unless Chef::Config[:config_file].nil? # log_location might be an event logger and if so we cannot pass as a command argument # but shed no tears! If the logger is an event logger, it must have been configured # as such in the config file and chef-client will use that when no arg is passed here config_params += " -L #{resolve_log_location}" if resolve_log_location.is_a?(String) - + # Starts a new process and waits till the process exits result = shell_out( @@ -204,8 +204,8 @@ class Chef Chef::Log.debug "#{result.stderr}" rescue Mixlib::ShellOut::CommandTimeout => e Chef::Log.error "chef-client timed out\n(#{e})" - Chef::Log.error(<<-EOF) - Your chef-client run timed out. You can increase the time chef-client is given + Chef::Log.error(<<-EOF) + Your chef-client run timed out. You can increase the time chef-client is given to complete by configuring windows_service.watchdog_timeout in your client.rb. EOF rescue Mixlib::ShellOut::ShellCommandFailed => e @@ -225,12 +225,12 @@ class Chef # Lifted from Chef::Application, with addition of optional startup parameters # for playing nicely with Windows Services - def reconfigure(startup_parameters=[]) + def reconfigure(startup_parameters = []) configure_chef startup_parameters configure_logging Chef::Config[:chef_server_url] = config[:chef_server_url] if config.has_key? :chef_server_url - unless Chef::Config[:exception_handlers].any? {|h| Chef::Handler::ErrorReport === h} + unless Chef::Config[:exception_handlers].any? { |h| Chef::Handler::ErrorReport === h } Chef::Config[:exception_handlers] << Chef::Handler::ErrorReport.new end @@ -251,7 +251,7 @@ class Chef def configure_stdout_logger stdout_logger = MonoLogger.new(STDOUT) stdout_logger.formatter = Chef::Log.logger.formatter - Chef::Log.loggers << stdout_logger + Chef::Log.loggers << stdout_logger end # Based on config and whether or not STDOUT is a tty, should we setup a @@ -326,7 +326,6 @@ class Chef Chef::Application.fatal!("Unknown error processing config file #{Chef::Config[:config_file]} with error #{error.message}", 2) end end - end end end @@ -334,5 +333,5 @@ end # To run this file as a service, it must be called as a script from within # the Windows Service framework. In that case, kick off the main loop! if __FILE__ == $0 - Chef::Application::WindowsService.mainloop + Chef::Application::WindowsService.mainloop end diff --git a/lib/chef/application/windows_service_manager.rb b/lib/chef/application/windows_service_manager.rb index 7a89766cb4..129e3f5ee3 100644 --- a/lib/chef/application/windows_service_manager.rb +++ b/lib/chef/application/windows_service_manager.rb @@ -67,7 +67,7 @@ class Chef :long => "--version", :description => "Show chef version", :boolean => true, - :proc => lambda {|v| puts "Chef: #{::Chef::VERSION}"}, + :proc => lambda { |v| puts "Chef: #{::Chef::VERSION}" }, :exit => 0 def initialize(service_options) @@ -169,7 +169,7 @@ class Chef return ::Win32::Service.exists?(@service_name) end - def take_action(action=nil, desired_state=nil) + def take_action(action = nil, desired_state = nil) if service_exists? if current_state != desired_state ::Win32::Service.send(action, @service_name) @@ -196,7 +196,6 @@ class Chef sleep 1 end end - end end end diff --git a/lib/chef/audit/audit_event_proxy.rb b/lib/chef/audit/audit_event_proxy.rb index 667e1db592..0ea7f99a97 100644 --- a/lib/chef/audit/audit_event_proxy.rb +++ b/lib/chef/audit/audit_event_proxy.rb @@ -79,15 +79,14 @@ class Chef outermost_group_desc = describe_groups.shift return outermost_group_desc, { - :name => example.description, - :desc => example.full_description, - :resource_type => resource_type, - :resource_name => resource_name, - :context => describe_groups, - :line_number => example.metadata[:line_number], + :name => example.description, + :desc => example.full_description, + :resource_type => resource_type, + :resource_name => resource_name, + :context => describe_groups, + :line_number => example.metadata[:line_number], } end - end end end diff --git a/lib/chef/audit/audit_reporter.rb b/lib/chef/audit/audit_reporter.rb index e647f143ae..ca54ce9795 100644 --- a/lib/chef/audit/audit_reporter.rb +++ b/lib/chef/audit/audit_reporter.rb @@ -24,7 +24,6 @@ require "time" class Chef class Audit class AuditReporter < EventDispatch::Base - attr_reader :rest_client, :audit_data, :ordered_control_groups, :run_status private :rest_client, :audit_data, :ordered_control_groups, :run_status @@ -154,13 +153,13 @@ class Chef end def headers(additional_headers = {}) - options = {"X-Ops-Audit-Report-Protocol-Version" => PROTOCOL_VERSION} + options = { "X-Ops-Audit-Report-Protocol-Version" => PROTOCOL_VERSION } options.merge(additional_headers) end def encode_gzip(data) "".tap do |out| - Zlib::GzipWriter.wrap(StringIO.new(out)){|gz| gz << data } + Zlib::GzipWriter.wrap(StringIO.new(out)) { |gz| gz << data } end end diff --git a/lib/chef/audit/control_group_data.rb b/lib/chef/audit/control_group_data.rb index 688341adad..e8d022d0fd 100644 --- a/lib/chef/audit/control_group_data.rb +++ b/lib/chef/audit/control_group_data.rb @@ -37,11 +37,11 @@ class Chef def to_hash { - :node_name => node_name, - :run_id => run_id, - :start_time => start_time, - :end_time => end_time, - :control_groups => control_groups.collect { |c| c.to_hash }, + :node_name => node_name, + :run_id => run_id, + :start_time => start_time, + :end_time => end_time, + :control_groups => control_groups.collect { |c| c.to_hash }, } end end @@ -49,7 +49,7 @@ class Chef class ControlGroupData attr_reader :name, :status, :number_succeeded, :number_failed, :controls, :metadata - def initialize(name, metadata={}) + def initialize(name, metadata = {}) @status = "success" @controls = [] @number_succeeded = 0 @@ -58,7 +58,6 @@ class Chef @metadata = metadata end - def example_success(control_data) @number_succeeded += 1 control = create_control(control_data) @@ -80,13 +79,13 @@ class Chef def to_hash # We sort it so the examples appear in the output in the same order # they appeared in the recipe - controls.sort! {|x,y| x.line_number <=> y.line_number} + controls.sort! { |x, y| x.line_number <=> y.line_number } h = { - :name => name, - :status => status, - :number_succeeded => number_succeeded, - :number_failed => number_failed, - :controls => controls.collect { |c| c.to_hash }, + :name => name, + :status => status, + :number_succeeded => number_succeeded, + :number_failed => number_failed, + :controls => controls.collect { |c| c.to_hash }, } # If there is a duplicate key, metadata will overwrite it add_display_only_data(h).merge(metadata) @@ -105,19 +104,18 @@ class Chef group[:id] = SecureRandom.uuid group[:controls].collect!.with_index do |c, i| # i is zero-indexed, and we want the display one-indexed - c[:sequence_number] = i+1 + c[:sequence_number] = i + 1 c end group end - end class ControlData attr_reader :name, :resource_type, :resource_name, :context, :line_number attr_accessor :status, :details - def initialize(control_data={}) + def initialize(control_data = {}) control_data.each do |k, v| self.instance_variable_set("@#{k}", v) end @@ -125,16 +123,15 @@ class Chef def to_hash h = { - :name => name, - :status => status, - :details => details, - :resource_type => resource_type, - :resource_name => resource_name, + :name => name, + :status => status, + :details => details, + :resource_type => resource_type, + :resource_name => resource_name, } h[:context] = context || [] h end end - end end diff --git a/lib/chef/audit/logger.rb b/lib/chef/audit/logger.rb index 9e1b779f5b..759683ccc8 100644 --- a/lib/chef/audit/logger.rb +++ b/lib/chef/audit/logger.rb @@ -20,7 +20,7 @@ require "stringio" class Chef class Audit class Logger - def self.puts(message="") + def self.puts(message = "") @buffer ||= StringIO.new @buffer.puts(message) diff --git a/lib/chef/audit/runner.rb b/lib/chef/audit/runner.rb index 561c50734c..8ee3b688aa 100644 --- a/lib/chef/audit/runner.rb +++ b/lib/chef/audit/runner.rb @@ -21,7 +21,6 @@ require "chef/audit/logger" class Chef class Audit class Runner - attr_reader :run_context private :run_context @@ -52,6 +51,7 @@ class Chef end private + # Prepare to run audits: # - Require files # - Configure RSpec @@ -189,7 +189,6 @@ class Chef runner = RSpec::Core::Runner.new(nil) runner.run_specs(RSpec.world.ordered_example_groups) end - end end end diff --git a/lib/chef/chef_class.rb b/lib/chef/chef_class.rb index 29996b7b7f..c1752bbd09 100644 --- a/lib/chef/chef_class.rb +++ b/lib/chef/chef_class.rb @@ -33,7 +33,6 @@ require "chef/platform/resource_handler_map" class Chef class << self - # # Public API # @@ -178,14 +177,17 @@ class Chef # these slurp in the resource+provider world, so be exceedingly lazy about requiring them @provider_priority_map ||= Chef::Platform::ProviderPriorityMap.instance end + # @api private def resource_priority_map @resource_priority_map ||= Chef::Platform::ResourcePriorityMap.instance end + # @api private def provider_handler_map @provider_handler_map ||= Chef::Platform::ProviderHandlerMap.instance end + # @api private def resource_handler_map @resource_handler_map ||= Chef::Platform::ResourceHandlerMap.instance @@ -204,7 +206,7 @@ class Chef # # @api private this will likely be removed in favor of an as-yet unwritten # `Chef.log` - def log_deprecation(message, location=nil) + def log_deprecation(message, location = nil) location ||= Chef::Log.caller_location # `run_context.events` is the primary deprecation target if we're in a # run. If we are not yet in a run, print to `Chef::Log`. diff --git a/lib/chef/chef_fs/chef_fs_data_store.rb b/lib/chef/chef_fs/chef_fs_data_store.rb index 389cea472e..fa2016734e 100644 --- a/lib/chef/chef_fs/chef_fs_data_store.rb +++ b/lib/chef/chef_fs/chef_fs_data_store.rb @@ -126,7 +126,6 @@ class Chef # - `delete(association_requests/NAME)` -> `get(/invitations.json)`, remove name, `set(/invitations.json)` # class ChefFSDataStore - # The base directories in a Chef Repo; even when these don't exist, a # matching GET for these objects will return an empty list instead of a # 404. @@ -154,7 +153,7 @@ class Chef # Generally will be a +ChefFS::FileSystem::ChefRepositoryFileSystemRoot+ # object, created from +ChefFS::Config.local_fs+. # - def initialize(chef_fs, chef_config=Chef::Config) + def initialize(chef_fs, chef_config = Chef::Config) @chef_fs = chef_fs @memory_store = ChefZero::DataStore::MemoryStore.new @repo_mode = chef_config[:repo_mode] @@ -260,7 +259,7 @@ class Chef end end - def get(path, request=nil) + def get(path, request = nil) if use_memory_store?(path) @memory_store.get(path) @@ -335,11 +334,11 @@ class Chef if cookbook_type == "cookbook_artifacts" result["metadata"] = result["metadata"].to_hash - result["metadata"].delete_if do |key,value| + result["metadata"].delete_if do |key, value| value == [] || - (value == {} && !%w{dependencies attributes recipes}.include?(key)) || - (value == "" && %w{source_url issues_url}.include?(key)) || - (value == false && key == "privacy") + (value == {} && !%w{dependencies attributes recipes}.include?(key)) || + (value == "" && %w{source_url issues_url}.include?(key)) || + (value == false && key == "privacy") end end @@ -537,8 +536,8 @@ class Chef result = with_entry([ path[0] ]) do |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 } + select { |name, version| name == path[1] }. + map { |name, version| version } end if result.empty? raise ChefZero::DataStore::DataNotFoundError.new(path) @@ -651,7 +650,7 @@ class Chef name_version = entry_name.split("-") name = name_version[0..-2].join("-") version = name_version[-1] - [name,version] + [name, version] end def to_chef_fs_path(path) @@ -798,7 +797,7 @@ class Chef end end - def get_dir(path, create=false) + def get_dir(path, create = false) result = Chef::ChefFS::FileSystem.resolve_path(chef_fs, path.join("/")) if result.exists? result diff --git a/lib/chef/chef_fs/command_line.rb b/lib/chef/chef_fs/command_line.rb index f3e63286f2..202d3cf4ff 100644 --- a/lib/chef/chef_fs/command_line.rb +++ b/lib/chef/chef_fs/command_line.rb @@ -24,7 +24,6 @@ require "chef/util/diff" class Chef module ChefFS module CommandLine - def self.diff_print(pattern, a_root, b_root, recurse_depth, output_mode, format_path = nil, diff_filter = nil, ui = nil) if format_path.nil? format_path = proc { |entry| entry.path_for_printing } diff --git a/lib/chef/chef_fs/config.rb b/lib/chef/chef_fs/config.rb index 19cea3b4ea..913a4097a3 100644 --- a/lib/chef/chef_fs/config.rb +++ b/lib/chef/chef_fs/config.rb @@ -26,7 +26,6 @@ class Chef # objects representing the server and local repository, respectively). # class Config - # Not all of our object types pluralize by adding an 's', so we map them # out here: INFLECTIONS = { @@ -44,7 +43,7 @@ class Chef "policies" => "policy", "policy_groups" => "policy_group", } - INFLECTIONS.each { |k,v| k.freeze; v.freeze } + INFLECTIONS.each { |k, v| k.freeze; v.freeze } INFLECTIONS.freeze # ChefFS supports three modes of operation: "static", "everything", and @@ -74,7 +73,6 @@ class Chef EVERYTHING_MODE_OBJECT_NAMES = (CHEF_11_OSS_STATIC_OBJECTS + CHEF_11_OSS_DYNAMIC_OBJECTS).freeze HOSTED_EVERYTHING_MODE_OBJECT_NAMES = (EVERYTHING_MODE_OBJECT_NAMES + RBAC_OBJECT_NAMES + CHEF_12_OBJECTS).freeze - # # Create a new Config object which can produce a chef_fs and local_fs. # @@ -243,12 +241,12 @@ class Chef # Print the given server path, relative to the current directory def format_path(entry) server_path = entry.path - if base_path && server_path[0,base_path.length] == base_path + if base_path && server_path[0, base_path.length] == base_path if server_path == base_path return "." - elsif server_path[base_path.length,1] == "/" + elsif server_path[base_path.length, 1] == "/" return server_path[base_path.length + 1, server_path.length - base_path.length - 1] - elsif base_path == "/" && server_path[0,1] == "/" + elsif base_path == "/" && server_path[0, 1] == "/" return server_path[1, server_path.length - 1] end end diff --git a/lib/chef/chef_fs/data_handler/acl_data_handler.rb b/lib/chef/chef_fs/data_handler/acl_data_handler.rb index 91e48101c4..8e61d29430 100644 --- a/lib/chef/chef_fs/data_handler/acl_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/acl_data_handler.rb @@ -7,12 +7,12 @@ class Chef def normalize(acl, entry) # Normalize the order of the keys for easier reading result = normalize_hash(acl, { - "create" => {}, - "read" => {}, - "update" => {}, - "delete" => {}, - "grant" => {}, - },) + "create" => {}, + "read" => {}, + "update" => {}, + "delete" => {}, + "grant" => {}, + },) result.keys.each do |key| result[key] = normalize_hash(result[key], { "actors" => [], "groups" => [] }) result[key]["actors"] = result[key]["actors"].sort diff --git a/lib/chef/chef_fs/data_handler/container_data_handler.rb b/lib/chef/chef_fs/data_handler/container_data_handler.rb index d1e8d2f3af..956e308a8d 100644 --- a/lib/chef/chef_fs/data_handler/container_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/container_data_handler.rb @@ -6,9 +6,9 @@ class Chef class ContainerDataHandler < DataHandlerBase def normalize(container, entry) normalize_hash(container, { - "containername" => remove_dot_json(entry.name), - "containerpath" => remove_dot_json(entry.name), - },) + "containername" => remove_dot_json(entry.name), + "containerpath" => remove_dot_json(entry.name), + },) end def preserve_key?(key) diff --git a/lib/chef/chef_fs/data_handler/cookbook_data_handler.rb b/lib/chef/chef_fs/data_handler/cookbook_data_handler.rb index f75f96f773..700a0d6c51 100644 --- a/lib/chef/chef_fs/data_handler/cookbook_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/cookbook_data_handler.rb @@ -9,18 +9,18 @@ class Chef version = entry.name name = entry.parent.name result = normalize_hash(cookbook, { - "name" => "#{name}-#{version}", - "version" => version, - "cookbook_name" => name, - "json_class" => "Chef::CookbookVersion", - "chef_type" => "cookbook_version", - "frozen?" => false, - "metadata" => {}, - },) + "name" => "#{name}-#{version}", + "version" => version, + "cookbook_name" => name, + "json_class" => "Chef::CookbookVersion", + "chef_type" => "cookbook_version", + "frozen?" => false, + "metadata" => {}, + },) result["metadata"] = normalize_hash(result["metadata"], { - "version" => version, - "name" => name, - },) + "version" => version, + "name" => name, + },) end def preserve_key?(key) diff --git a/lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb b/lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb index d56f662c5c..24ecc12188 100644 --- a/lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb @@ -13,8 +13,8 @@ class Chef # chef_type and data_bag come back in PUT and POST results, but we don't # use those in knife-essentials. normalize_hash(data_bag_item, { - "id" => remove_dot_json(entry.name) - },) + "id" => remove_dot_json(entry.name) + },) end def normalize_for_post(data_bag_item, entry) 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 41c5dd13e2..6b959752db 100644 --- a/lib/chef/chef_fs/data_handler/data_handler_base.rb +++ b/lib/chef/chef_fs/data_handler/data_handler_base.rb @@ -28,10 +28,10 @@ class Chef # Takes a name like blah.json and removes the .json from it. # def remove_dot_json(name) - if name.length < 5 || name[-5,5] != ".json" + if name.length < 5 || name[-5, 5] != ".json" raise "Invalid name #{path}: must end in .json" end - name[0,name.length-5] + name[0, name.length - 5] end # @@ -154,11 +154,11 @@ class Chef if object[key].size > 0 result << key first = true - object[key].each_pair do |k,v| + object[key].each_pair do |k, v| if first first = false else - result << " "*key.length + result << " " * key.length end result << " #{k.inspect} => #{v.inspect}\n" end @@ -195,7 +195,6 @@ class Chef on_error.call("Name must be '#{base_name}' (is '#{object['name']}')") end end - end # class DataHandlerBase end end diff --git a/lib/chef/chef_fs/data_handler/environment_data_handler.rb b/lib/chef/chef_fs/data_handler/environment_data_handler.rb index 3b9d5b4ec7..78d8df39f6 100644 --- a/lib/chef/chef_fs/data_handler/environment_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/environment_data_handler.rb @@ -7,14 +7,14 @@ class Chef class EnvironmentDataHandler < DataHandlerBase def normalize(environment, entry) normalize_hash(environment, { - "name" => remove_dot_json(entry.name), - "description" => "", - "cookbook_versions" => {}, - "default_attributes" => {}, - "override_attributes" => {}, - "json_class" => "Chef::Environment", - "chef_type" => "environment", - },) + "name" => remove_dot_json(entry.name), + "description" => "", + "cookbook_versions" => {}, + "default_attributes" => {}, + "override_attributes" => {}, + "json_class" => "Chef::Environment", + "chef_type" => "environment", + },) end def preserve_key?(key) diff --git a/lib/chef/chef_fs/data_handler/node_data_handler.rb b/lib/chef/chef_fs/data_handler/node_data_handler.rb index fcec74d2fb..cfde7301b0 100644 --- a/lib/chef/chef_fs/data_handler/node_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/node_data_handler.rb @@ -7,16 +7,16 @@ class Chef class NodeDataHandler < DataHandlerBase def normalize(node, entry) result = normalize_hash(node, { - "name" => remove_dot_json(entry.name), - "json_class" => "Chef::Node", - "chef_type" => "node", - "chef_environment" => "_default", - "override" => {}, - "normal" => {}, - "default" => {}, - "automatic" => {}, - "run_list" => [], - },) + "name" => remove_dot_json(entry.name), + "json_class" => "Chef::Node", + "chef_type" => "node", + "chef_environment" => "_default", + "override" => {}, + "normal" => {}, + "default" => {}, + "automatic" => {}, + "run_list" => [], + },) result["run_list"] = normalize_run_list(result["run_list"]) result end diff --git a/lib/chef/chef_fs/data_handler/organization_data_handler.rb b/lib/chef/chef_fs/data_handler/organization_data_handler.rb index d9f97b29ac..44f23e9612 100644 --- a/lib/chef/chef_fs/data_handler/organization_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/organization_data_handler.rb @@ -6,12 +6,12 @@ class Chef class OrganizationDataHandler < DataHandlerBase def normalize(organization, entry) result = normalize_hash(organization, { - "name" => entry.org, - "full_name" => entry.org, - "org_type" => "Business", - "clientname" => "#{entry.org}-validator", - "billing_plan" => "platform-free", - },) + "name" => entry.org, + "full_name" => entry.org, + "org_type" => "Business", + "clientname" => "#{entry.org}-validator", + "billing_plan" => "platform-free", + },) result end diff --git a/lib/chef/chef_fs/data_handler/policy_group_data_handler.rb b/lib/chef/chef_fs/data_handler/policy_group_data_handler.rb index e5c430ab64..75ff5e4567 100644 --- a/lib/chef/chef_fs/data_handler/policy_group_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/policy_group_data_handler.rb @@ -4,7 +4,6 @@ class Chef module ChefFS module DataHandler class PolicyGroupDataHandler < DataHandlerBase - def normalize(policy_group, entry) defaults = { "name" => remove_dot_json(entry.name), @@ -20,7 +19,6 @@ class Chef on_error.call("Policy group #{object_data["name"]} does not have any policies in it.") end end - end end end diff --git a/lib/chef/chef_fs/data_handler/role_data_handler.rb b/lib/chef/chef_fs/data_handler/role_data_handler.rb index eb10f7bb4a..9e0bc02e6c 100644 --- a/lib/chef/chef_fs/data_handler/role_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/role_data_handler.rb @@ -7,15 +7,15 @@ class Chef class RoleDataHandler < DataHandlerBase def normalize(role, entry) result = normalize_hash(role, { - "name" => remove_dot_json(entry.name), - "description" => "", - "json_class" => "Chef::Role", - "chef_type" => "role", - "default_attributes" => {}, - "override_attributes" => {}, - "run_list" => [], - "env_run_lists" => {}, - },) + "name" => remove_dot_json(entry.name), + "description" => "", + "json_class" => "Chef::Role", + "chef_type" => "role", + "default_attributes" => {}, + "override_attributes" => {}, + "run_list" => [], + "env_run_lists" => {}, + },) result["run_list"] = normalize_run_list(result["run_list"]) result["env_run_lists"].each_pair do |env, run_list| result["env_run_lists"][env] = normalize_run_list(run_list) diff --git a/lib/chef/chef_fs/data_handler/user_data_handler.rb b/lib/chef/chef_fs/data_handler/user_data_handler.rb index 392e67f822..09e794887a 100644 --- a/lib/chef/chef_fs/data_handler/user_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/user_data_handler.rb @@ -6,16 +6,16 @@ class Chef class UserDataHandler < DataHandlerBase def normalize(user, entry) normalize_hash(user, { - "name" => remove_dot_json(entry.name), - "username" => remove_dot_json(entry.name), - "display_name" => remove_dot_json(entry.name), - "admin" => false, - "json_class" => "Chef::WebUIUser", - "chef_type" => "webui_user", - "salt" => nil, - "password" => nil, - "openid" => nil, - },) + "name" => remove_dot_json(entry.name), + "username" => remove_dot_json(entry.name), + "display_name" => remove_dot_json(entry.name), + "admin" => false, + "json_class" => "Chef::WebUIUser", + "chef_type" => "webui_user", + "salt" => nil, + "password" => nil, + "openid" => nil, + },) end def preserve_key?(key) diff --git a/lib/chef/chef_fs/file_pattern.rb b/lib/chef/chef_fs/file_pattern.rb index 74be64cd84..5beec6dfdd 100644 --- a/lib/chef/chef_fs/file_pattern.rb +++ b/lib/chef/chef_fs/file_pattern.rb @@ -74,13 +74,13 @@ class Chef argument_is_absolute = Chef::ChefFS::PathUtils::is_absolute?(path) return false if is_absolute != argument_is_absolute - path = path[1,path.length-1] if argument_is_absolute + path = path[1, path.length - 1] if argument_is_absolute path_parts = Chef::ChefFS::PathUtils::split(path) # If the pattern is shorter than the path (or same size), children will be larger than the pattern, and will not match. return false if regexp_parts.length <= path_parts.length && !has_double_star # If the path doesn't match up to this point, children won't match either. - return false if path_parts.zip(regexp_parts).any? { |part,regexp| !regexp.nil? && !regexp.match(part) } + return false if path_parts.zip(regexp_parts).any? { |part, regexp| !regexp.nil? && !regexp.match(part) } # Otherwise, it's possible we could match: the path matches to this point, and the pattern is longer than the path. # TODO There is one edge case where the double star comes after some characters like abc**def--we could check whether the next # bit of path starts with abc in that case. @@ -111,7 +111,7 @@ class Chef # # This method assumes +could_match_children?(path)+ is +true+. def exact_child_name_under(path) - path = path[1,path.length-1] if Chef::ChefFS::PathUtils::is_absolute?(path) + path = path[1, path.length - 1] if Chef::ChefFS::PathUtils::is_absolute?(path) dirs_in_path = Chef::ChefFS::PathUtils::split(path).length return nil if exact_parts.length <= dirs_in_path return exact_parts[dirs_in_path] @@ -151,7 +151,7 @@ class Chef def match?(path) argument_is_absolute = Chef::ChefFS::PathUtils::is_absolute?(path) return false if is_absolute != argument_is_absolute - path = path[1,path.length-1] if argument_is_absolute + path = path[1, path.length - 1] if argument_is_absolute !!regexp.match(path) end @@ -275,15 +275,15 @@ class Chef exact = nil regexp << "." else - if part[0,1] == '\\' && part.length == 2 + if part[0, 1] == '\\' && part.length == 2 # backslash escapes are only supported on Unix, and are handled here by leaving the escape on (it means the same thing in a regex) - exact << part[1,1] if !exact.nil? - if regexp_escape_characters.include?(part[1,1]) + exact << part[1, 1] if !exact.nil? + if regexp_escape_characters.include?(part[1, 1]) regexp << part else - regexp << part[1,1] + regexp << part[1, 1] end - elsif part[0,1] == "[" && part.length > 1 + elsif part[0, 1] == "[" && part.length > 1 # [...] happens only on Unix, and is handled here by *not* backslashing (it means the same thing in and out of regex) exact = nil regexp << part diff --git a/lib/chef/chef_fs/file_system.rb b/lib/chef/chef_fs/file_system.rb index 6e25623a21..5865dd4b7c 100644 --- a/lib/chef/chef_fs/file_system.rb +++ b/lib/chef/chef_fs/file_system.rb @@ -95,9 +95,9 @@ class Chef # def self.resolve_path(entry, path) return entry if path.length == 0 - return resolve_path(entry.root, path) if path[0,1] == "/" && entry.root != entry - if path[0,1] == "/" - path = path[1,path.length-1] + return resolve_path(entry.root, path) if path[0, 1] == "/" && entry.root != entry + if path[0, 1] == "/" + path = path[1, path.length - 1] end result = entry diff --git a/lib/chef/chef_fs/file_system/chef_server/cookbook_artifacts_dir.rb b/lib/chef/chef_fs/file_system/chef_server/cookbook_artifacts_dir.rb index 020f8510b7..05f1330f75 100644 --- a/lib/chef/chef_fs/file_system/chef_server/cookbook_artifacts_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/cookbook_artifacts_dir.rb @@ -33,7 +33,6 @@ class Chef # - mysql-1a2b9e1298734dfe90444 # class CookbookArtifactsDir < CookbooksDir - def make_child_entry(name) result = @children.select { |child| child.name == name }.first if @children result || CookbookArtifactDir.new(name, self) 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 feb126f036..a6a062ab3c 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 @@ -58,7 +58,7 @@ class Chef :files => { :recursive => true }, :resources => { :ruby_only => true, :recursive => true }, :providers => { :ruby_only => true, :recursive => true }, - :root_files => { }, + :root_files => {}, } def add_child(child) @@ -99,7 +99,7 @@ class Chef parts = segment_file[:path].split("/") # Get or create the path to the file container = self - parts[0,parts.length-1].each do |part| + parts[0, parts.length - 1].each do |part| old_container = container container = old_container.children.select { |child| part == child.name }.first if !container @@ -108,7 +108,7 @@ class Chef end end # Create the file itself - container.add_child(CookbookFile.new(parts[parts.length-1], container, segment_file)) + container.add_child(CookbookFile.new(parts[parts.length - 1], container, segment_file)) end end @children = @children.sort_by { |c| c.name } diff --git a/lib/chef/chef_fs/file_system/chef_server/cookbooks_dir.rb b/lib/chef/chef_fs/file_system/chef_server/cookbooks_dir.rb index 75d7150f8e..ccbf9f9b67 100644 --- a/lib/chef/chef_fs/file_system/chef_server/cookbooks_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/cookbooks_dir.rb @@ -37,7 +37,6 @@ class Chef # mysql/ # class CookbooksDir < RestListDir - include Chef::Mixin::FileClass def make_child_entry(name) diff --git a/lib/chef/chef_fs/file_system/chef_server/organization_invites_entry.rb b/lib/chef/chef_fs/file_system/chef_server/organization_invites_entry.rb index 986a04ff4a..37b7af8b5e 100644 --- a/lib/chef/chef_fs/file_system/chef_server/organization_invites_entry.rb +++ b/lib/chef/chef_fs/file_system/chef_server/organization_invites_entry.rb @@ -37,7 +37,7 @@ class Chef def write(contents) desired_invites = minimize_value(Chef::JSONCompat.parse(contents, :create_additions => false)) - actual_invites = _read_json.inject({}) { |h,val| h[val["username"]] = val["id"]; h } + actual_invites = _read_json.inject({}) { |h, val| h[val["username"]] = val["id"]; h } invites = actual_invites.keys (desired_invites - invites).each do |invite| begin diff --git a/lib/chef/chef_fs/file_system/chef_server/policies_dir.rb b/lib/chef/chef_fs/file_system/chef_server/policies_dir.rb index ebb274a9eb..eb5945f250 100644 --- a/lib/chef/chef_fs/file_system/chef_server/policies_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/policies_dir.rb @@ -152,7 +152,6 @@ class Chef result end - end end end diff --git a/lib/chef/chef_fs/file_system/chef_server/policy_revision_entry.rb b/lib/chef/chef_fs/file_system/chef_server/policy_revision_entry.rb index 941c0268cc..bc3c1c23a1 100644 --- a/lib/chef/chef_fs/file_system/chef_server/policy_revision_entry.rb +++ b/lib/chef/chef_fs/file_system/chef_server/policy_revision_entry.rb @@ -8,9 +8,8 @@ class Chef # /policies/NAME-REVISION.json # Represents the actual data at /organizations/ORG/policies/NAME/revisions/REVISION class PolicyRevisionEntry < RestListEntry - # /policies/foo-1.0.0.json -> /policies/foo/revisions/1.0.0 - def api_path(options={}) + def api_path(options = {}) "#{parent.api_path}/#{policy_name}/revisions/#{revision_id}" end 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 6791b0cd29..488e9c0ed0 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 @@ -60,7 +60,6 @@ class Chef # the server version directly, and can't ask the server for a list of the endpoints it supports. # - # # Does GET /, assumes the result is of the format: # diff --git a/lib/chef/chef_fs/file_system/chef_server/rest_list_entry.rb b/lib/chef/chef_fs/file_system/chef_server/rest_list_entry.rb index 5af91e3768..85266848bd 100644 --- a/lib/chef/chef_fs/file_system/chef_server/rest_list_entry.rb +++ b/lib/chef/chef_fs/file_system/chef_server/rest_list_entry.rb @@ -38,10 +38,10 @@ class Chef end def api_child_name - if name.length < 5 || name[-5,5] != ".json" + if name.length < 5 || name[-5, 5] != ".json" raise "Invalid name #{path}: must end in .json" end - name[0,name.length-5] + name[0, name.length - 5] end def api_path @@ -180,7 +180,6 @@ class Chef end end end - end end end diff --git a/lib/chef/chef_fs/file_system/chef_server/versioned_cookbooks_dir.rb b/lib/chef/chef_fs/file_system/chef_server/versioned_cookbooks_dir.rb index 9abafed5e7..7b76c3bb7a 100644 --- a/lib/chef/chef_fs/file_system/chef_server/versioned_cookbooks_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/versioned_cookbooks_dir.rb @@ -39,7 +39,6 @@ class Chef # - mysql-1a2b9e1298734dfe90444 # class VersionedCookbooksDir < CookbooksDir - def make_child_entry(name) result = @children.select { |child| child.name == name }.first if @children result || VersionedCookbookDir.new(name, self) diff --git a/lib/chef/chef_fs/file_system/memory/memory_file.rb b/lib/chef/chef_fs/file_system/memory/memory_file.rb index 644273fa9f..7eabc8fcb1 100644 --- a/lib/chef/chef_fs/file_system/memory/memory_file.rb +++ b/lib/chef/chef_fs/file_system/memory/memory_file.rb @@ -9,6 +9,7 @@ class Chef super(name, parent) @value = value end + def read return @value end diff --git a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbooks_dir.rb b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbooks_dir.rb index 84f665066e..fa6ce9ba9e 100644 --- a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbooks_dir.rb +++ b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbooks_dir.rb @@ -59,7 +59,7 @@ class Chef # Use the copy/diff algorithm to copy it down so we don't destroy # chefignored data. This is terribly un-thread-safe. - Chef::ChefFS::FileSystem.copy_to(Chef::ChefFS::FilePattern.new("/#{cookbook_path}"), from_fs, child, nil, {:purge => true}) + Chef::ChefFS::FileSystem.copy_to(Chef::ChefFS::FilePattern.new("/#{cookbook_path}"), from_fs, child, nil, { :purge => true }) # Write out .uploaded-cookbook-version.json cookbook_file_path = File.join(file_path, cookbook_name) 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 37bd6fa1ac..b3f41b5bad 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 @@ -39,7 +39,6 @@ class Chef module ChefFS module FileSystem module Repository - # # Represents the root of a local Chef repository, with directories for # nodes, cookbooks, roles, etc. under it. @@ -60,7 +59,7 @@ class Chef # [chef_config] - a hash of options that looks suspiciously like the ones # stored in Chef::Config, containing at least these keys: # :versioned_cookbooks:: whether to include versions in cookbook names - def initialize(child_paths, root_paths=[], chef_config=Chef::Config) + def initialize(child_paths, root_paths = [], chef_config = Chef::Config) super("", nil) @child_paths = child_paths @root_paths = root_paths diff --git a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_versioned_cookbook_dir.rb b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_versioned_cookbook_dir.rb index f9a66240eb..5dc74d85da 100644 --- a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_versioned_cookbook_dir.rb +++ b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_versioned_cookbook_dir.rb @@ -29,7 +29,7 @@ class Chef # We need the canonical cookbook name if we are using versioned cookbooks, but we don't # want to spend a lot of time adding code to the main Chef libraries canonical_name = canonical_cookbook_name(File.basename(file_path)) - raise "When versioned_cookbooks mode is on, cookbook #{file_path} must match format -x.y.z" unless canonical_name + raise "When versioned_cookbooks mode is on, cookbook #{file_path} must match format -x.y.z" unless canonical_name # KLUDGE: We shouldn't have to use instance_variable_set loader.instance_variable_set(:@cookbook_name, canonical_name) loader.load_cookbooks 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 ac6c85db22..bee017f7a8 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 @@ -44,14 +44,14 @@ class Chef # Except cookbooks and data bag dirs, all things must be json files begin Dir.entries(file_path).sort. - map { |child_name| make_child_entry(child_name) }. - select { |child| child && can_have_child?(child.name, child.dir?) } + map { |child_name| make_child_entry(child_name) }. + select { |child| child && can_have_child?(child.name, child.dir?) } rescue Errno::ENOENT raise Chef::ChefFS::FileSystem::NotFoundError.new(self, $!) end end - def create_child(child_name, file_contents=nil) + def create_child(child_name, file_contents = nil) child = make_child_entry(child_name) if child.exists? raise Chef::ChefFS::FileSystem::AlreadyExistsError.new(:create_child, child) @@ -93,7 +93,7 @@ class Chef def read begin - File.open(file_path, "rb") {|f| f.read} + File.open(file_path, "rb") { |f| f.read } rescue Errno::ENOENT raise Chef::ChefFS::FileSystem::NotFoundError.new(self, $!) end diff --git a/lib/chef/chef_fs/knife.rb b/lib/chef/chef_fs/knife.rb index 90d4eddc07..399bf1c434 100644 --- a/lib/chef/chef_fs/knife.rb +++ b/lib/chef/chef_fs/knife.rb @@ -111,7 +111,7 @@ class Chef end # Use the original path because we can't be sure. inferred_path = arg - elsif arg[0,1] == "~" + elsif arg[0, 1] == "~" # Let's be nice and fix it if possible - but warn the user. ui.warn("A path relative to a user home directory has been provided: #{arg}") ui.warn("Paths provided need to be rooted at the chef-repo being considered or be relative paths.") diff --git a/lib/chef/chef_fs/parallelizer.rb b/lib/chef/chef_fs/parallelizer.rb index 6590431d91..5d05f41e94 100644 --- a/lib/chef/chef_fs/parallelizer.rb +++ b/lib/chef/chef_fs/parallelizer.rb @@ -54,7 +54,7 @@ class Chef def resize(to_threads, wait = true, timeout = nil) if to_threads < num_threads - threads_to_stop = @threads[to_threads..num_threads-1] + threads_to_stop = @threads[to_threads..num_threads - 1] @threads = @threads.slice(0, to_threads) threads_to_stop.each do |thread| @stop_thread[thread] = true diff --git a/lib/chef/chef_fs/parallelizer/flatten_enumerable.rb b/lib/chef/chef_fs/parallelizer/flatten_enumerable.rb index 7321aa0664..6094fab493 100644 --- a/lib/chef/chef_fs/parallelizer/flatten_enumerable.rb +++ b/lib/chef/chef_fs/parallelizer/flatten_enumerable.rb @@ -23,7 +23,7 @@ class Chef def flatten(value, levels, &block) if levels != 0 && value.respond_to?(:each) && !value.is_a?(String) value.each do |child| - flatten(child, levels.nil? ? levels : levels-1, &block) + flatten(child, levels.nil? ? levels : levels - 1, &block) end else block.call(value) diff --git a/lib/chef/chef_fs/parallelizer/parallel_enumerable.rb b/lib/chef/chef_fs/parallelizer/parallel_enumerable.rb index 60f283eabe..8df6a76e13 100644 --- a/lib/chef/chef_fs/parallelizer/parallel_enumerable.rb +++ b/lib/chef/chef_fs/parallelizer/parallel_enumerable.rb @@ -92,7 +92,7 @@ class Chef end end - def first(n=nil) + def first(n = nil) if n restricted_copy(@input_enumerable.first(n)).to_a else diff --git a/lib/chef/chef_fs/path_utils.rb b/lib/chef/chef_fs/path_utils.rb index 66dbd4f13b..4f889ba37f 100644 --- a/lib/chef/chef_fs/path_utils.rb +++ b/lib/chef/chef_fs/path_utils.rb @@ -22,7 +22,6 @@ require "pathname" class Chef module ChefFS class PathUtils - # A Chef-FS path is a path in a chef-repository that can be used to address # both files on a local file-system as well as objects on a chef server. # These paths are stricter than file-system paths allowed on various OSes. @@ -64,6 +63,7 @@ class Chef def self.is_absolute?(path) !!(path =~ /^#{regexp_path_separator}/) end + # Given a path which may only be partly real (i.e. /x/y/z when only /x exists, # or /x/y/*/blah when /x/y/z/blah exists), call File.realpath on the biggest # part that actually exists. The paths operated on here are not Chef-FS paths. @@ -114,13 +114,12 @@ class Chef return nil unless PathUtils.os_path_eq?(candidate_fragment, ancestor) if ancestor.length == path.length "" - elsif path[ancestor.length,1] =~ /#{PathUtils.regexp_path_separator}/ - path[ancestor.length+1..-1] + elsif path[ancestor.length, 1] =~ /#{PathUtils.regexp_path_separator}/ + path[ancestor.length + 1..-1] else nil end end - end end end diff --git a/lib/chef/client.rb b/lib/chef/client.rb index d5bd7a1928..7d2dcf8057 100644 --- a/lib/chef/client.rb +++ b/lib/chef/client.rb @@ -78,6 +78,7 @@ class Chef def node run_status.node end + def node=(value) run_status.node = value end @@ -151,7 +152,7 @@ class Chef # @option args [Array] :specific_recipes A list of recipe file paths # to load after the run list has been loaded. # - def initialize(json_attribs=nil, args={}) + def initialize(json_attribs = nil, args = {}) @json_attribs = json_attribs || {} @ohai = Ohai::System.new @@ -397,10 +398,10 @@ class Chef # it is fed non-UTF8 data. # # @api private - def rest_clean(client_name=node_name, config=Chef::Config) + def rest_clean(client_name = node_name, config = Chef::Config) @rest_clean ||= Chef::ServerAPI.new(config[:chef_server_url], client_name: client_name, - signing_key_filename: config[:client_key], validate_utf8: false) + signing_key_filename: config[:client_key], validate_utf8: false) end # Resource reporters send event information back to the chef server for @@ -605,7 +606,7 @@ class Chef # # @api private # - def register(client_name=node_name, config=Chef::Config) + def register(client_name = node_name, config = Chef::Config) if !config[:client_key] events.skipping_registration(client_name, config) Chef::Log.debug("Client key is unspecified - skipping registration") @@ -620,7 +621,7 @@ class Chef end # We now have the client key, and should use it from now on. @rest = Chef::ServerAPI.new(config[:chef_server_url], client_name: client_name, - signing_key_filename: config[:client_key]) + signing_key_filename: config[:client_key]) # force initialization of the rest_clean API object rest_clean(client_name, config) register_reporters @@ -942,7 +943,7 @@ class Chef # if it's an array, go through it and check each one, raise error at the last one if no files are found cookbook_paths = Array(Chef::Config[:cookbook_path]) Chef::Log.debug "Loading from cookbook_path: #{cookbook_paths.map { |path| File.expand_path(path) }.join(', ')}" - if cookbook_paths.all? {|path| empty_directory?(path) } + if cookbook_paths.all? { |path| empty_directory?(path) } msg = "None of the cookbook paths set in Chef::Config[:cookbook_path], #{cookbook_paths.inspect}, contain any cookbooks" Chef::Log.fatal(msg) raise Chef::Exceptions::CookbookNotFound, msg @@ -950,7 +951,6 @@ class Chef else Chef::Log.warn("Node #{node_name} has an empty run list.") if run_context.node.run_list.empty? end - end def has_admin_privileges? diff --git a/lib/chef/config.rb b/lib/chef/config.rb index 549872bfd7..8f357c5962 100644 --- a/lib/chef/config.rb +++ b/lib/chef/config.rb @@ -52,7 +52,6 @@ class Chef # * The functionality isn't likely to be useful outside of Chef # * The functionality makes use of a dependency we don't want to add to chef-config class Config - default :event_loggers do evt_loggers = [] if ChefConfig.windows? && !(Chef::Platform.windows_server_2003? || @@ -80,6 +79,5 @@ class Chef value end end - end end diff --git a/lib/chef/config_fetcher.rb b/lib/chef/config_fetcher.rb index 13f9fc3825..d8446d6b14 100644 --- a/lib/chef/config_fetcher.rb +++ b/lib/chef/config_fetcher.rb @@ -5,7 +5,6 @@ require "chef/json_compat" class Chef class ConfigFetcher - attr_reader :config_location def initialize(config_location) diff --git a/lib/chef/constants.rb b/lib/chef/constants.rb index b45bc12374..f32c3e6654 100644 --- a/lib/chef/constants.rb +++ b/lib/chef/constants.rb @@ -20,6 +20,7 @@ class Chef def NOT_PASSED.to_s "NOT_PASSED" end + def NOT_PASSED.inspect to_s end diff --git a/lib/chef/cookbook/chefignore.rb b/lib/chef/cookbook/chefignore.rb index f0cbf12d4e..ca5591688e 100644 --- a/lib/chef/cookbook/chefignore.rb +++ b/lib/chef/cookbook/chefignore.rb @@ -19,7 +19,6 @@ class Chef class Cookbook class Chefignore - COMMENTS_AND_WHITESPACE = /^\s*(?:#.*)?$/ attr_reader :ignores @@ -40,7 +39,7 @@ class Chef end def ignored?(file_name) - @ignores.any? {|glob| File.fnmatch?(glob, file_name)} + @ignores.any? { |glob| File.fnmatch?(glob, file_name) } end private @@ -72,4 +71,3 @@ class Chef end end end - diff --git a/lib/chef/cookbook/cookbook_collection.rb b/lib/chef/cookbook/cookbook_collection.rb index a9de718902..7fa30b66d1 100644 --- a/lib/chef/cookbook/cookbook_collection.rb +++ b/lib/chef/cookbook/cookbook_collection.rb @@ -30,15 +30,14 @@ class Chef # objects for lazily-loaded remote cookbooks), it gets transformed # into this. class CookbookCollection < Mash - # The input is a mapping of cookbook name to CookbookVersion objects. We # simply extract them - def initialize(cookbook_versions={}) + def initialize(cookbook_versions = {}) super() do |hash, key| raise Chef::Exceptions::CookbookNotFound, "Cookbook #{key} not found. " << "If you're loading #{key} from another cookbook, make sure you configure the dependency in your metadata" end - cookbook_versions.each{ |cookbook_name, cookbook_version| self[cookbook_name] = cookbook_version } + cookbook_versions.each { |cookbook_name, cookbook_version| self[cookbook_name] = cookbook_version } end # Validates that the cookbook metadata allows it to run on this instance. diff --git a/lib/chef/cookbook/cookbook_version_loader.rb b/lib/chef/cookbook/cookbook_version_loader.rb index 370a77ecaf..c420179145 100644 --- a/lib/chef/cookbook/cookbook_version_loader.rb +++ b/lib/chef/cookbook/cookbook_version_loader.rb @@ -7,7 +7,6 @@ require "chef/util/path_helper" class Chef class Cookbook class CookbookVersionLoader - FILETYPES_SUBJECT_TO_IGNORE = [ :attribute_filenames, :definition_filenames, :recipe_filenames, @@ -32,7 +31,7 @@ class Chef attr_reader :metadata_error - def initialize(path, chefignore=nil) + def initialize(path, chefignore = nil) @cookbook_path = File.expand_path( path ) # cookbook_path from which this was loaded # We keep a list of all cookbook paths that have been merged in @cookbook_paths = [ cookbook_path ] diff --git a/lib/chef/cookbook/file_system_file_vendor.rb b/lib/chef/cookbook/file_system_file_vendor.rb index 91f1c9f853..71c60bc85e 100644 --- a/lib/chef/cookbook/file_system_file_vendor.rb +++ b/lib/chef/cookbook/file_system_file_vendor.rb @@ -30,7 +30,6 @@ class Chef # locations, since in the chef-client case, that information is # non-sensical. class FileSystemFileVendor < FileVendor - attr_reader :cookbook_name attr_reader :repo_paths @@ -53,7 +52,6 @@ class Chef location end - end end end diff --git a/lib/chef/cookbook/file_vendor.rb b/lib/chef/cookbook/file_vendor.rb index 2501d4b8de..96aa5ee77d 100644 --- a/lib/chef/cookbook/file_vendor.rb +++ b/lib/chef/cookbook/file_vendor.rb @@ -17,13 +17,11 @@ # limitations under the License. # - class Chef class Cookbook # == Chef::Cookbook::FileVendor # This class handles fetching of cookbook files based on specificity. class FileVendor - @vendor_class = nil @initialization_options = nil @@ -66,7 +64,6 @@ class Chef def get_filename(filename) raise NotImplemented, "Subclasses must implement this method" end - end end end diff --git a/lib/chef/cookbook/metadata.rb b/lib/chef/cookbook/metadata.rb index 8050c4f892..916297a483 100644 --- a/lib/chef/cookbook/metadata.rb +++ b/lib/chef/cookbook/metadata.rb @@ -30,12 +30,10 @@ require "chef/json_compat" class Chef class Cookbook - # == Chef::Cookbook::Metadata # Chef::Cookbook::Metadata provides a convenient DSL for declaring metadata # about Chef Cookbooks. class Metadata - NAME = "name".freeze DESCRIPTION = "description".freeze LONG_DESCRIPTION = "long_description".freeze @@ -65,14 +63,14 @@ class Chef :replacing, :attributes, :groupings, :recipes, :version, :source_url, :issues_url, :privacy, :chef_versions, :ohai_versions ] - VERSION_CONSTRAINTS = {:depends => DEPENDENCIES, - :recommends => RECOMMENDATIONS, - :suggests => SUGGESTIONS, - :conflicts => CONFLICTING, - :provides => PROVIDING, - :replaces => REPLACING, - :chef_version => CHEF_VERSIONS, - :ohai_version => OHAI_VERSIONS } + VERSION_CONSTRAINTS = { :depends => DEPENDENCIES, + :recommends => RECOMMENDATIONS, + :suggests => SUGGESTIONS, + :conflicts => CONFLICTING, + :provides => PROVIDING, + :replaces => REPLACING, + :chef_version => CHEF_VERSIONS, + :ohai_version => OHAI_VERSIONS } include Chef::Mixin::ParamsValidate include Chef::Mixin::FromFile @@ -105,7 +103,7 @@ class Chef # === Returns # metadata def initialize - @name = nil + @name = nil @description = "" @long_description = "" @@ -173,7 +171,7 @@ class Chef # # === Returns # maintainer:: Returns the current maintainer. - def maintainer(arg=nil) + def maintainer(arg = nil) set_or_return( :maintainer, arg, @@ -188,7 +186,7 @@ class Chef # # === Returns # maintainer_email:: Returns the current maintainer email. - def maintainer_email(arg=nil) + def maintainer_email(arg = nil) set_or_return( :maintainer_email, arg, @@ -203,7 +201,7 @@ class Chef # # === Returns # license:: Returns the current license - def license(arg=nil) + def license(arg = nil) set_or_return( :license, arg, @@ -218,7 +216,7 @@ class Chef # # === Returns # description:: Returns the description - def description(arg=nil) + def description(arg = nil) set_or_return( :description, arg, @@ -233,7 +231,7 @@ class Chef # # === Returns # long_description:: Returns the long description - def long_description(arg=nil) + def long_description(arg = nil) set_or_return( :long_description, arg, @@ -249,7 +247,7 @@ class Chef # # === Returns # version:: Returns the current version - def version(arg=nil) + def version(arg = nil) if arg @version = Chef::Version.new(arg) end @@ -264,7 +262,7 @@ class Chef # # === Returns # name:: Returns the current cookbook name. - def name(arg=nil) + def name(arg = nil) set_or_return( :name, arg, @@ -321,7 +319,7 @@ class Chef # === Returns # versions:: Returns the list of versions for the platform def recommends(cookbook, *version_args) - version = new_args_format(:recommends, cookbook, version_args) + version = new_args_format(:recommends, cookbook, version_args) constraint = validate_version_constraint(:recommends, cookbook, version) @recommendations[cookbook] = constraint.to_s @recommendations[cookbook] @@ -622,11 +620,11 @@ class Chef metadata = new() VERSION_CONSTRAINTS.each do |dependency_type, hash_key| if dependency_group = o[hash_key] - dependency_group.each do |cb_name, constraints| - if metadata.respond_to?(method_name) - metadata.public_send(method_name, cb_name, *Array(constraints)) - end - end + dependency_group.each do |cb_name, constraints| + if metadata.respond_to?(method_name) + metadata.public_send(method_name, cb_name, *Array(constraints)) + end + end end end true @@ -644,7 +642,7 @@ class Chef # # === Returns # source_url:: Returns the current source URL. - def source_url(arg=nil) + def source_url(arg = nil) set_or_return( :source_url, arg, @@ -659,7 +657,7 @@ class Chef # # === Returns # issues_url:: Returns the current issues URL. - def issues_url(arg=nil) + def issues_url(arg = nil) set_or_return( :issues_url, arg, @@ -676,7 +674,7 @@ class Chef # === Returns # privacy:: Whether this cookbook is private or not # - def privacy(arg=nil) + def privacy(arg = nil) set_or_return( :privacy, arg, @@ -733,14 +731,14 @@ class Chef elsif version_constraints.size == 1 version_constraints.first else - msg=<<-OBSOLETED + msg = <<-OBSOLETED The dependency specification syntax you are using is no longer valid. You may not specify more than one version constraint for a particular cookbook. Consult https://docs.chef.io/config_rb_metadata.html for the updated syntax. -Called by: #{caller_name} '#{dep_name}', #{version_constraints.map {|vc| vc.inspect}.join(", ")} +Called by: #{caller_name} '#{dep_name}', #{version_constraints.map { |vc| vc.inspect }.join(", ")} Called from: -#{caller[0...5].map {|line| " " + line}.join("\n")} +#{caller[0...5].map { |line| " " + line }.join("\n")} OBSOLETED raise Exceptions::ObsoleteDependencySyntax, msg end @@ -751,7 +749,7 @@ OBSOLETED rescue Chef::Exceptions::InvalidVersionConstraint => e Log.debug(e) - msg=<<-INVALID + msg = <<-INVALID The version constraint syntax you are using is not valid. If you recently upgraded to Chef 0.10.0, be aware that you no may longer use "<<" and ">>" for 'less than' and 'greater than'; use '<' and '>' instead. @@ -759,7 +757,7 @@ Consult https://docs.chef.io/config_rb_metadata.html for more information. Called by: #{caller_name} '#{dep_name}', '#{constraint_str}' Called from: -#{caller[0...5].map {|line| " " + line}.join("\n")} +#{caller[0...5].map { |line| " " + line }.join("\n")} INVALID raise Exceptions::InvalidVersionConstraint, msg end @@ -773,7 +771,7 @@ INVALID def validate_string_array(arry) if arry.kind_of?(Array) arry.each do |choice| - validate( {:choice => choice}, {:choice => {:kind_of => String}} ) + validate( { :choice => choice }, { :choice => { :kind_of => String } } ) end end end @@ -783,28 +781,28 @@ INVALID # Raise an exception if the members of the array do not match the defaults # === Parameters # opts:: The options hash - def validate_choice_array(opts) - if opts[:choice].kind_of?(Array) - case opts[:type] - when "string" - validator = [ String ] - when "array" - validator = [ Array ] - when "hash" - validator = [ Hash ] - when "symbol" - validator = [ Symbol ] - when "boolean" - validator = [ TrueClass, FalseClass ] - when "numeric" - validator = [ Numeric ] - end + def validate_choice_array(opts) + if opts[:choice].kind_of?(Array) + case opts[:type] + when "string" + validator = [ String ] + when "array" + validator = [ Array ] + when "hash" + validator = [ Hash ] + when "symbol" + validator = [ Symbol ] + when "boolean" + validator = [ TrueClass, FalseClass ] + when "numeric" + validator = [ Numeric ] + end - opts[:choice].each do |choice| - validate( {:choice => choice}, {:choice => {:kind_of => validator}} ) - end + opts[:choice].each do |choice| + validate( { :choice => choice }, { :choice => { :kind_of => validator } } ) end end + end # For backwards compatibility, remap Boolean values to String # true is mapped to "required" @@ -864,7 +862,6 @@ INVALID acc end end - end #== Chef::Cookbook::MinimalMetadata @@ -881,6 +878,5 @@ INVALID from_hash(params) end end - end end diff --git a/lib/chef/cookbook/remote_file_vendor.rb b/lib/chef/cookbook/remote_file_vendor.rb index d483c54f8f..e02fbeac56 100644 --- a/lib/chef/cookbook/remote_file_vendor.rb +++ b/lib/chef/cookbook/remote_file_vendor.rb @@ -24,7 +24,6 @@ class Chef # This FileVendor loads files by either fetching them from the local cache, or # if not available, loading them from the remote server. class RemoteFileVendor < FileVendor - attr_reader :rest attr_reader :cookbook_name @@ -45,7 +44,7 @@ class Chef end raise "No such segment #{segment} in cookbook #{@cookbook_name}" unless @manifest[segment] - found_manifest_record = @manifest[segment].find {|manifest_record| manifest_record[:path] == filename } + found_manifest_record = @manifest[segment].find { |manifest_record| manifest_record[:path] == filename } raise "No such file #{filename} in #{@cookbook_name}" unless found_manifest_record cache_filename = File.join("cookbooks", @cookbook_name, found_manifest_record["path"]) @@ -81,7 +80,6 @@ class Chef def validate_cached_copy(cache_filename) CookbookCacheCleaner.instance.mark_file_as_valid(cache_filename) end - end end end diff --git a/lib/chef/cookbook/synchronizer.rb b/lib/chef/cookbook/synchronizer.rb index 9955bae6bb..e5b6f2ede9 100644 --- a/lib/chef/cookbook/synchronizer.rb +++ b/lib/chef/cookbook/synchronizer.rb @@ -4,13 +4,11 @@ require "chef/server_api" require "singleton" class Chef - # Keep track of the filenames that we use in both eager cookbook # downloading (during sync_cookbooks) and lazy (during the run # itself, through FileVendor). After the run is over, clean up the # cache. class CookbookCacheCleaner - attr_accessor :skip_removal # Setup a notification to clear the valid_cache_entries when a Chef client @@ -56,7 +54,6 @@ class Chef Chef::Log.info("Skipping removal of unused files from the cache") end end - end # Synchronizes the locally cached copies of cookbooks with the files on the @@ -141,7 +138,7 @@ class Chef # === Returns # true:: Always returns true def sync_cookbooks - Chef::Log.info("Loading cookbooks [#{cookbooks.map {|ckbk| ckbk.name + '@' + ckbk.version}.join(', ')}]") + Chef::Log.info("Loading cookbooks [#{cookbooks.map { |ckbk| ckbk.name + '@' + ckbk.version }.join(', ')}]") Chef::Log.debug("Cookbooks detail: #{cookbooks.inspect}") clear_obsoleted_cookbooks @@ -176,7 +173,7 @@ class Chef # Saves the full_path to the file of the cookbook to be updated # in the manifest later def save_full_file_path(file, full_path) - @cookbook_full_file_paths[file.cookbook] ||= { } + @cookbook_full_file_paths[file.cookbook] ||= {} @cookbook_full_file_paths[file.cookbook][file.segment] ||= [ ] @cookbook_full_file_paths[file.cookbook][file.segment] << full_path end @@ -289,6 +286,5 @@ class Chef def server_api Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end - end end diff --git a/lib/chef/cookbook/syntax_check.rb b/lib/chef/cookbook/syntax_check.rb index d6849584c4..3181afd563 100644 --- a/lib/chef/cookbook/syntax_check.rb +++ b/lib/chef/cookbook/syntax_check.rb @@ -29,7 +29,6 @@ class Chef # Encapsulates the process of validating the ruby syntax of files in Chef # cookbooks. class SyntaxCheck - # == Chef::Cookbook::SyntaxCheck::PersistentSet # Implements set behavior with disk-based persistence. Objects in the set # are expected to be strings containing only characters that are valid in @@ -38,12 +37,11 @@ class Chef # This class is used to track which files have been syntax checked so # that known good files are not rechecked. class PersistentSet - attr_reader :cache_path # Create a new PersistentSet. Values in the set are persisted by # creating a file in the +cache_path+ directory. - def initialize(cache_path=Chef::Config[:syntax_check_cache_path]) + def initialize(cache_path = Chef::Config[:syntax_check_cache_path]) @cache_path = cache_path @cache_path_created = false end @@ -66,7 +64,6 @@ class Chef FileUtils.mkdir_p(cache_path) @cache_path_created = true end - end include Chef::Mixin::ShellOut @@ -82,7 +79,7 @@ class Chef # Creates a new SyntaxCheck given the +cookbook_name+ and a +cookbook_path+. # If no +cookbook_path+ is given, +Chef::Config.cookbook_path+ is used. - def self.for_cookbook(cookbook_name, cookbook_path=nil) + def self.for_cookbook(cookbook_name, cookbook_path = nil) cookbook_path ||= Chef::Config.cookbook_path unless cookbook_path raise ArgumentError, "Cannot find cookbook #{cookbook_name} unless Chef::Config.cookbook_path is set or an explicit cookbook path is given" @@ -209,7 +206,7 @@ class Chef # Debug a syntax error in a template. def invalid_erb_file(erb_file, error_message) - file_relative_path = erb_file[/^#{Regexp.escape(cookbook_path+File::Separator)}(.*)/, 1] + 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) } nil @@ -244,7 +241,7 @@ class Chef # Debugs ruby syntax errors by printing the path to the file and any # diagnostic info given in +error_message+ def invalid_ruby_file(ruby_file, error_message) - file_relative_path = ruby_file[/^#{Regexp.escape(cookbook_path+File::Separator)}(.*)/, 1] + 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) } false @@ -254,7 +251,6 @@ class Chef def ruby Gem.ruby end - end end end diff --git a/lib/chef/cookbook_loader.rb b/lib/chef/cookbook_loader.rb index 27e0bc5aaa..df5a475152 100644 --- a/lib/chef/cookbook_loader.rb +++ b/lib/chef/cookbook_loader.rb @@ -30,7 +30,6 @@ require "chef/cookbook/metadata" # class Chef class CookbookLoader - attr_reader :cookbooks_by_name attr_reader :merged_cookbooks attr_reader :cookbook_paths @@ -44,7 +43,7 @@ class Chef @cookbooks_by_name = Mash.new @loaded_cookbooks = {} @metadata = Mash.new - @cookbooks_paths = Hash.new {|h,k| h[k] = []} # for deprecation warnings + @cookbooks_paths = Hash.new { |h, k| h[k] = [] } # for deprecation warnings @chefignores = {} @repo_paths = repo_paths.map do |repo_path| repo_path = File.expand_path(repo_path) @@ -62,7 +61,7 @@ class Chef def merged_cookbook_paths # for deprecation warnings merged_cookbook_paths = {} - @merged_cookbooks.each {|c| merged_cookbook_paths[c] = @cookbooks_paths[c]} + @merged_cookbooks.each { |c| merged_cookbook_paths[c] = @cookbooks_paths[c] } merged_cookbook_paths end @@ -119,7 +118,7 @@ class Chef alias :key? :has_key? def each - @cookbooks_by_name.keys.sort { |a,b| a.to_s <=> b.to_s }.each do |cname| + @cookbooks_by_name.keys.sort { |a, b| a.to_s <=> b.to_s }.each do |cname| yield(cname, @cookbooks_by_name[cname]) end end @@ -177,6 +176,5 @@ class Chef def cookbook_loaders_for(cookbook_name) @loaders_by_name[cookbook_name.to_s] end - end end diff --git a/lib/chef/cookbook_manifest.rb b/lib/chef/cookbook_manifest.rb index f3df5c48aa..1295266b19 100644 --- a/lib/chef/cookbook_manifest.rb +++ b/lib/chef/cookbook_manifest.rb @@ -19,11 +19,9 @@ require "chef/util/path_helper" require "chef/log" class Chef - # Handles the details of representing a cookbook in JSON form for uploading # to a Chef Server. class CookbookManifest - # Duplicates the same constant in CookbookVersion. We cannot remove it # there because it is treated by other code as part of CookbookVersion's # public API (also used in some deprecated methods). @@ -152,6 +150,7 @@ class Chef def named_cookbook_url "#{cookbook_url_path}/#{name}" end + # Adds the `force=true` parameter to the upload URL. This allows # the user to overwrite a frozen cookbook (a PUT against the # normal #save_url raises a 409 Conflict in this case). @@ -169,7 +168,7 @@ class Chef COOKBOOK_SEGMENTS.each do |segment| next unless @manifest.has_key?(segment) - filenames = @manifest[segment].map{|manifest_record| manifest_record["name"]} + filenames = @manifest[segment].map { |manifest_record| manifest_record["name"] } cookbook_version.replace_segment_filenames(segment, filenames) end @@ -185,16 +184,16 @@ class Chef # See #preferred_manifest_record for a description an individual manifest record. def generate_manifest manifest = Mash.new({ - :recipes => Array.new, - :definitions => Array.new, - :libraries => Array.new, - :attributes => Array.new, - :files => Array.new, - :templates => Array.new, - :resources => Array.new, - :providers => Array.new, - :root_files => Array.new, - },) + :recipes => Array.new, + :definitions => Array.new, + :libraries => Array.new, + :attributes => Array.new, + :files => Array.new, + :templates => Array.new, + :resources => Array.new, + :providers => Array.new, + :root_files => Array.new, + },) @checksums = {} if !root_paths || root_paths.size == 0 @@ -212,11 +211,11 @@ class Chef csum = checksum_cookbook_file(segment_file) @checksums[csum] = segment_file rs = Mash.new({ - :name => file_name, - :path => path, - :checksum => csum, - :specificity => specificity, - },) + :name => file_name, + :path => path, + :checksum => csum, + :specificity => specificity, + },) manifest[segment] << rs end diff --git a/lib/chef/cookbook_site_streaming_uploader.rb b/lib/chef/cookbook_site_streaming_uploader.rb index 6e669f24ba..71ce3f86c2 100644 --- a/lib/chef/cookbook_site_streaming_uploader.rb +++ b/lib/chef/cookbook_site_streaming_uploader.rb @@ -30,11 +30,9 @@ class Chef # # inspired by http://stanislavvitvitskiy.blogspot.com/2008/12/multipart-post-in-ruby.html class CookbookSiteStreamingUploader - DefaultHeaders = { "accept" => "application/json", "x-chef-version" => ::Chef::VERSION } class << self - def create_build_dir(cookbook) tmp_cookbook_path = Tempfile.new("chef-#{cookbook.name}-build") tmp_cookbook_path.close @@ -114,14 +112,14 @@ class Chef # TODO: tim: 2009-12-28: It'd be nice to remove this special case, and # always hash the entire request body. In the file case it would just be # expanded multipart text - the entire body of the POST. - content_body = parts.inject("") { |result,part| result + part.read(0, part.size) } + content_body = parts.inject("") { |result, part| result + part.read(0, part.size) } content_file.rewind if content_file # we consumed the file for the above operation, so rewind it. signing_options = { - :http_method=>http_verb, - :path=>url.path, - :user_id=>user_id, - :timestamp=>timestamp} + :http_method => http_verb, + :path => url.path, + :user_id => user_id, + :timestamp => timestamp } (content_file && signing_options[:file] = content_file) || (signing_options[:body] = (content_body || "")) headers.merge!(Mixlib::Authentication::SignedHeaderAuth.signing_object(signing_options).sign(secret_key)) @@ -129,7 +127,7 @@ class Chef content_file.rewind if content_file # net/http doesn't like symbols for header keys, so we'll to_s each one just in case - headers = DefaultHeaders.merge(Hash[*headers.map{ |k,v| [k.to_s, v] }.flatten]) + headers = DefaultHeaders.merge(Hash[*headers.map { |k, v| [k.to_s, v] }.flatten]) req = case http_verb when :put @@ -160,7 +158,6 @@ class Chef end res end - end class StreamPart @@ -201,7 +198,7 @@ class Chef end def size - @parts.inject(0) {|size, part| size + part.size} + @parts.inject(0) { |size, part| size + part.size } end def read(how_much, dst_buf = nil) @@ -239,6 +236,5 @@ class Chef dst_buf ? dst_buf.replace(result || "") : result end end - end end diff --git a/lib/chef/cookbook_uploader.rb b/lib/chef/cookbook_uploader.rb index a9f255df43..e409d78d30 100644 --- a/lib/chef/cookbook_uploader.rb +++ b/lib/chef/cookbook_uploader.rb @@ -13,7 +13,6 @@ require "chef/server_api" class Chef class CookbookUploader - attr_reader :cookbooks attr_reader :path attr_reader :opts @@ -37,7 +36,7 @@ class Chef # in Chef::Config. # * :concurrency An integer that decided how many threads will be used to # perform concurrent uploads - def initialize(cookbooks, opts={}) + def initialize(cookbooks, opts = {}) @opts = opts @cookbooks = Array(cookbooks) @rest = opts[:rest] || Chef::ServerAPI.new(Chef::Config[:chef_server_url]) @@ -55,7 +54,7 @@ class Chef checksum_files.merge!(cb.checksums) end - checksums = checksum_files.inject({}){|memo,elt| memo[elt.first]=nil ; memo} + checksums = checksum_files.inject({}) { |memo, elt| memo[elt.first] = nil ; memo } new_sandbox = rest.post("sandboxes", { :checksums => checksums }) Chef::Log.info("Uploading files") @@ -83,7 +82,7 @@ class Chef # in eventual consistency) retries = 0 begin - rest.put(sandbox_url, {:is_completed => true}) + rest.put(sandbox_url, { :is_completed => true }) rescue Net::HTTPServerException => e if e.message =~ /^400/ && (retries += 1) <= 5 sleep 2 @@ -95,7 +94,6 @@ class Chef # files are uploaded, so save the manifest cookbooks.each do |cb| - manifest = Chef::CookbookManifest.new(cb, policy_mode: policy_mode?) save_url = opts[:force] ? manifest.force_save_url : manifest.save_url @@ -120,7 +118,7 @@ class Chef # but we need the base64 encoding for the content-md5 # header checksum64 = Base64.encode64([checksum].pack("H*")).strip - file_contents = File.open(file, "rb") {|f| f.read} + file_contents = File.open(file, "rb") { |f| f.read } # Custom headers. 'content-type' disables JSON serialization of the request body. headers = { "content-type" => "application/x-binary", "content-md5" => checksum64, "accept" => "application/json" } @@ -152,6 +150,5 @@ class Chef def policy_mode? @policy_mode end - end end diff --git a/lib/chef/cookbook_version.rb b/lib/chef/cookbook_version.rb index dc8a93b91e..ec0739061e 100644 --- a/lib/chef/cookbook_version.rb +++ b/lib/chef/cookbook_version.rb @@ -28,14 +28,12 @@ require "chef/cookbook_manifest" require "chef/server_api" class Chef - # == Chef::CookbookVersion # CookbookVersion is a model object encapsulating the data about a Chef # cookbook. Chef supports maintaining multiple versions of a cookbook on a # single server; each version is represented by a distinct instance of this # class. class CookbookVersion - include Comparable COOKBOOK_SEGMENTS = [ :resources, :providers, :recipes, :definitions, :libraries, :attributes, :files, :templates, :root_files ] @@ -300,7 +298,7 @@ class Chef if segment == :files || segment == :templates error_message = "Cookbook '#{name}' (#{version}) does not contain a file at any of these locations:\n" error_locations = if filename.is_a?(Array) - filename.map{|name| " #{File.join(segment.to_s, name)}"} + filename.map { |name| " #{File.join(segment.to_s, name)}" } else [ " #{segment}/#{node[:platform]}-#{node[:platform_version]}/#{filename}", @@ -312,7 +310,7 @@ class Chef error_message << error_locations.join("\n") existing_files = segment_filenames(segment) # Strip the root_dir prefix off all files for readability - existing_files.map!{|path| path[root_dir.length+1..-1]} if root_dir + existing_files.map! { |path| path[root_dir.length + 1..-1] } if root_dir # Show the files that the cookbook does have. If the user made a typo, # hopefully they'll see it here. unless existing_files.empty? @@ -325,7 +323,7 @@ class Chef end end - def preferred_filename_on_disk_location(node, segment, filename, current_filepath=nil) + def preferred_filename_on_disk_location(node, segment, filename, current_filepath = nil) manifest_record = preferred_manifest_record(node, segment, filename) if current_filepath && (manifest_record["checksum"] == self.class.checksum_cookbook_file(current_filepath)) nil @@ -354,7 +352,7 @@ class Chef # cookbook find them by filespecificity again. but it's the shortest # path to "success" for now. if manifest_record_path =~ /(#{Regexp.escape(segment.to_s)}\/[^\/]+\/#{Regexp.escape(dirname)})\/.+$/ - specificity_dirname = $1 + specificity_dirname = $1 non_specific_path = manifest_record_path[/#{Regexp.escape(segment.to_s)}\/[^\/]+\/#{Regexp.escape(dirname)}\/(.+)$/, 1] # Record the specificity_dirname only if it's in the list of # valid preferences @@ -369,7 +367,6 @@ class Chef raise Chef::Exceptions::FileNotFound, "cookbook #{name} has no directory #{segment}/default/#{dirname}" unless best_pref filenames_by_pref[best_pref] - end # Determine the manifest records from the most specific directory @@ -389,7 +386,7 @@ class Chef # dirname argument as above, which is what # preferences_for_path returns. It could be # "files/ubuntu-9.10/dirname", for example. - specificity_dirname = $1 + specificity_dirname = $1 # Record the specificity_dirname only if it's in the list of # valid preferences @@ -449,7 +446,7 @@ class Chef search_path end - relative_search_path.map {|relative_path| File.join(segment.to_s, relative_path)} + relative_search_path.map { |relative_path| File.join(segment.to_s, relative_path) } else if segment.to_sym == :root_files [path] @@ -501,7 +498,6 @@ class Chef rendered_manifest end - def to_hash # TODO: this should become deprecated when the API for CookbookManifest becomes stable cookbook_manifest.to_hash @@ -512,7 +508,6 @@ class Chef cookbook_manifest.to_json end - def metadata_json_file File.join(root_paths[0], "metadata.json") end @@ -554,7 +549,7 @@ class Chef self end - def self.load(name, version="_latest") + def self.load(name, version = "_latest") version = "_latest" if version == "latest" from_hash(chef_server_rest.get("cookbooks/#{name}/#{version}")) end @@ -610,13 +605,13 @@ class Chef preferences = preferences_for_path(node, segment, filename) # in order of prefernce, look for the filename in the manifest - preferences.find {|preferred_filename| manifest_records_by_path[preferred_filename] } + preferences.find { |preferred_filename| manifest_records_by_path[preferred_filename] } end # For each filename, produce a mapping of base filename (i.e. recipe name # or attribute file) to on disk location def filenames_by_name(filenames) - filenames.select{|filename| filename =~ /\.rb$/}.inject({}){|memo, filename| memo[File.basename(filename, ".rb")] = filename ; memo } + filenames.select { |filename| filename =~ /\.rb$/ }.inject({}) { |memo, filename| memo[File.basename(filename, ".rb")] = filename ; memo } end def file_vendor @@ -625,6 +620,5 @@ class Chef end @file_vendor end - end end diff --git a/lib/chef/daemon.rb b/lib/chef/daemon.rb index 2cf72d7764..242419890c 100644 --- a/lib/chef/daemon.rb +++ b/lib/chef/daemon.rb @@ -61,7 +61,7 @@ class Chef # String:: # Location of the pid file for @name def pid_file - Chef::Config[:pid_file] or "/tmp/#{@name}.pid" + Chef::Config[:pid_file] or "/tmp/#{@name}.pid" end # Suck the pid out of pid_file @@ -100,7 +100,7 @@ class Chef # ==== Alternatives # If group is left out, the user will be used (changing to user:user) # - def _change_privilege(user, group=user) + def _change_privilege(user, group = user) uid, gid = Process.euid, Process.egid begin diff --git a/lib/chef/data_bag.rb b/lib/chef/data_bag.rb index bb598d1fdb..c8409b6712 100644 --- a/lib/chef/data_bag.rb +++ b/lib/chef/data_bag.rb @@ -28,7 +28,6 @@ require "chef/server_api" class Chef class DataBag - include Chef::Mixin::FromFile include Chef::Mixin::ParamsValidate @@ -48,7 +47,7 @@ class Chef @chef_server_rest = chef_server_rest end - def name(arg=nil) + def name(arg = nil) set_or_return( :name, arg, @@ -90,7 +89,7 @@ class Chef bag end - def self.list(inflate=false) + def self.list(inflate = false) if Chef::Config[:solo] paths = Array(Chef::Config[:data_bag_path]) names = [] @@ -99,9 +98,9 @@ class Chef raise Chef::Exceptions::InvalidDataBagPath, "Data bag path '#{path}' is invalid" end - names += Dir.glob(File.join(Chef::Util::PathHelper.escape_glob(path), "*")).map{|f|File.basename(f)}.sort + names += Dir.glob(File.join(Chef::Util::PathHelper.escape_glob(path), "*")).map { |f| File.basename(f) }.sort end - names.inject({}) {|h, n| h[n] = n; h} + names.inject({}) { |h, n| h[n] = n; h } else if inflate # Can't search for all data bags like other objects, fall back to N+1 :( @@ -170,6 +169,5 @@ class Chef def to_s "data_bag[#{@name}]" end - end end diff --git a/lib/chef/data_bag_item.rb b/lib/chef/data_bag_item.rb index 9c22d31bcd..7a7e7afdca 100644 --- a/lib/chef/data_bag_item.rb +++ b/lib/chef/data_bag_item.rb @@ -30,7 +30,6 @@ require "chef/json_compat" class Chef class DataBagItem - extend Forwardable include Chef::Mixin::FromFile @@ -82,7 +81,7 @@ class Chef @raw_data = new_data end - def data_bag(arg=nil) + def data_bag(arg = nil) set_or_return( :data_bag, arg, @@ -164,12 +163,12 @@ class Chef end end - def destroy(data_bag=self.data_bag(), databag_item=name) + def destroy(data_bag = self.data_bag(), databag_item = name) chef_server_rest.delete("data/#{data_bag}/#{databag_item}") end # Save this Data Bag Item via RESTful API - def save(item_id=@raw_data["id"]) + def save(item_id = @raw_data["id"]) r = chef_server_rest begin if Chef::Config[:why_run] @@ -192,9 +191,9 @@ class Chef def ==(other) other.respond_to?(:to_hash) && - other.respond_to?(:data_bag) && - (other.to_hash == to_hash) && - (other.data_bag.to_s == data_bag.to_s) + other.respond_to?(:data_bag) && + (other.to_hash == to_hash) && + (other.data_bag.to_s == data_bag.to_s) end # As a string @@ -207,12 +206,11 @@ class Chef end def pretty_print(pretty_printer) - pretty_printer.pp({"data_bag_item('#{data_bag}', '#{id}')" => self.to_hash}) + pretty_printer.pp({ "data_bag_item('#{data_bag}', '#{id}')" => self.to_hash }) end def id @raw_data["id"] end - end end diff --git a/lib/chef/deprecation/provider/cookbook_file.rb b/lib/chef/deprecation/provider/cookbook_file.rb index 166368df5a..03360d7550 100644 --- a/lib/chef/deprecation/provider/cookbook_file.rb +++ b/lib/chef/deprecation/provider/cookbook_file.rb @@ -16,18 +16,15 @@ # limitations under the License. # - class Chef module Deprecation module Provider - # == Deprecation::Provider::CookbookFile # This module contains the deprecated functions of # Chef::Provider::CookbookFile. These functions are refactored to # different components. They are frozen and will be removed in Chef 13. # module CookbookFile - def file_cache_location @file_cache_location ||= begin cookbook = run_context.cookbook_collection[resource_cookbook] @@ -48,7 +45,6 @@ class Chef backup @new_resource.path end end - end end end diff --git a/lib/chef/deprecation/provider/file.rb b/lib/chef/deprecation/provider/file.rb index f788513b50..42ed97391c 100644 --- a/lib/chef/deprecation/provider/file.rb +++ b/lib/chef/deprecation/provider/file.rb @@ -21,14 +21,12 @@ require "chef/util/path_helper" class Chef module Deprecation module Provider - # == Deprecation::Provider::File # This module contains the deprecated functions of # Chef::Provider::File. These functions are refactored to different # components. They are frozen and will be removed in Chef 13. # module File - def diff_current_from_content(new_content) result = nil Tempfile.open("chef-diff") do |file| @@ -41,7 +39,6 @@ class Chef def is_binary?(path) ::File.open(path) do |file| - buff = file.read(Chef::Config[:diff_filesize_threshold]) buff = "" if buff.nil? return buff !~ /^[\r[:print:]]*$/ @@ -52,13 +49,13 @@ class Chef suppress_resource_reporting = false return [ "(diff output suppressed by config)" ] if Chef::Config[:diff_disabled] - return [ "(no temp file with new content, diff output suppressed)" ] unless ::File.exists?(temp_path) # should never happen? + return [ "(no temp file with new content, diff output suppressed)" ] unless ::File.exists?(temp_path) # should never happen? # solaris does not support diff -N, so create tempfile to diff against if we are creating a new file target_path = if ::File.exists?(@current_resource.path) @current_resource.path else - suppress_resource_reporting = true # suppress big diffs going to resource reporting service + suppress_resource_reporting = true # suppress big diffs going to resource reporting service tempfile = Tempfile.new("chef-tempfile") tempfile.path end @@ -119,13 +116,13 @@ class Chef description << diff_current_from_content(@new_resource.content) converge_by(description) do backup @new_resource.path if ::File.exists?(@new_resource.path) - ::File.open(@new_resource.path, "w") {|f| f.write @new_resource.content } + ::File.open(@new_resource.path, "w") { |f| f.write @new_resource.content } Chef::Log.info("#{@new_resource} contents updated") end end end - def update_new_file_state(path=@new_resource.path) + def update_new_file_state(path = @new_resource.path) if !::File.directory?(path) @new_resource.checksum(checksum(path)) end @@ -163,7 +160,7 @@ class Chef end end - def backup(file=nil) + def backup(file = nil) file ||= @new_resource.path if @new_resource.backup != false && @new_resource.backup > 0 && ::File.exist?(file) time = Time.now @@ -181,7 +178,7 @@ class Chef # Clean up after the number of backups slice_number = @new_resource.backup - backup_files = Dir[Chef::Util::PathHelper.escape_glob(prefix, ".#{@new_resource.path}") + ".chef-*"].sort { |a,b| b <=> a } + backup_files = Dir[Chef::Util::PathHelper.escape_glob(prefix, ".#{@new_resource.path}") + ".chef-*"].sort { |a, b| b <=> a } if backup_files.length >= @new_resource.backup remainder = backup_files.slice(slice_number..-1) remainder.each do |backup_to_delete| @@ -191,7 +188,6 @@ class Chef end end end - end end end diff --git a/lib/chef/deprecation/provider/remote_directory.rb b/lib/chef/deprecation/provider/remote_directory.rb index f6242a4557..bbf026f4fc 100644 --- a/lib/chef/deprecation/provider/remote_directory.rb +++ b/lib/chef/deprecation/provider/remote_directory.rb @@ -20,7 +20,6 @@ class Chef module Deprecation module Provider module RemoteDirectory - def directory_root_in_cookbook_cache Chef.log_deprecation "the Chef::Provider::RemoteDirectory#directory_root_in_cookbook_cache method is deprecated" @@ -43,9 +42,8 @@ class Chef end # Clean all the paths... this is required because of the join - files.map {|f| Chef::Util::PathHelper.cleanpath(f)} + files.map { |f| Chef::Util::PathHelper.cleanpath(f) } end - end end end diff --git a/lib/chef/deprecation/provider/remote_file.rb b/lib/chef/deprecation/provider/remote_file.rb index a73181e15c..6f58a3b560 100644 --- a/lib/chef/deprecation/provider/remote_file.rb +++ b/lib/chef/deprecation/provider/remote_file.rb @@ -19,14 +19,12 @@ class Chef module Deprecation module Provider - # == Deprecation::Provider::RemoteFile # This module contains the deprecated functions of # Chef::Provider::RemoteFile. These functions are refactored to different # components. They are frozen and will be removed in Chef 13. # module RemoteFile - def current_resource_matches_target_checksum? @new_resource.checksum && @current_resource.checksum && @current_resource.checksum =~ /^#{Regexp.escape(@new_resource.checksum)}/ end @@ -64,7 +62,7 @@ class Chef end def http_client_opts(source) - opts={} + opts = {} # CHEF-3140 # 1. If it's already compressed, trying to compress it more will # probably be counter-productive. @@ -78,7 +76,6 @@ class Chef end opts end - end end end diff --git a/lib/chef/deprecation/provider/template.rb b/lib/chef/deprecation/provider/template.rb index ea5a880798..dc672a7aea 100644 --- a/lib/chef/deprecation/provider/template.rb +++ b/lib/chef/deprecation/provider/template.rb @@ -21,14 +21,12 @@ require "chef/deprecation/mixin/template" class Chef module Deprecation module Provider - # == Deprecation::Provider::Template # This module contains the deprecated functions of # Chef::Provider::Template. These functions are refactored to different # components. They are frozen and will be removed in Chef 13. # module Template - include Chef::Deprecation::Mixin::Template def template_finder @@ -56,7 +54,6 @@ class Chef def content_matches? @current_resource.checksum == @new_resource.checksum end - end end end diff --git a/lib/chef/deprecation/warnings.rb b/lib/chef/deprecation/warnings.rb index b015669625..e0e846b8c9 100644 --- a/lib/chef/deprecation/warnings.rb +++ b/lib/chef/deprecation/warnings.rb @@ -19,7 +19,6 @@ class Chef module Deprecation module Warnings - def add_deprecation_warnings_for(method_names) method_names.each do |name| m = instance_method(name) @@ -32,7 +31,6 @@ class Chef end end end - end end end diff --git a/lib/chef/digester.rb b/lib/chef/digester.rb index 6e4588a661..a5ae89a63d 100644 --- a/lib/chef/digester.rb +++ b/lib/chef/digester.rb @@ -69,6 +69,5 @@ class Chef end digest.hexdigest end - end end diff --git a/lib/chef/dsl/audit.rb b/lib/chef/dsl/audit.rb index 98271dc5cb..3085e4d516 100644 --- a/lib/chef/dsl/audit.rb +++ b/lib/chef/dsl/audit.rb @@ -21,7 +21,6 @@ require "chef/exceptions" class Chef module DSL module Audit - # Can encompass tests in a `control` block or `describe` block # Adds the controls group and block (containing controls to execute) to the runner's list of pending examples def control_group(*args, &block) @@ -37,15 +36,14 @@ class Chef # This DSL will only work in the Recipe class because that exposes the cookbook_name cookbook_name = self.cookbook_name metadata = { - cookbook_name: cookbook_name, - cookbook_version: self.run_context.cookbook_collection[cookbook_name].version, - recipe_name: self.recipe_name, - line_number: block.source_location[1], + cookbook_name: cookbook_name, + cookbook_version: self.run_context.cookbook_collection[cookbook_name].version, + recipe_name: self.recipe_name, + line_number: block.source_location[1], } run_context.audits[name] = Struct.new(:args, :block, :metadata).new(args, block, metadata) end - end end end diff --git a/lib/chef/dsl/chef_provisioning.rb b/lib/chef/dsl/chef_provisioning.rb index d2b6aabb17..a91d297d02 100644 --- a/lib/chef/dsl/chef_provisioning.rb +++ b/lib/chef/dsl/chef_provisioning.rb @@ -37,7 +37,7 @@ class Chef with_image_options with_machine_options }.each do |method_name| - eval(<<-EOM, binding, __FILE__, __LINE__+1) + eval(<<-EOM, binding, __FILE__, __LINE__ + 1) def #{method_name}(*args, &block) Chef::DSL::ChefProvisioning.load_chef_provisioning self.#{method_name}(*args, &block) diff --git a/lib/chef/dsl/cheffish.rb b/lib/chef/dsl/cheffish.rb index 3314ffd4d5..de052bbe5c 100644 --- a/lib/chef/dsl/cheffish.rb +++ b/lib/chef/dsl/cheffish.rb @@ -44,7 +44,7 @@ class Chef with_chef_local_server get_private_key }.each do |method_name| - eval(<<-EOM, binding, __FILE__, __LINE__+1) + eval(<<-EOM, binding, __FILE__, __LINE__ + 1) def #{method_name}(*args, &block) Chef::DSL::Cheffish.load_cheffish self.#{method_name}(*args, &block) diff --git a/lib/chef/dsl/data_query.rb b/lib/chef/dsl/data_query.rb index 865d914d13..7a6fa710c0 100644 --- a/lib/chef/dsl/data_query.rb +++ b/lib/chef/dsl/data_query.rb @@ -24,7 +24,6 @@ require "chef/encrypted_data_bag_item/check_encrypted" class Chef module DSL - # ==Chef::DSL::DataQuery # Provides DSL for querying data from the chef-server via search or data # bag. @@ -55,7 +54,7 @@ class Chef raise end - def data_bag_item(bag, item, secret=nil) + def data_bag_item(bag, item, secret = nil) DataBag.validate_name!(bag.to_s) DataBagItem.validate_id!(item) @@ -73,13 +72,12 @@ class Chef raise end end - + item rescue Exception Log.error("Failed to load data bag item: #{bag.inspect} #{item.inspect}") raise end - end end end diff --git a/lib/chef/dsl/declare_resource.rb b/lib/chef/dsl/declare_resource.rb index 91fe62c263..bdf36be578 100644 --- a/lib/chef/dsl/declare_resource.rb +++ b/lib/chef/dsl/declare_resource.rb @@ -22,7 +22,6 @@ require "chef/exceptions" class Chef module DSL module DeclareResource - # # Instantiates a resource (via #build_resource), then adds it to the # resource collection. Note that resource classes are looked up directly, @@ -48,7 +47,7 @@ class Chef # action :delete # end # - def declare_resource(type, name, created_at=nil, run_context: self.run_context, create_if_missing: false, &resource_attrs_block) + def declare_resource(type, name, created_at = nil, run_context: self.run_context, create_if_missing: false, &resource_attrs_block) created_at ||= caller[0] if create_if_missing @@ -86,7 +85,7 @@ class Chef # action :delete # end # - def build_resource(type, name, created_at=nil, run_context: self.run_context, &resource_attrs_block) + def build_resource(type, name, created_at = nil, run_context: self.run_context, &resource_attrs_block) created_at ||= caller[0] Thread.exclusive do require "chef/resource_builder" unless defined?(Chef::ResourceBuilder) @@ -100,7 +99,7 @@ class Chef run_context: run_context, cookbook_name: cookbook_name, recipe_name: recipe_name, - enclosing_provider: self.is_a?(Chef::Provider) ? self : nil, + enclosing_provider: self.is_a?(Chef::Provider) ? self : nil, ).build(&resource_attrs_block) end end diff --git a/lib/chef/dsl/definitions.rb b/lib/chef/dsl/definitions.rb index 1358f67720..60b1cf6f61 100644 --- a/lib/chef/dsl/definitions.rb +++ b/lib/chef/dsl/definitions.rb @@ -9,7 +9,7 @@ class Chef # module Definitions def self.add_definition(dsl_name) - module_eval <<-EOM, __FILE__, __LINE__+1 + module_eval <<-EOM, __FILE__, __LINE__ + 1 def #{dsl_name}(*args, &block) evaluate_resource_definition(#{dsl_name.inspect}, *args, &block) end @@ -25,7 +25,6 @@ class Chef # # @api private def evaluate_resource_definition(definition_name, *args, &block) - # This dupes the high level object, but we still need to dup the params new_def = run_context.definitions[definition_name].dup diff --git a/lib/chef/dsl/include_attribute.rb b/lib/chef/dsl/include_attribute.rb index b1b9dc4dac..daf943ef44 100644 --- a/lib/chef/dsl/include_attribute.rb +++ b/lib/chef/dsl/include_attribute.rb @@ -21,7 +21,6 @@ require "chef/log" class Chef module DSL module IncludeAttribute - # Loads the attribute file specified by the short name of the # file, e.g., loads specified cookbook's # "attributes/mailservers.rb" @@ -51,7 +50,6 @@ class Chef [file_spec, "default"] end end - end end end @@ -59,5 +57,3 @@ end # **DEPRECATED** # This used to be part of chef/mixin/language_include_attribute. Load the file to activate the deprecation code. require "chef/mixin/language_include_attribute" - - diff --git a/lib/chef/dsl/include_recipe.rb b/lib/chef/dsl/include_recipe.rb index 9abd7d135b..307f2bae95 100644 --- a/lib/chef/dsl/include_recipe.rb +++ b/lib/chef/dsl/include_recipe.rb @@ -21,7 +21,6 @@ require "chef/log" class Chef module DSL module IncludeRecipe - def include_recipe(*recipe_names) run_context.include_recipe(*recipe_names, current_cookbook: cookbook_name) end @@ -34,7 +33,6 @@ class Chef Chef::Log.warn("require_recipe is deprecated and will be removed in a future release, please use include_recipe") include_recipe(*args) end - end end end diff --git a/lib/chef/dsl/platform_introspection.rb b/lib/chef/dsl/platform_introspection.rb index a3a978d418..d018a9dfef 100644 --- a/lib/chef/dsl/platform_introspection.rb +++ b/lib/chef/dsl/platform_introspection.rb @@ -18,15 +18,12 @@ class Chef module DSL - # == Chef::DSL::PlatformIntrospection # Provides the DSL for platform-dependent switch logic, such as # #value_for_platform. module PlatformIntrospection - # Implementation class for determining platform dependent values class PlatformDependentValue - # Create a platform dependent value object. # === Arguments # platform_hash (Hash) a hash of the same structure as Chef::Platform, @@ -45,7 +42,7 @@ class Chef # :default => default_value def initialize(platform_hash) @values = {} - platform_hash.each { |platforms, value| set(platforms, value)} + platform_hash.each { |platforms, value| set(platforms, value) } end def value_for_node(node) @@ -110,7 +107,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 { |platform| @values[platform.to_s] = normalize_keys(value) } value end end @@ -134,8 +131,6 @@ class Chef end end - - # Given a hash similar to the one we use for Platforms, select a value from the hash. Supports # per platform defaults, along with a single base default. Arrays may be passed as hash keys and # will be expanded. @@ -168,11 +163,8 @@ class Chef has_platform end - - # Implementation class for determining platform family dependent values class PlatformFamilyDependentValue - # Create a platform family dependent value object. # === Arguments # platform_family_hash (Hash) a map of platform families to values. @@ -193,7 +185,7 @@ class Chef def initialize(platform_family_hash) @values = {} @values["default"] = nil - platform_family_hash.each { |platform_families, value| set(platform_families, value)} + platform_family_hash.each { |platform_families, value| set(platform_families, value) } end def value_for_node(node) @@ -221,7 +213,6 @@ class Chef end end - # Given a hash mapping platform families to values, select a value from the hash. Supports a single # base default if platform family is not in the map. Arrays may be passed as hash keys and will be # expanded @@ -249,7 +240,6 @@ class Chef platform_family.to_s == node[:platform_family] end end - end end end @@ -257,4 +247,3 @@ end # **DEPRECATED** # This used to be part of chef/mixin/language. Load the file to activate the deprecation code. require "chef/mixin/language" - diff --git a/lib/chef/dsl/powershell.rb b/lib/chef/dsl/powershell.rb index ff5fee93a5..1a900af6f6 100644 --- a/lib/chef/dsl/powershell.rb +++ b/lib/chef/dsl/powershell.rb @@ -21,7 +21,7 @@ require "chef/util/powershell/ps_credential" class Chef module DSL module Powershell - def ps_credential(username="placeholder", password) + def ps_credential(username = "placeholder", password) Chef::Util::Powershell::PSCredential.new(username, password) end end diff --git a/lib/chef/dsl/reboot_pending.rb b/lib/chef/dsl/reboot_pending.rb index c3cf9a9a51..9a60817bac 100644 --- a/lib/chef/dsl/reboot_pending.rb +++ b/lib/chef/dsl/reboot_pending.rb @@ -22,14 +22,12 @@ require "chef/dsl/registry_helper" class Chef module DSL module RebootPending - include Chef::DSL::RegistryHelper include Chef::DSL::PlatformIntrospection # Returns true if the system needs a reboot or is expected to reboot # Note that we will silently miss any other platform-specific reboot notices besides Windows+Ubuntu. def reboot_pending? - # don't break when used as a mixin in contexts without #node (e.g. specs). if self.respond_to?(:node, true) && node.run_context.reboot_requested? true @@ -42,17 +40,17 @@ class Chef # RebootRequired key contains Update IDs with a value of 1 if they require a reboot. # The existence of RebootRequired alone is sufficient on my Windows 8.1 workstation in Windows Update - registry_key_exists?('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired') || + registry_key_exists?('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired') || # Vista + Server 2008 and newer may have reboots pending from CBS - registry_key_exists?('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending') || + registry_key_exists?('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending') || # The mere existence of the UpdateExeVolatile key should indicate a pending restart for certain updates # http://support.microsoft.com/kb/832475 - Chef::Platform.windows_server_2003? && - (registry_key_exists?('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile') && - !registry_get_values('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile').select { |v| v[:name] == "Flags" }[0].nil? && - [1,2,3].include?(registry_get_values('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile').select { |v| v[:name] == "Flags" }[0][:data])) + Chef::Platform.windows_server_2003? && + (registry_key_exists?('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile') && + !registry_get_values('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile').select { |v| v[:name] == "Flags" }[0].nil? && + [1, 2, 3].include?(registry_get_values('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile').select { |v| v[:name] == "Flags" }[0][:data])) elsif platform?("ubuntu") # This should work for Debian as well if update-notifier-common happens to be installed. We need an API for that. File.exists?("/var/run/reboot-required") diff --git a/lib/chef/dsl/recipe.rb b/lib/chef/dsl/recipe.rb index 6d254df48d..614e90bff4 100644 --- a/lib/chef/dsl/recipe.rb +++ b/lib/chef/dsl/recipe.rb @@ -26,12 +26,10 @@ require "chef/dsl/declare_resource" class Chef module DSL - # == Chef::DSL::Recipe # Provides the primary recipe DSL functionality for defining Chef resource # objects via method calls. module Recipe - include Chef::Mixin::ShellOut include Chef::Mixin::PowershellOut diff --git a/lib/chef/dsl/registry_helper.rb b/lib/chef/dsl/registry_helper.rb index 256b4eca1e..63da635ef1 100644 --- a/lib/chef/dsl/registry_helper.rb +++ b/lib/chef/dsl/registry_helper.rb @@ -33,22 +33,27 @@ class Chef registry = Chef::Win32::Registry.new(run_context, architecture) registry.key_exists?(key_path) end + def registry_get_values(key_path, architecture = :machine) registry = Chef::Win32::Registry.new(run_context, architecture) registry.get_values(key_path) end + def registry_has_subkeys?(key_path, architecture = :machine) registry = Chef::Win32::Registry.new(run_context, architecture) registry.has_subkeys?(key_path) end + def registry_get_subkeys(key_path, architecture = :machine) registry = Chef::Win32::Registry.new(run_context, architecture) registry.get_subkeys(key_path) end + def registry_value_exists?(key_path, value, architecture = :machine) registry = Chef::Win32::Registry.new(run_context, architecture) registry.value_exists?(key_path, value) end + def registry_data_exists?(key_path, value, architecture = :machine) registry = Chef::Win32::Registry.new(run_context, architecture) registry.data_exists?(key_path, value) @@ -56,4 +61,3 @@ class Chef end end end - diff --git a/lib/chef/dsl/resources.rb b/lib/chef/dsl/resources.rb index aba602da7e..7bbfeb2914 100644 --- a/lib/chef/dsl/resources.rb +++ b/lib/chef/dsl/resources.rb @@ -34,7 +34,7 @@ class Chef def self.add_resource_dsl(dsl_name) begin - module_eval(<<-EOM, __FILE__, __LINE__+1) + module_eval(<<-EOM, __FILE__, __LINE__ + 1) def #{dsl_name}(*args, &block) Chef.log_deprecation("Cannot create resource #{dsl_name} with more than one argument. All arguments except the name (\#{args[0].inspect}) will be ignored. This will cause an error in Chef 13. Arguments: \#{args}") if args.size > 1 declare_resource(#{dsl_name.inspect}, args[0], caller[0], &block) @@ -48,8 +48,9 @@ class Chef end end end + def self.remove_resource_dsl(dsl_name) - remove_method(dsl_name) + remove_method(dsl_name) rescue NameError end end diff --git a/lib/chef/encrypted_data_bag_item.rb b/lib/chef/encrypted_data_bag_item.rb index dc1c00cb27..e13ada8b41 100644 --- a/lib/chef/encrypted_data_bag_item.rb +++ b/lib/chef/encrypted_data_bag_item.rb @@ -125,7 +125,7 @@ class Chef::EncryptedDataBagItem self.new(raw_hash, secret) end - def self.load_secret(path=nil) + def self.load_secret(path = nil) path ||= Chef::Config[:encrypted_data_bag_secret] if !path raise ArgumentError, "No secret specified and no secret found at #{Chef::Config.platform_specific_path('/etc/chef/encrypted_data_bag_secret')}" @@ -151,5 +151,4 @@ class Chef::EncryptedDataBagItem end secret end - end diff --git a/lib/chef/encrypted_data_bag_item/assertions.rb b/lib/chef/encrypted_data_bag_item/assertions.rb index bbdcf7a721..0cbca30b5f 100644 --- a/lib/chef/encrypted_data_bag_item/assertions.rb +++ b/lib/chef/encrypted_data_bag_item/assertions.rb @@ -20,17 +20,15 @@ require "chef/encrypted_data_bag_item/unacceptable_encrypted_data_bag_item_forma require "chef/encrypted_data_bag_item/unsupported_cipher" class Chef::EncryptedDataBagItem - class EncryptedDataBagRequirementsFailure < StandardError end module Assertions - def assert_format_version_acceptable!(format_version) unless format_version.kind_of?(Integer) and format_version >= Chef::Config[:data_bag_decrypt_minimum_version] raise UnacceptableEncryptedDataBagItemFormat, "The encrypted data bag item has format version `#{format_version}', " + - "but the config setting 'data_bag_decrypt_minimum_version' requires version `#{Chef::Config[:data_bag_decrypt_minimum_version]}'" + "but the config setting 'data_bag_decrypt_minimum_version' requires version `#{Chef::Config[:data_bag_decrypt_minimum_version]}'" end end @@ -48,7 +46,5 @@ class Chef::EncryptedDataBagItem raise EncryptedDataBagRequirementsFailure, "The used Encrypted Data Bags version requires an OpenSSL version with \"#{algorithm}\" algorithm support" end end - end - end diff --git a/lib/chef/encrypted_data_bag_item/check_encrypted.rb b/lib/chef/encrypted_data_bag_item/check_encrypted.rb index cc378194ff..c15e7bb241 100644 --- a/lib/chef/encrypted_data_bag_item/check_encrypted.rb +++ b/lib/chef/encrypted_data_bag_item/check_encrypted.rb @@ -21,7 +21,6 @@ require "chef/encrypted_data_bag_item/encryptor" class Chef::EncryptedDataBagItem # Common code for checking if a data bag appears encrypted module CheckEncrypted - # Tries to autodetect if the item's raw hash appears to be encrypted. def encrypted?(raw_data) data = raw_data.reject { |k, _| k == "id" } # Remove the "id" key. @@ -51,6 +50,5 @@ class Chef::EncryptedDataBagItem false # version means something else... assume not encrypted. end end - end end diff --git a/lib/chef/encrypted_data_bag_item/decryptor.rb b/lib/chef/encrypted_data_bag_item/decryptor.rb index 652c5bf718..404de4f571 100644 --- a/lib/chef/encrypted_data_bag_item/decryptor.rb +++ b/lib/chef/encrypted_data_bag_item/decryptor.rb @@ -27,7 +27,6 @@ require "chef/encrypted_data_bag_item/decryption_failure" require "chef/encrypted_data_bag_item/assertions" class Chef::EncryptedDataBagItem - #=== Decryptor # For backwards compatibility, Chef implements decryption/deserialization for # older encrypted data bag item formats in addition to the current version. @@ -111,7 +110,6 @@ class Chef::EncryptedDataBagItem end class Version1Decryptor < Version0Decryptor - attr_reader :encrypted_data attr_reader :key @@ -157,11 +155,9 @@ class Chef::EncryptedDataBagItem d end end - end class Version2Decryptor < Version1Decryptor - def decrypted_data validate_hmac! unless @decrypted_data super @@ -191,7 +187,6 @@ class Chef::EncryptedDataBagItem end class Version3Decryptor < Version1Decryptor - def initialize(encrypted_data, key) super assert_aead_requirements_met!(algorithm) @@ -218,8 +213,6 @@ class Chef::EncryptedDataBagItem d end end - end - end end diff --git a/lib/chef/encrypted_data_bag_item/encrypted_data_bag_item_assertions.rb b/lib/chef/encrypted_data_bag_item/encrypted_data_bag_item_assertions.rb index e45c34248e..7d5726082d 100644 --- a/lib/chef/encrypted_data_bag_item/encrypted_data_bag_item_assertions.rb +++ b/lib/chef/encrypted_data_bag_item/encrypted_data_bag_item_assertions.rb @@ -17,12 +17,10 @@ # class Chef::EncryptedDataBagItem - class EncryptedDataBagRequirementsFailure < StandardError end module Assertions - def assert_requirements_met! unless OpenSSL::Cipher.method_defined?(:auth_data=) raise EncryptedDataBagRequirementsFailure, "The used Encrypted Data Bags version requires Ruby >= 2.0" @@ -31,7 +29,5 @@ class Chef::EncryptedDataBagItem raise EncryptedDataBagRequirementsFailure, "The used Encrypted Data Bags version requires an OpenSSL version with \"#{algorithm}\" algorithm support" end end - end - end diff --git a/lib/chef/encrypted_data_bag_item/encryptor.rb b/lib/chef/encrypted_data_bag_item/encryptor.rb index 83d5fa47ab..d041663377 100644 --- a/lib/chef/encrypted_data_bag_item/encryptor.rb +++ b/lib/chef/encrypted_data_bag_item/encryptor.rb @@ -26,16 +26,14 @@ require "chef/encrypted_data_bag_item/encryption_failure" require "chef/encrypted_data_bag_item/assertions" class Chef::EncryptedDataBagItem - # Implementation class for converting plaintext data bag item values to an # encrypted value, including any necessary wrappers and metadata. module Encryptor - # "factory" method that creates an encryptor object with the proper class # for the desired encrypted data bag format version. # # +Chef::Config[:data_bag_encrypt_version]+ determines which version is used. - def self.new(value, secret, iv=nil) + def self.new(value, secret, iv = nil) format_version = Chef::Config[:data_bag_encrypt_version] case format_version when 1 @@ -65,7 +63,7 @@ class Chef::EncryptedDataBagItem # * iv: The optional +iv+ parameter is intended for testing use only. When # *not* supplied, Encryptor will use OpenSSL to generate a secure random # IV, which is what you want. - def initialize(plaintext_data, key, iv=nil) + def initialize(plaintext_data, key, iv = nil) @plaintext_data = plaintext_data @key = key @iv = iv && Base64.decode64(iv) @@ -132,7 +130,6 @@ class Chef::EncryptedDataBagItem end class Version2Encryptor < Version1Encryptor - # Returns a wrapped and encrypted version of +plaintext_data+ suitable for # using as the value in an encrypted data bag item. def for_encrypted_item @@ -162,7 +159,7 @@ class Chef::EncryptedDataBagItem class Version3Encryptor < Version1Encryptor include Chef::EncryptedDataBagItem::Assertions - def initialize(plaintext_data, key, iv=nil) + def initialize(plaintext_data, key, iv = nil) super assert_aead_requirements_met!(algorithm) @auth_tag = nil @@ -218,8 +215,6 @@ class Chef::EncryptedDataBagItem def self.encryptor_keys super + %w{ auth_tag } end - end - end end diff --git a/lib/chef/environment.rb b/lib/chef/environment.rb index 164901c107..0d01fcd05c 100644 --- a/lib/chef/environment.rb +++ b/lib/chef/environment.rb @@ -28,7 +28,6 @@ require "chef/server_api" class Chef class Environment - DEFAULT = "default" include Chef::Mixin::ParamsValidate @@ -55,7 +54,7 @@ class Chef Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end - def name(arg=nil) + def name(arg = nil) set_or_return( :name, arg, @@ -63,7 +62,7 @@ class Chef ) end - def description(arg=nil) + def description(arg = nil) set_or_return( :description, arg, @@ -71,7 +70,7 @@ class Chef ) end - def default_attributes(arg=nil) + def default_attributes(arg = nil) set_or_return( :default_attributes, arg, @@ -83,7 +82,7 @@ class Chef default_attributes(attrs) end - def override_attributes(arg=nil) + def override_attributes(arg = nil) set_or_return( :override_attributes, arg, @@ -95,7 +94,7 @@ class Chef override_attributes(attrs) end - def cookbook_versions(arg=nil) + def cookbook_versions(arg = nil) set_or_return( :cookbook_versions, arg, @@ -110,12 +109,12 @@ class Chef def cookbook(cookbook, version) validate({ - :version => version - },{ - :version => { - :callbacks => { "should be a valid version requirement" => lambda { |v| Chef::Environment.validate_cookbook_version(v) } } - } - },) + :version => version + }, { + :version => { + :callbacks => { "should be a valid version requirement" => lambda { |v| Chef::Environment.validate_cookbook_version(v) } } + } + },) @cookbook_versions[cookbook] = version end @@ -231,7 +230,7 @@ class Chef environment end - def self.list(inflate=false) + def self.list(inflate = false) if inflate response = Hash.new Chef::Search::Query.new.search(:environment) do |e| @@ -321,6 +320,5 @@ class Chef false end end - end end diff --git a/lib/chef/event_dispatch/base.rb b/lib/chef/event_dispatch/base.rb index 585a3db174..09e6b825f3 100644 --- a/lib/chef/event_dispatch/base.rb +++ b/lib/chef/event_dispatch/base.rb @@ -1,5 +1,4 @@ class Chef - # ==EventDispatch # Classes in EventDispatch deal with collecting, distributing, and handling # information in response to events that occur during a chef-client run. @@ -21,13 +20,11 @@ class Chef # consider the feature "beta" for now and be prepared for possible breaking # changes in point releases. module EventDispatch - # == EventDispatch::Base # EventDispatch::Base is a completely abstract base class that defines the # API used by both the classes that collect event information and those # that process them. class Base - # Called at the very start of a Chef Run def run_start(version) end @@ -298,7 +295,7 @@ class Chef # # Called before action is executed on a resource. - def resource_action_start(resource, action, notification_type=nil, notifier=nil) + def resource_action_start(resource, action, notification_type = nil, notifier = nil) end # Called when a resource action has been skipped b/c of a conditional @@ -381,7 +378,7 @@ class Chef end # Emit a message about something being deprecated. - def deprecation(message, location=caller(2..2)[0]) + def deprecation(message, location = caller(2..2)[0]) end def run_list_expanded(run_list_expansion) @@ -394,7 +391,6 @@ class Chef # callback for it. def msg(message) end - end end end diff --git a/lib/chef/event_dispatch/dispatcher.rb b/lib/chef/event_dispatch/dispatcher.rb index dae2c3f6b4..f80baee44b 100644 --- a/lib/chef/event_dispatch/dispatcher.rb +++ b/lib/chef/event_dispatch/dispatcher.rb @@ -2,13 +2,11 @@ require "chef/event_dispatch/base" class Chef module EventDispatch - # == EventDispatch::Dispatcher # The Dispatcher handles receiving event data from the sources # (Chef::Client, Resources and Providers, etc.) and publishing the data to # the registered subscribers. class Dispatcher < Base - attr_reader :subscribers def initialize(*subscribers) @@ -54,7 +52,7 @@ class Chef end # Special case deprecation, since it needs to know its caller - def deprecation(message, location=caller(2..2)[0]) + def deprecation(message, location = caller(2..2)[0]) call_subscribers(:deprecation, message, location) end end diff --git a/lib/chef/event_dispatch/dsl.rb b/lib/chef/event_dispatch/dsl.rb index d370c37fae..999d536fbe 100644 --- a/lib/chef/event_dispatch/dsl.rb +++ b/lib/chef/event_dispatch/dsl.rb @@ -55,6 +55,7 @@ class Chef end private + def validate!(event_type) all_event_types = (Chef::EventDispatch::Base.instance_methods - Object.instance_methods) raise Chef::Exceptions::InvalidEventType, "Invalid event type: #{event_type}" unless all_event_types.include?(event_type) diff --git a/lib/chef/event_loggers/windows_eventlog.rb b/lib/chef/event_loggers/windows_eventlog.rb index 1d16b66087..01f38c5341 100644 --- a/lib/chef/event_loggers/windows_eventlog.rb +++ b/lib/chef/event_loggers/windows_eventlog.rb @@ -95,7 +95,6 @@ class Chef e.backtrace.join("\n")], ) end - end end end diff --git a/lib/chef/exceptions.rb b/lib/chef/exceptions.rb index 6fe364a91b..96eca839dd 100644 --- a/lib/chef/exceptions.rb +++ b/lib/chef/exceptions.rb @@ -24,7 +24,6 @@ class Chef # Chef's custom exceptions are all contained within the Chef::Exceptions # namespace. class Exceptions - ConfigurationError = ChefConfig::ConfigurationError # Backcompat with Chef::ShellOut code: @@ -33,7 +32,7 @@ class Chef def self.const_missing(const_name) if const_name == :ShellCommandFailed Chef::Log.warn("Chef::Exceptions::ShellCommandFailed is deprecated, use Mixlib::ShellOut::ShellCommandFailed") - called_from = caller[0..3].inject("Called from:\n") {|msg, trace_line| msg << " #{trace_line}\n" } + called_from = caller[0..3].inject("Called from:\n") { |msg, trace_line| msg << " #{trace_line}\n" } Chef::Log.warn(called_from) Mixlib::ShellOut::ShellCommandFailed else @@ -250,7 +249,7 @@ class Chef attr_reader :expansion - def initialize(message_or_expansion=NULL) + def initialize(message_or_expansion = NULL) @expansion = nil case message_or_expansion when NULL @@ -263,7 +262,6 @@ class Chef super("The expanded run list includes nonexistent roles: #{missing_roles}") end end - end # Exception class for collecting multiple failures. Used when running # delayed notifications so that chef can process each delayed @@ -310,7 +308,6 @@ class Chef end class CookbookVersionSelection - # Compound exception: In run_list expansion and resolution, # run_list items referred to cookbooks that don't exist and/or # have no versions available. @@ -369,7 +366,6 @@ class Chef Chef::JSONCompat.to_json(result, *a) end end - end # CookbookVersionSelection # When the server sends a redirect, RFC 2616 states a user-agent should @@ -449,7 +445,7 @@ This error is most often caused by network issues (proxies, etc) outside of chef class RunFailedWrappingError < RuntimeError attr_reader :wrapped_errors def initialize(*errors) - errors = errors.select {|e| !e.nil?} + errors = errors.select { |e| !e.nil? } output = "Found #{errors.size} errors, they are stored in the backtrace" @wrapped_errors = errors super output @@ -457,8 +453,8 @@ This error is most often caused by network issues (proxies, etc) outside of chef def fill_backtrace backtrace = [] - wrapped_errors.each_with_index do |e,i| - backtrace << "#{i+1}) #{e.class} - #{e.message}" + wrapped_errors.each_with_index do |e, i| + backtrace << "#{i + 1}) #{e.class} - #{e.message}" backtrace += e.backtrace if e.backtrace backtrace << "" unless i == wrapped_errors.length - 1 end diff --git a/lib/chef/file_access_control.rb b/lib/chef/file_access_control.rb index 50a1ea29bb..ba03278d72 100644 --- a/lib/chef/file_access_control.rb +++ b/lib/chef/file_access_control.rb @@ -20,12 +20,10 @@ require "chef/log" class Chef - # == Chef::FileAccessControl # FileAccessControl objects set the owner, group and mode of +file+ to # the values specified by a value object, usually a Chef::Resource. class FileAccessControl - if RUBY_PLATFORM =~ /mswin|mingw|windows/ require "chef/file_access_control/windows" include FileAccessControl::Windows @@ -70,6 +68,5 @@ class Chef def log_string @resource || @file end - end end diff --git a/lib/chef/file_cache.rb b/lib/chef/file_cache.rb index 9a90048ba6..fea15ba6e8 100644 --- a/lib/chef/file_cache.rb +++ b/lib/chef/file_cache.rb @@ -39,7 +39,7 @@ class Chef # # === Returns # true - def store(path, contents, perm=0640) + def store(path, contents, perm = 0640) validate( { :path => path, @@ -102,7 +102,7 @@ class Chef # # === Raises # Chef::Exceptions::FileNotFound:: If it cannot find the file in the cache - def load(path, read=true) + def load(path, read = true) validate( { :path => path @@ -201,7 +201,7 @@ class Chef # # === Returns # String:: The fully expanded path - def create_cache_path(path, create_if_missing=true) + def create_cache_path(path, create_if_missing = true) cache_dir = File.expand_path(File.join(file_cache_path, path)) if create_if_missing create_path(cache_dir) @@ -215,7 +215,6 @@ class Chef def file_cache_path Chef::Config[:file_cache_path] end - end end end diff --git a/lib/chef/file_content_management/content_base.rb b/lib/chef/file_content_management/content_base.rb index 6080e37180..514fb5d8e3 100644 --- a/lib/chef/file_content_management/content_base.rb +++ b/lib/chef/file_content_management/content_base.rb @@ -19,7 +19,6 @@ class Chef class FileContentManagement class ContentBase - attr_reader :run_context attr_reader :new_resource attr_reader :current_resource diff --git a/lib/chef/file_content_management/deploy.rb b/lib/chef/file_content_management/deploy.rb index 67dcbfa424..1e3ae55c21 100644 --- a/lib/chef/file_content_management/deploy.rb +++ b/lib/chef/file_content_management/deploy.rb @@ -35,4 +35,3 @@ class Chef end end end - diff --git a/lib/chef/file_content_management/deploy/mv_unix.rb b/lib/chef/file_content_management/deploy/mv_unix.rb index 9c265e0a21..3805b3bef3 100644 --- a/lib/chef/file_content_management/deploy/mv_unix.rb +++ b/lib/chef/file_content_management/deploy/mv_unix.rb @@ -74,4 +74,3 @@ class Chef end end end - diff --git a/lib/chef/file_content_management/deploy/mv_windows.rb b/lib/chef/file_content_management/deploy/mv_windows.rb index b3ef021e76..3577445eec 100644 --- a/lib/chef/file_content_management/deploy/mv_windows.rb +++ b/lib/chef/file_content_management/deploy/mv_windows.rb @@ -30,7 +30,6 @@ class Chef class FileContentManagement class Deploy class MvWindows - Security = Chef::ReservedNames::Win32::Security ACL = Security::ACL @@ -96,10 +95,8 @@ class Chef dst_so.owner = dst_sd.owner dst_so.set_dacl(apply_dacl, dst_sd.dacl_inherits?) if dacl_present dst_so.set_sacl(apply_sacl, dst_sd.sacl_inherits?) if sacl_present - end end end end end - diff --git a/lib/chef/file_content_management/tempfile.rb b/lib/chef/file_content_management/tempfile.rb index 522a9fc43c..099198b8d0 100644 --- a/lib/chef/file_content_management/tempfile.rb +++ b/lib/chef/file_content_management/tempfile.rb @@ -21,7 +21,6 @@ require "tempfile" class Chef class FileContentManagement class Tempfile - attr_reader :new_resource def initialize(new_resource) @@ -64,7 +63,7 @@ class Chef # def tempfile_basename basename = ::File.basename(@new_resource.name) - basename.insert 0, "." unless Chef::Platform.windows? # dotfile if we're not on windows + basename.insert 0, "." unless Chef::Platform.windows? # dotfile if we're not on windows basename end @@ -90,7 +89,6 @@ class Chef end end end - end end end diff --git a/lib/chef/formatters/base.rb b/lib/chef/formatters/base.rb index 3a3e3336cc..a894655d74 100644 --- a/lib/chef/formatters/base.rb +++ b/lib/chef/formatters/base.rb @@ -24,12 +24,10 @@ require "chef/formatters/error_mapper" require "chef/formatters/indentable_output_stream" class Chef - # == Chef::Formatters # Formatters handle printing output about the progress/status of a chef # client run to the user's screen. module Formatters - class UnknownFormatter < StandardError; end def self.formatters_by_name @@ -60,7 +58,6 @@ class Chef # == Formatters::Base # Base class that all formatters should inherit from. class Base < EventDispatch::Base - include ErrorMapper def self.cli_name(name) @@ -212,7 +209,7 @@ class Chef file_load_failed(path, exception) end - def deprecation(message, location=caller(2..2)[0]) + def deprecation(message, location = caller(2..2)[0]) Chef::Log.deprecation("#{message} at #{location}") end @@ -221,18 +218,15 @@ class Chef end end - # == NullFormatter # Formatter that doesn't actually produce any output. You can use this to # disable the use of output formatters. class NullFormatter < Base - cli_name(:null) def is_formatter? false end end - end end diff --git a/lib/chef/formatters/doc.rb b/lib/chef/formatters/doc.rb index ab450cdeac..ad7688977d 100644 --- a/lib/chef/formatters/doc.rb +++ b/lib/chef/formatters/doc.rb @@ -3,11 +3,9 @@ require "chef/config" class Chef module Formatters - # Formatter similar to RSpec's documentation formatter. Uses indentation to # show context. class Doc < Formatters::Base - attr_reader :start_time, :end_time, :successful_audits, :failed_audits private :successful_audits, :failed_audits @@ -240,7 +238,7 @@ class Chef end # Called before action is executed on a resource. - def resource_action_start(resource, action, notification_type=nil, notifier=nil) + def resource_action_start(resource, action, notification_type = nil, notifier = nil) if resource.cookbook_name && resource.recipe_name resource_recipe = "#{resource.cookbook_name}::#{resource.recipe_name}" else @@ -282,7 +280,7 @@ class Chef # Called when a resource has no converge actions, e.g., it was already correct. def resource_up_to_date(resource, action) - @up_to_date_resources+= 1 + @up_to_date_resources += 1 puts " (up to date)", :stream => resource unindent end @@ -293,7 +291,6 @@ class Chef end def output_record(line) - end # Called when a change has been made to a resource. May be called multiple @@ -369,7 +366,7 @@ class Chef end end - def deprecation(message, location=caller(2..2)[0]) + def deprecation(message, location = caller(2..2)[0]) if Chef::Config[:treat_deprecation_warnings_as_errors] super end diff --git a/lib/chef/formatters/error_descriptor.rb b/lib/chef/formatters/error_descriptor.rb index eba1f057d8..d6669edf59 100644 --- a/lib/chef/formatters/error_descriptor.rb +++ b/lib/chef/formatters/error_descriptor.rb @@ -22,7 +22,6 @@ class Chef # == Formatters::ErrorDescription # Class for displaying errors on STDOUT. class ErrorDescription - attr_reader :sections def initialize(title) @@ -31,7 +30,7 @@ class Chef end def section(heading, text) - @sections << {heading => (text or "")} + @sections << { heading => (text or "") } end def display(out) @@ -61,7 +60,6 @@ class Chef out.puts text out.puts "\n" end - end end end diff --git a/lib/chef/formatters/error_inspectors.rb b/lib/chef/formatters/error_inspectors.rb index 9221ecda4d..bc891e3649 100644 --- a/lib/chef/formatters/error_inspectors.rb +++ b/lib/chef/formatters/error_inspectors.rb @@ -8,7 +8,6 @@ require "chef/formatters/error_inspectors/cookbook_sync_error_inspector" class Chef module Formatters - # == ErrorInspectors # Error inspectors wrap exceptions and contextual information. They # generate diagnostic messages about possible causes of the error for user diff --git a/lib/chef/formatters/error_inspectors/api_error_formatting.rb b/lib/chef/formatters/error_inspectors/api_error_formatting.rb index 0ea313eb92..5840bded83 100644 --- a/lib/chef/formatters/error_inspectors/api_error_formatting.rb +++ b/lib/chef/formatters/error_inspectors/api_error_formatting.rb @@ -20,24 +20,22 @@ require "chef/http/authenticator" class Chef module Formatters - module APIErrorFormatting - NETWORK_ERROR_CLASSES = [Errno::ECONNREFUSED, Timeout::Error, Errno::ETIMEDOUT, SocketError] def describe_network_errors(error_description) - error_description.section("Networking Error:",<<-E) + error_description.section("Networking Error:", <<-E) #{exception.message} Your chef_server_url may be misconfigured, or the network could be down. E - error_description.section("Relevant Config Settings:",<<-E) + error_description.section("Relevant Config Settings:", <<-E) chef_server_url "#{server_url}" E end def describe_eof_error(error_description) - error_description.section("Authentication Error:",<<-E) + error_description.section("Authentication Error:", <<-E) Received an EOF on transport socket. This almost always indicates a network error external to chef-client. Some causes include: @@ -74,18 +72,18 @@ broken virtual networking code. def describe_401_error(error_description) if clock_skew? - error_description.section("Authentication Error:",<<-E) + error_description.section("Authentication Error:", <<-E) Failed to authenticate to the chef server (http 401). The request failed because your clock has drifted by more than 15 minutes. Syncing your clock to an NTP Time source should resolve the issue. E else - error_description.section("Authentication Error:",<<-E) + error_description.section("Authentication Error:", <<-E) Failed to authenticate to the chef server (http 401). E error_description.section("Server Response:", format_rest_error) - error_description.section("Relevant Config Settings:",<<-E) + error_description.section("Relevant Config Settings:", <<-E) chef_server_url "#{server_url}" node_name "#{username}" client_key "#{api_key}" @@ -97,10 +95,10 @@ E end def describe_400_error(error_description) - error_description.section("Invalid Request Data:",<<-E) + error_description.section("Invalid Request Data:", <<-E) The data in your request was invalid (HTTP 400). E - error_description.section("Server Response:",format_rest_error) + error_description.section("Server Response:", format_rest_error) end def describe_406_error(error_description, response) @@ -110,7 +108,7 @@ E min_server_version = version_header["min_version"] max_server_version = version_header["max_version"] - error_description.section("Incompatible server API version:",<<-E) + error_description.section("Incompatible server API version:", <<-E) This version of the API that this Chef request specified is not supported by the Chef server you sent this request to. The server supports a min API version of #{min_server_version} and a max API version of #{max_server_version}. Chef just made a request with an API version of #{client_api_version}. @@ -122,18 +120,17 @@ E end def describe_500_error(error_description) - error_description.section("Unknown Server Error:",<<-E) + error_description.section("Unknown Server Error:", <<-E) The server had a fatal error attempting to load the node data. E error_description.section("Server Response:", format_rest_error) end def describe_503_error(error_description) - error_description.section("Server Unavailable","The Chef Server is temporarily unavailable") + error_description.section("Server Unavailable", "The Chef Server is temporarily unavailable") error_description.section("Server Response:", format_rest_error) end - # Fallback for unexpected/uncommon http errors def describe_http_error(error_description) error_description.section("Unexpected API Request Failure:", format_rest_error) @@ -179,7 +176,6 @@ E "Cannot fetch the contents of the response." end end - end end end diff --git a/lib/chef/formatters/error_inspectors/compile_error_inspector.rb b/lib/chef/formatters/error_inspectors/compile_error_inspector.rb index 589f98ddf2..d1020b8658 100644 --- a/lib/chef/formatters/error_inspectors/compile_error_inspector.rb +++ b/lib/chef/formatters/error_inspectors/compile_error_inspector.rb @@ -19,12 +19,10 @@ class Chef module Formatters module ErrorInspectors - # == CompileErrorInspector # Wraps exceptions that occur during the compile phase of a Chef run and # tries to find the code responsible for the error. class CompileErrorInspector - attr_reader :path attr_reader :exception @@ -40,7 +38,7 @@ class Chef error_description.section(exception.class.name, exception.message) if found_error_in_cookbooks? - traceback = filtered_bt.map {|line| " #{line}"}.join("\n") + traceback = filtered_bt.map { |line| " #{line}" }.join("\n") error_description.section("Cookbook Trace:", traceback) error_description.section("Relevant File Content:", context) end @@ -107,22 +105,22 @@ class Chef def culprit_backtrace_entry @culprit_backtrace_entry ||= begin - bt_entry = filtered_bt.first - Chef::Log.debug("Backtrace entry for compile error: '#{bt_entry}'") - bt_entry + bt_entry = filtered_bt.first + Chef::Log.debug("Backtrace entry for compile error: '#{bt_entry}'") + bt_entry end end def culprit_line @culprit_line ||= begin - line_number = culprit_backtrace_entry[/^(?:.\:)?[^:]+:([\d]+)/,1].to_i + line_number = culprit_backtrace_entry[/^(?:.\:)?[^:]+:([\d]+)/, 1].to_i Chef::Log.debug("Line number of compile error: '#{line_number}'") line_number end end def culprit_file - @culprit_file ||= culprit_backtrace_entry[/^((?:.\:)?[^:]+):([\d]+)/,1] + @culprit_file ||= culprit_backtrace_entry[/^((?:.\:)?[^:]+):([\d]+)/, 1] end def filtered_bt @@ -136,8 +134,8 @@ class Chef def backtrace_lines_in_cookbooks @backtrace_lines_in_cookbooks ||= begin - filters = Array(Chef::Config.cookbook_path).map {|p| /^#{Regexp.escape(p)}/i } - r = exception.backtrace.select {|line| filters.any? {|filter| line =~ filter }} + filters = Array(Chef::Config.cookbook_path).map { |p| /^#{Regexp.escape(p)}/i } + r = exception.backtrace.select { |line| filters.any? { |filter| line =~ filter } } Chef::Log.debug("Filtered backtrace of compile error: #{r.join(",")}") r end @@ -146,9 +144,7 @@ class Chef def exception_message_modifying_frozen? exception.message.include?("can't modify frozen") end - end - end end end diff --git a/lib/chef/formatters/error_inspectors/cookbook_resolve_error_inspector.rb b/lib/chef/formatters/error_inspectors/cookbook_resolve_error_inspector.rb index b60b9d91d1..9cd22d25e1 100644 --- a/lib/chef/formatters/error_inspectors/cookbook_resolve_error_inspector.rb +++ b/lib/chef/formatters/error_inspectors/cookbook_resolve_error_inspector.rb @@ -22,7 +22,6 @@ class Chef module Formatters module ErrorInspectors class CookbookResolveErrorInspector - attr_reader :exception attr_reader :expanded_run_list @@ -42,7 +41,7 @@ class Chef when *NETWORK_ERROR_CLASSES describe_network_errors(error_description) else - error_description.section("Unexpected Error:","#{exception.class.name}: #{exception.message}") + error_description.section("Unexpected Error:", "#{exception.class.name}: #{exception.message}") end end @@ -56,7 +55,7 @@ class Chef # TODO: we're rescuing errors from Node.find_or_create # * could be no write on nodes container # * could be no read on the node - error_description.section("Authorization Error",<<-E) + error_description.section("Authorization Error", <<-E) This client is not authorized to read some of the information required to access its cookbooks (HTTP 403). @@ -128,7 +127,7 @@ EOM end def expanded_run_list_ul - @expanded_run_list.map {|i| "* #{i}"}.join("\n") + @expanded_run_list.map { |i| "* #{i}" }.join("\n") end # In my tests, the error from the server is double JSON encoded, but we @@ -161,8 +160,6 @@ EOM rescue Exception maybe_json_string end - - end end end diff --git a/lib/chef/formatters/error_inspectors/cookbook_sync_error_inspector.rb b/lib/chef/formatters/error_inspectors/cookbook_sync_error_inspector.rb index 5ac39d7a83..d38a049a39 100644 --- a/lib/chef/formatters/error_inspectors/cookbook_sync_error_inspector.rb +++ b/lib/chef/formatters/error_inspectors/cookbook_sync_error_inspector.rb @@ -21,7 +21,6 @@ require "chef/formatters/error_inspectors/api_error_formatting" class Chef module Formatters module ErrorInspectors - # == CookbookSyncErrorInspector # Generates human-friendly explanations for errors encountered during # cookbook sync. @@ -29,7 +28,6 @@ class Chef # TODO: Not sure what errors are commonly seen during cookbook sync, so # the messaging is kinda generic. class CookbookSyncErrorInspector - include APIErrorFormatting attr_reader :exception @@ -48,7 +46,7 @@ class Chef when *NETWORK_ERROR_CLASSES describe_network_errors(error_description) else - error_description.section("Unexpected Error:","#{exception.class.name}: #{exception.message}") + error_description.section("Unexpected Error:", "#{exception.class.name}: #{exception.message}") end end @@ -75,7 +73,6 @@ class Chef describe_http_error(error_description) end end - end end end diff --git a/lib/chef/formatters/error_inspectors/node_load_error_inspector.rb b/lib/chef/formatters/error_inspectors/node_load_error_inspector.rb index b3196caddb..b1e883e2b5 100644 --- a/lib/chef/formatters/error_inspectors/node_load_error_inspector.rb +++ b/lib/chef/formatters/error_inspectors/node_load_error_inspector.rb @@ -21,12 +21,9 @@ require "chef/formatters/error_inspectors/api_error_formatting" class Chef module Formatters module ErrorInspectors - - # == APIErrorInspector # Wraps exceptions caused by API calls to the server. class NodeLoadErrorInspector - include APIErrorFormatting attr_reader :exception @@ -44,11 +41,11 @@ class Chef when Net::HTTPServerException, Net::HTTPFatalError humanize_http_exception(error_description) when Chef::Exceptions::PrivateKeyMissing - error_description.section("Private Key Not Found:",<<-E) + error_description.section("Private Key Not Found:", <<-E) Your private key could not be loaded. If the key file exists, ensure that it is readable by chef-client. E - error_description.section("Relevant Config Settings:",<<-E) + error_description.section("Relevant Config Settings:", <<-E) client_key "#{api_key}" E when EOFError @@ -56,7 +53,7 @@ E when *NETWORK_ERROR_CLASSES describe_network_errors(error_description) else - error_description.section("Unexpected Error:","#{exception.class.name}: #{exception.message}") + error_description.section("Unexpected Error:", "#{exception.class.name}: #{exception.message}") end end @@ -70,12 +67,12 @@ E # TODO: we're rescuing errors from Node.find_or_create # * could be no write on nodes container # * could be no read on the node - error_description.section("Authorization Error",<<-E) + error_description.section("Authorization Error", <<-E) Your client is not authorized to load the node data (HTTP 403). E error_description.section("Server Response:", format_rest_error) - error_description.section("Possible Causes:",<<-E) + error_description.section("Possible Causes:", <<-E) * Your client (#{username}) may have misconfigured authorization permissions. E when Net::HTTPBadRequest @@ -98,10 +95,10 @@ E # one, e.g., PUT http://wrong.url/nodes/node-name becomes a GET after a # redirect. def describe_404_error(error_description) - error_description.section("Resource Not Found:",<<-E) + error_description.section("Resource Not Found:", <<-E) The server returned a HTTP 404. This usually indicates that your chef_server_url is incorrect. E - error_description.section("Relevant Config Settings:",<<-E) + error_description.section("Relevant Config Settings:", <<-E) chef_server_url "#{server_url}" E end @@ -121,9 +118,7 @@ E def clock_skew? exception.response.body =~ /synchronize the clock/i end - end - end end end diff --git a/lib/chef/formatters/error_inspectors/registration_error_inspector.rb b/lib/chef/formatters/error_inspectors/registration_error_inspector.rb index 8c070742f7..e88dd05f69 100644 --- a/lib/chef/formatters/error_inspectors/registration_error_inspector.rb +++ b/lib/chef/formatters/error_inspectors/registration_error_inspector.rb @@ -1,7 +1,6 @@ class Chef module Formatters module ErrorInspectors - # == RegistrationErrorInspector # Wraps exceptions that occur during the client registration process and # suggests possible causes. @@ -26,25 +25,25 @@ class Chef when Net::HTTPServerException, Net::HTTPFatalError humanize_http_exception(error_description) when Errno::ECONNREFUSED, Timeout::Error, Errno::ETIMEDOUT, SocketError - error_description.section("Network Error:",<<-E) + error_description.section("Network Error:", <<-E) There was a network error connecting to the Chef Server: #{exception.message} E - error_description.section("Relevant Config Settings:",<<-E) + error_description.section("Relevant Config Settings:", <<-E) chef_server_url "#{server_url}" If your chef_server_url is correct, your network could be down. E when Chef::Exceptions::PrivateKeyMissing - error_description.section("Private Key Not Found:",<<-E) + error_description.section("Private Key Not Found:", <<-E) Your private key could not be loaded. If the key file exists, ensure that it is readable by chef-client. E - error_description.section("Relevant Config Settings:",<<-E) + error_description.section("Relevant Config Settings:", <<-E) validation_key "#{api_key}" E when Chef::Exceptions::InvalidRedirect - error_description.section("Invalid Redirect:",<<-E) + error_description.section("Invalid Redirect:", <<-E) Change your server location in client.rb to the server's FQDN to avoid unwanted redirections. E when EOFError @@ -59,18 +58,18 @@ E case response when Net::HTTPUnauthorized if clock_skew? - error_description.section("Authentication Error:",<<-E) + error_description.section("Authentication Error:", <<-E) Failed to authenticate to the chef server (http 401). The request failed because your clock has drifted by more than 15 minutes. Syncing your clock to an NTP Time source should resolve the issue. E else - error_description.section("Authentication Error:",<<-E) + error_description.section("Authentication Error:", <<-E) Failed to authenticate to the chef server (http 401). E error_description.section("Server Response:", format_rest_error) - error_description.section("Relevant Config Settings:",<<-E) + error_description.section("Relevant Config Settings:", <<-E) chef_server_url "#{server_url}" validation_client_name "#{username}" validation_key "#{api_key}" @@ -79,34 +78,34 @@ If these settings are correct, your validation_key may be invalid. E end when Net::HTTPForbidden - error_description.section("Authorization Error:",<<-E) + error_description.section("Authorization Error:", <<-E) Your validation client is not authorized to create the client for this node (HTTP 403). E - error_description.section("Possible Causes:",<<-E) + error_description.section("Possible Causes:", <<-E) * There may already be a client named "#{config[:node_name]}" * Your validation client (#{username}) may have misconfigured authorization permissions. E when Net::HTTPBadRequest - error_description.section("Invalid Request Data:",<<-E) + error_description.section("Invalid Request Data:", <<-E) The data in your request was invalid (HTTP 400). E - error_description.section("Server Response:",format_rest_error) + error_description.section("Server Response:", format_rest_error) when Net::HTTPNotFound - error_description.section("Resource Not Found:",<<-E) + error_description.section("Resource Not Found:", <<-E) The server returned a HTTP 404. This usually indicates that your chef_server_url is incorrect. E - error_description.section("Relevant Config Settings:",<<-E) + error_description.section("Relevant Config Settings:", <<-E) chef_server_url "#{server_url}" E when Net::HTTPNotAcceptable describe_406_error(error_description, response) when Net::HTTPInternalServerError - error_description.section("Unknown Server Error:",<<-E) + error_description.section("Unknown Server Error:", <<-E) The server had a fatal error attempting to load the node data. E error_description.section("Server Response:", format_rest_error) when Net::HTTPBadGateway, Net::HTTPServiceUnavailable - error_description.section("Server Unavailable","The Chef Server is temporarily unavailable") + error_description.section("Server Unavailable", "The Chef Server is temporarily unavailable") error_description.section("Server Response:", format_rest_error) else error_description.section("Unexpected API Request Failure:", format_rest_error) @@ -140,7 +139,6 @@ E rescue Exception exception.response.body end - end end end diff --git a/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb b/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb index 73e2f0c4d3..0d121a6371 100644 --- a/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb +++ b/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb @@ -21,7 +21,6 @@ class Chef module Formatters module ErrorInspectors class ResourceFailureInspector - attr_reader :resource attr_reader :action attr_reader :exception @@ -69,13 +68,11 @@ class Chef relevant_lines = ["# In #{file}\n\n"] - current_line = line - 1 current_line = 0 if current_line < 0 nesting = 0 loop do - # low rent parser. try to gracefully handle nested blocks in resources nesting += 1 if lines[current_line] =~ /[\s]+do[\s]*/ nesting -= 1 if lines[current_line] =~ /end[\s]*$/ @@ -99,8 +96,8 @@ class Chef end def filtered_bt - filters = Array(Chef::Config.cookbook_path).map {|p| /^#{Regexp.escape(p)}/ } - exception.backtrace.select {|line| filters.any? {|filter| line =~ filter }} + filters = Array(Chef::Config.cookbook_path).map { |p| /^#{Regexp.escape(p)}/ } + exception.backtrace.select { |line| filters.any? { |filter| line =~ filter } } end private @@ -112,15 +109,12 @@ class Chef end def parse_source - resource.source_line[/^(([\w]:)?[^:]+):([\d]+)/,1] + resource.source_line[/^(([\w]:)?[^:]+):([\d]+)/, 1] end def parse_line(source) - resource.source_line[/^#{Regexp.escape(source)}:([\d]+)/,1].to_i + resource.source_line[/^#{Regexp.escape(source)}:([\d]+)/, 1].to_i end - - - end end 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 08fcdea609..78d35646a4 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 @@ -23,7 +23,6 @@ class Chef module Formatters module ErrorInspectors class RunListExpansionErrorInspector - include APIErrorFormatting attr_reader :exception @@ -36,7 +35,7 @@ class Chef def add_explanation(error_description) case exception when Errno::ECONNREFUSED, Timeout::Error, Errno::ETIMEDOUT, SocketError - error_description.section("Networking Error:",<<-E) + error_description.section("Networking Error:", <<-E) #{exception.message} Your chef_server_url may be misconfigured, or the network could be down. @@ -48,13 +47,13 @@ E when EOFError describe_eof_error(error_description) else - error_description.section("Unexpected Error:","#{exception.class.name}: #{exception.message}") + error_description.section("Unexpected Error:", "#{exception.class.name}: #{exception.message}") end end def describe_missing_role(error_description) error_description.section("Missing Role(s) in Run List:", missing_roles_explained) - original_run_list = node.run_list.map {|item| "* #{item}"}.join("\n") + original_run_list = node.run_list.map { |item| "* #{item}" }.join("\n") error_description.section("Original Run List", original_run_list) end @@ -76,12 +75,12 @@ E response = exception.response case response when Net::HTTPUnauthorized - error_description.section("Authentication Error:",<<-E) + error_description.section("Authentication Error:", <<-E) Failed to authenticate to the chef server (http 401). E error_description.section("Server Response:", format_rest_error) - error_description.section("Relevant Config Settings:",<<-E) + error_description.section("Relevant Config Settings:", <<-E) chef_server_url "#{server_url}" node_name "#{username}" client_key "#{api_key}" @@ -92,29 +91,28 @@ E # TODO: we're rescuing errors from Node.find_or_create # * could be no write on nodes container # * could be no read on the node - error_description.section("Authorization Error",<<-E) + error_description.section("Authorization Error", <<-E) Your client is not authorized to load one or more of your roles (HTTP 403). E error_description.section("Server Response:", format_rest_error) - error_description.section("Possible Causes:",<<-E) + error_description.section("Possible Causes:", <<-E) * Your client (#{username}) may have misconfigured authorization permissions. E when Net::HTTPNotAcceptable describe_406_error(error_description, response) when Net::HTTPInternalServerError - error_description.section("Unknown Server Error:",<<-E) + error_description.section("Unknown Server Error:", <<-E) The server had a fatal error attempting to load a role. E error_description.section("Server Response:", format_rest_error) when Net::HTTPBadGateway, Net::HTTPServiceUnavailable - error_description.section("Server Unavailable","The Chef Server is temporarily unavailable") + error_description.section("Server Unavailable", "The Chef Server is temporarily unavailable") error_description.section("Server Response:", format_rest_error) else error_description.section("Unexpected API Request Failure:", format_rest_error) end end - end end end diff --git a/lib/chef/formatters/error_mapper.rb b/lib/chef/formatters/error_mapper.rb index 4786a20465..5cffecab96 100644 --- a/lib/chef/formatters/error_mapper.rb +++ b/lib/chef/formatters/error_mapper.rb @@ -23,7 +23,6 @@ class Chef # Formatters::ErrorDescription objects based on node, # exception, and configuration information. module ErrorMapper - # Failed to register this client with the server. def self.registration_failed(node_name, exception, config) error_inspector = ErrorInspectors::RegistrationErrorInspector.new(node_name, exception, config) diff --git a/lib/chef/formatters/indentable_output_stream.rb b/lib/chef/formatters/indentable_output_stream.rb index e5e84e0f65..d0517e90cc 100644 --- a/lib/chef/formatters/indentable_output_stream.rb +++ b/lib/chef/formatters/indentable_output_stream.rb @@ -2,7 +2,6 @@ class Chef module Formatters # Handles basic indentation and colorization tasks class IndentableOutputStream - attr_reader :out attr_reader :err attr_accessor :indent diff --git a/lib/chef/formatters/minimal.rb b/lib/chef/formatters/minimal.rb index 94fbfd3818..b005ca4c8f 100644 --- a/lib/chef/formatters/minimal.rb +++ b/lib/chef/formatters/minimal.rb @@ -1,10 +1,7 @@ require "chef/formatters/base" class Chef - module Formatters - - # == Formatters::Minimal # Shows the progress of the chef run by printing single characters, and # displays a summary of updates at the conclusion of the run. For events @@ -13,18 +10,16 @@ class Chef # if the resource is up to date, skipped by not_if/only_if, or updated, # respectively. class Minimal < Formatters::Base - cli_name(:minimal) cli_name(:min) attr_reader :updated_resources attr_reader :updates_by_resource - def initialize(out, err) super @updated_resources = [] - @updates_by_resource = Hash.new {|h, k| h[k] = []} + @updates_by_resource = Hash.new { |h, k| h[k] = [] } end # Called at the very start of a Chef Run @@ -168,7 +163,7 @@ class Chef end # Called before action is executed on a resource. - def resource_action_start(resource, action, notification_type=nil, notifier=nil) + def resource_action_start(resource, action, notification_type = nil, notifier = nil) end # Called when a resource fails, but will retry. @@ -229,8 +224,6 @@ class Chef # callback for it. def msg(message) end - end end end - diff --git a/lib/chef/guard_interpreter/default_guard_interpreter.rb b/lib/chef/guard_interpreter/default_guard_interpreter.rb index c125d85ba3..449ca9a316 100644 --- a/lib/chef/guard_interpreter/default_guard_interpreter.rb +++ b/lib/chef/guard_interpreter/default_guard_interpreter.rb @@ -41,4 +41,3 @@ class Chef end end end - diff --git a/lib/chef/guard_interpreter/resource_guard_interpreter.rb b/lib/chef/guard_interpreter/resource_guard_interpreter.rb index 7aa9950207..a34f74544d 100644 --- a/lib/chef/guard_interpreter/resource_guard_interpreter.rb +++ b/lib/chef/guard_interpreter/resource_guard_interpreter.rb @@ -21,7 +21,6 @@ require "chef/guard_interpreter" class Chef class GuardInterpreter class ResourceGuardInterpreter < DefaultGuardInterpreter - def initialize(parent_resource, command, opts, &block) super(command, opts) @parent_resource = parent_resource @@ -42,9 +41,9 @@ class Chef # We need to make sure we check for Script first because any resource # that can get to here is an Execute resource. if @resource.is_a? Chef::Resource::Script - block_attributes = @command_opts.merge({:code => @command}) + block_attributes = @command_opts.merge({ :code => @command }) else - block_attributes = @command_opts.merge({:command => @command}) + block_attributes = @command_opts.merge({ :command => @command }) end # Handles cases like powershell_script where default @@ -62,7 +61,7 @@ class Chef protected - def evaluate_action(action=nil, &block) + def evaluate_action(action = nil, &block) @resource.instance_eval(&block) run_action = action || @resource.action @@ -71,7 +70,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 { |action_to_run| @resource.run_action(action_to_run) } resource_updated = @resource.updated rescue Mixlib::ShellOut::ShellCommandFailed resource_updated = nil diff --git a/lib/chef/handler.rb b/lib/chef/handler.rb index b720a11a45..e5affa0a53 100644 --- a/lib/chef/handler.rb +++ b/lib/chef/handler.rb @@ -56,7 +56,6 @@ class Chef # end # class Handler - # The list of currently configured start handlers def self.start_handlers Array(Chef::Config[:start_handlers]) @@ -230,6 +229,5 @@ class Chef def data @run_status.to_hash end - end end diff --git a/lib/chef/handler/error_report.rb b/lib/chef/handler/error_report.rb index e84a817e06..fd61cfb7bf 100644 --- a/lib/chef/handler/error_report.rb +++ b/lib/chef/handler/error_report.rb @@ -22,12 +22,10 @@ require "chef/resource/directory" class Chef class Handler class ErrorReport < ::Chef::Handler - def report Chef::FileCache.store("failed-run-data.json", Chef::JSONCompat.to_json_pretty(data), 0640) Chef::Log.fatal("Saving node information to #{Chef::FileCache.load("failed-run-data.json", false)}") end - end end end diff --git a/lib/chef/handler/json_file.rb b/lib/chef/handler/json_file.rb index 91bd6e1559..9b6a3a862d 100644 --- a/lib/chef/handler/json_file.rb +++ b/lib/chef/handler/json_file.rb @@ -22,10 +22,9 @@ require "chef/resource/directory" class Chef class Handler class JsonFile < ::Chef::Handler - attr_reader :config - def initialize(config={}) + def initialize(config = {}) @config = config @config[:path] ||= "/var/chef/reports" @config @@ -41,7 +40,6 @@ class Chef build_report_dir savetime = Time.now.strftime("%Y%m%d%H%M%S") File.open(File.join(config[:path], "chef-run-report-#{savetime}.json"), "w") do |file| - #ensure start time and end time are output in the json properly in the event activesupport happens to be on the system run_data = data run_data[:start_time] = run_data[:start_time].to_s @@ -57,7 +55,6 @@ class Chef File.chmod(00700, config[:path]) end end - end end end diff --git a/lib/chef/http.rb b/lib/chef/http.rb index e4a778611d..9d6d2fb626 100644 --- a/lib/chef/http.rb +++ b/lib/chef/http.rb @@ -31,11 +31,9 @@ require "chef/platform/query_helpers" require "chef/exceptions" class Chef - # == Chef::HTTP # Basic HTTP client, with support for adding features via middleware class HTTP - # Class for applying middleware behaviors to streaming # responses. Collects stream handlers (if any) from each # middleware. When #handle_chunk is called, the chunk gets @@ -58,10 +56,8 @@ class Chef handler.handle_chunk(chunk) end end - end - def self.middlewares @middlewares ||= [] end @@ -81,7 +77,7 @@ class Chef # all subsequent requests. For example, when initialized with a base url # http://localhost:4000, a call to +get+ with 'nodes' will make an # HTTP GET request to http://localhost:4000/nodes - def initialize(url, options={}) + def initialize(url, options = {}) @url = url @default_headers = options[:headers] || {} @sign_on_redirect = true @@ -99,7 +95,7 @@ class Chef # # === Parameters # path:: path part of the request URL - def head(path, headers={}) + def head(path, headers = {}) request(:HEAD, path, headers) end @@ -107,7 +103,7 @@ class Chef # # === Parameters # path:: The path to GET - def get(path, headers={}) + def get(path, headers = {}) request(:GET, path, headers) end @@ -115,7 +111,7 @@ class Chef # # === Parameters # path:: path part of the request URL - def put(path, json, headers={}) + def put(path, json, headers = {}) request(:PUT, path, headers, json) end @@ -123,7 +119,7 @@ class Chef # # === Parameters # path:: path part of the request URL - def post(path, json, headers={}) + def post(path, json, headers = {}) request(:POST, path, headers, json) end @@ -131,13 +127,13 @@ class Chef # # === Parameters # path:: path part of the request URL - def delete(path, headers={}) + def delete(path, headers = {}) request(:DELETE, path, headers) end # Makes an HTTP request to +path+ with the given +method+, +headers+, and # +data+ (if applicable). - def request(method, path, headers={}, data=false) + def request(method, path, headers = {}, data = false) url = create_url(path) method, url, headers, data = apply_request_middleware(method, url, headers, data) @@ -160,7 +156,7 @@ class Chef # # If no block is given, the tempfile is returned, which means it's up to # you to unlink the tempfile when you're done with it. - def streaming_request(path, headers={}, &block) + def streaming_request(path, headers = {}, &block) url = create_url(path) response, rest_request, return_value = nil, nil, nil tempfile = nil @@ -196,7 +192,7 @@ class Chef raise end - def http_client(base_url=nil) + def http_client(base_url = nil) base_url ||= url if chef_zero_uri?(base_url) # PERFORMANCE CRITICAL: *MUST* lazy require here otherwise we load up webrick @@ -272,7 +268,7 @@ class Chef if block_given? request, response = client.request(method, url, body, headers, &response_handler) else - request, response = client.request(method, url, body, headers) {|r| r.read_body } + request, response = client.request(method, url, body, headers) { |r| r.read_body } return_value = response.read_body end @last_response = response @@ -284,7 +280,7 @@ class Chef elsif redirect_location = redirected_to(response) if [:GET, :HEAD].include?(method) follow_redirect do - send_http_request(method, url+redirect_location, headers, body, &response_handler) + send_http_request(method, url + redirect_location, headers, body, &response_handler) end else raise Exceptions::InvalidRedirect, "#{method} request was redirected from #{url} to #{redirect_location}. Only GET and HEAD support redirects." @@ -295,7 +291,6 @@ class Chef end end - # Wraps an HTTP request with retry logic. # === Arguments # url:: URL of the request, used for error messages @@ -308,7 +303,7 @@ class Chef # handle HTTP 50X Error if response.kind_of?(Net::HTTPServerError) && !Chef::Config.local_mode if http_retry_count - http_attempts + 1 > 0 - sleep_time = 1 + (2 ** http_attempts) + rand(2 ** http_attempts) + sleep_time = 1 + (2**http_attempts) + rand(2**http_attempts) Chef::Log.error("Server returned error #{response.code} for #{url}, retrying #{http_attempts}/#{http_retry_count} in #{sleep_time}s") sleep(sleep_time) redo @@ -384,7 +379,7 @@ class Chef response["location"] end - def build_headers(method, url, headers={}, json_body=false) + def build_headers(method, url, headers = {}, json_body = false) headers = @default_headers.merge(headers) headers["Content-Length"] = json_body.bytesize.to_s if json_body headers.merge!(Chef::Config[:custom_http_headers]) if Chef::Config[:custom_http_headers] @@ -412,7 +407,6 @@ class Chef raise end - public ############################################################################ @@ -425,6 +419,5 @@ class Chef def last_response @last_response end - end end diff --git a/lib/chef/http/auth_credentials.rb b/lib/chef/http/auth_credentials.rb index 3db8b1bfe8..6005932acd 100644 --- a/lib/chef/http/auth_credentials.rb +++ b/lib/chef/http/auth_credentials.rb @@ -28,7 +28,7 @@ class Chef class AuthCredentials attr_reader :client_name, :key - def initialize(client_name=nil, key=nil) + def initialize(client_name = nil, key = nil) @client_name, @key = client_name, key end @@ -36,7 +36,7 @@ class Chef !!key end - def signature_headers(request_params={}) + def signature_headers(request_params = {}) raise ArgumentError, "Cannot sign the request without a client name, check that :node_name is assigned" if client_name.nil? Chef::Log.debug("Signing the request as #{client_name}") @@ -48,10 +48,9 @@ class Chef host = request_params.delete(:host) || "localhost" sign_obj = Mixlib::Authentication::SignedHeaderAuth.signing_object(request_params) - signed = sign_obj.sign(key).merge({:host => host}) - signed.inject({}){|memo, kv| memo["#{kv[0].to_s.upcase}"] = kv[1];memo} + signed = sign_obj.sign(key).merge({ :host => host }) + signed.inject({}) { |memo, kv| memo["#{kv[0].to_s.upcase}"] = kv[1];memo } end - end end end diff --git a/lib/chef/http/authenticator.rb b/lib/chef/http/authenticator.rb index d84f8dde55..b755c82503 100644 --- a/lib/chef/http/authenticator.rb +++ b/lib/chef/http/authenticator.rb @@ -23,7 +23,6 @@ require "openssl" class Chef class HTTP class Authenticator - DEFAULT_SERVER_API_VERSION = "1" attr_reader :signing_key_filename @@ -33,7 +32,7 @@ class Chef attr_accessor :sign_request - def initialize(opts={}) + def initialize(opts = {}) @raw_key = nil @sign_request = true @signing_key_filename = opts[:signing_key_filename] @@ -46,8 +45,8 @@ class Chef end end - def handle_request(method, url, headers={}, data=false) - headers.merge!({"X-Ops-Server-API-Version" => @api_version}) + def handle_request(method, url, headers = {}, data = false) + headers.merge!({ "X-Ops-Server-API-Version" => @api_version }) headers.merge!(authentication_headers(method, url, data, headers)) if sign_requests? [method, url, headers, data] end @@ -90,7 +89,7 @@ class Chef raise Chef::Exceptions::InvalidPrivateKey, msg end - def authentication_headers(method, url, json_body=nil, headers=nil) + def authentication_headers(method, url, json_body = nil, headers = nil) request_params = { :http_method => method, :path => url.path, diff --git a/lib/chef/http/basic_client.rb b/lib/chef/http/basic_client.rb index 5f0415996f..608e68ed2d 100644 --- a/lib/chef/http/basic_client.rb +++ b/lib/chef/http/basic_client.rb @@ -28,7 +28,6 @@ require "chef/http/http_request" class Chef class HTTP class BasicClient - HTTPS = "https".freeze attr_reader :url @@ -40,7 +39,7 @@ class Chef # url:: An URI for the remote server. # === Options: # ssl_policy:: The SSL Policy to use, defaults to DefaultSSLPolicy - def initialize(url, opts={}) + def initialize(url, opts = {}) @url = url @ssl_policy = opts[:ssl_policy] || DefaultSSLPolicy @http_client = build_http_client @@ -54,7 +53,7 @@ class Chef @url.port end - def request(method, url, req_body, base_headers={}) + def request(method, url, req_body, base_headers = {}) http_request = HTTPRequest.new(method, url, req_body, base_headers).http_request Chef::Log.debug("Initiating #{method} to #{url}") Chef::Log.debug("---- HTTP Request Header Data: ----") @@ -105,12 +104,12 @@ class Chef # here since we are really just trying to get the string built correctly. if String === proxy && !proxy.strip.empty? if proxy.match(/^.*:\/\//) - proxy = URI.parse(proxy.strip) + proxy = URI.parse(proxy.strip) else - proxy = URI.parse("#{url.scheme}://#{proxy.strip}") - end + proxy = URI.parse("#{url.scheme}://#{proxy.strip}") + end end - + no_proxy = Chef::Config[:no_proxy] || env["NO_PROXY"] || env["no_proxy"] excludes = no_proxy.to_s.split(/\s*,\s*/).compact excludes = excludes.map { |exclude| exclude =~ /:\d+$/ ? exclude : "#{exclude}:*" } @@ -151,19 +150,18 @@ class Chef def http_proxy_user(http_proxy) http_proxy.user || Chef::Config["#{url.scheme}_proxy_user"] || - env["#{url.scheme.upcase}_PROXY_USER"] || env["#{url.scheme}_proxy_user"] + env["#{url.scheme.upcase}_PROXY_USER"] || env["#{url.scheme}_proxy_user"] end def http_proxy_pass(http_proxy) http_proxy.password || Chef::Config["#{url.scheme}_proxy_pass"] || - env["#{url.scheme.upcase}_PROXY_PASS"] || env["#{url.scheme}_proxy_pass"] + env["#{url.scheme.upcase}_PROXY_PASS"] || env["#{url.scheme}_proxy_pass"] end def configure_ssl(http_client) http_client.use_ssl = true ssl_policy.apply_to(http_client) end - end end end diff --git a/lib/chef/http/cookie_manager.rb b/lib/chef/http/cookie_manager.rb index a99a8f1cd9..4885f7ddab 100644 --- a/lib/chef/http/cookie_manager.rb +++ b/lib/chef/http/cookie_manager.rb @@ -20,18 +20,16 @@ require "chef/http/cookie_jar" class Chef class HTTP - # An HTTP middleware to manage storing/sending cookies in HTTP requests. # Most HTTP communication in Chef does not need cookies, it was originally # implemented to support OpenID, but it's not known who might be relying on # it, so it's included with Chef::REST class CookieManager - - def initialize(options={}) + def initialize(options = {}) @cookies = CookieJar.instance end - def handle_request(method, url, headers={}, data=false) + def handle_request(method, url, headers = {}, data = false) @host, @port = url.host, url.port if @cookies.has_key?("#{@host}:#{@port}") headers["Cookie"] = @cookies["#{@host}:#{@port}"] @@ -53,7 +51,6 @@ class Chef def handle_stream_complete(http_response, rest_request, return_value) [http_response, rest_request, return_value] end - end end end diff --git a/lib/chef/http/decompressor.rb b/lib/chef/http/decompressor.rb index c9b808861c..280c891164 100644 --- a/lib/chef/http/decompressor.rb +++ b/lib/chef/http/decompressor.rb @@ -21,7 +21,6 @@ require "chef/http/http_request" class Chef class HTTP - # Middleware-esque class for handling compression in HTTP responses. class Decompressor class NoopInflater @@ -50,12 +49,12 @@ class Chef DEFLATE = "deflate".freeze IDENTITY = "identity".freeze - def initialize(opts={}) + def initialize(opts = {}) @disable_gzip = false handle_options(opts) end - def handle_request(method, url, headers={}, data=false) + def handle_request(method, url, headers = {}, data = false) headers[HTTPRequest::ACCEPT_ENCODING] = HTTPRequest::ENCODING_GZIP_DEFLATE unless gzip_disabled? [method, url, headers, data] end @@ -114,7 +113,6 @@ class Chef end end - # gzip is disabled using the disable_gzip => true option in the # constructor. When gzip is disabled, no 'Accept-Encoding' header will be # set, and the response will not be decompressed, no matter what the @@ -137,8 +135,6 @@ class Chef end end end - - end end end diff --git a/lib/chef/http/http_request.rb b/lib/chef/http/http_request.rb index 1590537f19..f98e2bbbf0 100644 --- a/lib/chef/http/http_request.rb +++ b/lib/chef/http/http_request.rb @@ -37,7 +37,6 @@ require "chef/version" class Chef class HTTP class HTTPRequest - engine = defined?(RUBY_ENGINE) ? RUBY_ENGINE : "ruby" UA_COMMON = "/#{::Chef::VERSION} (#{engine}-#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}; ohai-#{Ohai::VERSION}; #{RUBY_PLATFORM}; +https://chef.io)" @@ -72,7 +71,7 @@ class Chef attr_reader :method, :url, :headers, :http_client, :http_request - def initialize(method, url, req_body, base_headers={}) + def initialize(method, url, req_body, base_headers = {}) @method, @url = method, url @request_body = nil build_headers(base_headers) @@ -145,13 +144,12 @@ class Chef # for the url scheme (80;443) - Fixes CHEF-5355 host_header = uri_safe_host.dup host_header << ":#{port}" unless URI_SCHEME_DEFAULT_PORT[@url.scheme] == port.to_i - @headers["Host"] = host_header unless @headers.keys.any? {|k| k.downcase.to_s == HOST_LOWER } + @headers["Host"] = host_header unless @headers.keys.any? { |k| k.downcase.to_s == HOST_LOWER } @headers end - - def configure_http_request(request_body=nil) + def configure_http_request(request_body = nil) req_path = "#{path}" req_path << "?#{query}" if query @@ -181,7 +179,6 @@ class Chef # Overwrite default UA @http_request[USER_AGENT] = self.class.user_agent end - end end end diff --git a/lib/chef/http/json_input.rb b/lib/chef/http/json_input.rb index 2fd1501b1d..ae2c0ac2b7 100644 --- a/lib/chef/http/json_input.rb +++ b/lib/chef/http/json_input.rb @@ -21,17 +21,15 @@ require "chef/json_compat" class Chef class HTTP - # Middleware that takes json input and turns it into raw text class JSONInput - attr_accessor :opts - def initialize(opts={}) + def initialize(opts = {}) @opts = opts end - def handle_request(method, url, headers={}, data=false) + def handle_request(method, url, headers = {}, data = false) if data && should_encode_as_json?(headers) headers.delete_if { |key, _value| key.downcase == "content-type" } headers["Content-Type"] = "application/json" @@ -64,10 +62,9 @@ class Chef # ruby/Net::HTTP don't enforce capitalized headers (it normalizes them # for you before sending the request), so we have to account for all # the variations we might find - requested_content_type = headers.find {|k, v| k.downcase == "content-type" } + requested_content_type = headers.find { |k, v| k.downcase == "content-type" } requested_content_type.nil? || requested_content_type.last.include?("json") end - end end end diff --git a/lib/chef/http/json_output.rb b/lib/chef/http/json_output.rb index 6814fa1a55..982b329e4d 100644 --- a/lib/chef/http/json_output.rb +++ b/lib/chef/http/json_output.rb @@ -22,19 +22,17 @@ require "chef/log" class Chef class HTTP - # Middleware that takes an HTTP response, parses it as JSON if possible. class JSONOutput - attr_accessor :raw_output attr_accessor :inflate_json_class - def initialize(opts={}) + def initialize(opts = {}) @raw_output = opts[:raw_output] @inflate_json_class = opts[:inflate_json_class] end - def handle_request(method, url, headers={}, data=false) + def handle_request(method, url, headers = {}, data = false) # Ideally this should always set Accept to application/json, but # Chef::REST is sometimes used to make non-JSON requests, so it sets # Accept to the desired value before middlewares get called. @@ -72,7 +70,6 @@ class Chef def stream_response_handler(response) nil end - end end end diff --git a/lib/chef/http/json_to_model_output.rb b/lib/chef/http/json_to_model_output.rb index 99878fe629..c69080ad57 100644 --- a/lib/chef/http/json_to_model_output.rb +++ b/lib/chef/http/json_to_model_output.rb @@ -20,12 +20,11 @@ require "chef/http/json_output" class Chef class HTTP - # A Middleware-ish thing that takes an HTTP response, parses it as JSON if # possible, and converts it into an appropriate model object if it contains # a `json_class` key. class JSONToModelOutput < JSONOutput - def initialize(opts={}) + def initialize(opts = {}) opts[:inflate_json_class] = true if !opts.has_key?(:inflate_json_class) super end diff --git a/lib/chef/http/remote_request_id.rb b/lib/chef/http/remote_request_id.rb index ba6108e063..f186242f7e 100644 --- a/lib/chef/http/remote_request_id.rb +++ b/lib/chef/http/remote_request_id.rb @@ -20,12 +20,11 @@ require "chef/request_id" class Chef class HTTP class RemoteRequestID - - def initialize(opts={}) + def initialize(opts = {}) end - def handle_request(method, url, headers={}, data=false) - headers.merge!({"X-REMOTE-REQUEST-ID" => Chef::RequestID.instance.request_id}) + def handle_request(method, url, headers = {}, data = false) + headers.merge!({ "X-REMOTE-REQUEST-ID" => Chef::RequestID.instance.request_id }) [method, url, headers, data] end @@ -40,7 +39,6 @@ class Chef def handle_stream_complete(http_response, rest_request, return_value) [http_response, rest_request, return_value] end - end end end diff --git a/lib/chef/http/simple.rb b/lib/chef/http/simple.rb index bdbc31c9f1..270aad00bd 100644 --- a/lib/chef/http/simple.rb +++ b/lib/chef/http/simple.rb @@ -24,9 +24,7 @@ require "chef/http/validate_content_length" class Chef class HTTP - class Simple < HTTP - use Decompressor use CookieManager @@ -34,7 +32,6 @@ class Chef # because the order of middlewares is reversed when handling # responses. use ValidateContentLength - end end end diff --git a/lib/chef/http/simple_json.rb b/lib/chef/http/simple_json.rb index 7357d859ee..685c9b40d6 100644 --- a/lib/chef/http/simple_json.rb +++ b/lib/chef/http/simple_json.rb @@ -24,9 +24,7 @@ require "chef/http/validate_content_length" class Chef class HTTP - class SimpleJSON < HTTP - use JSONInput use JSONOutput use CookieManager @@ -37,7 +35,6 @@ class Chef # because the order of middlewares is reversed when handling # responses. use ValidateContentLength - end end end diff --git a/lib/chef/http/socketless_chef_zero_client.rb b/lib/chef/http/socketless_chef_zero_client.rb index ef2e8732cc..71028ec200 100644 --- a/lib/chef/http/socketless_chef_zero_client.rb +++ b/lib/chef/http/socketless_chef_zero_client.rb @@ -47,14 +47,11 @@ require "chef_zero/server" class Chef class HTTP - # HTTP Client class that talks directly to Zero via the Rack interface. class SocketlessChefZeroClient - # This module is extended into Net::HTTP Response objects created from # Socketless Chef Zero responses. module ResponseExts - # Net::HTTP raises an error if #read_body is called with a block or # file argument after the body has already been read from the network. # @@ -72,7 +69,6 @@ class Chef super end end - end attr_reader :url @@ -133,7 +129,7 @@ class Chef 511 => "Network Authentication Required", } - STATUS_MESSAGE.values.each {|v| v.freeze } + STATUS_MESSAGE.values.each { |v| v.freeze } STATUS_MESSAGE.freeze def initialize(base_url) @@ -195,13 +191,10 @@ class Chef private def headers_extracted_from_options - options.reject {|name, _| KNOWN_OPTIONS.include?(name) }.map { |name, value| + options.reject { |name, _| KNOWN_OPTIONS.include?(name) }.map { |name, value| [name.to_s.split("_").map { |segment| segment.capitalize }.join("-"), value] } end - - end - end end diff --git a/lib/chef/http/ssl_policies.rb b/lib/chef/http/ssl_policies.rb index f49fca02f6..41cd23d636 100644 --- a/lib/chef/http/ssl_policies.rb +++ b/lib/chef/http/ssl_policies.rb @@ -26,11 +26,9 @@ require "chef/util/path_helper" class Chef class HTTP - # == Chef::HTTP::DefaultSSLPolicy # Configures SSL behavior on an HTTP object via visitor pattern. class DefaultSSLPolicy - def self.apply_to(http_client) new(http_client).apply http_client @@ -112,11 +110,9 @@ class Chef rescue OpenSSL::X509::StoreError => e raise e unless e.message == "cert already in hash table" end - end class APISSLPolicy < DefaultSSLPolicy - def set_verify_mode if config[:ssl_verify_mode] == :verify_peer or config[:verify_api_cert] http_client.verify_mode = OpenSSL::SSL::VERIFY_PEER @@ -125,6 +121,5 @@ class Chef end end end - end end diff --git a/lib/chef/http/validate_content_length.rb b/lib/chef/http/validate_content_length.rb index c92360adfe..4dbadefcb3 100644 --- a/lib/chef/http/validate_content_length.rb +++ b/lib/chef/http/validate_content_length.rb @@ -21,13 +21,11 @@ require "chef/log" class Chef class HTTP - # Middleware that validates the Content-Length header against the downloaded number of bytes. # # This must run before the decompressor middleware, since otherwise we will count the uncompressed # streamed bytes, rather than the on-the-wire compressed bytes. class ValidateContentLength - class ContentLengthCounter attr_accessor :content_length @@ -41,10 +39,10 @@ class Chef end end - def initialize(opts={}) + def initialize(opts = {}) end - def handle_request(method, url, headers={}, data=false) + def handle_request(method, url, headers = {}, data = false) [method, url, headers, data] end diff --git a/lib/chef/json_compat.rb b/lib/chef/json_compat.rb index 79b86a4a37..91baf68242 100644 --- a/lib/chef/json_compat.rb +++ b/lib/chef/json_compat.rb @@ -44,7 +44,6 @@ class Chef CHEF_RUNLISTEXPANSION = "Chef::RunListExpansion".freeze class < /^[a-z0-9\-_]+$/) end - def name(arg=nil) + def name(arg = nil) set_or_return(:name, arg, :kind_of => String) end - def public_key(arg=nil) + def public_key(arg = nil) raise Chef::Exceptions::InvalidKeyAttribute, "you cannot set the public_key if create_key is true" if !arg.nil? && @create_key set_or_return(:public_key, arg, :kind_of => String) end - def private_key(arg=nil) + def private_key(arg = nil) set_or_return(:private_key, arg, :kind_of => String) end @@ -104,13 +103,13 @@ class Chef @create_key = nil end - def create_key(arg=nil) + def create_key(arg = nil) raise Chef::Exceptions::InvalidKeyAttribute, "you cannot set create_key to true if the public_key field exists" if arg == true && !@public_key.nil? set_or_return(:create_key, arg, :kind_of => [TrueClass, FalseClass]) end - def expiration_date(arg=nil) + def expiration_date(arg = nil) set_or_return(:expiration_date, arg, :regex => /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z|infinity)$/) end @@ -148,7 +147,7 @@ class Chef end end - payload = {"name" => @name} + payload = { "name" => @name } payload["public_key"] = @public_key unless @public_key.nil? payload["create_key"] = @create_key if @create_key payload["expiration_date"] = @expiration_date unless @expiration_date.nil? @@ -165,7 +164,7 @@ class Chef end # set @name and pass put_name if you wish to update the name of an existing key put_name to @name - def update(put_name=nil) + def update(put_name = nil) if @name.nil? && put_name.nil? raise Chef::Exceptions::MissingKeyAttribute, "the name field must be populated or you must pass a name to update when update is called" end @@ -227,33 +226,33 @@ class Chef Chef::Key.from_json(json) end - def self.list_by_user(actor, inflate=false) + def self.list_by_user(actor, inflate = false) keys = Chef::ServerAPI.new(Chef::Config[:chef_server_root]).get("users/#{actor}/keys") self.list(keys, actor, :load_by_user, inflate) end - def self.list_by_client(actor, inflate=false) + def self.list_by_client(actor, inflate = false) keys = Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("clients/#{actor}/keys") self.list(keys, actor, :load_by_client, inflate) end def self.load_by_user(actor, key_name) response = Chef::ServerAPI.new(Chef::Config[:chef_server_root]).get("users/#{actor}/keys/#{key_name}") - Chef::Key.from_hash(response.merge({"user" => actor})) + Chef::Key.from_hash(response.merge({ "user" => actor })) end def self.load_by_client(actor, key_name) response = Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("clients/#{actor}/keys/#{key_name}") - Chef::Key.from_hash(response.merge({"client" => actor})) + Chef::Key.from_hash(response.merge({ "client" => actor })) end def self.generate_fingerprint(public_key) - openssl_key_object = OpenSSL::PKey::RSA.new(public_key) - data_string = OpenSSL::ASN1::Sequence([ - OpenSSL::ASN1::Integer.new(openssl_key_object.public_key.n), - OpenSSL::ASN1::Integer.new(openssl_key_object.public_key.e), - ]) - OpenSSL::Digest::SHA1.hexdigest(data_string.to_der).scan(/../).join(":") + openssl_key_object = OpenSSL::PKey::RSA.new(public_key) + data_string = OpenSSL::ASN1::Sequence([ + OpenSSL::ASN1::Integer.new(openssl_key_object.public_key.n), + OpenSSL::ASN1::Integer.new(openssl_key_object.public_key.e), + ]) + OpenSSL::Digest::SHA1.hexdigest(data_string.to_der).scan(/../).join(":") end private diff --git a/lib/chef/knife.rb b/lib/chef/knife.rb index 56a23e0dde..545c79eef2 100644 --- a/lib/chef/knife.rb +++ b/lib/chef/knife.rb @@ -34,7 +34,6 @@ require "pp" class Chef class Knife - Chef::HTTP::HTTPRequest.user_agent = "Chef Knife#{Chef::HTTP::HTTPRequest::UA_COMMON}" include Mixlib::CLI @@ -72,7 +71,7 @@ class Chef @ui ||= Chef::Knife::UI.new(STDOUT, STDERR, STDIN, {}) end - def self.msg(msg="") + def self.msg(msg = "") ui.msg(msg) end @@ -195,7 +194,7 @@ class Chef # args::: usually ARGV # options::: A Mixlib::CLI option parser hash. These +options+ are how # subcommands know about global knife CLI options - def self.run(args, options={}) + def self.run(args, options = {}) # Fallback debug logging. Normally the logger isn't configured until we # read the config, but this means any logging that happens before the # config file is read may be lost. If the KNIFE_DEBUG variable is set, we @@ -250,7 +249,7 @@ class Chef if category_commands = guess_category(args) list_commands(category_commands) - elsif missing_plugin = ( OFFICIAL_PLUGINS.find {|plugin| plugin == args[0]} ) + elsif missing_plugin = ( OFFICIAL_PLUGINS.find { |plugin| plugin == args[0] } ) ui.info("The #{missing_plugin} commands were moved to plugins in Chef 0.10") ui.info("You can install the plugin with `(sudo) gem install knife-#{missing_plugin}`") ui.info("Use `chef gem install knife-#{missing_plugin}` instead if using ChefDK") @@ -261,7 +260,7 @@ class Chef exit 10 end - def self.list_commands(preferred_category=nil) + def self.list_commands(preferred_category = nil) category_desc = preferred_category ? preferred_category + " " : "" msg "Available #{category_desc}subcommands: (for details, knife SUB-COMMAND --help)\n\n" subcommand_loader.list_commands(preferred_category).sort.each do |category, commands| @@ -285,7 +284,7 @@ class Chef # Create a new instance of the current class configured for the given # arguments and options - def initialize(argv=[]) + def initialize(argv = []) super() # having to call super in initialize is the most annoying anti-pattern :( @ui = Chef::Knife::UI.new(STDOUT, STDERR, STDIN, config) @@ -510,7 +509,7 @@ class Chef response.body end - def create_object(object, pretty_name=nil, &block) + def create_object(object, pretty_name = nil, &block) output = edit_data(object) if Kernel.block_given? @@ -526,7 +525,7 @@ class Chef output(output) if config[:print_after] end - def delete_object(klass, name, delete_name=nil, &block) + def delete_object(klass, name, delete_name = nil, &block) confirm("Do you really want to delete #{name}") if Kernel.block_given? diff --git a/lib/chef/knife/bootstrap.rb b/lib/chef/knife/bootstrap.rb index a1172aefc9..9c5efa1fc5 100644 --- a/lib/chef/knife/bootstrap.rb +++ b/lib/chef/knife/bootstrap.rb @@ -250,7 +250,7 @@ class Chef Chef::Config[:knife][:bootstrap_vault_item] } - def initialize(argv=[]) + def initialize(argv = []) super @client_builder = Chef::Knife::Bootstrap::ClientBuilder.new( chef_config: Chef::Config, @@ -312,8 +312,8 @@ 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} - bootstrap_files << Gem.find_files(File.join("chef","knife","bootstrap","#{template}.erb")) + Chef::Util::PathHelper.home(".chef", "bootstrap", "#{template}.erb") { |p| bootstrap_files << p } + bootstrap_files << Gem.find_files(File.join("chef", "knife", "bootstrap", "#{template}.erb")) bootstrap_files.flatten! template_file = Array(bootstrap_files).find do |bootstrap_template| @@ -367,8 +367,8 @@ class Chef # chef-vault integration must use the new client-side hawtness, otherwise to use the # new client-side hawtness, just delete your validation key. - if chef_vault_handler.doing_chef_vault? || - (Chef::Config[:validation_key] && !File.exist?(File.expand_path(Chef::Config[:validation_key]))) + if chef_vault_handler.doing_chef_vault? || + (Chef::Config[:validation_key] && !File.exist?(File.expand_path(Chef::Config[:validation_key]))) unless config[:chef_node_name] ui.error("You must pass a node name with -N when bootstrapping with user credentials") @@ -449,7 +449,7 @@ class Chef if config[:use_sudo] sudo_prefix = config[:use_sudo_password] ? "echo '#{config[:ssh_password]}' | sudo -S " : "sudo " - command = config[:preserve_home] ? "#{sudo_prefix} #{command}" : "#{sudo_prefix} -H #{command}" + command = config[:preserve_home] ? "#{sudo_prefix} #{command}" : "#{sudo_prefix} -H #{command}" end command @@ -474,7 +474,6 @@ class Chef def incomplete_policyfile_options? (!!config[:policy_name] ^ config[:policy_group]) end - end end end diff --git a/lib/chef/knife/bootstrap/chef_vault_handler.rb b/lib/chef/knife/bootstrap/chef_vault_handler.rb index ca37cc5544..941b17c841 100644 --- a/lib/chef/knife/bootstrap/chef_vault_handler.rb +++ b/lib/chef/knife/bootstrap/chef_vault_handler.rb @@ -21,7 +21,6 @@ class Chef class Knife class Bootstrap < Knife class ChefVaultHandler - # @return [Hash] knife merged config, typically @config attr_accessor :knife_config @@ -136,7 +135,7 @@ class Chef ChefVault::Item.load(vault, item) end - public :load_chef_bootstrap_vault_item # for stubbing + public :load_chef_bootstrap_vault_item # for stubbing # Helper to very lazily require the chef-vault gem def require_chef_vault! @@ -152,7 +151,6 @@ class Chef raise error_message end end - end end end diff --git a/lib/chef/knife/bootstrap/client_builder.rb b/lib/chef/knife/bootstrap/client_builder.rb index cab33cd811..05cc8d9348 100644 --- a/lib/chef/knife/bootstrap/client_builder.rb +++ b/lib/chef/knife/bootstrap/client_builder.rb @@ -27,7 +27,6 @@ class Chef class Knife class Bootstrap < Knife class ClientBuilder - # @return [Hash] knife merged config, typically @config attr_accessor :knife_config # @return [Hash] chef config object diff --git a/lib/chef/knife/client_bulk_delete.rb b/lib/chef/knife/client_bulk_delete.rb index af3e862a18..d3d7711d4d 100644 --- a/lib/chef/knife/client_bulk_delete.rb +++ b/lib/chef/knife/client_bulk_delete.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class ClientBulkDelete < Knife - deps do require "chef/api_client_v1" require "chef/json_compat" diff --git a/lib/chef/knife/client_create.rb b/lib/chef/knife/client_create.rb index ecacb36833..1d912aaa14 100644 --- a/lib/chef/knife/client_create.rb +++ b/lib/chef/knife/client_create.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class ClientCreate < Knife - deps do require "chef/api_client_v1" require "chef/json_compat" diff --git a/lib/chef/knife/client_delete.rb b/lib/chef/knife/client_delete.rb index e1b2365361..313e8ea564 100644 --- a/lib/chef/knife/client_delete.rb +++ b/lib/chef/knife/client_delete.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class ClientDelete < Knife - deps do require "chef/api_client_v1" require "chef/json_compat" @@ -54,7 +53,6 @@ class Chef object.destroy } end - end end end diff --git a/lib/chef/knife/client_edit.rb b/lib/chef/knife/client_edit.rb index c05b677a28..32d3853511 100644 --- a/lib/chef/knife/client_edit.rb +++ b/lib/chef/knife/client_edit.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class ClientEdit < Knife - deps do require "chef/api_client_v1" require "chef/json_compat" diff --git a/lib/chef/knife/client_key_create.rb b/lib/chef/knife/client_key_create.rb index 520798013e..68ad4d16d2 100644 --- a/lib/chef/knife/client_key_create.rb +++ b/lib/chef/knife/client_key_create.rb @@ -32,7 +32,7 @@ class Chef attr_reader :actor - def initialize(argv=[]) + def initialize(argv = []) super(argv) @service_object = nil end diff --git a/lib/chef/knife/client_key_delete.rb b/lib/chef/knife/client_key_delete.rb index 3e27148475..64eae2e27c 100644 --- a/lib/chef/knife/client_key_delete.rb +++ b/lib/chef/knife/client_key_delete.rb @@ -31,7 +31,7 @@ class Chef attr_reader :actor - def initialize(argv=[]) + def initialize(argv = []) super(argv) @service_object = nil end diff --git a/lib/chef/knife/client_key_edit.rb b/lib/chef/knife/client_key_edit.rb index 65657520bb..1dbd3c487b 100644 --- a/lib/chef/knife/client_key_edit.rb +++ b/lib/chef/knife/client_key_edit.rb @@ -34,7 +34,7 @@ class Chef attr_reader :actor - def initialize(argv=[]) + def initialize(argv = []) super(argv) @service_object = nil end @@ -77,4 +77,3 @@ class Chef end end end - diff --git a/lib/chef/knife/client_key_list.rb b/lib/chef/knife/client_key_list.rb index 01e0fe2b25..194ad42931 100644 --- a/lib/chef/knife/client_key_list.rb +++ b/lib/chef/knife/client_key_list.rb @@ -34,7 +34,7 @@ class Chef attr_reader :actor - def initialize(argv=[]) + def initialize(argv = []) super(argv) @service_object = nil end diff --git a/lib/chef/knife/client_key_show.rb b/lib/chef/knife/client_key_show.rb index 1611631a67..77f9e96c5a 100644 --- a/lib/chef/knife/client_key_show.rb +++ b/lib/chef/knife/client_key_show.rb @@ -31,7 +31,7 @@ class Chef attr_reader :actor - def initialize(argv=[]) + def initialize(argv = []) super(argv) @service_object = nil end diff --git a/lib/chef/knife/client_list.rb b/lib/chef/knife/client_list.rb index b17de0f3ad..c50260a083 100644 --- a/lib/chef/knife/client_list.rb +++ b/lib/chef/knife/client_list.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class ClientList < Knife - deps do require "chef/api_client_v1" require "chef/json_compat" diff --git a/lib/chef/knife/client_reregister.rb b/lib/chef/knife/client_reregister.rb index 5d9b2c0962..06347816a5 100644 --- a/lib/chef/knife/client_reregister.rb +++ b/lib/chef/knife/client_reregister.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class ClientReregister < Knife - deps do require "chef/api_client_v1" require "chef/json_compat" diff --git a/lib/chef/knife/client_show.rb b/lib/chef/knife/client_show.rb index ce3bf458b2..c875b83093 100644 --- a/lib/chef/knife/client_show.rb +++ b/lib/chef/knife/client_show.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class ClientShow < Knife - include Knife::Core::MultiAttributeReturnOption deps do @@ -43,7 +42,6 @@ class Chef client = Chef::ApiClientV1.load(@client_name) output(format_for_display(client)) end - end end end diff --git a/lib/chef/knife/configure.rb b/lib/chef/knife/configure.rb index c48ecb7442..e62a9dd05c 100644 --- a/lib/chef/knife/configure.rb +++ b/lib/chef/knife/configure.rb @@ -97,7 +97,7 @@ EOH user_create = Chef::Knife::UserCreate.new user_create.name_args = [ new_client_name ] user_create.config[:user_password] = config[:user_password] || - ui.ask("Please enter a password for the new user: ") {|q| q.echo = false} + ui.ask("Please enter a password for the new user: ") { |q| q.echo = false } user_create.config[:admin] = true user_create.config[:file] = new_client_key user_create.config[:yes] = true @@ -133,7 +133,7 @@ EOH def ask_user_for_config server_name = guess_servername - @chef_server = config[:chef_server_url] || ask_question("Please enter the chef server URL: ", :default => "https://#{server_name}:443") + @chef_server = config[:chef_server_url] || ask_question("Please enter the chef server URL: ", :default => "https://#{server_name}:443") if config[:initial] @new_client_name = config[:node_name] || ask_question("Please enter a name for the new user: ", :default => Etc.getlogin) @admin_client_name = config[:admin_client_name] || ask_question("Please enter the existing admin name: ", :default => "admin") diff --git a/lib/chef/knife/configure_client.rb b/lib/chef/knife/configure_client.rb index 7d0b3d260d..4871afb67c 100644 --- a/lib/chef/knife/configure_client.rb +++ b/lib/chef/knife/configure_client.rb @@ -44,7 +44,6 @@ class Chef validation.puts(IO.read(Chef::Config[:validation_key])) end end - end end end diff --git a/lib/chef/knife/cookbook_bulk_delete.rb b/lib/chef/knife/cookbook_bulk_delete.rb index 5ab97dc408..dd47f120c0 100644 --- a/lib/chef/knife/cookbook_bulk_delete.rb +++ b/lib/chef/knife/cookbook_bulk_delete.rb @@ -22,7 +22,6 @@ require "chef/knife" class Chef class Knife class CookbookBulkDelete < Knife - deps do require "chef/knife/cookbook_delete" require "chef/cookbook_version" @@ -58,9 +57,8 @@ class Chef ui.msg "" end - cookbooks_names.each do |cookbook_name| - versions = rest.get("cookbooks/#{cookbook_name}")[cookbook_name]["versions"].map {|v| v["version"]}.flatten + versions = rest.get("cookbooks/#{cookbook_name}")[cookbook_name]["versions"].map { |v| v["version"] }.flatten versions.each do |version| object = rest.delete("cookbooks/#{cookbook_name}/#{version}#{config[:purge] ? "?purge=true" : ""}") ui.info("Deleted cookbook #{cookbook_name.ljust(25)} [#{version}]") diff --git a/lib/chef/knife/cookbook_create.rb b/lib/chef/knife/cookbook_create.rb index 2aeecc6e2a..f3b6e069b2 100644 --- a/lib/chef/knife/cookbook_create.rb +++ b/lib/chef/knife/cookbook_create.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class CookbookCreate < Knife - deps do require "chef/json_compat" require "uri" @@ -182,11 +181,11 @@ EOH def create_changelog(dir, cookbook_name) msg("** Creating CHANGELOG for cookbook: #{cookbook_name}") - unless File.exists?(File.join(dir,cookbook_name,"CHANGELOG.md")) - open(File.join(dir, cookbook_name, "CHANGELOG.md"),"w") do |file| + unless File.exists?(File.join(dir, cookbook_name, "CHANGELOG.md")) + open(File.join(dir, cookbook_name, "CHANGELOG.md"), "w") do |file| file.puts <<-EOH #{cookbook_name} CHANGELOG -#{'='*"#{cookbook_name} CHANGELOG".length} +#{'=' * "#{cookbook_name} CHANGELOG".length} This file is used to list changes made in each version of the #{cookbook_name} cookbook. @@ -271,10 +270,10 @@ e.g. == License and Authors Authors: TODO: List authors EOH - when "md","mkd","txt" + when "md", "mkd", "txt" file.puts <<-EOH #{cookbook_name} Cookbook -#{'='*"#{cookbook_name} Cookbook".length} +#{'=' * "#{cookbook_name} Cookbook".length} TODO: Enter the cookbook description here. e.g. @@ -345,7 +344,7 @@ EOH else file.puts <<-EOH #{cookbook_name} Cookbook -#{'='*"#{cookbook_name} Cookbook".length} +#{'=' * "#{cookbook_name} Cookbook".length} TODO: Enter the cookbook description here. e.g. @@ -442,7 +441,6 @@ EOH def parameter_empty?(parameter) parameter.nil? || parameter.empty? end - end end end diff --git a/lib/chef/knife/cookbook_delete.rb b/lib/chef/knife/cookbook_delete.rb index e6a70d693c..3c303e3652 100644 --- a/lib/chef/knife/cookbook_delete.rb +++ b/lib/chef/knife/cookbook_delete.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class CookbookDelete < Knife - attr_accessor :cookbook_name, :version deps do @@ -86,7 +85,7 @@ class Chef def available_versions @available_versions ||= rest.get("cookbooks/#{@cookbook_name}").map do |name, url_and_version| - url_and_version["versions"].map {|url_by_version| url_by_version["version"]} + url_and_version["versions"].map { |url_by_version| url_by_version["version"] } end.flatten rescue Net::HTTPServerException => e if e.to_s =~ /^404/ @@ -145,7 +144,6 @@ class Chef path += "?purge=true" if config[:purge] rest.delete(path) end - end end end diff --git a/lib/chef/knife/cookbook_download.rb b/lib/chef/knife/cookbook_download.rb index 8c8f0cc677..46825d8ad2 100644 --- a/lib/chef/knife/cookbook_download.rb +++ b/lib/chef/knife/cookbook_download.rb @@ -22,7 +22,6 @@ require "chef/knife" class Chef class Knife class CookbookDownload < Knife - attr_reader :version attr_accessor :cookbook_name @@ -98,7 +97,6 @@ class Chef end def determine_version - if available_versions.nil? nil elsif available_versions.size == 1 @@ -138,7 +136,6 @@ class Chef end @version end - end end end diff --git a/lib/chef/knife/cookbook_list.rb b/lib/chef/knife/cookbook_list.rb index ea81f5d286..c9c25d0360 100644 --- a/lib/chef/knife/cookbook_list.rb +++ b/lib/chef/knife/cookbook_list.rb @@ -22,7 +22,6 @@ require "chef/knife" class Chef class Knife class CookbookList < Knife - banner "knife cookbook list (options)" option :with_uri, diff --git a/lib/chef/knife/cookbook_metadata.rb b/lib/chef/knife/cookbook_metadata.rb index b13ab18a57..c421afa6ab 100644 --- a/lib/chef/knife/cookbook_metadata.rb +++ b/lib/chef/knife/cookbook_metadata.rb @@ -22,7 +22,6 @@ require "chef/knife" class Chef class Knife class CookbookMetadata < Knife - deps do require "chef/cookbook_loader" require "chef/cookbook/metadata" @@ -102,7 +101,6 @@ class Chef ui.stderr.puts e.message exit 1 end - end end end diff --git a/lib/chef/knife/cookbook_metadata_from_file.rb b/lib/chef/knife/cookbook_metadata_from_file.rb index ec46379da7..3834ca93b7 100644 --- a/lib/chef/knife/cookbook_metadata_from_file.rb +++ b/lib/chef/knife/cookbook_metadata_from_file.rb @@ -24,7 +24,6 @@ require "chef/knife" class Chef class Knife class CookbookMetadataFromFile < Knife - deps do require "chef/cookbook/metadata" end @@ -38,7 +37,6 @@ class Chef @metadata = Chef::Knife::CookbookMetadata.new @metadata.generate_metadata_from_file(cookbook, file) end - end end end diff --git a/lib/chef/knife/cookbook_show.rb b/lib/chef/knife/cookbook_show.rb index 1a1ba36825..5db22d08cd 100644 --- a/lib/chef/knife/cookbook_show.rb +++ b/lib/chef/knife/cookbook_show.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class CookbookShow < Knife - deps do require "chef/json_compat" require "uri" @@ -96,7 +95,3 @@ class Chef end end end - - - - diff --git a/lib/chef/knife/cookbook_site_download.rb b/lib/chef/knife/cookbook_site_download.rb index 541e60c977..76e13f077a 100644 --- a/lib/chef/knife/cookbook_site_download.rb +++ b/lib/chef/knife/cookbook_site_download.rb @@ -20,7 +20,6 @@ require "chef/knife" class Chef class Knife class CookbookSiteDownload < Knife - deps do require "fileutils" end @@ -57,6 +56,7 @@ class Chef end private + def cookbooks_api_url "https://supermarket.chef.io/api/v1/cookbooks" end diff --git a/lib/chef/knife/cookbook_site_install.rb b/lib/chef/knife/cookbook_site_install.rb index 14be2d750f..6df212b980 100644 --- a/lib/chef/knife/cookbook_site_install.rb +++ b/lib/chef/knife/cookbook_site_install.rb @@ -23,7 +23,6 @@ require "shellwords" class Chef class Knife class CookbookSiteInstall < Knife - deps do require "chef/mixin/shell_out" require "chef/knife/core/cookbook_scm_repo" @@ -142,7 +141,7 @@ class Chef def extract_cookbook(upstream_file, version) ui.info("Uncompressing #{@cookbook_name} version #{version}.") # FIXME: Detect if we have the bad tar from git on Windows: https://github.com/opscode/chef/issues/1753 - extract_command="tar zxvf \"#{convert_path upstream_file}\"" + extract_command = "tar zxvf \"#{convert_path upstream_file}\"" if Chef::Platform.windows? extract_command << " --force-local" end diff --git a/lib/chef/knife/cookbook_site_list.rb b/lib/chef/knife/cookbook_site_list.rb index 2c7c5d6df2..ea7be703aa 100644 --- a/lib/chef/knife/cookbook_site_list.rb +++ b/lib/chef/knife/cookbook_site_list.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class CookbookSiteList < Knife - banner "knife cookbook site list (options)" category "cookbook site" @@ -33,14 +32,14 @@ class Chef def run if config[:with_uri] cookbooks = Hash.new - get_cookbook_list.each{ |k,v| cookbooks[k] = v["cookbook"] } + get_cookbook_list.each { |k, v| cookbooks[k] = v["cookbook"] } ui.output(format_for_display(cookbooks)) else ui.msg(ui.list(get_cookbook_list.keys.sort, :columns_down)) end end - def get_cookbook_list(items=10, start=0, cookbook_collection={}) + def get_cookbook_list(items = 10, start = 0, cookbook_collection = {}) cookbooks_url = "https://supermarket.chef.io/api/v1/cookbooks?items=#{items}&start=#{start}" cr = noauth_rest.get(cookbooks_url) cr["items"].each do |cookbook| @@ -56,7 +55,3 @@ class Chef end end end - - - - diff --git a/lib/chef/knife/cookbook_site_search.rb b/lib/chef/knife/cookbook_site_search.rb index 2629761385..46e970e274 100644 --- a/lib/chef/knife/cookbook_site_search.rb +++ b/lib/chef/knife/cookbook_site_search.rb @@ -20,7 +20,6 @@ require "chef/knife" class Chef class Knife class CookbookSiteSearch < Knife - banner "knife cookbook site search QUERY (options)" category "cookbook site" @@ -28,7 +27,7 @@ class Chef output(search_cookbook(name_args[0])) end - def search_cookbook(query, items=10, start=0, cookbook_collection={}) + def search_cookbook(query, items = 10, start = 0, cookbook_collection = {}) cookbooks_url = "https://supermarket.chef.io/api/v1/search?q=#{query}&items=#{items}&start=#{start}" cr = noauth_rest.get(cookbooks_url) cr["items"].each do |cookbook| @@ -44,8 +43,3 @@ class Chef end end end - - - - - diff --git a/lib/chef/knife/cookbook_site_share.rb b/lib/chef/knife/cookbook_site_share.rb index fcb666dbae..04048269a0 100644 --- a/lib/chef/knife/cookbook_site_share.rb +++ b/lib/chef/knife/cookbook_site_share.rb @@ -22,7 +22,6 @@ require "chef/mixin/shell_out" class Chef class Knife class CookbookSiteShare < Knife - include Chef::Mixin::ShellOut deps do @@ -103,7 +102,6 @@ class Chef ui.error("Could not find cookbook #{cookbook_name} in your cookbook path.") exit(1) end - end def get_category(cookbook_name) @@ -125,12 +123,12 @@ class Chef def do_upload(cookbook_filename, cookbook_category, user_id, user_secret_filename) uri = "https://supermarket.chef.io/api/v1/cookbooks" - category_string = Chef::JSONCompat.to_json({ "category"=>cookbook_category }) + category_string = Chef::JSONCompat.to_json({ "category" => cookbook_category }) http_resp = Chef::CookbookSiteStreamingUploader.post(uri, user_id, user_secret_filename, { - :tarball => File.open(cookbook_filename), - :cookbook => category_string, - }) + :tarball => File.open(cookbook_filename), + :cookbook => category_string, + }) res = Chef::JSONCompat.from_json(http_resp.body) if http_resp.code.to_i != 201 @@ -165,6 +163,5 @@ class Chef @tar_cmd end end - end end diff --git a/lib/chef/knife/cookbook_site_show.rb b/lib/chef/knife/cookbook_site_show.rb index 2956ca2879..f02b20c46d 100644 --- a/lib/chef/knife/cookbook_site_show.rb +++ b/lib/chef/knife/cookbook_site_show.rb @@ -20,7 +20,6 @@ require "chef/knife" class Chef class Knife class CookbookSiteShow < Knife - banner "knife cookbook site show COOKBOOK [VERSION] (options)" category "cookbook site" @@ -37,7 +36,7 @@ class Chef end end - def get_cookbook_list(items=10, start=0, cookbook_collection={}) + def get_cookbook_list(items = 10, start = 0, cookbook_collection = {}) cookbooks_url = "https://supermarket.chef.io/api/v1/cookbooks?items=#{items}&start=#{start}" cr = noauth_rest.get(cookbooks_url) cr["items"].each do |cookbook| @@ -53,8 +52,3 @@ class Chef end end end - - - - - diff --git a/lib/chef/knife/cookbook_site_unshare.rb b/lib/chef/knife/cookbook_site_unshare.rb index 310f6ac41d..e63e70a2a2 100644 --- a/lib/chef/knife/cookbook_site_unshare.rb +++ b/lib/chef/knife/cookbook_site_unshare.rb @@ -22,7 +22,6 @@ require "chef/knife" class Chef class Knife class CookbookSiteUnshare < Knife - deps do require "chef/json_compat" end @@ -50,7 +49,6 @@ class Chef ui.info "Unshared all versions of the cookbook #{@cookbook_name}" end - end end end diff --git a/lib/chef/knife/cookbook_site_vendor.rb b/lib/chef/knife/cookbook_site_vendor.rb index 291715cc0b..891eafd534 100644 --- a/lib/chef/knife/cookbook_site_vendor.rb +++ b/lib/chef/knife/cookbook_site_vendor.rb @@ -20,7 +20,6 @@ require "chef/knife" require "chef/knife/cookbook_site_install" class Chef::Knife::CookbookSiteVendor < Chef::Knife::CookbookSiteInstall - def self.load_deps superclass.load_deps end @@ -42,5 +41,4 @@ DEPRECATED: please use knife cookbook site install B category "deprecated" - end diff --git a/lib/chef/knife/cookbook_test.rb b/lib/chef/knife/cookbook_test.rb index f7931e321b..6cfb85e11f 100644 --- a/lib/chef/knife/cookbook_test.rb +++ b/lib/chef/knife/cookbook_test.rb @@ -23,7 +23,6 @@ require "chef/knife" class Chef class Knife class CookbookTest < Knife - deps do require "chef/cookbook_loader" require "chef/cookbook/syntax_check" @@ -76,7 +75,6 @@ class Chef end end - def test_ruby(syntax_checker) ui.info("Validating ruby files") exit(1) unless syntax_checker.validate_ruby_files @@ -90,7 +88,6 @@ class Chef def cookbook_loader @cookbook_loader ||= Chef::CookbookLoader.new(config[:cookbook_path]) end - end end end diff --git a/lib/chef/knife/cookbook_upload.rb b/lib/chef/knife/cookbook_upload.rb index 9cbd8f09d1..1b360439d4 100644 --- a/lib/chef/knife/cookbook_upload.rb +++ b/lib/chef/knife/cookbook_upload.rb @@ -24,7 +24,6 @@ require "chef/cookbook_uploader" class Chef class Knife class CookbookUpload < Knife - CHECKSUM = "checksum" MATCH_CHECKSUM = /[0-9a-f]{32,}/ @@ -101,7 +100,7 @@ class Chef # Get a list of cookbooks and their versions from the server # to check for the existence of a cookbook's dependencies. @server_side_cookbooks = Chef::CookbookVersion.list_all_versions - justify_width = @server_side_cookbooks.map {|name| name.size}.max.to_i + 2 + justify_width = @server_side_cookbooks.map { |name| name.size }.max.to_i + 2 if config[:all] cookbook_repo.load_cookbooks cookbooks_for_upload = [] @@ -145,7 +144,6 @@ class Chef end end - upload_failures += @name_args.length - @cookbooks_to_upload.length if upload_failures == 0 @@ -259,7 +257,7 @@ WARNING info[CHECKSUM].nil? || info[CHECKSUM] !~ MATCH_CHECKSUM end unless broken_files.empty? - broken_filenames = Array(broken_files).map {|path, info| path} + broken_filenames = Array(broken_files).map { |path, info| path } ui.error "The cookbook #{cookbook.name} has one or more broken files" ui.error "This is probably caused by broken symlinks in the cookbook directory" ui.error "The broken file(s) are: #{broken_filenames.join(' ')}" @@ -275,7 +273,7 @@ WARNING end unless missing_dependencies.empty? - missing_cookbook_names = missing_dependencies.map { |cookbook_name, version| "'#{cookbook_name}' version '#{version}'"} + missing_cookbook_names = missing_dependencies.map { |cookbook_name, version| "'#{cookbook_name}' version '#{version}'" } ui.error "Cookbook #{cookbook.name} depends on cookbooks which are not currently" ui.error "being uploaded and cannot be found on the server." ui.error "The missing cookbook(s) are: #{missing_cookbook_names.join(', ')}" @@ -287,7 +285,7 @@ WARNING if @server_side_cookbooks[cookbook_name].nil? false else - versions = @server_side_cookbooks[cookbook_name]["versions"].collect {|versions| versions["version"]} + versions = @server_side_cookbooks[cookbook_name]["versions"].collect { |versions| versions["version"] } Log.debug "Versions of cookbook '#{cookbook_name}' returned by the server: #{versions.join(", ")}" @server_side_cookbooks[cookbook_name]["versions"].each do |versions_hash| if Chef::VersionConstraint.new(version).include?(versions_hash["version"]) diff --git a/lib/chef/knife/core/bootstrap_context.rb b/lib/chef/knife/core/bootstrap_context.rb index a863e0cdb7..9175bb76f1 100644 --- a/lib/chef/knife/core/bootstrap_context.rb +++ b/lib/chef/knife/core/bootstrap_context.rb @@ -29,7 +29,6 @@ class Chef # * @run_list - the run list for the node to boostrap # class BootstrapContext - attr_accessor :client_pem def initialize(config, run_list, chef_config, secret = nil) @@ -193,7 +192,6 @@ validation_client_name "#{@chef_config[:validation_client_name]}" end content end - end end end diff --git a/lib/chef/knife/core/cookbook_scm_repo.rb b/lib/chef/knife/core/cookbook_scm_repo.rb index 4779bb5405..ceb3ba3de7 100644 --- a/lib/chef/knife/core/cookbook_scm_repo.rb +++ b/lib/chef/knife/core/cookbook_scm_repo.rb @@ -21,7 +21,6 @@ require "chef/mixin/shell_out" class Chef class Knife class CookbookSCMRepo - DIRTY_REPO = /^[\s]+M/ include Chef::Mixin::ShellOut @@ -31,7 +30,7 @@ class Chef attr_reader :use_current_branch attr_reader :ui - def initialize(repo_path, ui, opts={}) + def initialize(repo_path, ui, opts = {}) @repo_path = repo_path @ui = ui @default_branch = "master" @@ -119,7 +118,7 @@ class Chef end def branch_exists?(branch_name) - git("branch --no-color").stdout.lines.any? {|l| l =~ /\s#{Regexp.escape(branch_name)}(?:\s|$)/ } + git("branch --no-color").stdout.lines.any? { |l| l =~ /\s#{Regexp.escape(branch_name)}(?:\s|$)/ } end def get_current_branch() @@ -153,8 +152,6 @@ class Chef def git(command) shell_out!("git #{command}", :cwd => repo_path) end - end end end - diff --git a/lib/chef/knife/core/custom_manifest_loader.rb b/lib/chef/knife/core/custom_manifest_loader.rb index e5ebce2585..8e2b95915b 100644 --- a/lib/chef/knife/core/custom_manifest_loader.rb +++ b/lib/chef/knife/core/custom_manifest_loader.rb @@ -18,7 +18,6 @@ require "chef/version" class Chef class Knife class SubcommandLoader - # # Load a subcommand from a user-supplied # manifest file diff --git a/lib/chef/knife/core/gem_glob_loader.rb b/lib/chef/knife/core/gem_glob_loader.rb index 2aabf4cf46..6802be29ef 100644 --- a/lib/chef/knife/core/gem_glob_loader.rb +++ b/lib/chef/knife/core/gem_glob_loader.rb @@ -50,7 +50,7 @@ class Chef files = Dir[File.join(Chef::Util::PathHelper.escape_glob(File.expand_path("../../../knife", __FILE__)), "*.rb")] subcommand_files = {} files.each do |knife_file| - rel_path = knife_file[/#{CHEF_ROOT}#{Regexp.escape(File::SEPARATOR)}(.*)\.rb/,1] + rel_path = knife_file[/#{CHEF_ROOT}#{Regexp.escape(File::SEPARATOR)}(.*)\.rb/, 1] subcommand_files[rel_path] = knife_file end subcommand_files @@ -77,7 +77,7 @@ class Chef private - def find_files_latest_gems(glob, check_load_path=true) + def find_files_latest_gems(glob, check_load_path = true) files = [] if check_load_path @@ -103,7 +103,7 @@ class Chef def latest_gem_specs @latest_gem_specs ||= if Gem::Specification.respond_to? :latest_specs - Gem::Specification.latest_specs(true) # find prerelease gems + Gem::Specification.latest_specs(true) # find prerelease gems else Gem.source_index.latest_specs(true) end diff --git a/lib/chef/knife/core/generic_presenter.rb b/lib/chef/knife/core/generic_presenter.rb index 4ba9a15100..0a5084b6bb 100644 --- a/lib/chef/knife/core/generic_presenter.rb +++ b/lib/chef/knife/core/generic_presenter.rb @@ -21,7 +21,6 @@ require "chef/knife/core/text_formatter" class Chef class Knife module Core - # Allows includer knife commands to return multiple attributes # @brief knife node show NAME -a ATTR1 -a ATTR2 module MultiAttributeReturnOption @@ -32,7 +31,7 @@ class Chef option :attribute, :short => "-a ATTR1 [-a ATTR2]", :long => "--attribute ATTR1 [--attribute ATTR2] ", - :proc => lambda {|val| @attrs_to_show << val}, + :proc => lambda { |val| @attrs_to_show << val }, :description => "Show one or more attributes" end end @@ -43,7 +42,6 @@ class Chef # This is not an abstract base class, and it is suitable for displaying # most kinds of objects that knife needs to display. class GenericPresenter - attr_reader :ui attr_reader :config @@ -133,7 +131,7 @@ class Chef end def format_list_for_display(list) - config[:with_uri] ? list : list.keys.sort { |a,b| a <=> b } + config[:with_uri] ? list : list.keys.sort { |a, b| a <=> b } end def format_for_display(data) @@ -142,7 +140,7 @@ class Chef elsif config[:id_only] name_or_id_for(data) elsif config[:environment] && data.respond_to?(:chef_environment) - {"chef_environment" => data.chef_environment} + { "chef_environment" => data.chef_environment } else data end @@ -162,7 +160,7 @@ class Chef else raise ArgumentError, "format_data_subset_for_display requires attribute, run_list, or id_only config option to be set" end - {name_or_id_for(data) => subset } + { name_or_id_for(data) => subset } end def name_or_id_for(data) @@ -173,7 +171,6 @@ class Chef config[:attribute] || config[:run_list] end - def extract_nested_value(data, nested_value_spec) nested_value_spec.split(".").each do |attr| if data.nil? @@ -181,7 +178,7 @@ class Chef # Must check :[] before attr because spec can include # `keys` - want the key named `keys`, not a list of # available keys. - elsif data.respond_to?(:[]) && data.has_key?(attr) + elsif data.respond_to?(:[]) && data.has_key?(attr) data = data[attr] elsif data.respond_to?(attr.to_sym) data = data.send(attr.to_sym) @@ -207,16 +204,15 @@ class Chef end else versions_by_cookbook = item.inject({}) do |collected, ( cookbook, versions )| - collected[cookbook] = versions["versions"].map {|v| v["version"]} + collected[cookbook] = versions["versions"].map { |v| v["version"] } collected end - key_length = versions_by_cookbook.empty? ? 0 : versions_by_cookbook.keys.map {|name| name.size }.max + 2 + key_length = versions_by_cookbook.empty? ? 0 : versions_by_cookbook.keys.map { |name| name.size }.max + 2 versions_by_cookbook.sort.map do |cookbook, versions| "#{cookbook.ljust(key_length)} #{versions.join(' ')}" end end end - end end end diff --git a/lib/chef/knife/core/hashed_command_loader.rb b/lib/chef/knife/core/hashed_command_loader.rb index aecf738332..7b6c1c4c08 100644 --- a/lib/chef/knife/core/hashed_command_loader.rb +++ b/lib/chef/knife/core/hashed_command_loader.rb @@ -38,7 +38,7 @@ class Chef find_longest_key(manifest[KEY]["plugins_by_category"], category_words, " ") end - def list_commands(pref_category=nil) + def list_commands(pref_category = nil) if pref_category || manifest[KEY]["plugins_by_category"].key?(pref_category) { pref_category => manifest[KEY]["plugins_by_category"][pref_category] } else diff --git a/lib/chef/knife/core/node_editor.rb b/lib/chef/knife/core/node_editor.rb index 9b5f0a435f..61b13aa882 100644 --- a/lib/chef/knife/core/node_editor.rb +++ b/lib/chef/knife/core/node_editor.rb @@ -124,7 +124,6 @@ class Chef abort "You must set your EDITOR environment variable or configure your editor via knife.rb" end end - end end end diff --git a/lib/chef/knife/core/node_presenter.rb b/lib/chef/knife/core/node_presenter.rb index a5837f268c..e6470bff00 100644 --- a/lib/chef/knife/core/node_presenter.rb +++ b/lib/chef/knife/core/node_presenter.rb @@ -22,7 +22,6 @@ require "chef/knife/core/generic_presenter" class Chef class Knife module Core - # This module may be included into a knife subcommand class to automatically # add configuration options used by the NodePresenter module NodeFormattingOptions @@ -52,7 +51,6 @@ class Chef # A customized presenter for Chef::Node objects. Supports variable-length # output formats for displaying node data class NodePresenter < GenericPresenter - def format(data) if parse_format_option == :json summarize_json(data) @@ -98,7 +96,7 @@ class Chef # special case ec2 with their split horizon whatsis. ip = (node[:ec2] && node[:ec2][:public_ipv4]) || node[:ipaddress] - summarized=<<-SUMMARY + summarized = <<-SUMMARY #{ui.color('Node Name:', :bold)} #{ui.color(node.name, :bold)} SUMMARY show_policy = !(node.policy_name.nil? && node.policy_group.nil?) @@ -128,13 +126,13 @@ ROLES #{key('Tags:')} #{node.tags.join(', ')} SUMMARY if config[:medium_output] || config[:long_output] - summarized +=<<-MORE + summarized += <<-MORE #{key('Attributes:')} #{text_format(node.normal_attrs)} MORE end if config[:long_output] - summarized +=<<-MOST + summarized += <<-MOST #{key('Default Attributes:')} #{text_format(node.default_attrs)} #{key('Override Attributes:')} @@ -152,9 +150,7 @@ MOST def key(key_text) ui.color(key_text, :cyan) end - end end end end - diff --git a/lib/chef/knife/core/object_loader.rb b/lib/chef/knife/core/object_loader.rb index 04496933e4..26e3c98253 100644 --- a/lib/chef/knife/core/object_loader.rb +++ b/lib/chef/knife/core/object_loader.rb @@ -24,7 +24,6 @@ class Chef class Knife module Core class ObjectLoader - attr_reader :ui attr_reader :klass @@ -108,7 +107,6 @@ class Chef def file_exists_and_is_readable?(file) File.exist?(file) && File.readable?(file) end - end end end diff --git a/lib/chef/knife/core/status_presenter.rb b/lib/chef/knife/core/status_presenter.rb index 13bcf5cab2..4535b9566c 100644 --- a/lib/chef/knife/core/status_presenter.rb +++ b/lib/chef/knife/core/status_presenter.rb @@ -22,7 +22,6 @@ require "chef/knife/core/generic_presenter" class Chef class Knife module Core - # This module may be included into a knife subcommand class to automatically # add configuration options used by the StatusPresenter module StatusFormattingOptions @@ -52,7 +51,6 @@ class Chef # A customized presenter for Chef::Node objects. Supports variable-length # output formats for displaying node data class StatusPresenter < GenericPresenter - def format(data) if parse_format_option == :json summarize_json(data) @@ -93,7 +91,7 @@ class Chef # the volume of output is adjusted accordingly. Uses colors if enabled # in the ui object. def summarize(list) - summarized="" + summarized = "" list.each do |data| node = data # special case ec2 with their split horizon whatsis. @@ -130,7 +128,7 @@ class Chef line_parts << platform end - summarized=summarized + line_parts.join(", ") + ".\n" + summarized = summarized + line_parts.join(", ") + ".\n" end summarized end @@ -150,7 +148,6 @@ class Chef seconds = (difference % 60) return [hours, minutes, seconds] end - end end end diff --git a/lib/chef/knife/core/subcommand_loader.rb b/lib/chef/knife/core/subcommand_loader.rb index 2b8bbc929d..95ab219c80 100644 --- a/lib/chef/knife/core/subcommand_loader.rb +++ b/lib/chef/knife/core/subcommand_loader.rb @@ -96,7 +96,7 @@ class Chef end def force_load - @loaded=false + @loaded = false load_commands end @@ -128,7 +128,6 @@ class Chef category_words, " ") end - # # This is shared between the custom_manifest_loader and the gem_glob_loader # @@ -137,7 +136,7 @@ class Chef files = Dir[File.join(Chef::Util::PathHelper.escape_glob(File.expand_path("../../../knife", __FILE__)), "*.rb")] subcommand_files = {} files.each do |knife_file| - rel_path = knife_file[/#{CHEF_ROOT}#{Regexp.escape(File::SEPARATOR)}(.*)\.rb/,1] + rel_path = knife_file[/#{CHEF_ROOT}#{Regexp.escape(File::SEPARATOR)}(.*)\.rb/, 1] subcommand_files[rel_path] = knife_file end subcommand_files diff --git a/lib/chef/knife/core/text_formatter.rb b/lib/chef/knife/core/text_formatter.rb index 006a6fc9cf..6de09cb1a5 100644 --- a/lib/chef/knife/core/text_formatter.rb +++ b/lib/chef/knife/core/text_formatter.rb @@ -20,7 +20,6 @@ class Chef class Knife module Core class TextFormatter - attr_reader :data attr_reader :ui @@ -45,7 +44,7 @@ class Chef buffer = "" if data.respond_to?(:keys) - justify_width = data.keys.map {|k| k.to_s.size }.max.to_i + 1 + justify_width = data.keys.map { |k| k.to_s.size }.max.to_i + 1 data.sort.each do |key, value| # key: ['value'] should be printed as key: value if value.kind_of?(Array) && value.size == 1 && is_singleton(value[0]) @@ -68,7 +67,7 @@ class Chef buffer << text_format(data[index]) # Separate items with newlines if it's an array of hashes or an # array of arrays - buffer << "\n" if !is_singleton(data[index]) && index != data.size-1 + buffer << "\n" if !is_singleton(data[index]) && index != data.size - 1 end else buffer << "#{data}\n" diff --git a/lib/chef/knife/core/ui.rb b/lib/chef/knife/core/ui.rb index f5002c8598..32da3cd4ba 100644 --- a/lib/chef/knife/core/ui.rb +++ b/lib/chef/knife/core/ui.rb @@ -25,11 +25,9 @@ require "tempfile" class Chef class Knife - #==Chef::Knife::UI # The User Interaction class used by knife. class UI - extend Forwardable attr_reader :stdout @@ -137,7 +135,7 @@ class Chef @presenter.interchange? end - def ask_question(question, opts={}) + def ask_question(question, opts = {}) question = question + "[#{opts[:default]}] " if opts[:default] if opts[:default] and config[:defaults] @@ -163,7 +161,6 @@ class Chef end end - # Hash -> Hash # Works the same as edit_data but # returns a hash rather than a JSON string/Fully infated object @@ -172,7 +169,7 @@ class Chef Chef::JSONCompat.parse(raw) end - def edit_data(data, parse_output=true) + def edit_data(data, parse_output = true) output = Chef::JSONCompat.to_json_pretty(data) if (!config[:disable_editing]) Tempfile.open([ "knife-edit-", ".json" ]) do |tf| @@ -226,7 +223,7 @@ class Chef end # See confirm method for argument information - def confirm_without_exit(question, append_instructions=true, default_choice=nil) + def confirm_without_exit(question, append_instructions = true, default_choice = nil) return true if config[:yes] stdout.print question @@ -264,13 +261,12 @@ class Chef # append_instructions => Should print '? (Y/N)' as instructions # default_choice => Set to true for 'Y', and false for 'N' as default answer # - def confirm(question, append_instructions=true, default_choice=nil) + def confirm(question, append_instructions = true, default_choice = nil) unless confirm_without_exit(question, append_instructions, default_choice) exit 3 end true end - end end end diff --git a/lib/chef/knife/data_bag_delete.rb b/lib/chef/knife/data_bag_delete.rb index a3cb008ec0..254f5fc004 100644 --- a/lib/chef/knife/data_bag_delete.rb +++ b/lib/chef/knife/data_bag_delete.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class DataBagDelete < Knife - deps do require "chef/data_bag" end @@ -47,5 +46,3 @@ class Chef end end end - - diff --git a/lib/chef/knife/data_bag_edit.rb b/lib/chef/knife/data_bag_edit.rb index c9ce079a22..ba39207db1 100644 --- a/lib/chef/knife/data_bag_edit.rb +++ b/lib/chef/knife/data_bag_edit.rb @@ -72,6 +72,3 @@ class Chef end end end - - - diff --git a/lib/chef/knife/data_bag_from_file.rb b/lib/chef/knife/data_bag_from_file.rb index f2cbb1369b..e029ec4b22 100644 --- a/lib/chef/knife/data_bag_from_file.rb +++ b/lib/chef/knife/data_bag_from_file.rb @@ -60,6 +60,7 @@ class Chef end private + def data_bags_path @data_bag_path ||= "data_bags" end diff --git a/lib/chef/knife/data_bag_list.rb b/lib/chef/knife/data_bag_list.rb index a2b700f186..1b2d2225aa 100644 --- a/lib/chef/knife/data_bag_list.rb +++ b/lib/chef/knife/data_bag_list.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class DataBagList < Knife - deps do require "chef/data_bag" end @@ -40,7 +39,3 @@ class Chef end end end - - - - diff --git a/lib/chef/knife/data_bag_secret_options.rb b/lib/chef/knife/data_bag_secret_options.rb index 7e458007f0..491b8639e7 100644 --- a/lib/chef/knife/data_bag_secret_options.rb +++ b/lib/chef/knife/data_bag_secret_options.rb @@ -136,7 +136,6 @@ class Chef def knife_config Chef::Config.key?(:knife) ? Chef::Config[:knife] : {} end - end end end diff --git a/lib/chef/knife/data_bag_show.rb b/lib/chef/knife/data_bag_show.rb index 505235538a..8375a8ea19 100644 --- a/lib/chef/knife/data_bag_show.rb +++ b/lib/chef/knife/data_bag_show.rb @@ -63,7 +63,6 @@ class Chef end output(display) end - end end end diff --git a/lib/chef/knife/delete.rb b/lib/chef/knife/delete.rb index aeb4744873..d5d4a4c4bd 100644 --- a/lib/chef/knife/delete.rb +++ b/lib/chef/knife/delete.rb @@ -105,4 +105,3 @@ class Chef end end end - diff --git a/lib/chef/knife/deps.rb b/lib/chef/knife/deps.rb index 0be83a8bf1..99a24e405b 100644 --- a/lib/chef/knife/deps.rb +++ b/lib/chef/knife/deps.rb @@ -61,12 +61,12 @@ class Chef def print_dependencies_tree(entry, dependencies, printed = {}, depth = 0) dependencies[entry.path] = get_dependencies(entry) if !dependencies[entry.path] - output "#{' '*depth}#{format_path(entry)}" + output "#{' ' * depth}#{format_path(entry)}" if !printed[entry.path] && (config[:recurse] || depth == 0) printed[entry.path] = true dependencies[entry.path].each do |child| child_entry = Chef::ChefFS::FileSystem.resolve_path(@root, child) - print_dependencies_tree(child_entry, dependencies, printed, depth+1) + print_dependencies_tree(child_entry, dependencies, printed, depth + 1) end end end @@ -96,7 +96,7 @@ class Chef end end if role["env_run_lists"] - role["env_run_lists"].each_pair do |env,run_list| + role["env_run_lists"].each_pair do |env, run_list| dependencies_from_runlist(run_list).each do |dependency| result << dependency if !result.include?(dependency) end diff --git a/lib/chef/knife/diff.rb b/lib/chef/knife/diff.rb index 580e9e513f..d965490f0a 100644 --- a/lib/chef/knife/diff.rb +++ b/lib/chef/knife/diff.rb @@ -66,4 +66,3 @@ class Chef end end end - diff --git a/lib/chef/knife/download.rb b/lib/chef/knife/download.rb index f2af0e0152..c609760509 100644 --- a/lib/chef/knife/download.rb +++ b/lib/chef/knife/download.rb @@ -66,4 +66,3 @@ class Chef end end end - diff --git a/lib/chef/knife/edit.rb b/lib/chef/knife/edit.rb index 608ce82a8f..00358b2d09 100644 --- a/lib/chef/knife/edit.rb +++ b/lib/chef/knife/edit.rb @@ -70,4 +70,3 @@ class Chef end end end - diff --git a/lib/chef/knife/environment_compare.rb b/lib/chef/knife/environment_compare.rb index 1a3389e2c8..120dc6c7e3 100644 --- a/lib/chef/knife/environment_compare.rb +++ b/lib/chef/knife/environment_compare.rb @@ -15,37 +15,36 @@ # See the License for the specific language governing permissions and # limitations under the License. # - + require "chef/knife" - + class Chef class Knife class EnvironmentCompare < Knife - deps do require "chef/environment" end - + banner "knife environment compare [ENVIRONMENT..] (options)" option :all, :short => "-a", :long => "--all", :description => "Show all cookbooks", - :boolean => true + :boolean => true option :mismatch, :short => "-m", :long => "--mismatch", :description => "Only show mismatching versions", :boolean => true - + def run # Get the commandline environments or all if none are provided. - environments = environment_list + environments = environment_list # Get a list of all cookbooks that have constraints and their environment. - constraints = constraint_list(environments) + constraints = constraint_list(environments) # Get the total list of cookbooks that have constraints cookbooks = cookbook_list(constraints) @@ -55,7 +54,7 @@ class Chef ui.error "Cannot find any environment cookbook constraints" exit 1 end - + # Get all cookbooks so we can compare them all cookbooks = rest.get("/cookbooks?num_versions=1") if config[:all] @@ -77,11 +76,11 @@ class Chef else environments = Chef::Environment.list end - end + end def constraint_list(environments) constraints = {} - environments.each do |env,url| + environments.each do |env, url| # Because you cannot modify the default environment I filter it out here. unless env == "_default" envdata = Chef::Environment.load(env) @@ -91,22 +90,22 @@ class Chef end constraints end - + def cookbook_list(constraints) result = {} constraints.each { |env, cb| result.merge!(cb) } result - end + end def matrix_output(cookbooks, constraints) rows = [ "" ] environments = [] - constraints.each { |e,v| environments << e.to_s } + constraints.each { |e, v| environments << e.to_s } columns = environments.count + 1 environments.each { |env| rows << ui.color(env, :bold) } - cookbooks.each do |c,v| + cookbooks.each do |c, v| total = [] - environments.each { |n| total << constraints[n][c]} + environments.each { |n| total << constraints[n][c] } if total.uniq.count == 1 next if config[:mismatch] color = :white @@ -116,12 +115,11 @@ class Chef rows << ui.color(c, :bold) environments.each do |e| tag = constraints[e][c] || "latest" - rows << ui.color(tag, color) + rows << ui.color(tag, color) end end ui.list(rows, :uneven_columns_across, columns) end - end end end diff --git a/lib/chef/knife/environment_create.rb b/lib/chef/knife/environment_create.rb index 9f022bb49a..21cfcceb16 100644 --- a/lib/chef/knife/environment_create.rb +++ b/lib/chef/knife/environment_create.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class EnvironmentCreate < Knife - deps do require "chef/environment" require "chef/json_compat" diff --git a/lib/chef/knife/environment_delete.rb b/lib/chef/knife/environment_delete.rb index 869d1c74fe..8644945ef7 100644 --- a/lib/chef/knife/environment_delete.rb +++ b/lib/chef/knife/environment_delete.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class EnvironmentDelete < Knife - deps do require "chef/environment" require "chef/json_compat" diff --git a/lib/chef/knife/environment_edit.rb b/lib/chef/knife/environment_edit.rb index 43f0b067ae..30e6834021 100644 --- a/lib/chef/knife/environment_edit.rb +++ b/lib/chef/knife/environment_edit.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class EnvironmentEdit < Knife - deps do require "chef/environment" require "chef/json_compat" diff --git a/lib/chef/knife/environment_from_file.rb b/lib/chef/knife/environment_from_file.rb index 4640632b32..978d40edcc 100644 --- a/lib/chef/knife/environment_from_file.rb +++ b/lib/chef/knife/environment_from_file.rb @@ -19,7 +19,6 @@ class Chef class Knife class EnvironmentFromFile < Knife - deps do require "chef/environment" require "chef/knife/core/object_loader" @@ -62,7 +61,6 @@ class Chef ui.info("Updated Environment #{updated.name}") end - def run if config[:all] == true load_all_environments diff --git a/lib/chef/knife/environment_list.rb b/lib/chef/knife/environment_list.rb index f278046bf9..c37ff6425c 100644 --- a/lib/chef/knife/environment_list.rb +++ b/lib/chef/knife/environment_list.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class EnvironmentList < Knife - deps do require "chef/environment" require "chef/json_compat" diff --git a/lib/chef/knife/environment_show.rb b/lib/chef/knife/environment_show.rb index 6d260adbd6..ff7fc4a817 100644 --- a/lib/chef/knife/environment_show.rb +++ b/lib/chef/knife/environment_show.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class EnvironmentShow < Knife - include Knife::Core::MultiAttributeReturnOption deps do diff --git a/lib/chef/knife/exec.rb b/lib/chef/knife/exec.rb index 0aa8ea2ba8..f6dd80b2fd 100644 --- a/lib/chef/knife/exec.rb +++ b/lib/chef/knife/exec.rb @@ -20,7 +20,6 @@ require "chef/knife" require "chef/util/path_helper" class Chef::Knife::Exec < Chef::Knife - banner "knife exec [SCRIPT] (options)" option :exec, @@ -83,5 +82,4 @@ class Chef::Knife::Exec < Chef::Knife ui.error("\"#{x}\" not found in current directory or script_path, giving up.") exit(1) end - end diff --git a/lib/chef/knife/help.rb b/lib/chef/knife/help.rb index f4221f233a..343f5c5013 100644 --- a/lib/chef/knife/help.rb +++ b/lib/chef/knife/help.rb @@ -19,7 +19,6 @@ class Chef class Knife class Help < Chef::Knife - banner "knife help [list|TOPIC]" def run @@ -43,8 +42,6 @@ MOAR_HELP @query = name_args.join("-") end - - case @query when "topics", "list" print_help_topics @@ -67,7 +64,7 @@ MOAR_HELP def print_help_topics ui.info "Available help topics are: " - help_topics.collect {|t| t.gsub(/knife-/, "") }.sort.each do |topic| + help_topics.collect { |t| t.gsub(/knife-/, "") }.sort.each do |topic| ui.msg " #{topic}" end end diff --git a/lib/chef/knife/index_rebuild.rb b/lib/chef/knife/index_rebuild.rb index c317d767b5..21a525f1c3 100644 --- a/lib/chef/knife/index_rebuild.rb +++ b/lib/chef/knife/index_rebuild.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class IndexRebuild < Knife - banner "knife index rebuild (options)" option :yes, :short => "-y", @@ -40,7 +39,6 @@ class Chef nag output rest.post("/search/reindex", {}) end - end def grab_api_info @@ -128,7 +126,6 @@ class Chef "chef-server-ctl" end end - end end end diff --git a/lib/chef/knife/key_create.rb b/lib/chef/knife/key_create.rb index 9288fd91e8..398b8fac48 100644 --- a/lib/chef/knife/key_create.rb +++ b/lib/chef/knife/key_create.rb @@ -29,7 +29,6 @@ class Chef # # @attr_accessor [Hash] cli input, see UserKeyCreate and ClientKeyCreate for what could populate it class KeyCreate - attr_accessor :config def initialize(actor, actor_field_name, ui, config) @@ -40,7 +39,7 @@ class Chef end def public_key_or_key_name_error_msg -< "application/json"} + headers = { "Content-Type" => "application/json" } if config[:proxy_auth] headers["x-ops-request-source"] = "web" @@ -97,7 +97,6 @@ class Chef exit 1 end end - end # class Raw end end diff --git a/lib/chef/knife/recipe_list.rb b/lib/chef/knife/recipe_list.rb index 8f76e494ad..550568f2d2 100644 --- a/lib/chef/knife/recipe_list.rb +++ b/lib/chef/knife/recipe_list.rb @@ -18,7 +18,6 @@ require "chef/knife" class Chef::Knife::RecipeList < Chef::Knife - banner "knife recipe list [PATTERN]" def run @@ -28,5 +27,4 @@ class Chef::Knife::RecipeList < Chef::Knife end output(recipes) end - end diff --git a/lib/chef/knife/rehash.rb b/lib/chef/knife/rehash.rb index 7c16260fed..3e7bab7e0f 100644 --- a/lib/chef/knife/rehash.rb +++ b/lib/chef/knife/rehash.rb @@ -21,7 +21,7 @@ require "chef/knife/core/subcommand_loader" class Chef class Knife - class Rehash < Chef::Knife + class Rehash < Chef::Knife banner "knife rehash" def run @@ -42,7 +42,7 @@ class Chef output = if Chef::Knife::SubcommandLoader.plugin_manifest? Chef::Knife::SubcommandLoader.plugin_manifest else - { Chef::Knife::SubcommandLoader::HashedCommandLoader::KEY => {}} + { Chef::Knife::SubcommandLoader::HashedCommandLoader::KEY => {} } end output[Chef::Knife::SubcommandLoader::HashedCommandLoader::KEY]["plugins_paths"] = Chef::Knife.subcommand_files output[Chef::Knife::SubcommandLoader::HashedCommandLoader::KEY]["plugins_by_category"] = Chef::Knife.subcommands_by_category diff --git a/lib/chef/knife/role_bulk_delete.rb b/lib/chef/knife/role_bulk_delete.rb index 2ec0afb182..32e8903de6 100644 --- a/lib/chef/knife/role_bulk_delete.rb +++ b/lib/chef/knife/role_bulk_delete.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class RoleBulkDelete < Knife - deps do require "chef/role" require "chef/json_compat" @@ -63,8 +62,3 @@ class Chef end end end - - - - - diff --git a/lib/chef/knife/role_create.rb b/lib/chef/knife/role_create.rb index 23bf0c372b..86ffe5bbc6 100644 --- a/lib/chef/knife/role_create.rb +++ b/lib/chef/knife/role_create.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class RoleCreate < Knife - deps do require "chef/role" require "chef/json_compat" @@ -51,5 +50,3 @@ class Chef end end end - - diff --git a/lib/chef/knife/role_delete.rb b/lib/chef/knife/role_delete.rb index 4162f5b9f4..cf07061f7b 100644 --- a/lib/chef/knife/role_delete.rb +++ b/lib/chef/knife/role_delete.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class RoleDelete < Knife - deps do require "chef/role" require "chef/json_compat" @@ -40,8 +39,6 @@ class Chef delete_object(Chef::Role, @role_name) end - end end end - diff --git a/lib/chef/knife/role_edit.rb b/lib/chef/knife/role_edit.rb index 129d55cacd..0340516b2d 100644 --- a/lib/chef/knife/role_edit.rb +++ b/lib/chef/knife/role_edit.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class RoleEdit < Knife - deps do require "chef/role" require "chef/json_compat" @@ -43,6 +42,3 @@ class Chef end end end - - - diff --git a/lib/chef/knife/role_env_run_list_add.rb b/lib/chef/knife/role_env_run_list_add.rb index 207484597e..8570e587b9 100644 --- a/lib/chef/knife/role_env_run_list_add.rb +++ b/lib/chef/knife/role_env_run_list_add.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class RoleEnvRunListAdd < Knife - deps do require "chef/role" require "chef/json_compat" @@ -34,13 +33,13 @@ class Chef :long => "--after ITEM", :description => "Place the ENTRY in the run list after ITEM" - def add_to_env_run_list(role, environment, entries, after=nil) + def add_to_env_run_list(role, environment, entries, after = nil) if after nlist = [] unless role.env_run_lists.key?(environment) role.env_run_lists_add(environment => nlist) end - role.run_list_for(environment).each do |entry| + role.run_list_for(environment).each do |entry| nlist << entry if entry == after entries.each { |e| nlist << e } @@ -80,7 +79,6 @@ class Chef config[:env_run_list] = true output(format_for_display(role)) end - end end end diff --git a/lib/chef/knife/role_env_run_list_clear.rb b/lib/chef/knife/role_env_run_list_clear.rb index d9dc96c87d..1f525b2d92 100644 --- a/lib/chef/knife/role_env_run_list_clear.rb +++ b/lib/chef/knife/role_env_run_list_clear.rb @@ -22,7 +22,6 @@ require "chef/knife" class Chef class Knife class RoleEnvRunListClear < Knife - deps do require "chef/role" require "chef/json_compat" @@ -49,7 +48,6 @@ class Chef config[:env_run_list] = true output(format_for_display(role)) end - end end end diff --git a/lib/chef/knife/role_env_run_list_remove.rb b/lib/chef/knife/role_env_run_list_remove.rb index ae30d0a884..0f44e9c6af 100644 --- a/lib/chef/knife/role_env_run_list_remove.rb +++ b/lib/chef/knife/role_env_run_list_remove.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class RoleEnvRunListRemove < Knife - deps do require "chef/role" require "chef/json_compat" @@ -30,14 +29,14 @@ class Chef banner "knife role env_run_list remove [ROLE] [ENVIRONMENT] [ENTRIES]" def remove_from_env_run_list(role, environment, item_to_remove) - nlist = [] - role.run_list_for(environment).each do |entry| - nlist << entry unless entry == item_to_remove - #unless entry == @name_args[2] - # nlist << entry - #end - end - role.env_run_lists_add(environment => nlist) + nlist = [] + role.run_list_for(environment).each do |entry| + nlist << entry unless entry == item_to_remove + #unless entry == @name_args[2] + # nlist << entry + #end + end + role.env_run_lists_add(environment => nlist) end def run @@ -51,7 +50,6 @@ class Chef config[:env_run_list] = true output(format_for_display(role)) end - end end end diff --git a/lib/chef/knife/role_env_run_list_replace.rb b/lib/chef/knife/role_env_run_list_replace.rb index ae0c7a63b5..d015c3338a 100644 --- a/lib/chef/knife/role_env_run_list_replace.rb +++ b/lib/chef/knife/role_env_run_list_replace.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class RoleEnvRunListReplace < Knife - deps do require "chef/role" require "chef/json_compat" @@ -31,7 +30,7 @@ class Chef def replace_in_env_run_list(role, environment, old_entry, new_entry) nlist = [] - role.run_list_for(environment).each do |entry| + role.run_list_for(environment).each do |entry| if entry == old_entry nlist << new_entry else @@ -53,7 +52,6 @@ class Chef config[:env_run_list] = true output(format_for_display(role)) end - end end end diff --git a/lib/chef/knife/role_env_run_list_set.rb b/lib/chef/knife/role_env_run_list_set.rb index f53616e151..9e02e38f1d 100644 --- a/lib/chef/knife/role_env_run_list_set.rb +++ b/lib/chef/knife/role_env_run_list_set.rb @@ -22,7 +22,6 @@ require "chef/knife" class Chef class Knife class RoleEnvRunListSet < Knife - deps do require "chef/role" require "chef/json_compat" @@ -64,7 +63,6 @@ class Chef config[:env_run_list] = true output(format_for_display(role)) end - end end end diff --git a/lib/chef/knife/role_from_file.rb b/lib/chef/knife/role_from_file.rb index 157c8b8889..2d36eadf33 100644 --- a/lib/chef/knife/role_from_file.rb +++ b/lib/chef/knife/role_from_file.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class RoleFromFile < Knife - deps do require "chef/role" require "chef/knife/core/object_loader" @@ -45,12 +44,6 @@ class Chef ui.info("Updated Role #{updated.name}!") end end - end end end - - - - - diff --git a/lib/chef/knife/role_list.rb b/lib/chef/knife/role_list.rb index 02a1bcb43e..dc3a3b26f0 100644 --- a/lib/chef/knife/role_list.rb +++ b/lib/chef/knife/role_list.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class RoleList < Knife - deps do require "chef/node" require "chef/json_compat" @@ -40,4 +39,3 @@ class Chef end end end - diff --git a/lib/chef/knife/role_run_list_add.rb b/lib/chef/knife/role_run_list_add.rb index 3ce0439a7f..eacaeaf732 100644 --- a/lib/chef/knife/role_run_list_add.rb +++ b/lib/chef/knife/role_run_list_add.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class RoleRunListAdd < Knife - deps do require "chef/role" require "chef/json_compat" @@ -34,13 +33,13 @@ class Chef :long => "--after ITEM", :description => "Place the ENTRY in the run list after ITEM" - def add_to_env_run_list(role, environment, entries, after=nil) + def add_to_env_run_list(role, environment, entries, after = nil) if after nlist = [] unless role.env_run_lists.key?(environment) role.env_run_lists_add(environment => nlist) end - role.run_list_for(environment).each do |entry| + role.run_list_for(environment).each do |entry| nlist << entry if entry == after entries.each { |e| nlist << e } @@ -80,7 +79,6 @@ class Chef config[:env_run_list] = true output(format_for_display(role)) end - end end end diff --git a/lib/chef/knife/role_run_list_clear.rb b/lib/chef/knife/role_run_list_clear.rb index 81678d39ef..eb8934c40c 100644 --- a/lib/chef/knife/role_run_list_clear.rb +++ b/lib/chef/knife/role_run_list_clear.rb @@ -22,7 +22,6 @@ require "chef/knife" class Chef class Knife class RoleRunListClear < Knife - deps do require "chef/role" require "chef/json_compat" @@ -49,7 +48,6 @@ class Chef config[:env_run_list] = true output(format_for_display(role)) end - end end end diff --git a/lib/chef/knife/role_run_list_remove.rb b/lib/chef/knife/role_run_list_remove.rb index f9f8e1dbb1..a679335d15 100644 --- a/lib/chef/knife/role_run_list_remove.rb +++ b/lib/chef/knife/role_run_list_remove.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class RoleRunListRemove < Knife - deps do require "chef/role" require "chef/json_compat" @@ -30,14 +29,14 @@ class Chef banner "knife role run_list remove [ROLE] [ENTRY]" def remove_from_env_run_list(role, environment, item_to_remove) - nlist = [] - role.run_list_for(environment).each do |entry| - nlist << entry unless entry == item_to_remove - #unless entry == @name_args[2] - # nlist << entry - #end - end - role.env_run_lists_add(environment => nlist) + nlist = [] + role.run_list_for(environment).each do |entry| + nlist << entry unless entry == item_to_remove + #unless entry == @name_args[2] + # nlist << entry + #end + end + role.env_run_lists_add(environment => nlist) end def run @@ -51,7 +50,6 @@ class Chef config[:env_run_list] = true output(format_for_display(role)) end - end end end diff --git a/lib/chef/knife/role_run_list_replace.rb b/lib/chef/knife/role_run_list_replace.rb index e12a77d487..9ba7f87bb7 100644 --- a/lib/chef/knife/role_run_list_replace.rb +++ b/lib/chef/knife/role_run_list_replace.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class RoleRunListReplace < Knife - deps do require "chef/role" require "chef/json_compat" @@ -31,7 +30,7 @@ class Chef def replace_in_env_run_list(role, environment, old_entry, new_entry) nlist = [] - role.run_list_for(environment).each do |entry| + role.run_list_for(environment).each do |entry| if entry == old_entry nlist << new_entry else @@ -53,7 +52,6 @@ class Chef config[:env_run_list] = true output(format_for_display(role)) end - end end end diff --git a/lib/chef/knife/role_run_list_set.rb b/lib/chef/knife/role_run_list_set.rb index 644af1c381..4dfac0383d 100644 --- a/lib/chef/knife/role_run_list_set.rb +++ b/lib/chef/knife/role_run_list_set.rb @@ -22,7 +22,6 @@ require "chef/knife" class Chef class Knife class RoleRunListSet < Knife - deps do require "chef/role" require "chef/json_compat" @@ -64,7 +63,6 @@ class Chef config[:env_run_list] = true output(format_for_display(role)) end - end end end diff --git a/lib/chef/knife/role_show.rb b/lib/chef/knife/role_show.rb index a3af0baf6a..eaedc75d70 100644 --- a/lib/chef/knife/role_show.rb +++ b/lib/chef/knife/role_show.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class RoleShow < Knife - include Knife::Core::MultiAttributeReturnOption deps do @@ -31,7 +30,6 @@ class Chef banner "knife role show ROLE (options)" - def run @role_name = @name_args[0] @@ -44,9 +42,6 @@ class Chef role = Chef::Role.load(@role_name) output(format_for_display(config[:environment] ? role.environment(config[:environment]) : role)) end - end end end - - diff --git a/lib/chef/knife/search.rb b/lib/chef/knife/search.rb index ecb323abe3..0407d30ccd 100644 --- a/lib/chef/knife/search.rb +++ b/lib/chef/knife/search.rb @@ -22,7 +22,6 @@ require "chef/knife/core/node_presenter" class Chef class Knife class Search < Knife - include Knife::Core::MultiAttributeReturnOption deps do @@ -106,7 +105,7 @@ class Chef formatted_item = Hash.new if item.is_a?(Hash) # doing a little magic here to set the correct name - formatted_item[item["__display_name"]] = item.reject{|k| k == "__display_name"} + formatted_item[item["__display_name"]] = item.reject { |k| k == "__display_name" } else formatted_item = format_for_display(item) end @@ -120,7 +119,7 @@ class Chef end if ui.interchange? - output({:results => result_count, :rows => result_items}) + output({ :results => result_count, :rows => result_items }) else ui.log "#{result_count} items found" ui.log("\n") @@ -195,7 +194,6 @@ class Chef final_filter["__display_name"] = [ "name" ] return final_filter end - end end end diff --git a/lib/chef/knife/serve.rb b/lib/chef/knife/serve.rb index 3f97962eae..aa475801bc 100644 --- a/lib/chef/knife/serve.rb +++ b/lib/chef/knife/serve.rb @@ -4,7 +4,6 @@ require "chef/local_mode" class Chef class Knife class Serve < Knife - banner "knife serve (options)" option :repo_mode, diff --git a/lib/chef/knife/ssh.rb b/lib/chef/knife/ssh.rb index fb36fb67f4..6f48b01809 100644 --- a/lib/chef/knife/ssh.rb +++ b/lib/chef/knife/ssh.rb @@ -22,7 +22,6 @@ require "chef/knife" class Chef class Knife class Ssh < Knife - deps do require "net/ssh" require "net/ssh/multi" @@ -165,7 +164,7 @@ class Chef if @action_nodes.length == 0 ui.fatal("No nodes returned from search!") else - ui.fatal("#{@action_nodes.length} #{@action_nodes.length > 1 ? "nodes": "node"} found, " + + ui.fatal("#{@action_nodes.length} #{@action_nodes.length > 1 ? "nodes" : "node"} found, " + "but does not have the required attribute to establish the connection. " + "Try setting another attribute to open the connection using --attribute.") end @@ -209,7 +208,7 @@ class Chef next if item.nil? # next if we couldn't find the specified attribute in the # returned node object - host = extract_nested_value(item,get_ssh_attribute(item)) + host = extract_nested_value(item, get_ssh_attribute(item)) next if host.nil? ssh_port = item[:cloud].nil? ? nil : item[:cloud][:public_ssh_port] srv = [host, ssh_port] @@ -227,7 +226,7 @@ class Chef # @param port [String] SSH port for this session. # @param user [String] Optional username for this session. # @return [Hash] - def session_options(host, port, user=nil) + def session_options(host, port, user = nil) ssh_config = Net::SSH.configuration_for(host) {}.tap do |opts| # Chef::Config[:knife][:ssh_user] is parsed in #configure_user and written to config[:ssh_user] @@ -297,7 +296,7 @@ class Chef ui.msg(str) end - def ssh_command(command, subsession=nil) + def ssh_command(command, subsession = nil) exit_status = 0 subsession ||= session command = fixup_sudo(command) @@ -425,7 +424,7 @@ class Chef end.join(" \\; ") end - tmux_name = "'knife ssh #{@name_args[0].gsub(/:/,'=')}'" + tmux_name = "'knife ssh #{@name_args[0].gsub(/:/, '=')}'" begin server = session.servers_for.first cmd = ["tmux new-session -d -s #{tmux_name}", @@ -446,13 +445,13 @@ class Chef end Appscript.app("/Applications/Utilities/Terminal.app").windows.first.activate - Appscript.app("System Events").application_processes["Terminal.app"].keystroke("n", :using=>:command_down) + Appscript.app("System Events").application_processes["Terminal.app"].keystroke("n", :using => :command_down) term = Appscript.app("Terminal") window = term.windows.first.get (session.servers_for.size - 1).times do |i| window.activate - Appscript.app("System Events").application_processes["Terminal.app"].keystroke("t", :using=>:command_down) + Appscript.app("System Events").application_processes["Terminal.app"].keystroke("t", :using => :command_down) end session.servers_for.each_with_index do |server, tab_number| @@ -569,7 +568,6 @@ class Chef end private :search_nodes - end end end diff --git a/lib/chef/knife/ssl_check.rb b/lib/chef/knife/ssl_check.rb index 87cb82c8b1..d73548a4bd 100644 --- a/lib/chef/knife/ssl_check.rb +++ b/lib/chef/knife/ssl_check.rb @@ -22,7 +22,6 @@ require "chef/config" class Chef class Knife class SslCheck < Chef::Knife - deps do require "pp" require "socket" @@ -206,7 +205,7 @@ ADVICE def debug_invalid_host noverify_socket.connect subject = noverify_socket.peer_cert.subject - cn_field_tuple = subject.to_a.find {|field| field[0] == "CN" } + cn_field_tuple = subject.to_a.find { |field| field[0] == "CN" } cn = cn_field_tuple[1] ui.error("You are attempting to connect to: '#{host}'") @@ -253,6 +252,7 @@ ADVICE end private + def trusted_certificates if configuration.trusted_certs_dir && Dir.exist?(configuration.trusted_certs_dir) Dir.glob(File.join(configuration.trusted_certs_dir, "*.{crt,pem}")) diff --git a/lib/chef/knife/ssl_fetch.rb b/lib/chef/knife/ssl_fetch.rb index 3d9db57c07..b21dca1191 100644 --- a/lib/chef/knife/ssl_fetch.rb +++ b/lib/chef/knife/ssl_fetch.rb @@ -22,7 +22,6 @@ require "chef/config" class Chef class Knife class SslFetch < Chef::Knife - deps do require "pp" require "socket" @@ -87,10 +86,9 @@ class Chef end end - def cn_of(certificate) subject = certificate.subject - cn_field_tuple = subject.to_a.find {|field| field[0] == "CN" } + cn_field_tuple = subject.to_a.find { |field| field[0] == "CN" } cn_field_tuple[1] end @@ -120,7 +118,7 @@ class Chef cn = cn_of(cert) filename = File.join(trusted_certs_dir, "#{normalize_cn(cn)}.crt") ui.msg("Adding certificate for #{cn} in #{filename}") - File.open(filename, File::CREAT|File::TRUNC|File::RDWR, 0644) do |f| + File.open(filename, File::CREAT | File::TRUNC | File::RDWR, 0644) do |f| f.print(cert.to_s) end end @@ -152,8 +150,6 @@ TRUST_TRUST end exit 1 end - - end end end diff --git a/lib/chef/knife/status.rb b/lib/chef/knife/status.rb index 48e7a2a49d..e32e6986af 100644 --- a/lib/chef/knife/status.rb +++ b/lib/chef/knife/status.rb @@ -61,10 +61,10 @@ class Chef if config[:long_output] opts = {} else - opts = {filter_result: + opts = { filter_result: { name: ["name"], ipaddress: ["ipaddress"], ohai_time: ["ohai_time"], - ec2: ["ec2"], run_list: ["run_list"], platform: ["platform"], - platform_version: ["platform_version"], chef_environment: ["chef_environment"]}} + ec2: ["ec2"], run_list: ["run_list"], platform: ["platform"], + platform_version: ["platform_version"], chef_environment: ["chef_environment"] } } end @query ||= "" @@ -76,7 +76,7 @@ class Chef time = Time.now.to_i # AND NOT is not valid lucene syntax, so don't use append_to_query @query << " " unless @query.empty? - @query << "NOT ohai_time:[#{(time - 60*60)} TO #{time}]" + @query << "NOT ohai_time:[#{(time - 60 * 60)} TO #{time}]" end if config[:hide_by_mins] @@ -84,7 +84,7 @@ class Chef time = Time.now.to_i # AND NOT is not valid lucene syntax, so don't use append_to_query @query << " " unless @query.empty? - @query << "NOT ohai_time:[#{(time - hidemins*60)} TO #{time}]" + @query << "NOT ohai_time:[#{(time - hidemins * 60)} TO #{time}]" end @query = @query.empty? ? "*:*" : @query @@ -104,7 +104,6 @@ class Chef end }) end - end end end diff --git a/lib/chef/knife/tag_create.rb b/lib/chef/knife/tag_create.rb index e8cfe11303..fc88b835bb 100644 --- a/lib/chef/knife/tag_create.rb +++ b/lib/chef/knife/tag_create.rb @@ -23,7 +23,6 @@ require "chef/knife" class Chef class Knife class TagCreate < Knife - deps do require "chef/node" end diff --git a/lib/chef/knife/tag_delete.rb b/lib/chef/knife/tag_delete.rb index d00ec2f60b..da57912c55 100644 --- a/lib/chef/knife/tag_delete.rb +++ b/lib/chef/knife/tag_delete.rb @@ -23,7 +23,6 @@ require "chef/knife" class Chef class Knife class TagDelete < Knife - deps do require "chef/node" end diff --git a/lib/chef/knife/tag_list.rb b/lib/chef/knife/tag_list.rb index 2665e53bf4..3cabe77718 100644 --- a/lib/chef/knife/tag_list.rb +++ b/lib/chef/knife/tag_list.rb @@ -23,7 +23,6 @@ require "chef/knife" class Chef class Knife class TagList < Knife - deps do require "chef/node" end diff --git a/lib/chef/knife/upload.rb b/lib/chef/knife/upload.rb index 90b9a1562b..d0bf89fa7f 100644 --- a/lib/chef/knife/upload.rb +++ b/lib/chef/knife/upload.rb @@ -68,4 +68,3 @@ class Chef end end end - diff --git a/lib/chef/knife/user_create.rb b/lib/chef/knife/user_create.rb index 9613ec795d..93e6c121e1 100644 --- a/lib/chef/knife/user_create.rb +++ b/lib/chef/knife/user_create.rb @@ -23,7 +23,6 @@ require "chef/knife/osc_user_create" class Chef class Knife class UserCreate < Knife - attr_accessor :user_field deps do @@ -69,7 +68,7 @@ class Chef end def osc_11_warning -<<-EOF + <<-EOF IF YOU ARE USING CHEF SERVER 12+, PLEASE FOLLOW THE INSTRUCTIONS UNDER knife user create --help. You only passed a single argument to knife user create. For backwards compatibility, when only a single argument is passed, @@ -144,8 +143,6 @@ EOF end end end - - end end end diff --git a/lib/chef/knife/user_delete.rb b/lib/chef/knife/user_delete.rb index a6eb89bc17..dba3e26f21 100644 --- a/lib/chef/knife/user_delete.rb +++ b/lib/chef/knife/user_delete.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class UserDelete < Knife - deps do require "chef/user_v1" require "chef/json_compat" @@ -30,7 +29,7 @@ class Chef banner "knife user delete USER (options)" def osc_11_warning -<<-EOF + <<-EOF The Chef Server you are using does not support the username field. This means it is an Open Source 11 Server. knife user delete for Open Source 11 Server is being deprecated. @@ -89,7 +88,6 @@ EOF else # proceed with EC / CS delete delete_object(@user_name) end - end end end diff --git a/lib/chef/knife/user_edit.rb b/lib/chef/knife/user_edit.rb index 5aa1c56796..319d635998 100644 --- a/lib/chef/knife/user_edit.rb +++ b/lib/chef/knife/user_edit.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class UserEdit < Knife - deps do require "chef/user_v1" require "chef/json_compat" @@ -30,7 +29,7 @@ class Chef banner "knife user edit USER (options)" def osc_11_warning -<<-EOF + <<-EOF The Chef Server you are using does not support the username field. This means it is an Open Source 11 Server. knife user edit for Open Source 11 Server is being deprecated. @@ -75,7 +74,6 @@ EOF ui.msg("User unchanged, not saving.") end end - end end end diff --git a/lib/chef/knife/user_key_create.rb b/lib/chef/knife/user_key_create.rb index c5c983979d..95a98a2f4f 100644 --- a/lib/chef/knife/user_key_create.rb +++ b/lib/chef/knife/user_key_create.rb @@ -34,7 +34,7 @@ class Chef attr_reader :actor - def initialize(argv=[]) + def initialize(argv = []) super(argv) @service_object = nil end diff --git a/lib/chef/knife/user_key_delete.rb b/lib/chef/knife/user_key_delete.rb index 1dafc4879d..1c559f2ef0 100644 --- a/lib/chef/knife/user_key_delete.rb +++ b/lib/chef/knife/user_key_delete.rb @@ -31,7 +31,7 @@ class Chef attr_reader :actor - def initialize(argv=[]) + def initialize(argv = []) super(argv) @service_object = nil end diff --git a/lib/chef/knife/user_key_edit.rb b/lib/chef/knife/user_key_edit.rb index ce59876e39..561af8edd0 100644 --- a/lib/chef/knife/user_key_edit.rb +++ b/lib/chef/knife/user_key_edit.rb @@ -34,7 +34,7 @@ class Chef attr_reader :actor - def initialize(argv=[]) + def initialize(argv = []) super(argv) @service_object = nil end @@ -77,4 +77,3 @@ class Chef end end end - diff --git a/lib/chef/knife/user_key_list.rb b/lib/chef/knife/user_key_list.rb index 1d777bad18..799c069182 100644 --- a/lib/chef/knife/user_key_list.rb +++ b/lib/chef/knife/user_key_list.rb @@ -34,7 +34,7 @@ class Chef attr_reader :actor - def initialize(argv=[]) + def initialize(argv = []) super(argv) @service_object = nil end diff --git a/lib/chef/knife/user_key_show.rb b/lib/chef/knife/user_key_show.rb index 3887238b20..e09d5e04ed 100644 --- a/lib/chef/knife/user_key_show.rb +++ b/lib/chef/knife/user_key_show.rb @@ -31,7 +31,7 @@ class Chef attr_reader :actor - def initialize(argv=[]) + def initialize(argv = []) super(argv) @service_object = nil end diff --git a/lib/chef/knife/user_list.rb b/lib/chef/knife/user_list.rb index 88e834025d..ec5567f217 100644 --- a/lib/chef/knife/user_list.rb +++ b/lib/chef/knife/user_list.rb @@ -23,7 +23,6 @@ require "chef/knife" class Chef class Knife class UserList < Knife - deps do require "chef/user_v1" require "chef/json_compat" @@ -39,7 +38,6 @@ class Chef def run output(format_list_for_display(Chef::UserV1.list)) end - end end end diff --git a/lib/chef/knife/user_reregister.rb b/lib/chef/knife/user_reregister.rb index 3e093da6a5..1d9715a97c 100644 --- a/lib/chef/knife/user_reregister.rb +++ b/lib/chef/knife/user_reregister.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class UserReregister < Knife - deps do require "chef/user_v1" require "chef/json_compat" @@ -30,7 +29,7 @@ class Chef banner "knife user reregister USER (options)" def osc_11_warning -<<-EOF + <<-EOF The Chef Server you are using does not support the username field. This means it is an Open Source 11 Server. knife user reregister for Open Source 11 Server is being deprecated. @@ -83,7 +82,6 @@ EOF ui.msg key end end - end end end diff --git a/lib/chef/knife/user_show.rb b/lib/chef/knife/user_show.rb index 0f70b86603..0d536be7c5 100644 --- a/lib/chef/knife/user_show.rb +++ b/lib/chef/knife/user_show.rb @@ -21,7 +21,6 @@ require "chef/knife" class Chef class Knife class UserShow < Knife - include Knife::Core::MultiAttributeReturnOption deps do @@ -32,7 +31,7 @@ class Chef banner "knife user show USER (options)" def osc_11_warning -<<-EOF + <<-EOF The Chef Server you are using does not support the username field. This means it is an Open Source 11 Server. knife user show for Open Source 11 Server is being deprecated. @@ -72,7 +71,6 @@ EOF output(format_for_display(user)) end end - end end end diff --git a/lib/chef/knife/xargs.rb b/lib/chef/knife/xargs.rb index f16890cba5..7428ee2b0e 100644 --- a/lib/chef/knife/xargs.rb +++ b/lib/chef/knife/xargs.rb @@ -22,7 +22,7 @@ class Chef :long => "--pattern [PATTERN]", :short => "-p [PATTERN]", :description => "Pattern on command line (if these are not specified, a list of patterns is expected on standard input). Multiple patterns may be passed in this way.", - :arg_arity => [1,-1] + :arg_arity => [1, -1] option :diff, :long => "--[no-]diff", @@ -260,8 +260,6 @@ class Chef end str end - end end end - diff --git a/lib/chef/local_mode.rb b/lib/chef/local_mode.rb index a1b0910156..745952809e 100644 --- a/lib/chef/local_mode.rb +++ b/lib/chef/local_mode.rb @@ -23,7 +23,6 @@ end class Chef module LocalMode - # Create a chef local server (if the configuration requires one) for the # duration of the given block. # @@ -107,7 +106,7 @@ class Chef if port.is_a?(String) parts = port.split(",") if parts.size == 1 - a,b = parts[0].split("-",2) + a, b = parts[0].split("-", 2) if b a.to_i.upto(b.to_i) else diff --git a/lib/chef/log.rb b/lib/chef/log.rb index 5b22b3c00e..8ce978548e 100644 --- a/lib/chef/log.rb +++ b/lib/chef/log.rb @@ -51,7 +51,7 @@ class Chef caller(0..20).select { |c| !c.start_with?(chef_gem_path) }.first end - def self.deprecation(msg=nil, location=caller(2..2)[0], &block) + def self.deprecation(msg = nil, location = caller(2..2)[0], &block) if msg msg << " at #{Array(location).join("\n")}" msg = msg.join("") if msg.respond_to?(:join) @@ -63,6 +63,5 @@ class Chef warn(msg, &block) end end - end end diff --git a/lib/chef/log/syslog.rb b/lib/chef/log/syslog.rb index 0fe3593fe5..58d6671095 100644 --- a/lib/chef/log/syslog.rb +++ b/lib/chef/log/syslog.rb @@ -32,7 +32,7 @@ class Chef attr_accessor :sync, :formatter - def initialize(program_name = "chef-client", facility = ::Syslog::LOG_DAEMON, logopts=nil) + def initialize(program_name = "chef-client", facility = ::Syslog::LOG_DAEMON, logopts = nil) super return if defined? ::Logger::Syslog::SYSLOG ::Logger::Syslog.const_set :SYSLOG, SYSLOG @@ -43,4 +43,3 @@ class Chef end end end - diff --git a/lib/chef/log/winevt.rb b/lib/chef/log/winevt.rb index e5afb4ed3c..ecfcbfcf26 100644 --- a/lib/chef/log/winevt.rb +++ b/lib/chef/log/winevt.rb @@ -42,7 +42,7 @@ class Chef attr_accessor :sync, :formatter, :level - def initialize(eventlog=nil) + def initialize(eventlog = nil) @eventlog = eventlog || ::Win32::EventLog::open("Application") end @@ -93,7 +93,6 @@ class Chef :data => [msg], ) end - end end end diff --git a/lib/chef/mash.rb b/lib/chef/mash.rb index e43ba6a0ae..f558e1ce7b 100644 --- a/lib/chef/mash.rb +++ b/lib/chef/mash.rb @@ -49,7 +49,6 @@ # This class has dubious semantics and we only have it so that people can write # params[:key] instead of params['key']. class Mash < Hash - # @param constructor # The default value for the mash. Defaults to an empty hash. # @@ -71,7 +70,7 @@ class Mash < Hash def initialize_copy(orig) super # Handle nested values - each do |k,v| + each do |k, v| if v.kind_of?(Mash) || v.is_a?(Array) self[k] = v.dup end @@ -142,7 +141,7 @@ class Mash < Hash # # @return [Array] The values at each of the provided keys def values_at(*indices) - indices.collect {|key| self[convert_key(key)]} + indices.collect { |key| self[convert_key(key)] } end # @param hash The hash to merge with the mash. @@ -166,7 +165,7 @@ class Mash < Hash # { :one => 1, :two => 2, :three => 3 }.except(:one) # #=> { "two" => 2, "three" => 3 } def except(*keys) - super(*keys.map {|k| convert_key(k)}) + super(*keys.map { |k| convert_key(k) }) end # Used to provide the same interface as Hash. @@ -195,6 +194,7 @@ class Mash < Hash end protected + # @param key The key to convert. # # @param [Object] diff --git a/lib/chef/mixin/api_version_request_handling.rb b/lib/chef/mixin/api_version_request_handling.rb index b91a1dfe0a..3da67bcfe5 100644 --- a/lib/chef/mixin/api_version_request_handling.rb +++ b/lib/chef/mixin/api_version_request_handling.rb @@ -60,7 +60,6 @@ Please refer to the documentation on how to manage your keys via the key rotatio https://docs.chef.io/server_security.html#key-rotation EOH end - end end end diff --git a/lib/chef/mixin/checksum.rb b/lib/chef/mixin/checksum.rb index f223894c39..f71a7def12 100644 --- a/lib/chef/mixin/checksum.rb +++ b/lib/chef/mixin/checksum.rb @@ -22,11 +22,9 @@ require "chef/digester" class Chef module Mixin module Checksum - def checksum(file) Chef::Digester.checksum_for_file(file) end - end end end diff --git a/lib/chef/mixin/command.rb b/lib/chef/mixin/command.rb index 8e0b105274..1cade4fa34 100644 --- a/lib/chef/mixin/command.rb +++ b/lib/chef/mixin/command.rb @@ -24,7 +24,6 @@ require "etc" class Chef module Mixin - #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # NOTE: # The popen4 method upon which all the code here is based has a race @@ -75,7 +74,7 @@ class Chef # # === Returns # Returns the exit status of args[:command] - def run_command(args={}) + def run_command(args = {}) status, stdout, stderr = run_command_and_return_stdout_stderr(args) status @@ -84,7 +83,7 @@ class Chef # works same as above, except that it returns stdout and stderr # requirement => platforms like solaris 9,10 has weird issues where # even in command failure the exit code is zero, so we need to lookup stderr. - def run_command_and_return_stdout_stderr(args={}) + def run_command_and_return_stdout_stderr(args = {}) command_output = "" args[:ignore_failure] ||= false @@ -143,7 +142,7 @@ class Chef return status, stdout_string, stderr_string end - def handle_command_failures(status, command_output, opts={}) + def handle_command_failures(status, command_output, opts = {}) return if opts[:ignore_failure] opts[:returns] ||= 0 return if Array(opts[:returns]).include?(status.exitstatus) @@ -165,7 +164,7 @@ class Chef # # === Returns # Returns the result of #run_command - def run_command_with_systems_locale(args={}) + def run_command_with_systems_locale(args = {}) args[:environment] ||= {} args[:environment]["LC_ALL"] = ENV["LC_ALL"] run_command args @@ -186,7 +185,6 @@ class Chef block.call end end - end end end diff --git a/lib/chef/mixin/command/unix.rb b/lib/chef/mixin/command/unix.rb index 3d97b961aa..211a8dc0c1 100644 --- a/lib/chef/mixin/command/unix.rb +++ b/lib/chef/mixin/command/unix.rb @@ -27,7 +27,7 @@ class Chef # The original appears in external/open4.rb in its unmodified form. # # Thanks Ara! - def popen4(cmd, args={}, &b) + def popen4(cmd, args = {}, &b) # Ruby 1.8 suffers from intermittent segfaults believed to be due to GC while IO.select # See CHEF-2916 / CHEF-1305 GC.disable @@ -89,7 +89,7 @@ class Chef Process.uid = args[:user] end - args[:environment].each do |key,value| + args[:environment].each do |key, value| ENV[key] = value end @@ -116,7 +116,7 @@ class Chef $VERBOSE = verbose end - [pw.first, pr.last, pe.last, ps.last].each{|fd| fd.close} + [pw.first, pr.last, pe.last, ps.last].each { |fd| fd.close } begin e = Marshal.load ps.first @@ -205,7 +205,7 @@ class Chef results.last end ensure - pi.each{|fd| fd.close unless fd.closed?} + pi.each { |fd| fd.close unless fd.closed? } end else [cid, pw.last, pr.first, pe.first] @@ -213,7 +213,6 @@ class Chef ensure GC.enable end - end end end diff --git a/lib/chef/mixin/command/windows.rb b/lib/chef/mixin/command/windows.rb index 5580aaec59..8612d8d48b 100644 --- a/lib/chef/mixin/command/windows.rb +++ b/lib/chef/mixin/command/windows.rb @@ -24,14 +24,13 @@ class Chef module Mixin module Command module Windows - def popen4(cmd, args={}, &b) - + def popen4(cmd, args = {}, &b) # By default, we are waiting before we yield the block. args[:waitlast] ||= false #XXX :user, :group, :environment support? - Open3.popen3(cmd) do |stdin,stdout,stderr,cid| + Open3.popen3(cmd) do |stdin, stdout, stderr, cid| if b if args[:waitlast] b[cid, stdin, stdout, stderr] @@ -65,7 +64,6 @@ class Chef end $? end - end end end diff --git a/lib/chef/mixin/convert_to_class_name.rb b/lib/chef/mixin/convert_to_class_name.rb index 5029474de9..de413febb0 100644 --- a/lib/chef/mixin/convert_to_class_name.rb +++ b/lib/chef/mixin/convert_to_class_name.rb @@ -40,10 +40,10 @@ class Chef rname end - def convert_to_snake_case(str, namespace=nil) + 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]/) { |s| "_" + s } str.downcase! str.sub!(/^\_/, "") str @@ -51,8 +51,8 @@ class Chef def normalize_snake_case_name(str) str = str.dup - str.gsub!(/[^A-Za-z0-9_]/,"_") - str.gsub!(/^(_+)?/,"") + str.gsub!(/[^A-Za-z0-9_]/, "_") + str.gsub!(/^(_+)?/, "") str end @@ -120,7 +120,6 @@ class Chef end end end - end end end diff --git a/lib/chef/mixin/create_path.rb b/lib/chef/mixin/create_path.rb index 233f7b9521..4f03c80de3 100644 --- a/lib/chef/mixin/create_path.rb +++ b/lib/chef/mixin/create_path.rb @@ -18,7 +18,6 @@ class Chef module Mixin module CreatePath - # Creates a given path, including all directories that lead up to it. # Like mkdir_p, but without the leaking. # @@ -67,7 +66,6 @@ class Chef rescue Errno::EEXIST end end - end end end diff --git a/lib/chef/mixin/deep_merge.rb b/lib/chef/mixin/deep_merge.rb index c0b2d0d0c5..228a16616c 100644 --- a/lib/chef/mixin/deep_merge.rb +++ b/lib/chef/mixin/deep_merge.rb @@ -26,7 +26,6 @@ class Chef # deep_merge is available under the MIT license from # http://trac.misuse.org/science/wiki/DeepMerge module DeepMerge - extend self def merge(first, second) @@ -134,7 +133,6 @@ class Chef def deep_merge(source, dest) deep_merge!(safe_dup(source), safe_dup(dest)) end - end end end diff --git a/lib/chef/mixin/deprecation.rb b/lib/chef/mixin/deprecation.rb index 04c40dcf29..2c2191f9e7 100644 --- a/lib/chef/mixin/deprecation.rb +++ b/lib/chef/mixin/deprecation.rb @@ -18,11 +18,9 @@ class Chef module Mixin - - - def self.deprecated_constants - @deprecated_constants ||= {} - end + def self.deprecated_constants + @deprecated_constants ||= {} + end # Add a deprecated constant to the Chef::Mixin namespace. # === Arguments @@ -33,34 +31,33 @@ class Chef # deprecate_constant(:RecipeDefinitionDSLCore, Chef::DSL::Recipe, <<-EOM) # Chef::Mixin::RecipeDefinitionDSLCore is deprecated, use Chef::DSL::Recipe instead. # EOM - def self.deprecate_constant(name, replacement, message) - deprecated_constants[name] = {:replacement => replacement, :message => message} - end + def self.deprecate_constant(name, replacement, message) + deprecated_constants[name] = { :replacement => replacement, :message => message } + end # Const missing hook to look up deprecated constants defined with # deprecate_constant. Emits a warning to the logger and returns the # replacement constant. Will call super, most likely causing an exception # for the missing constant, if +name+ is not found in the # deprecated_constants collection. - def self.const_missing(name) - if new_const = deprecated_constants[name] - Chef::Log.warn(new_const[:message]) - Chef::Log.warn("Called from: \n#{caller[0...3].map {|l| "\t#{l}"}.join("\n")}") - new_const[:replacement] - else - super - end + def self.const_missing(name) + if new_const = deprecated_constants[name] + Chef::Log.warn(new_const[:message]) + Chef::Log.warn("Called from: \n#{caller[0...3].map { |l| "\t#{l}" }.join("\n")}") + new_const[:replacement] + else + super end + end module Deprecation - class DeprecatedObjectProxyBase KEEPERS = %w{__id__ __send__ instance_eval == equal? initialize object_id} - instance_methods.each { |method_name| undef_method(method_name) unless KEEPERS.include?(method_name.to_s)} + instance_methods.each { |method_name| undef_method(method_name) unless KEEPERS.include?(method_name.to_s) } end class DeprecatedInstanceVariable < DeprecatedObjectProxyBase - def initialize(target, ivar_name, level=nil) + def initialize(target, ivar_name, level = nil) @target, @ivar_name = target, ivar_name @level ||= :warn end @@ -80,7 +77,7 @@ class Chef called_from = called_from.flatten log("Accessing #{@ivar_name} by the variable @#{@ivar_name} is deprecated. Support will be removed in a future release.") log("Please update your cookbooks to use #{@ivar_name} in place of @#{@ivar_name}. Accessed from:") - called_from.each {|l| log(l)} + called_from.each { |l| log(l) } end def log(msg) @@ -88,10 +85,9 @@ class Chef # send to Chef::Log. No one but me should use method_missing, ever. Chef::Log.logger.send(@level, msg) end - end - def deprecated_ivar(obj, name, level=nil) + def deprecated_ivar(obj, name, level = nil) DeprecatedInstanceVariable.new(obj, name, level) end @@ -100,22 +96,22 @@ class Chef deprecated_attr_writer(name, alternative) end - def deprecated_attr_reader(name, alternative, level=:warn) + def deprecated_attr_reader(name, alternative, level = :warn) define_method(name) do Chef.log_deprecation("#{self.class}.#{name} is deprecated. Support will be removed in a future release.") Chef.log_deprecation(alternative) Chef.log_deprecation("Called from:") - caller[0..3].each {|c| Chef.log_deprecation(c)} + caller[0..3].each { |c| Chef.log_deprecation(c) } instance_variable_get("@#{name}") end end - def deprecated_attr_writer(name, alternative, level=:warn) + def deprecated_attr_writer(name, alternative, level = :warn) define_method("#{name}=") do |value| Chef.log_deprecation("Writing to #{self.class}.#{name} with #{name}= is deprecated. Support will be removed in a future release.") Chef.log_deprecation(alternative) Chef.log_deprecation("Called from:") - caller[0..3].each {|c| Chef.log_deprecation(c)} + caller[0..3].each { |c| Chef.log_deprecation(c) } instance_variable_set("@#{name}", value) end end diff --git a/lib/chef/mixin/descendants_tracker.rb b/lib/chef/mixin/descendants_tracker.rb index e6c59d305e..b0f0ff2227 100644 --- a/lib/chef/mixin/descendants_tracker.rb +++ b/lib/chef/mixin/descendants_tracker.rb @@ -21,7 +21,6 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # - # This is lifted from rails activesupport (note the copyright above): # https://github.com/rails/rails/blob/9f84e60ac9d7bf07d6ae1bc94f3941f5b8f1a228/activesupport/lib/active_support/descendants_tracker.rb @@ -42,7 +41,7 @@ class Chef end def find_descendants_by_name(klass, name) - descendants(klass).first {|c| c.name == name } + descendants(klass).first { |c| c.name == name } end # This is the only method that is not thread safe, but is only ever called diff --git a/lib/chef/mixin/enforce_ownership_and_permissions.rb b/lib/chef/mixin/enforce_ownership_and_permissions.rb index e02c34748f..17fce0145e 100644 --- a/lib/chef/mixin/enforce_ownership_and_permissions.rb +++ b/lib/chef/mixin/enforce_ownership_and_permissions.rb @@ -21,7 +21,6 @@ require "chef/file_access_control" class Chef module Mixin module EnforceOwnershipAndPermissions - def access_controls @access_controls ||= Chef::FileAccessControl.new(current_resource, new_resource, self) end @@ -33,7 +32,6 @@ class Chef access_controls.set_all new_resource.updated_by_last_action(true) if access_controls.modified? end - end end end diff --git a/lib/chef/mixin/file_class.rb b/lib/chef/mixin/file_class.rb index 166dd5796a..62df9d1622 100644 --- a/lib/chef/mixin/file_class.rb +++ b/lib/chef/mixin/file_class.rb @@ -21,7 +21,6 @@ class Chef module Mixin module FileClass - def file_class @host_os_file ||= if Chef::Platform.windows? require "chef/win32/file" diff --git a/lib/chef/mixin/from_file.rb b/lib/chef/mixin/from_file.rb index a6692d798d..094f79b20f 100644 --- a/lib/chef/mixin/from_file.rb +++ b/lib/chef/mixin/from_file.rb @@ -20,7 +20,6 @@ class Chef module Mixin module FromFile - # Loads a given ruby file, and runs instance_eval against it in the context of the current # object. # @@ -44,7 +43,6 @@ class Chef raise IOError, "Cannot open or read #{filename}!" end end - end end end diff --git a/lib/chef/mixin/get_source_from_package.rb b/lib/chef/mixin/get_source_from_package.rb index abab763436..555dd634f8 100644 --- a/lib/chef/mixin/get_source_from_package.rb +++ b/lib/chef/mixin/get_source_from_package.rb @@ -15,7 +15,6 @@ # limitations under the License. # - # # mixin to make this syntax work without specifying a source: # diff --git a/lib/chef/mixin/homebrew_user.rb b/lib/chef/mixin/homebrew_user.rb index 888c1bcbfd..b6b0778874 100644 --- a/lib/chef/mixin/homebrew_user.rb +++ b/lib/chef/mixin/homebrew_user.rb @@ -62,7 +62,6 @@ class Chef Chef::Log.debug "Found Homebrew owner #{Etc.getpwuid(owner).name}; executing `brew` commands as them" owner end - end end end diff --git a/lib/chef/mixin/language.rb b/lib/chef/mixin/language.rb index 3f53645a55..0855410fb2 100644 --- a/lib/chef/mixin/language.rb +++ b/lib/chef/mixin/language.rb @@ -22,7 +22,6 @@ require "chef/mixin/deprecation" class Chef module Mixin - # == [DEPRECATED] Chef::Mixin::DeprecatedLanguageModule # This module is a temporary replacement for the previous # Chef::Mixin::Language. That module's functionality was split into two @@ -34,10 +33,8 @@ class Chef # This module is loaded via const_missing hook when Chef::Mixin::Language # is accessed. See chef/mixin/deprecation for details. module DeprecatedLanguageModule - include Chef::DSL::PlatformIntrospection include Chef::DSL::DataQuery - end deprecate_constant(:Language, DeprecatedLanguageModule, <<-EOM) diff --git a/lib/chef/mixin/language_include_attribute.rb b/lib/chef/mixin/language_include_attribute.rb index 39a04bb701..879d27b302 100644 --- a/lib/chef/mixin/language_include_attribute.rb +++ b/lib/chef/mixin/language_include_attribute.rb @@ -21,7 +21,6 @@ require "chef/mixin/deprecation" class Chef module Mixin - # DEPRECATED: This is just here for compatibility, use # Chef::DSL::IncludeAttribute instead. @@ -29,7 +28,5 @@ class Chef Chef::Mixin::LanguageIncludeAttribute is deprecated. Use Chef::DSL::IncludeAttribute instead. EOM - end end - diff --git a/lib/chef/mixin/language_include_recipe.rb b/lib/chef/mixin/language_include_recipe.rb index 9dd64673a1..98dbd48114 100644 --- a/lib/chef/mixin/language_include_recipe.rb +++ b/lib/chef/mixin/language_include_recipe.rb @@ -21,12 +21,9 @@ require "chef/mixin/deprecation" class Chef module Mixin - deprecate_constant(:LanguageIncludeRecipe, Chef::DSL::IncludeRecipe, <<-EOM) Chef::Mixin::LanguageIncludeRecipe is deprecated, use Chef::DSL::IncludeRecipe instead. EOM - end end - diff --git a/lib/chef/mixin/params_validate.rb b/lib/chef/mixin/params_validate.rb index a51b24df24..598c6c3c23 100644 --- a/lib/chef/mixin/params_validate.rb +++ b/lib/chef/mixin/params_validate.rb @@ -140,7 +140,7 @@ class Chef end # Raise an exception if the parameter is not found. - def _pv_required(opts, key, is_required=true, explicitly_allows_nil=false) + def _pv_required(opts, key, is_required = true, explicitly_allows_nil = false) if is_required return true if opts.has_key?(key.to_s) && (explicitly_allows_nil || !opts[key.to_s].nil?) return true if opts.has_key?(key.to_sym) && (explicitly_allows_nil || !opts[key.to_sym].nil?) @@ -329,7 +329,7 @@ class Chef # property :x, name_property: true # ``` # - def _pv_name_property(opts, key, is_name_property=true) + def _pv_name_property(opts, key, is_name_property = true) if is_name_property if opts[key].nil? raise CannotValidateStaticallyError, "name_property cannot be evaluated without a resource." if self == Chef::Mixin::ParamsValidate @@ -462,7 +462,6 @@ class Chef # (which is the norm). extend self - # Used by #set_or_return to avoid emitting a deprecation warning for # "value nil" and to keep default stickiness working exactly the same # @api private @@ -476,7 +475,7 @@ class Chef value end - def call(resource, value=NOT_PASSED) + def call(resource, value = NOT_PASSED) # setting to nil does a get if value.nil? && !explicitly_accepts_nil?(resource) get(resource) diff --git a/lib/chef/mixin/path_sanity.rb b/lib/chef/mixin/path_sanity.rb index 6c1b26fabd..5c0ce88933 100644 --- a/lib/chef/mixin/path_sanity.rb +++ b/lib/chef/mixin/path_sanity.rb @@ -19,8 +19,7 @@ class Chef module Mixin module PathSanity - - def enforce_path_sanity(env=ENV) + def enforce_path_sanity(env = ENV) if Chef::Config[:enforce_path_sanity] env["PATH"] = "" if env["PATH"].nil? path_separator = Chef::Platform.windows? ? ";" : ":" @@ -62,7 +61,6 @@ class Chef def gem_bindir Gem.bindir end - end end end diff --git a/lib/chef/mixin/powershell_type_coercions.rb b/lib/chef/mixin/powershell_type_coercions.rb index 60c04e85ae..3ccaadd6f4 100644 --- a/lib/chef/mixin/powershell_type_coercions.rb +++ b/lib/chef/mixin/powershell_type_coercions.rb @@ -20,17 +20,16 @@ class Chef module Mixin module PowershellTypeCoercions - def type_coercions @type_coercions ||= { - Fixnum => { :type => lambda { |x| x.to_s }}, - Float => { :type => lambda { |x| x.to_s }}, - FalseClass => { :type => lambda { |x| "$false" }}, - TrueClass => { :type => lambda { |x| "$true" }}, - Hash => {:type => Proc.new { |x| translate_hash(x)}}, - Array => {:type => Proc.new { |x| translate_array(x)}}, - Chef::Node::ImmutableMash => {:type => Proc.new { |x| translate_hash(x)}}, - Chef::Node::ImmutableArray => {:type => Proc.new { |x| translate_array(x)}}, + Fixnum => { :type => lambda { |x| x.to_s } }, + Float => { :type => lambda { |x| x.to_s } }, + FalseClass => { :type => lambda { |x| "$false" } }, + TrueClass => { :type => lambda { |x| "$true" } }, + Hash => { :type => Proc.new { |x| translate_hash(x) } }, + Array => { :type => Proc.new { |x| translate_array(x) } }, + Chef::Node::ImmutableMash => { :type => Proc.new { |x| translate_hash(x) } }, + Chef::Node::ImmutableArray => { :type => Proc.new { |x| translate_array(x) } }, } end @@ -49,7 +48,7 @@ class Chef private def translate_hash(x) - translated = x.inject([]) do |memo, (k,v)| + translated = x.inject([]) do |memo, (k, v)| memo << "#{k}=#{translate_type(v)}" end "@{#{translated.join(';')}}" diff --git a/lib/chef/mixin/properties.rb b/lib/chef/mixin/properties.rb index af4e2c2c09..2e33d2d0e7 100644 --- a/lib/chef/mixin/properties.rb +++ b/lib/chef/mixin/properties.rb @@ -17,7 +17,7 @@ class Chef # # @return [Hash] The list of property names and types. # - def properties(include_superclass=true) + def properties(include_superclass = true) if include_superclass result = {} ancestors.reverse_each { |c| result.merge!(c.properties(false)) if c.respond_to?(:properties) } @@ -92,10 +92,10 @@ class Chef # @example With type and options # property :x, String, default: 'hi' # - def property(name, type=NOT_PASSED, **options) + def property(name, type = NOT_PASSED, **options) name = name.to_sym - options.each { |k,v| options[k.to_sym] = v if k.is_a?(String) } + options.each { |k, v| options[k.to_sym] = v if k.is_a?(String) } options[:instance_variable_name] = :"@#{name}" if !options.has_key?(:instance_variable_name) options.merge!(name: name, declared_in: self) @@ -200,7 +200,7 @@ class Chef # If state_attrs *excludes* something which is currently desired state, # mark it as desired_state: false. - local_properties.each do |name,property| + local_properties.each do |name, property| if property.desired_state? && !names.include?(name) self.property name, desired_state: false end @@ -248,7 +248,7 @@ class Chef # If identity_properties *excludes* something which is currently part of # the identity, mark it as identity: false. - properties.each do |name,property| + properties.each do |name, property| if property.identity? && !names.include?(name) self.property name, identity: false diff --git a/lib/chef/mixin/provides.rb b/lib/chef/mixin/provides.rb index 5885752752..34a078c010 100644 --- a/lib/chef/mixin/provides.rb +++ b/lib/chef/mixin/provides.rb @@ -7,7 +7,7 @@ class Chef # TODO no longer needed, remove or deprecate? include Chef::Mixin::DescendantsTracker - def provides(short_name, opts={}, &block) + def provides(short_name, opts = {}, &block) raise NotImplementedError, :provides end diff --git a/lib/chef/mixin/proxified_socket.rb b/lib/chef/mixin/proxified_socket.rb index c3b0f7688c..87d2a2f186 100644 --- a/lib/chef/mixin/proxified_socket.rb +++ b/lib/chef/mixin/proxified_socket.rb @@ -20,7 +20,6 @@ require "proxifier" class Chef module Mixin module ProxifiedSocket - # This looks at the environment variables and leverages Proxifier to # make the TCPSocket respect ENV['https_proxy'] or ENV['http_proxy'] if # they are present @@ -32,7 +31,6 @@ class Chef TCPSocket.new(host, port) end end - end end end diff --git a/lib/chef/mixin/securable.rb b/lib/chef/mixin/securable.rb index d83d009638..91087f7b97 100644 --- a/lib/chef/mixin/securable.rb +++ b/lib/chef/mixin/securable.rb @@ -19,8 +19,7 @@ class Chef module Mixin module Securable - - def owner(arg=nil) + def owner(arg = nil) set_or_return( :owner, arg, @@ -30,7 +29,7 @@ class Chef alias :user :owner - def group(arg=nil) + def group(arg = nil) set_or_return( :group, arg, @@ -38,28 +37,27 @@ class Chef ) end - def mode(arg=nil) + def mode(arg = nil) set_or_return( :mode, arg, :callbacks => { "not in valid numeric range" => lambda { |m| if m.kind_of?(String) - m =~ /^0/ || m="0#{m}" + m =~ /^0/ || m = "0#{m}" end # Windows does not support the sticky or setuid bits if Chef::Platform.windows? - Integer(m)<=0777 && Integer(m)>=0 + Integer(m) <= 0777 && Integer(m) >= 0 else - Integer(m)<=07777 && Integer(m)>=0 + Integer(m) <= 07777 && Integer(m) >= 0 end } }, ) end - #==WindowsMacros # Defines methods for adding attributes to a chef resource to describe # Windows file security metadata. @@ -108,10 +106,9 @@ class Chef # * `:one_level_deep` (optional): Boolean # def rights_attribute(name) - # equivalent to something like: # def rights(permissions=nil, principals=nil, args_hash=nil) - define_method(name) do |permissions=nil, principals=nil, args_hash=nil| + define_method(name) do |permissions = nil, principals = nil, args_hash = nil| rights = self.instance_variable_get("@#{name}".to_sym) unless permissions.nil? input = { @@ -120,17 +117,17 @@ class Chef } input.merge!(args_hash) unless args_hash.nil? - validations = {:permissions => { :required => true }, - :principals => { :required => true, :kind_of => [String, Array] }, - :applies_to_children => { :equal_to => [ true, false, :containers_only, :objects_only ]}, - :applies_to_self => { :kind_of => [ TrueClass, FalseClass ] }, - :one_level_deep => { :kind_of => [ TrueClass, FalseClass ] }, + validations = { :permissions => { :required => true }, + :principals => { :required => true, :kind_of => [String, Array] }, + :applies_to_children => { :equal_to => [ true, false, :containers_only, :objects_only ] }, + :applies_to_self => { :kind_of => [ TrueClass, FalseClass ] }, + :one_level_deep => { :kind_of => [ TrueClass, FalseClass ] }, } validate(input, validations) [ permissions ].flatten.each do |permission| if permission.is_a?(Integer) - if permission < 0 || permission > 1<<32 + if permission < 0 || permission > 1 << 32 raise ArgumentError, "permissions flags must be positive and <= 32 bits (#{permission})" end elsif !([:full_control, :modify, :read_execute, :read, :write].include?(permission.to_sym)) @@ -168,9 +165,7 @@ class Chef # Defines #inherits to describe Windows file security ACLs on the # including class module WindowsSecurableAttributes - - - def inherits(arg=nil) + def inherits(arg = nil) set_or_return( :inherits, arg, @@ -193,7 +188,6 @@ class Chef including_class.rights_attribute(:deny_rights) end end - end end end diff --git a/lib/chef/mixin/shell_out.rb b/lib/chef/mixin/shell_out.rb index d3598f64f5..8101b2b4d3 100644 --- a/lib/chef/mixin/shell_out.rb +++ b/lib/chef/mixin/shell_out.rb @@ -20,7 +20,6 @@ require "mixlib/shellout" class Chef module Mixin module ShellOut - # shell_out! runs a command on the system and will raise an error if the command fails, which is what you want # for debugging, shell_out and shell_out! both will display command output to the tty when the log level is debug # Generally speaking, 'extend Chef::Mixin::ShellOut' in your recipes and include 'Chef::Mixin::ShellOut' in your LWRPs diff --git a/lib/chef/mixin/template.rb b/lib/chef/mixin/template.rb index be46f0cd2c..c68a05bc44 100644 --- a/lib/chef/mixin/template.rb +++ b/lib/chef/mixin/template.rb @@ -22,7 +22,6 @@ require "erubis" class Chef module Mixin module Template - # == ChefContext # ChefContext was previously used to mix behavior into Erubis::Context so # that it would be available to templates. This behavior has now moved to @@ -39,7 +38,6 @@ class Chef # extended to add logic to a specific template. # class TemplateContext < Erubis::Context - include ChefContext attr_reader :_extension_modules @@ -105,10 +103,9 @@ class Chef def node return @node if @node raise "Could not find a value for node. If you are explicitly setting variables in a template, " + - "include a node variable if you plan to use it." + "include a node variable if you plan to use it." end - # # Takes the name of the partial, plus a hash of options. Returns a # string that contains the result of the evaluation of the partial. @@ -177,7 +174,7 @@ class Chef # this template. if Chef::Platform.windows? - output = output.gsub(/\r?\n/,"\r\n") + output = output.gsub(/\r?\n/, "\r\n") end output @@ -225,7 +222,7 @@ class Chef end def line_number - @line_number ||= $1.to_i if original_exception.backtrace.find {|line| line =~ /\(erubis\):(\d+)/ } + @line_number ||= $1.to_i if original_exception.backtrace.find { |line| line =~ /\(erubis\):(\d+)/ } end def source_location @@ -246,7 +243,7 @@ class Chef contextual_lines = lines[beginning_line, source_size] output = [] contextual_lines.each_with_index do |line, index| - line_number = (index+beginning_line+1).to_s.rjust(3) + line_number = (index + beginning_line + 1).to_s.rjust(3) output << "#{line_number}: #{line}" end output.join("\n") diff --git a/lib/chef/mixin/unformatter.rb b/lib/chef/mixin/unformatter.rb index 7dad56b270..537efc2932 100644 --- a/lib/chef/mixin/unformatter.rb +++ b/lib/chef/mixin/unformatter.rb @@ -19,14 +19,12 @@ class Chef module Mixin module Unformatter - def write(message) data = message.match(/(\[.+?\] )?([\w]+):(.*)$/) self.send(data[2].downcase.chomp.to_sym, data[3].strip) rescue NoMethodError self.send(:info, message) end - end end end diff --git a/lib/chef/mixin/uris.rb b/lib/chef/mixin/uris.rb index 5122177728..5f001511db 100644 --- a/lib/chef/mixin/uris.rb +++ b/lib/chef/mixin/uris.rb @@ -29,7 +29,6 @@ class Chef !!(%r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ source) end - def as_uri(source) begin URI.parse(source) @@ -38,7 +37,6 @@ class Chef URI.parse(URI.escape(source)) end end - end end end diff --git a/lib/chef/mixin/why_run.rb b/lib/chef/mixin/why_run.rb index be9808b1fe..c0ffb1541e 100644 --- a/lib/chef/mixin/why_run.rb +++ b/lib/chef/mixin/why_run.rb @@ -20,7 +20,6 @@ class Chef module Mixin module WhyRun - # ==ConvergeActions # ConvergeActions implements the logic for why run. A ConvergeActions # object wraps a collection of actions, which consist of a descriptive @@ -122,7 +121,6 @@ class Chef # method, which gets mixed in to providers. See that method's # documentation for examples. class ResourceRequirements - # Implements the logic for a single assertion/assumption. See the # documentation for ResourceRequirements for full discussion. class Assertion @@ -222,7 +220,6 @@ class Chef @assertion_failed end - # Runs the assertion/assumption logic. Will raise an Exception of the # type specified in #failure_message (or AssertionFailure by default) # if the requirement is not met and Chef is not running in why run @@ -247,7 +244,7 @@ class Chef def initialize(resource, run_context) @resource, @run_context = resource, run_context - @assertions = Hash.new {|h,k| h[k] = [] } + @assertions = Hash.new { |h, k| h[k] = [] } @blocked_actions = [] end @@ -313,7 +310,7 @@ class Chef def assert(*actions) assertion = Assertion.new yield assertion - actions.each {|action| @assertions[action] << assertion } + actions.each { |action| @assertions[action] << assertion } end # Run the assertion and assumption logic. diff --git a/lib/chef/mixin/wide_string.rb b/lib/chef/mixin/wide_string.rb index 4566bdd382..8295d4b559 100644 --- a/lib/chef/mixin/wide_string.rb +++ b/lib/chef/mixin/wide_string.rb @@ -19,7 +19,6 @@ class Chef module Mixin module WideString - def wstring(str) if str.nil? || str.encoding == Encoding::UTF_16LE str @@ -66,7 +65,6 @@ class Chef wstring.strip! wstring end - end end end diff --git a/lib/chef/mixin/windows_architecture_helper.rb b/lib/chef/mixin/windows_architecture_helper.rb index edda6cf401..12b3a5398f 100644 --- a/lib/chef/mixin/windows_architecture_helper.rb +++ b/lib/chef/mixin/windows_architecture_helper.rb @@ -16,7 +16,6 @@ # limitations under the License. # - require "chef/exceptions" require "chef/platform/query_helpers" require "chef/win32/process" if Chef::Platform.windows? @@ -25,7 +24,6 @@ require "chef/win32/system" if Chef::Platform.windows? class Chef module Mixin module WindowsArchitectureHelper - def node_windows_architecture(node) node[:kernel][:machine].to_sym end @@ -109,7 +107,6 @@ class Chef Chef::ReservedNames::Win32::System.wow64_revert_wow64_fs_redirection(original_redirection_state) end end - end end end diff --git a/lib/chef/mixin/windows_env_helper.rb b/lib/chef/mixin/windows_env_helper.rb index e46b40b240..b2e08edc08 100644 --- a/lib/chef/mixin/windows_env_helper.rb +++ b/lib/chef/mixin/windows_env_helper.rb @@ -16,7 +16,6 @@ # limitations under the License. # - require "chef/exceptions" require "chef/mixin/wide_string" require "chef/platform/query_helpers" diff --git a/lib/chef/mixin/xml_escape.rb b/lib/chef/mixin/xml_escape.rb index a278c81554..0d4f40d2b4 100644 --- a/lib/chef/mixin/xml_escape.rb +++ b/lib/chef/mixin/xml_escape.rb @@ -57,7 +57,6 @@ end class Chef module Mixin module XMLEscape - module PureRuby extend self @@ -95,7 +94,7 @@ class Chef PREDEFINED = { 38 => "&", # ampersand 60 => "<", # left angle bracket - 62 => ">" # right angle bracket + 62 => ">" # right angle bracket } # http://www.w3.org/TR/REC-xml/#charsets @@ -104,9 +103,9 @@ class Chef def xml_escape(unescaped_str) begin - unescaped_str.unpack("U*").map {|char| xml_escape_char!(char)}.join + unescaped_str.unpack("U*").map { |char| xml_escape_char!(char) }.join rescue - unescaped_str.unpack("C*").map {|char| xml_escape_char!(char)}.join + unescaped_str.unpack("C*").map { |char| xml_escape_char!(char) }.join end end @@ -114,8 +113,8 @@ class Chef def xml_escape_char!(char) char = CP1252[char] || char - char = 42 unless VALID.detect {|range| range.include? char} - char = PREDEFINED[char] || (char<128 ? char.chr : "&##{char};") + char = 42 unless VALID.detect { |range| range.include? char } + char = PREDEFINED[char] || (char < 128 ? char.chr : "&##{char};") end end @@ -125,7 +124,6 @@ class Chef def xml_escape(string) string.fast_xs end - end if "strings".respond_to?(:fast_xs) diff --git a/lib/chef/mixins.rb b/lib/chef/mixins.rb index 7ae7fe659e..b980e81287 100644 --- a/lib/chef/mixins.rb +++ b/lib/chef/mixins.rb @@ -11,4 +11,3 @@ require "chef/mixin/path_sanity" require "chef/mixin/template" require "chef/mixin/securable" require "chef/mixin/xml_escape" - diff --git a/lib/chef/monkey_patches/net-ssh-multi.rb b/lib/chef/monkey_patches/net-ssh-multi.rb index dd4da6865f..7c535ca8cf 100644 --- a/lib/chef/monkey_patches/net-ssh-multi.rb +++ b/lib/chef/monkey_patches/net-ssh-multi.rb @@ -44,17 +44,15 @@ if Net::SSH::Multi::Version::STRING == "1.1.0" || Net::SSH::Multi::Version::STRI module SSH module Multi class Server - # Make sure that server returns false if the ssh connection # has failed. - def busy?(include_invisible=false) + def busy?(include_invisible = false) !failed? && session && session.busy?(include_invisible) end - end class Session - def next_session(server, force=false) #:nodoc: + def next_session(server, force = false) #:nodoc: # don't retry a failed attempt return nil if server.failed? @@ -131,7 +129,6 @@ if Net::SSH::Multi::Version::STRING == "1.1.0" || Net::SSH::Multi::Version::STRI end end end - end end end diff --git a/lib/chef/monkey_patches/net_http.rb b/lib/chef/monkey_patches/net_http.rb index 6aad6029c3..eeb9def6df 100644 --- a/lib/chef/monkey_patches/net_http.rb +++ b/lib/chef/monkey_patches/net_http.rb @@ -21,7 +21,7 @@ module Net end end -if Net::HTTP.instance_methods.map {|m| m.to_s}.include?("proxy_uri") +if Net::HTTP.instance_methods.map { |m| m.to_s }.include?("proxy_uri") begin # Ruby 2.0 changes the way proxy support is implemented in Net::HTTP. # The implementation does not work correctly with IPv6 literals because it @@ -49,12 +49,10 @@ if Net::HTTP.instance_methods.map {|m| m.to_s}.include?("proxy_uri") Net::HTTP.new("::1", 80).proxy_uri rescue URI::InvalidURIError class Net::HTTP - def proxy_uri # :nodoc: ipv6_safe_addr = address.to_s.include?(":") ? "[#{address}]" : address @proxy_uri ||= URI("http://#{ipv6_safe_addr}:#{port}").find_proxy end - end end end diff --git a/lib/chef/monkey_patches/webrick-utils.rb b/lib/chef/monkey_patches/webrick-utils.rb index f7f2cf6ad4..ff275a434d 100644 --- a/lib/chef/monkey_patches/webrick-utils.rb +++ b/lib/chef/monkey_patches/webrick-utils.rb @@ -11,7 +11,7 @@ module WEBrick # create_listeners on Windows with Ruby > 2.0.0 does not # raise an error if we're already listening on a port. # - def create_listeners(address, port, logger=nil) + def create_listeners(address, port, logger = nil) # # utils.rb -- Miscellaneous utilities # @@ -40,7 +40,7 @@ module WEBrick sockets << sock rescue => ex logger.warn("TCPServer Error: #{ex}") if logger - last_error = ex + last_error = ex end } raise last_error if sockets.empty? diff --git a/lib/chef/monkey_patches/win32/registry.rb b/lib/chef/monkey_patches/win32/registry.rb index b8b3fb6fdd..e6c66d5433 100644 --- a/lib/chef/monkey_patches/win32/registry.rb +++ b/lib/chef/monkey_patches/win32/registry.rb @@ -21,9 +21,7 @@ require "win32/registry" module Win32 class Registry - module API - extend Chef::ReservedNames::Win32::API::Registry module_function @@ -42,7 +40,6 @@ module Win32 def DeleteKey(hkey, name) check RegDeleteKeyExW(hkey, name.to_wstring, 0, 0) end - end if RUBY_VERSION =~ /^2.1/ @@ -53,7 +50,7 @@ module Win32 when REG_SZ, REG_EXPAND_SZ data = data.to_s.encode(WCHAR) + WCHAR_NUL when REG_MULTI_SZ - data = data.to_a.map {|s| s.encode(WCHAR)}.join(WCHAR_NUL) << WCHAR_NUL << WCHAR_NUL + data = data.to_a.map { |s| s.encode(WCHAR) }.join(WCHAR_NUL) << WCHAR_NUL << WCHAR_NUL when REG_BINARY data = data.to_s when REG_DWORD diff --git a/lib/chef/monologger.rb b/lib/chef/monologger.rb index e0ca5c5be6..d80baa08cc 100644 --- a/lib/chef/monologger.rb +++ b/lib/chef/monologger.rb @@ -5,7 +5,6 @@ require "pp" # A subclass of Ruby's stdlib Logger with all the mutex and logrotation stuff # ripped out. class MonoLogger < Logger - # # === Synopsis # @@ -38,9 +37,7 @@ class MonoLogger < Logger end end - class LocklessLogDevice < LogDevice - def initialize(log = nil) @dev = @filename = @shift_age = @shift_size = nil if log.respond_to?(:write) and log.respond_to?(:close) @@ -83,8 +80,5 @@ class MonoLogger < Logger "# Logfile created on %s by %s\n" % [Time.now.to_s, Logger::ProgName] ) end - end - - end diff --git a/lib/chef/node.rb b/lib/chef/node.rb index eeb59a119f..e2c06f0a57 100644 --- a/lib/chef/node.rb +++ b/lib/chef/node.rb @@ -37,7 +37,6 @@ require "chef/whitelist" class Chef class Node - extend Forwardable def_delegators :attributes, :keys, :each_key, :each_value, :key?, :has_key? @@ -108,13 +107,13 @@ class Chef end # Set the name of this Node, or return the current name. - def name(arg=nil) + def name(arg = nil) if arg != nil validate( - {:name => arg }, - {:name => { :kind_of => String, - :cannot_be => :blank, - :regex => /^[\-[:alnum:]_:.]+$/} + { :name => arg }, + { :name => { :kind_of => String, + :cannot_be => :blank, + :regex => /^[\-[:alnum:]_:.]+$/ } },) @name = arg else @@ -122,7 +121,7 @@ class Chef end end - def chef_environment(arg=nil) + def chef_environment(arg = nil) set_or_return( :chef_environment, arg, @@ -145,9 +144,9 @@ class Chef # # @param arg [String] the new policy_name value # @return [String] the current policy_name, or the one you just set - def policy_name(arg=NULL_ARG) + def policy_name(arg = NULL_ARG) return @policy_name if arg.equal?(NULL_ARG) - validate({policy_name: arg}, { policy_name: { kind_of: [ String, NilClass ], regex: /^[\-:.[:alnum:]_]+$/ } }) + validate({ policy_name: arg }, { policy_name: { kind_of: [ String, NilClass ], regex: /^[\-:.[:alnum:]_]+$/ } }) @policy_name = arg end @@ -167,9 +166,9 @@ class Chef # # @param arg [String] the new policy_group value # @return [String] the current policy_group, or the one you just set - def policy_group(arg=NULL_ARG) + def policy_group(arg = NULL_ARG) return @policy_group if arg.equal?(NULL_ARG) - validate({policy_group: arg}, { policy_group: { kind_of: [ String, NilClass ], regex: /^[\-:.[:alnum:]_]+$/ } }) + validate({ policy_group: arg }, { policy_group: { kind_of: [ String, NilClass ], regex: /^[\-:.[:alnum:]_]+$/ } }) @policy_group = arg end @@ -365,7 +364,7 @@ class Chef normal_attrs_to_merge = consume_run_list(attrs) normal_attrs_to_merge = consume_chef_environment(normal_attrs_to_merge) Chef::Log.debug("Applying attributes from json file") - self.normal_attrs = Chef::Mixin::DeepMerge.merge(normal_attrs,normal_attrs_to_merge) + self.normal_attrs = Chef::Mixin::DeepMerge.merge(normal_attrs, normal_attrs_to_merge) self.tags # make sure they're defined end @@ -452,7 +451,7 @@ class Chef # passed in, which came from roles. def apply_expansion_attributes(expansion) loaded_environment = if chef_environment == "_default" - Chef::Environment.new.tap {|e| e.name("_default")} + Chef::Environment.new.tap { |e| e.name("_default") } else Chef::Environment.load(chef_environment) end @@ -561,17 +560,17 @@ class Chef node end - def self.list_by_environment(environment, inflate=false) + def self.list_by_environment(environment, inflate = false) if inflate response = Hash.new - 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}") { |n| response[n.name] = n unless n.nil? } response else Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("environments/#{environment}/nodes") end end - def self.list(inflate=false) + def self.list(inflate = false) if inflate response = Hash.new Chef::Search::Query.new.search(:node) do |n| @@ -655,7 +654,7 @@ class Chef def ==(other) if other.kind_of?(self.class) - self.name == other.name + self.name == other.name else false end @@ -695,6 +694,5 @@ class Chef end data end - end end diff --git a/lib/chef/node/attribute.rb b/lib/chef/node/attribute.rb index 0ed4a9360a..48067ce66d 100644 --- a/lib/chef/node/attribute.rb +++ b/lib/chef/node/attribute.rb @@ -24,14 +24,12 @@ require "chef/log" class Chef class Node - # == Attribute # Attribute implements a nested key-value (Hash) and flat collection # (Array) data structure supporting multiple levels of precedence, such # that a given key may have multiple values internally, but will only # return the highest precedence value when reading. class Attribute < Mash - include Immutablize include Enumerable @@ -144,34 +142,34 @@ class Chef end # return the cookbook level default attribute component - attr_reader :default + attr_reader :default # return the role level default attribute component - attr_reader :role_default + attr_reader :role_default # return the environment level default attribute component - attr_reader :env_default + attr_reader :env_default # return the force_default level attribute component - attr_reader :force_default + attr_reader :force_default # return the "normal" level attribute component - attr_reader :normal + attr_reader :normal # return the cookbook level override attribute component - attr_reader :override + attr_reader :override # return the role level override attribute component - attr_reader :role_override + attr_reader :role_override # return the enviroment level override attribute component - attr_reader :env_override + attr_reader :env_override # return the force override level attribute component - attr_reader :force_override + attr_reader :force_override # return the automatic level attribute component - attr_reader :automatic + attr_reader :automatic # This is used to track the top level key as we descend through method chaining into # a precedence level (e.g. node.default['foo']['bar']['baz']= results in 'foo' here). We @@ -179,36 +177,36 @@ class Chef # that we can invalidate the whole top-level deep merge cache for the top-level key. It is # the responsibility of the accessor on the Chef::Node object to reset this to nil, and then # the first VividMash#[] call can ||= and set this to the first key we encounter. - attr_accessor :top_level_breadcrumb + attr_accessor :top_level_breadcrumb # Cache of deep merged values by top-level key. This is a simple hash which has keys that are the # top-level keys of the node object, and we save the computed deep-merge for that key here. There is # no cache of subtrees. - attr_accessor :deep_merge_cache + attr_accessor :deep_merge_cache - def initialize(normal, default, override, automatic) - @set_unless_present = false + def initialize(normal, default, override, automatic) + @set_unless_present = false - @default = VividMash.new(self, default) - @env_default = VividMash.new(self, {}) - @role_default = VividMash.new(self, {}) - @force_default = VividMash.new(self, {}) + @default = VividMash.new(self, default) + @env_default = VividMash.new(self, {}) + @role_default = VividMash.new(self, {}) + @force_default = VividMash.new(self, {}) - @normal = VividMash.new(self, normal) + @normal = VividMash.new(self, normal) - @override = VividMash.new(self, override) - @role_override = VividMash.new(self, {}) - @env_override = VividMash.new(self, {}) - @force_override = VividMash.new(self, {}) + @override = VividMash.new(self, override) + @role_override = VividMash.new(self, {}) + @env_override = VividMash.new(self, {}) + @force_override = VividMash.new(self, {}) - @automatic = VividMash.new(self, automatic) + @automatic = VividMash.new(self, automatic) - @merged_attributes = nil - @combined_override = nil - @combined_default = nil - @top_level_breadcrumb = nil - @deep_merge_cache = {} - end + @merged_attributes = nil + @combined_override = nil + @combined_default = nil + @top_level_breadcrumb = nil + @deep_merge_cache = {} + end # Debug what's going on with an attribute. +args+ is a path spec to the # attribute you're interested in. For example, to debug where the value @@ -221,195 +219,195 @@ class Chef # the component, such as role default, normal, etc. and value is the # attribute value set at that precedence level. If there is no value at # that precedence level, +value+ will be the symbol +:not_present+. - def debug_value(*args) - components = COMPONENTS.map do |component| - ivar = instance_variable_get(component) - value = args.inject(ivar) do |so_far, key| - if so_far == :not_present - :not_present - elsif so_far.has_key?(key) - so_far[key] - else - :not_present - end - end - [component.to_s.sub(/^@/,""), value] - end - [["set_unless_enabled?", @set_unless_present]] + components - end + def debug_value(*args) + components = COMPONENTS.map do |component| + ivar = instance_variable_get(component) + value = args.inject(ivar) do |so_far, key| + if so_far == :not_present + :not_present + elsif so_far.has_key?(key) + so_far[key] + else + :not_present + end + end + [component.to_s.sub(/^@/, ""), value] + end + [["set_unless_enabled?", @set_unless_present]] + components + end # Enables or disables `||=`-like attribute setting. See, e.g., Node#set_unless - def set_unless_value_present=(setting) - @set_unless_present = setting - end + def set_unless_value_present=(setting) + @set_unless_present = setting + end # Invalidate a key in the deep_merge_cache. If called with nil, or no arg, this will invalidate # the entire deep_merge cache. In the case of the user doing node.default['foo']['bar']['baz']= # that eventually results in a call to reset_cache('foo') here. A node.default=hash_thing call # must invalidate the entire cache and re-deep-merge the entire node object. - def reset_cache(path = nil) - if path.nil? - @deep_merge_cache = {} - else - deep_merge_cache.delete(path.to_s) - end - end + def reset_cache(path = nil) + if path.nil? + @deep_merge_cache = {} + else + deep_merge_cache.delete(path.to_s) + end + end - alias :reset :reset_cache + alias :reset :reset_cache # Set the cookbook level default attribute component to +new_data+. - def default=(new_data) - reset - @default = VividMash.new(self, new_data) - end + def default=(new_data) + reset + @default = VividMash.new(self, new_data) + end # Set the role level default attribute component to +new_data+ - def role_default=(new_data) - reset - @role_default = VividMash.new(self, new_data) - end + def role_default=(new_data) + reset + @role_default = VividMash.new(self, new_data) + end # Set the environment level default attribute component to +new_data+ - def env_default=(new_data) - reset - @env_default = VividMash.new(self, new_data) - end + def env_default=(new_data) + reset + @env_default = VividMash.new(self, new_data) + end # Set the force_default (+default!+) level attributes to +new_data+ - def force_default=(new_data) - reset - @force_default = VividMash.new(self, new_data) - end + def force_default=(new_data) + reset + @force_default = VividMash.new(self, new_data) + end # Set the normal level attribute component to +new_data+ - def normal=(new_data) - reset - @normal = VividMash.new(self, new_data) - end + def normal=(new_data) + reset + @normal = VividMash.new(self, new_data) + end # Set the cookbook level override attribute component to +new_data+ - def override=(new_data) - reset - @override = VividMash.new(self, new_data) - end + def override=(new_data) + reset + @override = VividMash.new(self, new_data) + end # Set the role level override attribute component to +new_data+ - def role_override=(new_data) - reset - @role_override = VividMash.new(self, new_data) - end + def role_override=(new_data) + reset + @role_override = VividMash.new(self, new_data) + end # Set the environment level override attribute component to +new_data+ - def env_override=(new_data) - reset - @env_override = VividMash.new(self, new_data) - end + def env_override=(new_data) + reset + @env_override = VividMash.new(self, new_data) + end - def force_override=(new_data) - reset - @force_override = VividMash.new(self, new_data) - end + def force_override=(new_data) + reset + @force_override = VividMash.new(self, new_data) + end - def automatic=(new_data) - reset - @automatic = VividMash.new(self, new_data) - end + def automatic=(new_data) + reset + @automatic = VividMash.new(self, new_data) + end # # Deleting attributes # # clears attributes from all precedence levels - def rm(*args) - reset(args[0]) - # just easier to compute our retval, rather than collect+merge sub-retvals - ret = args.inject(merged_attributes) do |attr, arg| - if attr.nil? || !attr.respond_to?(:[]) - nil - else - begin - attr[arg] - rescue TypeError - raise TypeError, "Wrong type in index of attribute (did you use a Hash index on an Array?)" - end - end - end - rm_default(*args) - rm_normal(*args) - rm_override(*args) - ret - end + def rm(*args) + reset(args[0]) + # just easier to compute our retval, rather than collect+merge sub-retvals + ret = args.inject(merged_attributes) do |attr, arg| + if attr.nil? || !attr.respond_to?(:[]) + nil + else + begin + attr[arg] + rescue TypeError + raise TypeError, "Wrong type in index of attribute (did you use a Hash index on an Array?)" + end + end + end + rm_default(*args) + rm_normal(*args) + rm_override(*args) + ret + end # does ['foo']['bar'].delete('baz') - def remove_from_precedence_level(level, *args, key) - multimash = level.element(*args) - multimash.nil? ? nil : multimash.delete(key) - end + def remove_from_precedence_level(level, *args, key) + multimash = level.element(*args) + multimash.nil? ? nil : multimash.delete(key) + end - private :remove_from_precedence_level + private :remove_from_precedence_level # clears attributes from all default precedence levels # # equivalent to: force_default!['foo']['bar'].delete('baz') - def rm_default(*args) - reset(args[0]) - remove_from_precedence_level(force_default!(autovivify: false), *args) - end + def rm_default(*args) + reset(args[0]) + remove_from_precedence_level(force_default!(autovivify: false), *args) + end # clears attributes from normal precedence # # equivalent to: normal!['foo']['bar'].delete('baz') - def rm_normal(*args) - reset(args[0]) - remove_from_precedence_level(normal!(autovivify: false), *args) - end + def rm_normal(*args) + reset(args[0]) + remove_from_precedence_level(normal!(autovivify: false), *args) + end # clears attributes from all override precedence levels # # equivalent to: force_override!['foo']['bar'].delete('baz') - def rm_override(*args) - reset(args[0]) - remove_from_precedence_level(force_override!(autovivify: false), *args) - end + def rm_override(*args) + reset(args[0]) + remove_from_precedence_level(force_override!(autovivify: false), *args) + end # # Replacing attributes without merging # # sets default attributes without merging - def default!(opts={}) - # FIXME: do not flush whole cache - reset - MultiMash.new(self, @default, [], opts) - end + def default!(opts = {}) + # FIXME: do not flush whole cache + reset + MultiMash.new(self, @default, [], opts) + end # sets normal attributes without merging - def normal!(opts={}) - # FIXME: do not flush whole cache - reset - MultiMash.new(self, @normal, [], opts) - end + def normal!(opts = {}) + # FIXME: do not flush whole cache + reset + MultiMash.new(self, @normal, [], opts) + end # sets override attributes without merging - def override!(opts={}) - # FIXME: do not flush whole cache - reset - MultiMash.new(self, @override, [], opts) - end + def override!(opts = {}) + # FIXME: do not flush whole cache + reset + MultiMash.new(self, @override, [], opts) + end # clears from all default precedence levels and then sets force_default - def force_default!(opts={}) - # FIXME: do not flush whole cache - reset - MultiMash.new(self, @force_default, [@default, @env_default, @role_default], opts) - end + def force_default!(opts = {}) + # FIXME: do not flush whole cache + reset + MultiMash.new(self, @force_default, [@default, @env_default, @role_default], opts) + end # clears from all override precedence levels and then sets force_override - def force_override!(opts={}) - # FIXME: do not flush whole cache - reset - MultiMash.new(self, @force_override, [@override, @env_override, @role_override], opts) - end + def force_override!(opts = {}) + # FIXME: do not flush whole cache + reset + MultiMash.new(self, @force_override, [@override, @env_override, @role_override], opts) + end # # Accessing merged attributes. @@ -419,75 +417,75 @@ class Chef # all of node['foo'] even if the user only requires node['foo']['bar']['baz']. # - def merged_attributes(*path) - # immutablize( - merge_all(path) - # ) - end - - def combined_override(*path) - immutablize(merge_overrides(path)) - end - - def combined_default(*path) - immutablize(merge_defaults(path)) - end - - def [](key) - if deep_merge_cache.has_key?(key.to_s) - # return the cache of the deep merged values by top-level key - deep_merge_cache[key.to_s] - else - # save all the work of computing node[key] - deep_merge_cache[key.to_s] = merged_attributes(key) - end - end - - def []=(key, value) - raise Exceptions::ImmutableAttributeModification - end - - def has_key?(key) - COMPONENTS.any? do |component_ivar| - instance_variable_get(component_ivar).has_key?(key) - end - end - - alias :attribute? :has_key? - alias :member? :has_key? - alias :include? :has_key? - alias :key? :has_key? - - alias :each_attribute :each - - def method_missing(symbol, *args) - if args.empty? - if key?(symbol) - self[symbol] - else - raise NoMethodError, "Undefined method or attribute `#{symbol}' on `node'" - end - elsif symbol.to_s =~ /=$/ - key_to_set = symbol.to_s[/^(.+)=$/, 1] - self[key_to_set] = (args.length == 1 ? args[0] : args) - else - raise NoMethodError, "Undefined node attribute or method `#{symbol}' on `node'" - end - end - - def to_s - merged_attributes.to_s - end - - def inspect - "#<#{self.class} " << (COMPONENTS + [:@merged_attributes, :@properties]).map{|iv| - "#{iv}=#{instance_variable_get(iv).inspect}" - }.join(", ") << ">" - end - - def set_unless? - @set_unless_present - end + def merged_attributes(*path) + # immutablize( + merge_all(path) + # ) + end + + def combined_override(*path) + immutablize(merge_overrides(path)) + end + + def combined_default(*path) + immutablize(merge_defaults(path)) + end + + def [](key) + if deep_merge_cache.has_key?(key.to_s) + # return the cache of the deep merged values by top-level key + deep_merge_cache[key.to_s] + else + # save all the work of computing node[key] + deep_merge_cache[key.to_s] = merged_attributes(key) + end + end + + def []=(key, value) + raise Exceptions::ImmutableAttributeModification + end + + def has_key?(key) + COMPONENTS.any? do |component_ivar| + instance_variable_get(component_ivar).has_key?(key) + end + end + + alias :attribute? :has_key? + alias :member? :has_key? + alias :include? :has_key? + alias :key? :has_key? + + alias :each_attribute :each + + def method_missing(symbol, *args) + if args.empty? + if key?(symbol) + self[symbol] + else + raise NoMethodError, "Undefined method or attribute `#{symbol}' on `node'" + end + elsif symbol.to_s =~ /=$/ + key_to_set = symbol.to_s[/^(.+)=$/, 1] + self[key_to_set] = (args.length == 1 ? args[0] : args) + else + raise NoMethodError, "Undefined node attribute or method `#{symbol}' on `node'" + end + end + + def to_s + merged_attributes.to_s + end + + def inspect + "#<#{self.class} " << (COMPONENTS + [:@merged_attributes, :@properties]).map{|iv| + "#{iv}=#{instance_variable_get(iv).inspect}" + }.join(", ") << ">" + end + + def set_unless? + @set_unless_present + end private @@ -501,32 +499,32 @@ class Chef # raise any TypeError if it attempts to apply a hash key to an Integer/String/TrueClass, and just returns # nil in that case. # - def apply_path(component, path) - path ||= [] - path.inject(component) do |val, path_arg| - if val.respond_to?(:[]) - # Have an Array-like or Hash-like thing - if !val.respond_to?(:has_key?) - # Have an Array-like thing - val[path_arg] - elsif val.has_key?(path_arg) - # Hash-like thing (must check has_key? first to protect against Autovivification) - val[path_arg] - else - nil - end - else - nil - end - end - end + def apply_path(component, path) + path ||= [] + path.inject(component) do |val, path_arg| + if val.respond_to?(:[]) + # Have an Array-like or Hash-like thing + if !val.respond_to?(:has_key?) + # Have an Array-like thing + val[path_arg] + elsif val.has_key?(path_arg) + # Hash-like thing (must check has_key? first to protect against Autovivification) + val[path_arg] + else + nil + end + else + nil + end + end + end # For elements like Fixnums, true, nil... - def safe_dup(e) - e.dup - rescue TypeError - e - end + def safe_dup(e) + e.dup + rescue TypeError + e + end # Deep merge all attribute levels using hash-only merging between different precidence # levels (so override arrays completely replace arrays set at any default level). @@ -535,24 +533,24 @@ 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_all(path) - components = [ - merge_defaults(path), - apply_path(@normal, path), - merge_overrides(path), - apply_path(@automatic, path), - ] - - components.map! do |component| - safe_dup(component) - end + def merge_all(path) + components = [ + merge_defaults(path), + apply_path(@normal, path), + merge_overrides(path), + apply_path(@automatic, path), + ] - return nil if components.compact.empty? + components.map! do |component| + safe_dup(component) + end - components.inject(ImmutableMash.new({})) do |merged, component| - Chef::Mixin::DeepMerge.hash_only_merge!(merged, component) - end - end + return nil if components.compact.empty? + + components.inject(ImmutableMash.new({})) do |merged, component| + Chef::Mixin::DeepMerge.hash_only_merge!(merged, component) + end + end # Deep merge the default attribute levels with array merging. # @@ -560,12 +558,12 @@ 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) - DEFAULT_COMPONENTS.inject(nil) do |merged, component_ivar| - component_value = apply_path(instance_variable_get(component_ivar), path) - Chef::Mixin::DeepMerge.deep_merge(component_value, merged) - end - end + def merge_defaults(path) + DEFAULT_COMPONENTS.inject(nil) do |merged, component_ivar| + component_value = apply_path(instance_variable_get(component_ivar), path) + Chef::Mixin::DeepMerge.deep_merge(component_value, merged) + end + end # Deep merge the override attribute levels with array merging. # @@ -573,14 +571,12 @@ 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) - OVERRIDE_COMPONENTS.inject(nil) do |merged, component_ivar| - component_value = apply_path(instance_variable_get(component_ivar), path) - Chef::Mixin::DeepMerge.deep_merge(component_value, merged) - end - end - + def merge_overrides(path) + OVERRIDE_COMPONENTS.inject(nil) do |merged, component_ivar| + component_value = apply_path(instance_variable_get(component_ivar), path) + Chef::Mixin::DeepMerge.deep_merge(component_value, merged) + end + end end - end end diff --git a/lib/chef/node/attribute_collections.rb b/lib/chef/node/attribute_collections.rb index c52582a520..6249fbaa11 100644 --- a/lib/chef/node/attribute_collections.rb +++ b/lib/chef/node/attribute_collections.rb @@ -18,13 +18,11 @@ class Chef class Node - # == AttrArray # AttrArray is identical to Array, except that it keeps a reference to the # "root" (Chef::Node::Attribute) object, and will trigger a cache # invalidation on that object when mutated. class AttrArray < Array - MUTATOR_METHODS = [ :<<, :[]=, @@ -82,9 +80,8 @@ class Chef end def dup - Array.new(map {|e| safe_dup(e)}) + Array.new(map { |e| safe_dup(e) }) end - end # == VividMash @@ -130,7 +127,7 @@ class Chef end end - def initialize(root, data={}) + def initialize(root, data = {}) @root = root super(data) end @@ -204,7 +201,6 @@ class Chef def dup Mash.new(self) end - end # == MultiMash @@ -241,7 +237,7 @@ class Chef # Initialize with an array of mashes. For the delete return value to work # properly the mashes must come from the same attribute level (i.e. all # override or all default, but not a mix of both). - def initialize(root, primary_mash, mashes, opts={}) + def initialize(root, primary_mash, mashes, opts = {}) @root = root @primary_mash = primary_mash @mashes = mashes @@ -316,8 +312,6 @@ class Chef end return nil end - end - end end diff --git a/lib/chef/node/immutable_collections.rb b/lib/chef/node/immutable_collections.rb index c092c8cacc..2241d624fd 100644 --- a/lib/chef/node/immutable_collections.rb +++ b/lib/chef/node/immutable_collections.rb @@ -1,7 +1,6 @@ class Chef class Node - module Immutablize def immutablize(value) case value @@ -88,7 +87,7 @@ class Chef end def dup - Array.new(map {|e| safe_dup(e)}) + Array.new(map { |e| safe_dup(e) }) end def to_a @@ -106,7 +105,6 @@ class Chef end a end - end # == ImmutableMash @@ -122,7 +120,6 @@ class Chef # it is stale. # * Values can be accessed in attr_reader-like fashion via method_missing. class ImmutableMash < Mash - include Immutablize alias :internal_set :[]= @@ -212,8 +209,6 @@ class Chef end h end - end - end end diff --git a/lib/chef/node_map.rb b/lib/chef/node_map.rb index 99e4e2dbf9..87a3eed02a 100644 --- a/lib/chef/node_map.rb +++ b/lib/chef/node_map.rb @@ -18,7 +18,6 @@ class Chef class NodeMap - # # Set a key/value pair on the map with a filter. The filter must be true # when applied to the node in order to retrieve the value. @@ -49,7 +48,7 @@ class Chef # our place in it (just before the first value with the same preference level). insert_at = nil map[key] ||= [] - map[key].each_with_index do |matcher,index| + map[key].each_with_index do |matcher, index| cmp = compare_matchers(key, new_matcher, matcher) insert_at ||= index if cmp && cmp <= 0 end @@ -145,16 +144,16 @@ class Chef value = node[attribute] filter_values.empty? || - Array(filter_values).any? do |v| - Chef::VersionConstraint::Platform.new(v).include?(value) - end + Array(filter_values).any? do |v| + Chef::VersionConstraint::Platform.new(v).include?(value) + end end def filters_match?(node, filters) matches_black_white_list?(node, filters, :os) && - matches_black_white_list?(node, filters, :platform_family) && - matches_black_white_list?(node, filters, :platform) && - matches_version_list?(node, filters, :platform_version) + matches_black_white_list?(node, filters, :platform_family) && + matches_black_white_list?(node, filters, :platform) && + matches_version_list?(node, filters, :platform_version) end def block_matches?(node, block) diff --git a/lib/chef/null_logger.rb b/lib/chef/null_logger.rb index aae503c9da..a41b6d84ce 100644 --- a/lib/chef/null_logger.rb +++ b/lib/chef/null_logger.rb @@ -16,7 +16,6 @@ # limitations under the License. class Chef - # Null logger implementation that just ignores everything. This is used by # classes that are intended to be reused outside of Chef, but need to offer # logging functionality when used by other Chef code. @@ -26,7 +25,6 @@ class Chef # device, etc., are not implemented because any code calling those methods # probably expected a real logger and not this "fake" one. class NullLogger - def fatal(message, &block) end @@ -42,7 +40,7 @@ class Chef def debug(message, &block) end - def add(severity, message=nil, progname=nil) + def add(severity, message = nil, progname = nil) end def <<(message) @@ -67,6 +65,5 @@ class Chef def debug? false end - end end diff --git a/lib/chef/org.rb b/lib/chef/org.rb index ee4451fac0..a7795eb07f 100644 --- a/lib/chef/org.rb +++ b/lib/chef/org.rb @@ -22,7 +22,6 @@ require "chef/server_api" class Chef class Org - include Chef::Mixin::ParamsValidate def initialize(name) @@ -38,22 +37,22 @@ class Chef @chef_rest ||= Chef::ServerAPI.new(Chef::Config[:chef_server_root]) end - def name(arg=nil) + def name(arg = nil) set_or_return(:name, arg, :regex => /^[a-z0-9\-_]+$/) end - def full_name(arg=nil) + def full_name(arg = nil) set_or_return(:full_name, arg, :kind_of => String) end - def private_key(arg=nil) + def private_key(arg = nil) set_or_return(:private_key, arg, :kind_of => String) end - def guid(arg=nil) + def guid(arg = nil) set_or_return(:guid, arg, :kind_of => String) end @@ -73,13 +72,13 @@ class Chef end def create - payload = {:name => self.name, :full_name => self.full_name} + payload = { :name => self.name, :full_name => self.full_name } new_org = chef_rest.post("organizations", payload) Chef::Org.from_hash(self.to_hash.merge(new_org)) end def update - payload = {:name => self.name, :full_name => self.full_name} + payload = { :name => self.name, :full_name => self.full_name } new_org = chef_rest.put("organizations/#{name}", payload) Chef::Org.from_hash(self.to_hash.merge(new_org)) end @@ -101,7 +100,7 @@ class Chef end def associate_user(username) - request_body = {:user => username} + request_body = { :user => username } response = chef_rest.post "organizations/#{@name}/association_requests", request_body association_id = response["uri"].split("/").last chef_rest.put "users/#{username}/association_requests/#{association_id}", { :response => "accept" } @@ -130,11 +129,11 @@ class Chef end def self.load(org_name) - response = Chef::ServerAPI.new(Chef::Config[:chef_server_root]).get("organizations/#{org_name}") + response = Chef::ServerAPI.new(Chef::Config[:chef_server_root]).get("organizations/#{org_name}") Chef::Org.from_hash(response) end - def self.list(inflate=false) + def self.list(inflate = false) orgs = Chef::ServerAPI.new(Chef::Config[:chef_server_root]).get("organizations") if inflate orgs.inject({}) do |org_map, (name, _url)| diff --git a/lib/chef/platform.rb b/lib/chef/platform.rb index 165715267b..186bb8ebe5 100644 --- a/lib/chef/platform.rb +++ b/lib/chef/platform.rb @@ -22,9 +22,7 @@ require "chef/platform/provider_mapping" class Chef class Platform - # Functionality for this class is defined in chef/platform/provider_mapping # and chef/platform/query_helpers - end end diff --git a/lib/chef/platform/provider_mapping.rb b/lib/chef/platform/provider_mapping.rb index 478ed55385..ba7bebca3d 100644 --- a/lib/chef/platform/provider_mapping.rb +++ b/lib/chef/platform/provider_mapping.rb @@ -24,7 +24,6 @@ require "chef/provider" class Chef class Platform - class << self attr_writer :platforms @@ -45,7 +44,7 @@ class Chef end if platforms.has_key?(name_sym) - platform_versions = platforms[name_sym].select {|k, v| k != :default } + platform_versions = platforms[name_sym].select { |k, v| k != :default } if platforms[name_sym].has_key?(:default) provider_map.merge!(platforms[name_sym][:default]) end @@ -89,7 +88,7 @@ class Chef return platform, version end - def provider_for_resource(resource, action=:nothing) + def provider_for_resource(resource, action = :nothing) node = resource.run_context && resource.run_context.node raise ArgumentError, "Cannot find the provider for a resource with no run context set" unless node provider = find_provider_for_node(node, resource).new(resource, resource.run_context) @@ -183,32 +182,31 @@ class Chef private - def explicit_provider(platform, version, resource_type) - resource_type.kind_of?(Chef::Resource) ? resource_type.provider : nil - end + def explicit_provider(platform, version, resource_type) + resource_type.kind_of?(Chef::Resource) ? resource_type.provider : nil + end - def platform_provider(platform, version, resource_type) - pmap = Chef::Platform.find(platform, version) - rtkey = resource_type.kind_of?(Chef::Resource) ? resource_type.resource_name.to_sym : resource_type - pmap.has_key?(rtkey) ? pmap[rtkey] : nil - end + def platform_provider(platform, version, resource_type) + pmap = Chef::Platform.find(platform, version) + rtkey = resource_type.kind_of?(Chef::Resource) ? resource_type.resource_name.to_sym : resource_type + pmap.has_key?(rtkey) ? pmap[rtkey] : nil + end - include Chef::Mixin::ConvertToClassName + include Chef::Mixin::ConvertToClassName - def resource_matching_provider(platform, version, resource_type) - if resource_type.kind_of?(Chef::Resource) - class_name = resource_type.class.name ? resource_type.class.name.split("::").last : - convert_to_class_name(resource_type.resource_name.to_s) + def resource_matching_provider(platform, version, resource_type) + if resource_type.kind_of?(Chef::Resource) + class_name = resource_type.class.name ? resource_type.class.name.split("::").last : + convert_to_class_name(resource_type.resource_name.to_s) - if Chef::Provider.const_defined?(class_name) - Chef::Log.warn("Class Chef::Provider::#{class_name} does not declare 'provides #{convert_to_snake_case(class_name).to_sym.inspect}'.") - Chef::Log.warn("This will no longer work in Chef 13: you must use 'provides' to use the resource's DSL.") - return Chef::Provider.const_get(class_name) - end + if Chef::Provider.const_defined?(class_name) + Chef::Log.warn("Class Chef::Provider::#{class_name} does not declare 'provides #{convert_to_snake_case(class_name).to_sym.inspect}'.") + Chef::Log.warn("This will no longer work in Chef 13: you must use 'provides' to use the resource's DSL.") + return Chef::Provider.const_get(class_name) end - nil end - + nil + end end end end diff --git a/lib/chef/platform/query_helpers.rb b/lib/chef/platform/query_helpers.rb index 7a92fd3300..fd9c2803bb 100644 --- a/lib/chef/platform/query_helpers.rb +++ b/lib/chef/platform/query_helpers.rb @@ -18,7 +18,6 @@ class Chef class Platform - class << self def windows? ChefConfig.windows? @@ -99,7 +98,6 @@ class Chef metadata = cmdlet.run!.return_value metadata["RefreshMode"] == "Disabled" end - def supported_powershell_version?(node, version_string) return false unless node[:languages] && node[:languages][:powershell] @@ -107,7 +105,6 @@ class Chef Gem::Version.new(node[:languages][:powershell][:version]) >= Gem::Version.new(version_string) end - end end end diff --git a/lib/chef/platform/rebooter.rb b/lib/chef/platform/rebooter.rb index 622f35a5db..b210d11cec 100644 --- a/lib/chef/platform/rebooter.rb +++ b/lib/chef/platform/rebooter.rb @@ -26,13 +26,12 @@ class Chef extend Chef::Mixin::ShellOut class << self - def reboot!(node) reboot_info = node.run_context.reboot_info cmd = if Chef::Platform.windows? # should this do /f as well? do we then need a minimum delay to let apps quit? - "shutdown /r /t #{reboot_info[:delay_mins]*60} /c \"#{reboot_info[:reason]}\"" + "shutdown /r /t #{reboot_info[:delay_mins] * 60} /c \"#{reboot_info[:reason]}\"" else # probably Linux-only. "shutdown -r +#{reboot_info[:delay_mins]} \"#{reboot_info[:reason]}\"" diff --git a/lib/chef/platform/service_helpers.rb b/lib/chef/platform/service_helpers.rb index 13d710eefe..87b87d4c72 100644 --- a/lib/chef/platform/service_helpers.rb +++ b/lib/chef/platform/service_helpers.rb @@ -99,7 +99,7 @@ class Chef def systemd_is_init? ::File.exist?(Chef.path_to("/proc/1/comm")) && - ::File.open(Chef.path_to("/proc/1/comm")).gets.chomp == "systemd" + ::File.open(Chef.path_to("/proc/1/comm")).gets.chomp == "systemd" end def has_systemd_service_unit?(svc_name) diff --git a/lib/chef/policy_builder.rb b/lib/chef/policy_builder.rb index 56533e9a60..c2951ac3d2 100644 --- a/lib/chef/policy_builder.rb +++ b/lib/chef/policy_builder.rb @@ -21,7 +21,6 @@ require "chef/policy_builder/policyfile" require "chef/policy_builder/dynamic" class Chef - # PolicyBuilder contains classes that handles fetching policy from server or # disk and resolving any indirection (e.g. expanding run_list). # @@ -37,6 +36,5 @@ class Chef # * cookbooks sync'd to disk # * cookbook_hash is stored in run_context module PolicyBuilder - end end diff --git a/lib/chef/policy_builder/dynamic.rb b/lib/chef/policy_builder/dynamic.rb index c6c7deeee6..5152d05673 100644 --- a/lib/chef/policy_builder/dynamic.rb +++ b/lib/chef/policy_builder/dynamic.rb @@ -26,11 +26,9 @@ require "chef/exceptions" class Chef module PolicyBuilder - # PolicyBuilder that selects either a Policyfile or non-Policyfile # implementation based on the content of the node object. class Dynamic - extend Forwardable attr_reader :node @@ -149,9 +147,9 @@ class Chef # testing purposes; production code should call #load_node instead. def select_implementation(node) if policyfile_set_in_config? || - policyfile_attribs_in_node_json? || - node_has_policyfile_attrs?(node) || - policyfile_compat_mode_config? + policyfile_attribs_in_node_json? || + node_has_policyfile_attrs?(node) || + policyfile_compat_mode_config? @implementation = Policyfile.new(node_name, ohai_data, json_attribs, override_runlist, events) else @implementation = ExpandNodeObject.new(node_name, ohai_data, json_attribs, override_runlist, events) @@ -179,7 +177,6 @@ class Chef def policyfile_compat_mode_config? config[:deployment_group] && !config[:policy_document_native_api] end - end end end diff --git a/lib/chef/policy_builder/expand_node_object.rb b/lib/chef/policy_builder/expand_node_object.rb index f71036e4d1..af4a0f87d7 100644 --- a/lib/chef/policy_builder/expand_node_object.rb +++ b/lib/chef/policy_builder/expand_node_object.rb @@ -28,7 +28,6 @@ require "chef/chef_class" class Chef module PolicyBuilder - # ExpandNodeObject is the "classic" policy builder implementation. It # expands the run_list on a node object and then queries the chef-server # to find the correct set of cookbooks, given version constraints of the @@ -37,7 +36,6 @@ class Chef # Note that this class should only be used via PolicyBuilder::Dynamic and # not instantiated directly. class ExpandNodeObject - attr_reader :events attr_reader :node attr_reader :node_name @@ -68,7 +66,7 @@ class Chef Chef.set_run_context(run_context) end - def setup_run_context(specific_recipes=nil) + def setup_run_context(specific_recipes = nil) if Chef::Config[:solo] Chef::Cookbook::FileVendor.fetch_from_disk(Chef::Config[:cookbook_path]) cl = Chef::CookbookLoader.new(Chef::Config[:cookbook_path]) @@ -198,7 +196,7 @@ class Chef begin events.cookbook_resolution_start(@expanded_run_list_with_versions) cookbook_hash = api_service.post("environments/#{node.chef_environment}/cookbook_versions", - {:run_list => @expanded_run_list_with_versions}) + { :run_list => @expanded_run_list_with_versions }) cookbook_hash = cookbook_hash.inject({}) do |memo, (key, value)| memo[key] = Chef::CookbookVersion.from_hash(value) @@ -268,7 +266,6 @@ class Chef def config Chef::Config end - end end end diff --git a/lib/chef/policy_builder/policyfile.rb b/lib/chef/policy_builder/policyfile.rb index 1c0db91366..8c625b945c 100644 --- a/lib/chef/policy_builder/policyfile.rb +++ b/lib/chef/policy_builder/policyfile.rb @@ -27,7 +27,6 @@ require "chef/server_api" class Chef module PolicyBuilder - # Policyfile is an experimental policy builder implementation that gets run # list and cookbook version information from a single document. # @@ -46,7 +45,6 @@ class Chef # * chef-solo:: not currently supported. Need more design thought around # how this should work. class Policyfile - class UnsupportedFeature < StandardError; end class PolicyfileError < StandardError; end @@ -136,7 +134,6 @@ class Chef Chef::Log.info("Run List is [#{run_list}]") Chef::Log.info("Run List expands to [#{run_list_with_versions_for_display.join(', ')}]") - events.node_load_completed(node, run_list_with_versions_for_display, Chef::Config) node @@ -149,7 +146,7 @@ class Chef # run. # # @return [Chef::RunContext] - def setup_run_context(specific_recipes=nil) + def setup_run_context(specific_recipes = nil) Chef::Cookbook::FileVendor.fetch_from_remote(http_api) sync_cookbooks cookbook_collection = Chef::CookbookCollection.new(cookbooks_to_sync) @@ -258,7 +255,7 @@ class Chef named_run_list or raise ConfigurationError, "Policy '#{retrieved_policy_name}' revision '#{revision_id}' does not have named_run_list '#{named_run_list_name}'" + - "(available named_run_lists: [#{available_named_run_lists.join(', ')}])" + "(available named_run_lists: [#{available_named_run_lists.join(', ')}])" else policy["run_list"] end @@ -520,7 +517,6 @@ class Chef def inflate_cbv_object(raw_manifest) Chef::CookbookVersion.from_cb_artifact_data(raw_manifest) end - end end end diff --git a/lib/chef/property.rb b/lib/chef/property.rb index d7ef19ee3d..8198dd6700 100644 --- a/lib/chef/property.rb +++ b/lib/chef/property.rb @@ -87,12 +87,11 @@ class Chef # is fully initialized. # def initialize(**options) - options.each { |k,v| options[k.to_sym] = v; options.delete(k) if k.is_a?(String) } + options.each { |k, v| options[k.to_sym] = v; options.delete(k) if k.is_a?(String) } @options = options options[:name] = options[:name].to_sym if options[:name] options[:instance_variable_name] = options[:instance_variable_name].to_sym if options[:instance_variable_name] - # Replace name_attribute with name_property if options.has_key?(:name_attribute) # If we have both name_attribute and name_property and they differ, raise an error @@ -100,7 +99,7 @@ class Chef raise ArgumentError, "Cannot specify both name_property and name_attribute together on property #{self}." end # replace name_property with name_attribute in place - options = Hash[options.map { |k,v| k == :name_attribute ? [ :name_property, v ] : [ k,v ] }] + options = Hash[options.map { |k, v| k == :name_attribute ? [ :name_property, v ] : [ k, v ] }] @options = options end @@ -233,8 +232,8 @@ class Chef # @return [Hash] # def validation_options - @validation_options ||= options.reject { |k,v| - [:declared_in,:name,:instance_variable_name,:desired_state,:identity,:default,:name_property,:coerce,:required].include?(k) + @validation_options ||= options.reject { |k, v| + [:declared_in, :name, :instance_variable_name, :desired_state, :identity, :default, :name_property, :coerce, :required].include?(k) } end @@ -258,7 +257,7 @@ class Chef # will be returned without running, validating or coercing. If it is a # `get`, the non-lazy, coerced, validated value will always be returned. # - def call(resource, value=NOT_PASSED) + def call(resource, value = NOT_PASSED) if value == NOT_PASSED return get(resource) end @@ -342,7 +341,7 @@ class Chef resource.enclosing_provider && resource.enclosing_provider.new_resource && resource.enclosing_provider.new_resource.respond_to?(name) - Chef::Log.warn("#{Chef::Log.caller_location}: property #{name} is declared in both #{resource} and #{resource.enclosing_provider}. Use new_resource.#{name} instead. At #{Chef::Log.caller_location}") + Chef::Log.warn("#{Chef::Log.caller_location}: property #{name} is declared in both #{resource} and #{resource.enclosing_provider}. Use new_resource.#{name} instead. At #{Chef::Log.caller_location}") end if has_default? @@ -489,7 +488,7 @@ class Chef if modified_options.has_key?(:name_property) || modified_options.has_key?(:name_attribute) || modified_options.has_key?(:default) - options = options.reject { |k,v| k == :name_attribute || k == :name_property || k == :default } + options = options.reject { |k, v| k == :name_attribute || k == :name_property || k == :default } end self.class.new(options.merge(modified_options)) end @@ -506,7 +505,7 @@ class Chef # We prefer this form because the property name won't show up in the # stack trace if you use `define_method`. - declared_in.class_eval <<-EOM, __FILE__, __LINE__+1 + declared_in.class_eval <<-EOM, __FILE__, __LINE__ + 1 def #{name}(value=NOT_PASSED) raise "Property #{name} of \#{self} cannot be passed a block! If you meant to create a resource named #{name} instead, you'll need to first rename the property." if block_given? self.class.properties[#{name.inspect}].call(self, value) @@ -518,7 +517,7 @@ class Chef EOM rescue SyntaxError # If the name is not a valid ruby name, we use define_method. - declared_in.define_method(name) do |value=NOT_PASSED, &block| + declared_in.define_method(name) do |value = NOT_PASSED, &block| raise "Property #{name} of #{self} cannot be passed a block! If you meant to create a resource named #{name} instead, you'll need to first rename the property." if block self.class.properties[name].call(self, value) end @@ -577,7 +576,7 @@ class Chef # @api private def explicitly_accepts_nil?(resource) options.has_key?(:coerce) || - (options.has_key?(:is) && resource.send(:_pv_is, { name => nil }, name, options[:is], raise_error: false)) + (options.has_key?(:is) && resource.send(:_pv_is, { name => nil }, name, options[:is], raise_error: false)) end def get_value(resource) diff --git a/lib/chef/provider.rb b/lib/chef/provider.rb index eeef182f73..6a31f9d4b4 100644 --- a/lib/chef/provider.rb +++ b/lib/chef/provider.rb @@ -112,7 +112,7 @@ class Chef run_context.events end - def run_action(action=nil) + def run_action(action = nil) @action = action unless action.nil? # TODO: it would be preferable to get the action to be executed in the @@ -244,7 +244,7 @@ class Chef true end - def self.provides(short_name, opts={}, &block) + def self.provides(short_name, opts = {}, &block) Chef.provider_handler_map.set(short_name, self, opts, &block) end @@ -350,7 +350,6 @@ class Chef # # @api private module InlineResources - # Create a child run_context, compile the block, and converge it. # # @api private diff --git a/lib/chef/provider/apt_update.rb b/lib/chef/provider/apt_update.rb index 00c3ad16bb..b7d72002b1 100644 --- a/lib/chef/provider/apt_update.rb +++ b/lib/chef/provider/apt_update.rb @@ -51,6 +51,7 @@ class Chef end private + # Determines whether we need to run `apt-get update` # # @return [Boolean] @@ -72,7 +73,6 @@ class Chef shell_out!("apt-get -q update") end - end end end diff --git a/lib/chef/provider/batch.rb b/lib/chef/provider/batch.rb index bb294afd3f..ca9ec899e6 100644 --- a/lib/chef/provider/batch.rb +++ b/lib/chef/provider/batch.rb @@ -21,7 +21,6 @@ require "chef/provider/windows_script" class Chef class Provider class Batch < Chef::Provider::WindowsScript - provides :batch, os: "windows" def initialize(new_resource, run_context) @@ -39,7 +38,6 @@ class Chef def flags @new_resource.flags.nil? ? "/c" : new_resource.flags + " /c" end - end end end diff --git a/lib/chef/provider/breakpoint.rb b/lib/chef/provider/breakpoint.rb index a71c9e317d..c37e57e083 100644 --- a/lib/chef/provider/breakpoint.rb +++ b/lib/chef/provider/breakpoint.rb @@ -19,7 +19,6 @@ class Chef class Provider class Breakpoint < Chef::Provider - provides :breakpoint def load_current_resource @@ -32,7 +31,6 @@ class Chef run_context.resource_collection.iterator end end - end end end diff --git a/lib/chef/provider/cookbook_file.rb b/lib/chef/provider/cookbook_file.rb index 3ca0bbd47a..06a6fde431 100644 --- a/lib/chef/provider/cookbook_file.rb +++ b/lib/chef/provider/cookbook_file.rb @@ -23,7 +23,6 @@ require "chef/deprecation/warnings" class Chef class Provider class CookbookFile < Chef::Provider::File - provides :cookbook_file extend Chef::Deprecation::Warnings @@ -47,7 +46,6 @@ class Chef return true if !@new_resource.source.nil? && @action != :create_if_missing false end - end end end diff --git a/lib/chef/provider/cookbook_file/content.rb b/lib/chef/provider/cookbook_file/content.rb index 1d24dee3e7..29d0c98b0f 100644 --- a/lib/chef/provider/cookbook_file/content.rb +++ b/lib/chef/provider/cookbook_file/content.rb @@ -23,7 +23,6 @@ class Chef class Provider class CookbookFile class Content < Chef::FileContentManagement::ContentBase - private def file_for_provider diff --git a/lib/chef/provider/cron.rb b/lib/chef/provider/cron.rb index 01351603ca..36b67ab6a5 100644 --- a/lib/chef/provider/cron.rb +++ b/lib/chef/provider/cron.rb @@ -67,7 +67,7 @@ class Chef if cron_found @current_resource.time($2.to_sym) @current_resource.command($3) - cron_found=false + cron_found = false end when CRON_PATTERN if cron_found @@ -77,11 +77,11 @@ class Chef @current_resource.month($4) @current_resource.weekday($5) @current_resource.command($6) - cron_found=false + cron_found = false end next else - cron_found=false # We've got a Chef comment with no following crontab line + cron_found = false # We've got a Chef comment with no following crontab line next end end diff --git a/lib/chef/provider/cron/aix.rb b/lib/chef/provider/cron/aix.rb index 015c1f2096..d3e36f1783 100644 --- a/lib/chef/provider/cron/aix.rb +++ b/lib/chef/provider/cron/aix.rb @@ -22,7 +22,6 @@ class Chef class Provider class Cron class Aix < Chef::Provider::Cron::Unix - provides :cron, os: "aix" private diff --git a/lib/chef/provider/cron/unix.rb b/lib/chef/provider/cron/unix.rb index 108e73c9d3..5ce83f1163 100644 --- a/lib/chef/provider/cron/unix.rb +++ b/lib/chef/provider/cron/unix.rb @@ -76,7 +76,6 @@ class Chef raise Chef::Exceptions::Cron, "Error updating state of #{@new_resource.name}, exit: #{exit_status}, message: #{error_message}" end end - end end end diff --git a/lib/chef/provider/deploy.rb b/lib/chef/provider/deploy.rb index d53cce1311..eb94919c5f 100644 --- a/lib/chef/provider/deploy.rb +++ b/lib/chef/provider/deploy.rb @@ -26,7 +26,6 @@ require "chef/util/path_helper" class Chef class Provider class Deploy < Chef::Provider - include Chef::DSL::Recipe include Chef::Mixin::FromFile include Chef::Mixin::Command @@ -56,7 +55,7 @@ class Chef @shared_path = @new_resource.shared_path end - def sudo(command,&block) + def sudo(command, &block) execute(command, &block) end @@ -93,7 +92,6 @@ class Chef a.whyrun("Would assume callback file #{callback_file} included in release") end end - end def action_deploy @@ -175,7 +173,7 @@ class Chef restart end - def callback(what, callback_code=nil) + def callback(what, callback_code = nil) @collection = Chef::ResourceCollection.new case callback_code when Proc @@ -201,7 +199,7 @@ class Chef converge_by("execute migration command #{@new_resource.migration_command}") do Chef::Log.info "#{@new_resource} migrating #{@new_resource.user} with environment #{env_info}" - shell_out!(@new_resource.migration_command,run_options(:cwd=>release_path, :log_level => :info)) + shell_out!(@new_resource.migration_command, run_options(:cwd => release_path, :log_level => :info)) end end end @@ -221,7 +219,7 @@ class Chef else converge_by("restart app using command #{@new_resource.restart_command}") do Chef::Log.info("#{@new_resource} restarting app") - shell_out!(@new_resource.restart_command,run_options(:cwd=>@new_resource.current_path)) + shell_out!(@new_resource.restart_command, run_options(:cwd => @new_resource.current_path)) end end end @@ -391,7 +389,7 @@ class Chef end end - def run_options(run_opts={}) + def run_options(run_opts = {}) run_opts[:user] = @new_resource.user if @new_resource.user run_opts[:group] = @new_resource.group if @new_resource.group run_opts[:environment] = @new_resource.environment if @new_resource.environment diff --git a/lib/chef/provider/deploy/revision.rb b/lib/chef/provider/deploy/revision.rb index 0bd30ce762..30d93134ce 100644 --- a/lib/chef/provider/deploy/revision.rb +++ b/lib/chef/provider/deploy/revision.rb @@ -56,11 +56,11 @@ class Chef protected def release_created(release) - sorted_releases {|r| r.delete(release); r << release } + sorted_releases { |r| r.delete(release); r << release } end def release_deleted(release) - sorted_releases { |r| r.delete(release)} + sorted_releases { |r| r.delete(release) } end def release_slug @@ -102,7 +102,6 @@ class Chef Chef::FileCache.store("revision-deploys/#{new_resource.name}", Chef::JSONCompat.to_json(cache)) cache end - end end end diff --git a/lib/chef/provider/directory.rb b/lib/chef/provider/directory.rb index 3235a28cd1..298f3042c3 100644 --- a/lib/chef/provider/directory.rb +++ b/lib/chef/provider/directory.rb @@ -26,7 +26,6 @@ require "fileutils" class Chef class Provider class Directory < Chef::Provider::File - provides :directory def whyrun_supported? @@ -146,7 +145,6 @@ class Chef def managing_content? false end - end end end diff --git a/lib/chef/provider/dsc_resource.rb b/lib/chef/provider/dsc_resource.rb index 1f6a8f0ef6..eac8a829bd 100644 --- a/lib/chef/provider/dsc_resource.rb +++ b/lib/chef/provider/dsc_resource.rb @@ -132,7 +132,7 @@ class Chef create_reboot_resource if return_dsc_resource_result(result, "RebootRequired") result.return_value end - + def add_dsc_verbose_log(result) # We really want this information from the verbose stream, # however in some versions of WMF, Invoke-DscResource is not correctly @@ -148,7 +148,7 @@ class Chef end end - def invoke_resource(method, output_format=:object) + def invoke_resource(method, output_format = :object) properties = translate_type(@new_resource.properties) switches = "-Method #{method} -Name #{@new_resource.resource}"\ " -Property #{properties} -Verbose" @@ -160,7 +160,7 @@ class Chef "Invoke-DscResource #{switches}", output_format, ) - cmdlet.run!({}, {:timeout => new_resource.timeout}) + cmdlet.run!({}, { :timeout => new_resource.timeout }) end def return_dsc_resource_result(result, property_name) diff --git a/lib/chef/provider/dsc_script.rb b/lib/chef/provider/dsc_script.rb index b8686c4450..8cce146953 100644 --- a/lib/chef/provider/dsc_script.rb +++ b/lib/chef/provider/dsc_script.rb @@ -24,7 +24,6 @@ require "chef/util/path_helper" class Chef class Provider class DscScript < Chef::Provider - provides :dsc_script, os: "windows" def initialize(dsc_resource, run_context) @@ -37,7 +36,7 @@ class Chef }, :test => Proc.new { |config_manager, document, shellout_flags| config_manager.test_configuration(document, shellout_flags) - }} + } } end def action_run @@ -138,7 +137,7 @@ class Chef @dsc_resource.configuration_data_script elsif @dsc_resource.configuration_data configuration_data_path = "#{config_directory}/chef_dsc_config_data.psd1" - ::File.open(configuration_data_path, "wt") do | script | + ::File.open(configuration_data_path, "wt") do |script| script.write(@dsc_resource.configuration_data) end configuration_data_path @@ -165,7 +164,7 @@ class Chef 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 } - "converge DSC resource #{resource.name} by #{cleaned_messages.find_all{ |c| c != ''}.join("\n")}" + "converge DSC resource #{resource.name} by #{cleaned_messages.find_all { |c| c != '' }.join("\n")}" else # 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" diff --git a/lib/chef/provider/env.rb b/lib/chef/provider/env.rb index fda41aca39..5b252dd344 100644 --- a/lib/chef/provider/env.rb +++ b/lib/chef/provider/env.rb @@ -108,15 +108,15 @@ class Chef not new_values.include?(item) end.join(@new_resource.delim) - if new_value.empty? - return false #nothing left here, delete the key - else - old_value = @new_resource.value(new_value) - create_env - Chef::Log.debug("#{@new_resource} deleted #{old_value} element") - @new_resource.updated_by_last_action(true) - return true #we removed the element and updated; do not delete the key - end + if new_value.empty? + return false #nothing left here, delete the key + else + old_value = @new_resource.value(new_value) + create_env + Chef::Log.debug("#{@new_resource} deleted #{old_value} element") + @new_resource.updated_by_last_action(true) + return true #we removed the element and updated; do not delete the key + end end end diff --git a/lib/chef/provider/env/windows.rb b/lib/chef/provider/env/windows.rb index 684386abe4..7ee8ca6aaa 100644 --- a/lib/chef/provider/env/windows.rb +++ b/lib/chef/provider/env/windows.rb @@ -65,7 +65,6 @@ class Chef environment_variables[0].wmi_ole_object end end - end end end diff --git a/lib/chef/provider/erl_call.rb b/lib/chef/provider/erl_call.rb index 7167f3b8a5..905fd7fe2c 100644 --- a/lib/chef/provider/erl_call.rb +++ b/lib/chef/provider/erl_call.rb @@ -102,7 +102,6 @@ class Chef end end end - end end end diff --git a/lib/chef/provider/execute.rb b/lib/chef/provider/execute.rb index fde60ba33f..45f0ad5488 100644 --- a/lib/chef/provider/execute.rb +++ b/lib/chef/provider/execute.rb @@ -40,9 +40,9 @@ class Chef def define_resource_requirements # @todo: this should change to raise in some appropriate major version bump. - if creates && creates_relative? && !cwd - Chef::Log.warn "Providing a relative path for the creates attribute without the cwd is deprecated and will be changed to fail in the future (CHEF-3819)" - end + if creates && creates_relative? && !cwd + Chef::Log.warn "Providing a relative path for the creates attribute without the cwd is deprecated and will be changed to fail in the future (CHEF-3819)" + end end def timeout diff --git a/lib/chef/provider/file.rb b/lib/chef/provider/file.rb index 2be01889af..7f85085eeb 100644 --- a/lib/chef/provider/file.rb +++ b/lib/chef/provider/file.rb @@ -130,7 +130,7 @@ class Chef if ::File.exist?(@new_resource.path) requirements.assert(:delete) do |a| a.assertion { ::File.writable?(@new_resource.path) } - a.failure_message(Chef::Exceptions::InsufficientPermissions,"File #{@new_resource.path} exists but is not writable so it cannot be deleted") + a.failure_message(Chef::Exceptions::InsufficientPermissions, "File #{@new_resource.path} exists but is not writable so it cannot be deleted") end end @@ -266,7 +266,7 @@ class Chef else [ Chef::Exceptions::FileTypeMismatch, "File #{path} exists, but is a symlink to #{real_path} which is a #{file_type_string(real_path)}. " + - "Disable manage_symlink_source and set force_unlink to remove it.", + "Disable manage_symlink_source and set force_unlink to remove it.", "Assuming symlink #{path} or source file #{real_path} would have been fixed by a previous resource", ] end @@ -464,7 +464,7 @@ class Chef def short_cksum(checksum) return "none" if checksum.nil? - checksum.slice(0,6) + checksum.slice(0, 6) end def load_resource_attributes_from_file(resource) diff --git a/lib/chef/provider/git.rb b/lib/chef/provider/git.rb index f197729367..926cb8ef20 100644 --- a/lib/chef/provider/git.rb +++ b/lib/chef/provider/git.rb @@ -24,7 +24,6 @@ require "fileutils" class Chef class Provider class Git < Chef::Provider - provides :git def whyrun_supported? @@ -53,9 +52,9 @@ class Chef a.assertion { !(@new_resource.revision =~ /^origin\//) } a.failure_message Chef::Exceptions::InvalidRemoteGitReference, "Deploying remote branches is not supported. " + - "Specify the remote branch as a local branch for " + - "the git repository you're deploying from " + - "(ie: '#{@new_resource.revision.gsub('origin/', '')}' rather than '#{@new_resource.revision}')." + "Specify the remote branch as a local branch for " + + "the git repository you're deploying from " + + "(ie: '#{@new_resource.revision.gsub('origin/', '')}' rather than '#{@new_resource.revision}')." end requirements.assert(:all_actions) do |a| @@ -65,8 +64,8 @@ class Chef a.assertion { target_revision != nil } 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" + - "`git ls-remote '#{@new_resource.repository}' '#{rev_search_pattern}'` output: #{@resolved_reference}" + "Verify your (case-sensitive) repository URL and revision.\n" + + "`git ls-remote '#{@new_resource.repository}' '#{rev_search_pattern}'` output: #{@resolved_reference}" end end @@ -86,7 +85,7 @@ class Chef def action_export action_checkout converge_by("complete the export by removing #{@new_resource.destination}.git after checkout") do - FileUtils.rm_rf(::File.join(@new_resource.destination,".git")) + FileUtils.rm_rf(::File.join(@new_resource.destination, ".git")) end end @@ -113,14 +112,14 @@ class Chef end def target_dir_non_existent_or_empty? - !::File.exist?(@new_resource.destination) || Dir.entries(@new_resource.destination).sort == [".",".."] + !::File.exist?(@new_resource.destination) || Dir.entries(@new_resource.destination).sort == [".", ".."] end def find_current_revision Chef::Log.debug("#{@new_resource} finding current git revision") if ::File.exist?(::File.join(cwd, ".git")) # 128 is returned when we're not in a git repo. this is fine - result = shell_out!("git rev-parse HEAD", :cwd => cwd, :returns => [0,128]).stdout.strip + result = shell_out!("git rev-parse HEAD", :cwd => cwd, :returns => [0, 128]).stdout.strip end sha_hash?(result) ? result : nil end @@ -189,10 +188,9 @@ class Chef def setup_remote_tracking_branches(remote_name, remote_url) converge_by("set up remote tracking branches for #{remote_url} at #{remote_name}") do - Chef::Log.debug "#{@new_resource} configuring remote tracking branches for repository #{remote_url} "+ - "at remote #{remote_name}" + Chef::Log.debug "#{@new_resource} configuring remote tracking branches for repository #{remote_url} " + "at remote #{remote_name}" check_remote_command = "git config --get remote.#{remote_name}.url" - remote_status = shell_out!(check_remote_command, run_options(:cwd => @new_resource.destination, :returns => [0,1,2])) + remote_status = shell_out!(check_remote_command, run_options(:cwd => @new_resource.destination, :returns => [0, 1, 2])) case remote_status.exitstatus when 0, 2 # * Status 0 means that we already have a remote with this name, so we should update the url @@ -200,7 +198,7 @@ class Chef # * Status 2 means that we have multiple urls assigned to the same remote (not a good idea) # which we can fix by replacing them all with our target url (hence the --replace-all option) - if multiple_remotes?(remote_status) || !remote_matches?(remote_url,remote_status) + if multiple_remotes?(remote_status) || !remote_matches?(remote_url, remote_status) update_remote_url_command = "git config --replace-all remote.#{remote_name}.url #{remote_url}" shell_out!(update_remote_url_command, run_options(:cwd => @new_resource.destination)) end @@ -259,7 +257,7 @@ class Chef found.size == 1 ? found.first[0] : nil end - def find_revision(refs, revision, suffix="") + def find_revision(refs, revision, suffix = "") found = refs_search(refs, rev_match_pattern("refs/tags/", revision) + suffix) found = refs_search(refs, rev_match_pattern("refs/heads/", revision) + suffix) if found.empty? found = refs_search(refs, revision + suffix) if found.empty? @@ -293,7 +291,7 @@ class Chef private - def run_options(run_opts={}) + def run_options(run_opts = {}) env = {} if @new_resource.user run_opts[:user] = @new_resource.user @@ -314,7 +312,6 @@ class Chef env.merge!(@new_resource.environment) if @new_resource.environment run_opts[:environment] = env unless env.empty? run_opts - end def cwd @@ -328,7 +325,6 @@ class Chef def sha_hash?(string) string =~ /^[0-9a-f]{40}$/ end - end end end diff --git a/lib/chef/provider/group.rb b/lib/chef/provider/group.rb index 0c98730155..4ed6697d46 100644 --- a/lib/chef/provider/group.rb +++ b/lib/chef/provider/group.rb @@ -86,7 +86,7 @@ class Chef # :: If a change is not required def compare_group @change_desc = [ ] - if @new_resource.gid.to_s != @current_resource.gid.to_s + if @new_resource.gid.to_s != @current_resource.gid.to_s @change_desc << "change gid #{@current_resource.gid} to #{@new_resource.gid}" end @@ -177,7 +177,6 @@ class Chef def remove_group raise NotImplementedError, "subclasses of Chef::Provider::Group should define #remove_group" end - end end end diff --git a/lib/chef/provider/group/aix.rb b/lib/chef/provider/group/aix.rb index 196ce1345a..4a1b73a5d3 100644 --- a/lib/chef/provider/group/aix.rb +++ b/lib/chef/provider/group/aix.rb @@ -69,7 +69,7 @@ class Chef def set_options opts = "" - { :gid => "id" }.sort { |a,b| a[0] <=> b[0] }.each do |field, option| + { :gid => "id" }.sort { |a, b| a[0] <=> b[0] }.each do |field, option| if @current_resource.send(field) != @new_resource.send(field) if @new_resource.send(field) Chef::Log.debug("#{@new_resource} setting #{field} to #{@new_resource.send(field)}") @@ -79,7 +79,6 @@ class Chef end opts end - end end end diff --git a/lib/chef/provider/group/dscl.rb b/lib/chef/provider/group/dscl.rb index b433d57a03..2b704b439b 100644 --- a/lib/chef/provider/group/dscl.rb +++ b/lib/chef/provider/group/dscl.rb @@ -20,7 +20,6 @@ class Chef class Provider class Group class Dscl < Chef::Provider::Group - provides :group, os: "darwin" def dscl(*args) @@ -35,8 +34,8 @@ class Chef def safe_dscl(*args) result = dscl(*args) return "" if ( args.first =~ /^delete/ ) && ( result[1].exitstatus != 0 ) - raise(Chef::Exceptions::Group,"dscl error: #{result.inspect}") unless result[1].exitstatus == 0 - raise(Chef::Exceptions::Group,"dscl error: #{result.inspect}") if result[2] =~ /No such key: / + raise(Chef::Exceptions::Group, "dscl error: #{result.inspect}") unless result[1].exitstatus == 0 + raise(Chef::Exceptions::Group, "dscl error: #{result.inspect}") if result[2] =~ /No such key: / return result[2] end @@ -69,7 +68,7 @@ class Chef end # get a free GID greater than 200 - def get_free_gid(search_limit=1000) + def get_free_gid(search_limit = 1000) gid = nil; next_gid_guess = 200 groups_gids = safe_dscl("list /Groups gid") while(next_gid_guess < search_limit + 200) @@ -90,8 +89,8 @@ class Chef end def set_gid - @new_resource.gid(get_free_gid) if [nil,""].include? @new_resource.gid - raise(Chef::Exceptions::Group,"gid is already in use") if gid_used?(@new_resource.gid) + @new_resource.gid(get_free_gid) if [nil, ""].include? @new_resource.gid + raise(Chef::Exceptions::Group, "gid is already in use") if gid_used?(@new_resource.gid) safe_dscl("create /Groups/#{@new_resource.group_name} PrimaryGroupID #{@new_resource.gid}") end diff --git a/lib/chef/provider/group/groupadd.rb b/lib/chef/provider/group/groupadd.rb index 8f87054262..2be21e1848 100644 --- a/lib/chef/provider/group/groupadd.rb +++ b/lib/chef/provider/group/groupadd.rb @@ -20,7 +20,6 @@ class Chef class Provider class Group class Groupadd < Chef::Provider::Group - def required_binaries [ "/usr/sbin/groupadd", "/usr/sbin/groupmod", @@ -113,7 +112,7 @@ class Chef # :: A string containing the option and then the quoted value def set_options opts = "" - { :gid => "-g" }.sort { |a,b| a[0] <=> b[0] }.each do |field, option| + { :gid => "-g" }.sort { |a, b| a[0] <=> b[0] }.each do |field, option| if @current_resource.send(field) != @new_resource.send(field) if @new_resource.send(field) opts << " #{option} '#{@new_resource.send(field)}'" @@ -130,7 +129,6 @@ class Chef opts << " -o" if @new_resource.non_unique opts end - end end end diff --git a/lib/chef/provider/group/groupmod.rb b/lib/chef/provider/group/groupmod.rb index 8169e50595..249dd65b2f 100644 --- a/lib/chef/provider/group/groupmod.rb +++ b/lib/chef/provider/group/groupmod.rb @@ -20,7 +20,6 @@ class Chef class Provider class Group class Groupmod < Chef::Provider::Group - provides :group, os: "netbsd" def load_current_resource @@ -111,7 +110,7 @@ class Chef # # ==== Returns # :: A string containing the option and then the quoted value - def set_options(overwrite_gid=false) + def set_options(overwrite_gid = false) opts = "" if overwrite_gid || @new_resource.gid && (@current_resource.gid != @new_resource.gid) opts << " -g '#{@new_resource.gid}'" diff --git a/lib/chef/provider/group/pw.rb b/lib/chef/provider/group/pw.rb index 4fd78b6b31..d18cf45f2f 100644 --- a/lib/chef/provider/group/pw.rb +++ b/lib/chef/provider/group/pw.rb @@ -133,7 +133,6 @@ class Chef opts end - end end end diff --git a/lib/chef/provider/group/suse.rb b/lib/chef/provider/group/suse.rb index f6f4fa1e11..3b211f8f0d 100644 --- a/lib/chef/provider/group/suse.rb +++ b/lib/chef/provider/group/suse.rb @@ -55,7 +55,6 @@ class Chef def remove_member(member) shell_out!("groupmod -R #{member} #{@new_resource.group_name}") end - end end end diff --git a/lib/chef/provider/group/usermod.rb b/lib/chef/provider/group/usermod.rb index e4b19181aa..0e02e3a6e9 100644 --- a/lib/chef/provider/group/usermod.rb +++ b/lib/chef/provider/group/usermod.rb @@ -22,7 +22,6 @@ class Chef class Provider class Group class Usermod < Chef::Provider::Group::Groupadd - provides :group, os: %w{openbsd solaris2 hpux} provides :group, platform: "opensuse" @@ -84,7 +83,6 @@ class Chef "-a -G" end end - end end end diff --git a/lib/chef/provider/group/windows.rb b/lib/chef/provider/group/windows.rb index 3c052cb92a..110989b198 100644 --- a/lib/chef/provider/group/windows.rb +++ b/lib/chef/provider/group/windows.rb @@ -25,10 +25,9 @@ class Chef class Provider class Group class Windows < Chef::Provider::Group - provides :group, os: "windows" - def initialize(new_resource,run_context) + def initialize(new_resource, run_context) super @net_group = Chef::Util::Windows::NetGroup.new(@new_resource.group_name) end diff --git a/lib/chef/provider/http_request.rb b/lib/chef/provider/http_request.rb index 9a261b8d79..ef2bd0e227 100644 --- a/lib/chef/provider/http_request.rb +++ b/lib/chef/provider/http_request.rb @@ -22,7 +22,6 @@ require "chef/http/simple" class Chef class Provider class HttpRequest < Chef::Provider - provides :http_request attr_accessor :http @@ -55,7 +54,6 @@ class Chef # Send a GET request to @new_resource.url def action_get converge_by("#{@new_resource} GET to #{@new_resource.url}") do - message = check_message(@new_resource.message) body = @http.get( "#{@new_resource.url}", @@ -109,14 +107,13 @@ class Chef private - def check_message(message) - if message.kind_of?(Proc) - message.call - else - message - end + def check_message(message) + if message.kind_of?(Proc) + message.call + else + message end - + end end end end diff --git a/lib/chef/provider/ifconfig.rb b/lib/chef/provider/ifconfig.rb index 50b05304ff..d00d5cd155 100644 --- a/lib/chef/provider/ifconfig.rb +++ b/lib/chef/provider/ifconfig.rb @@ -67,7 +67,7 @@ class Chef @status.stdout.each_line do |line| if !line[0..9].strip.empty? @int_name = line[0..9].strip - @interfaces[@int_name] = {"hwaddr" => (line =~ /(HWaddr)/ ? ($') : "nil").strip.chomp } + @interfaces[@int_name] = { "hwaddr" => (line =~ /(HWaddr)/ ? ($') : "nil").strip.chomp } else @interfaces[@int_name]["inet_addr"] = (line =~ /inet addr:(\S+)/ ? ($1) : "nil") if line =~ /inet addr:/ @interfaces[@int_name]["bcast"] = (line =~ /Bcast:(\S+)/ ? ($1) : "nil") if line =~ /Bcast:/ @@ -193,6 +193,7 @@ class Chef end private + def add_command command = "ifconfig #{@new_resource.device} #{@new_resource.target}" command << " netmask #{@new_resource.mask}" if @new_resource.mask diff --git a/lib/chef/provider/ifconfig/aix.rb b/lib/chef/provider/ifconfig/aix.rb index 65c559a150..546a6f613f 100644 --- a/lib/chef/provider/ifconfig/aix.rb +++ b/lib/chef/provider/ifconfig/aix.rb @@ -67,6 +67,7 @@ class Chef end private + def add_command # ifconfig changes are temporary, chdev persist across reboots. raise Chef::Exceptions::Ifconfig, "interface metric attribute cannot be set for :add action" if @new_resource.metric @@ -88,10 +89,9 @@ 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 { |n| dec = dec + "." + netmask[n..n + 1].to_i(16).to_s(10) } dec end - end end end diff --git a/lib/chef/provider/ifconfig/debian.rb b/lib/chef/provider/ifconfig/debian.rb index 4752f784ae..e78b8c1979 100644 --- a/lib/chef/provider/ifconfig/debian.rb +++ b/lib/chef/provider/ifconfig/debian.rb @@ -67,7 +67,7 @@ iface <%= @new_resource.device %> inet static dir.run_action(:create) new_resource.updated_by_last_action(true) if dir.updated_by_last_action? # roll our own file_edit resource, this will not get reported until we have a file_edit resource - interfaces_dot_d_for_regexp = INTERFACES_DOT_D_DIR.gsub(/\./, '\.') # escape dots for the regexp + interfaces_dot_d_for_regexp = INTERFACES_DOT_D_DIR.gsub(/\./, '\.') # escape dots for the regexp regexp = %r{^\s*source\s+#{interfaces_dot_d_for_regexp}/\*\s*$} unless ::File.exists?(INTERFACES_FILE) && regexp.match(IO.read(INTERFACES_FILE)) converge_by("modifying #{INTERFACES_FILE} to source #{INTERFACES_DOT_D_DIR}") do @@ -77,7 +77,6 @@ iface <%= @new_resource.device %> inet static end end end - end end end diff --git a/lib/chef/provider/ifconfig/redhat.rb b/lib/chef/provider/ifconfig/redhat.rb index 0c28e6407a..52617bf4ac 100644 --- a/lib/chef/provider/ifconfig/redhat.rb +++ b/lib/chef/provider/ifconfig/redhat.rb @@ -41,7 +41,6 @@ class Chef } @config_path = "/etc/sysconfig/network-scripts/ifcfg-#{@new_resource.device}" end - end end end diff --git a/lib/chef/provider/link.rb b/lib/chef/provider/link.rb index b8cffee695..bf27e65e6d 100644 --- a/lib/chef/provider/link.rb +++ b/lib/chef/provider/link.rb @@ -27,7 +27,6 @@ require "chef/util/path_helper" class Chef class Provider class Link < Chef::Provider - provides :link include Chef::Mixin::EnforceOwnershipAndPermissions @@ -75,7 +74,7 @@ class Chef a.assertion do if @current_resource.to @current_resource.link_type == @new_resource.link_type and - (@current_resource.link_type == :symbolic or @current_resource.to != "") + (@current_resource.link_type == :symbolic or @current_resource.to != "") else true end @@ -118,7 +117,7 @@ class Chef end if @new_resource.link_type == :symbolic converge_by("create symlink at #{@new_resource.target_file} to #{@new_resource.to}") do - file_class.symlink(canonicalize(@new_resource.to),@new_resource.target_file) + file_class.symlink(canonicalize(@new_resource.to), @new_resource.target_file) Chef::Log.debug("#{@new_resource} created #{@new_resource.link_type} link from #{@new_resource.target_file} -> #{@new_resource.to}") Chef::Log.info("#{@new_resource} created") end diff --git a/lib/chef/provider/log.rb b/lib/chef/provider/log.rb index eef4077c07..40e2ced1be 100644 --- a/lib/chef/provider/log.rb +++ b/lib/chef/provider/log.rb @@ -17,14 +17,10 @@ # class Chef - class Provider - class Log - # Chef log provider, allows logging to chef's logs from recipes class ChefLog < Chef::Provider - provides :log def whyrun_supported? @@ -47,11 +43,7 @@ class Chef Chef::Log.send(@new_resource.level, @new_resource.message) @new_resource.updated_by_last_action(true) end - end - end - end - end diff --git a/lib/chef/provider/lwrp_base.rb b/lib/chef/provider/lwrp_base.rb index f5ba30ba15..26f7eb89d7 100644 --- a/lib/chef/provider/lwrp_base.rb +++ b/lib/chef/provider/lwrp_base.rb @@ -24,11 +24,9 @@ require "chef/dsl/include_recipe" class Chef class Provider - # == Chef::Provider::LWRPBase # Base class from which LWRP providers inherit. class LWRPBase < Provider - include Chef::DSL::Recipe # These were previously provided by Chef::Mixin::RecipeDefinitionDSLCore. diff --git a/lib/chef/provider/mdadm.rb b/lib/chef/provider/mdadm.rb index f99dcc1fd3..974527a6b5 100644 --- a/lib/chef/provider/mdadm.rb +++ b/lib/chef/provider/mdadm.rb @@ -22,7 +22,6 @@ require "chef/provider" class Chef class Provider class Mdadm < Chef::Provider - provides :mdadm def popen4 @@ -39,7 +38,7 @@ class Chef Chef::Log.debug("#{@new_resource} checking for software raid device #{@current_resource.raid_device}") device_not_found = 4 - mdadm = shell_out!("mdadm --detail --test #{@new_resource.raid_device}", :returns => [0,device_not_found]) + mdadm = shell_out!("mdadm --detail --test #{@new_resource.raid_device}", :returns => [0, device_not_found]) exists = (mdadm.status == 0) @current_resource.exists(exists) end @@ -86,7 +85,6 @@ class Chef Chef::Log.debug("#{@new_resource} raid device doesn't exist (#{@new_resource.raid_device}) - not stopping") end end - end end end diff --git a/lib/chef/provider/mount/aix.rb b/lib/chef/provider/mount/aix.rb index 9df2e63bf4..4f53f39e5d 100644 --- a/lib/chef/provider/mount/aix.rb +++ b/lib/chef/provider/mount/aix.rb @@ -42,7 +42,7 @@ class Chef # lsfs o/p = #MountPoint:Device:Vfs:Nodename:Type:Size:Options:AutoMount:Acct # search only for current mount point - shell_out("lsfs -c #{@new_resource.mount_point}").stdout.each_line do | line | + shell_out("lsfs -c #{@new_resource.mount_point}").stdout.each_line do |line| case line when /^#\s/ next @@ -61,7 +61,7 @@ class Chef Chef::Log.debug("Found mount #{device_fstab} to #{@new_resource.mount_point} in /etc/filesystems") next when /^#{Regexp.escape(@new_resource.mount_point)}/ - enabled=false + enabled = false Chef::Log.debug("Found conflicting mount point #{@new_resource.mount_point} in /etc/filesystems") end end @@ -167,13 +167,12 @@ class Chef end end ::File.open("/etc/filesystems", "w") do |fstab| - contents.each { |line| fstab.puts line} + contents.each { |line| fstab.puts line } end else Chef::Log.debug("#{@new_resource} is not enabled - nothing to do") end end - end end end diff --git a/lib/chef/provider/mount/mount.rb b/lib/chef/provider/mount/mount.rb index 0daacbf96d..c4f07c73e9 100644 --- a/lib/chef/provider/mount/mount.rb +++ b/lib/chef/provider/mount/mount.rb @@ -23,7 +23,6 @@ class Chef class Provider class Mount class Mount < Chef::Provider::Mount - provides :mount def initialize(new_resource, run_context) @@ -170,7 +169,7 @@ class Chef found = false ::File.readlines("/etc/fstab").reverse_each do |line| if !found && line =~ /^#{device_fstab_regex}\s+#{Regexp.escape(@new_resource.mount_point)}\s/ - found = true + found = true Chef::Log.debug("#{@new_resource} is removed from fstab") next else @@ -179,7 +178,7 @@ class Chef end ::File.open("/etc/fstab", "w") do |fstab| - contents.reverse_each { |line| fstab.puts line} + contents.reverse_each { |line| fstab.puts line } end else Chef::Log.debug("#{@new_resource} is not enabled - nothing to do") @@ -237,13 +236,13 @@ class Chef def device_mount_regex if network_device? # ignore trailing slash - Regexp.escape(device_real)+"/?" + Regexp.escape(device_real) + "/?" elsif ::File.symlink?(device_real) # This regular expression tries to match device_real. If that does not match it will try to match the target of device_real. # So given a symlink like this: # /dev/mapper/vgroot-tmp.vol -> /dev/dm-9 # First it will try to match "/dev/mapper/vgroot-tmp.vol". If there is no match it will try matching for "/dev/dm-9". - "(?:#{Regexp.escape(device_real)}|#{Regexp.escape(::File.expand_path(::File.readlink(device_real),::File.dirname(device_real)))})" + "(?:#{Regexp.escape(device_real)}|#{Regexp.escape(::File.expand_path(::File.readlink(device_real), ::File.dirname(device_real)))})" else Regexp.escape(device_real) end @@ -263,7 +262,6 @@ class Chef @current_resource.dump == @new_resource.dump and @current_resource.pass == @new_resource.pass end - end end end diff --git a/lib/chef/provider/mount/solaris.rb b/lib/chef/provider/mount/solaris.rb index 4d2381b6d8..a5a7a327cb 100644 --- a/lib/chef/provider/mount/solaris.rb +++ b/lib/chef/provider/mount/solaris.rb @@ -236,7 +236,7 @@ class Chef found = false ::File.readlines(VFSTAB).reverse_each do |line| if !found && line =~ /^#{device_regex}\s+\S+\s+#{Regexp.escape(mount_point)}/ - found = true + found = true Chef::Log.debug("#{new_resource} is removed from vfstab") next end diff --git a/lib/chef/provider/mount/windows.rb b/lib/chef/provider/mount/windows.rb index 3ffe326cac..fd66893c86 100644 --- a/lib/chef/provider/mount/windows.rb +++ b/lib/chef/provider/mount/windows.rb @@ -26,7 +26,6 @@ class Chef class Provider class Mount class Windows < Chef::Provider::Mount - provides :mount, os: "windows" def is_volume(name) @@ -79,7 +78,6 @@ class Chef Chef::Log.debug("#{@new_resource} is not mounted at #{@new_resource.mount_point}") end end - end end end diff --git a/lib/chef/provider/osx_profile.rb b/lib/chef/provider/osx_profile.rb index 2f5454ac15..fd788b85c4 100644 --- a/lib/chef/provider/osx_profile.rb +++ b/lib/chef/provider/osx_profile.rb @@ -51,7 +51,7 @@ class Chef @new_profile_identifier = @new_profile_hash["PayloadIdentifier"] else @new_profile_identifier = @new_resource.identifier || - @new_resource.profile_name + @new_resource.profile_name end if all_profiles.empty? @@ -62,7 +62,6 @@ class Chef end end @current_resource.profile(current_profile) - end def define_resource_requirements @@ -70,15 +69,15 @@ class Chef if @new_profile_identifier a.assertion { !@new_profile_identifier.nil? and - !@new_profile_identifier.end_with?(".mobileconfig") and - /^\w+(?:\.\w+)+$/.match(@new_profile_identifier) + !@new_profile_identifier.end_with?(".mobileconfig") and + /^\w+(?:\.\w+)+$/.match(@new_profile_identifier) } a.failure_message RuntimeError, "when removing using the identifier attribute, it must match the profile identifier" else - new_profile_name = @new_resource.profile_name + new_profile_name = @new_resource.profile_name a.assertion { !new_profile_name.end_with?(".mobileconfig") and - /^\w+(?:\.\w+)+$/.match(new_profile_name) + /^\w+(?:\.\w+)+$/.match(new_profile_name) } a.failure_message RuntimeError, "When removing by resource name, it must match the profile identifier " end @@ -206,7 +205,7 @@ class Chef shellout_results.exitstatus end - def get_installed_profiles(update=nil) + def get_installed_profiles(update = nil) if update node.run_state[:config_profiles] = query_installed_profiles else @@ -251,7 +250,6 @@ class Chef end end end - end end end diff --git a/lib/chef/provider/package.rb b/lib/chef/provider/package.rb index a051a5fedd..2ccf56f3d7 100644 --- a/lib/chef/provider/package.rb +++ b/lib/chef/provider/package.rb @@ -74,7 +74,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 { candidates_exist_for_all_uninstalled? || new_resource.source } 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 @@ -147,7 +147,7 @@ class Chef def action_remove if removing_package? - description = @new_resource.version ? "version #{@new_resource.version} of " : "" + description = @new_resource.version ? "version #{@new_resource.version} of " : "" converge_by("remove #{description}package #{@current_resource.package_name}") do multipackage_api_adapter(@current_resource.package_name, @new_resource.version) do |name, version| remove_package(name, version) @@ -208,7 +208,6 @@ class Chef preseed_package(preseed_file) multipackage_api_adapter(@new_resource.package_name, @current_resource.version) do |name, version| reconfig_package(name, version) - end Chef::Log.info("#{@new_resource} reconfigured") end @@ -558,7 +557,7 @@ class Chef # @param args [String] variable number of string arguments # @return [String] nicely concatenated string or empty string def a_to_s(*args) - args.reject {|i| i.nil? || i == "" }.join(" ") + args.reject { |i| i.nil? || i == "" }.join(" ") end end end diff --git a/lib/chef/provider/package/aix.rb b/lib/chef/provider/package/aix.rb index 732ca00b71..043c8f1567 100644 --- a/lib/chef/provider/package/aix.rb +++ b/lib/chef/provider/package/aix.rb @@ -25,7 +25,6 @@ class Chef class Provider class Package class Aix < Chef::Provider::Package - provides :package, os: "aix" provides :bff_package, os: "aix" @@ -53,7 +52,7 @@ class Chef if @package_source_found Chef::Log.debug("#{@new_resource} checking pkg status") ret = shell_out_with_timeout("installp -L -d #{@new_resource.source}") - ret.stdout.each_line do | line | + ret.stdout.each_line do |line| case line when /#{@new_resource.package_name}:/ fields = line.split(":") @@ -66,7 +65,7 @@ class Chef Chef::Log.debug("#{@new_resource} checking install state") ret = shell_out_with_timeout("lslpp -lcq #{@current_resource.package_name}") - ret.stdout.each_line do | line | + ret.stdout.each_line do |line| case line when /#{@current_resource.package_name}/ fields = line.split(":") @@ -85,7 +84,7 @@ class Chef def candidate_version return @candidate_version if @candidate_version ret = shell_out_with_timeout("installp -L -d #{@new_resource.source}") - ret.stdout.each_line do | line | + ret.stdout.each_line do |line| case line when /\w:#{Regexp.escape(@new_resource.package_name)}:(.*)/ fields = line.split(":") @@ -129,7 +128,6 @@ class Chef Chef::Log.debug("#{@new_resource} removed version #{@new_resource.version}") end end - end end end diff --git a/lib/chef/provider/package/apt.rb b/lib/chef/provider/package/apt.rb index ac730202b8..73c03c4ff7 100644 --- a/lib/chef/provider/package/apt.rb +++ b/lib/chef/provider/package/apt.rb @@ -24,7 +24,6 @@ class Chef class Provider class Package class Apt < Chef::Provider::Package - provides :package, platform_family: "debian" provides :apt_package, os: "linux" @@ -178,7 +177,6 @@ class Chef def run_noninteractive(command) shell_out_with_timeout!(command, :env => { "DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }) end - end end end diff --git a/lib/chef/provider/package/chocolatey.rb b/lib/chef/provider/package/chocolatey.rb index 0d320a3aad..14613b0218 100644 --- a/lib/chef/provider/package/chocolatey.rb +++ b/lib/chef/provider/package/chocolatey.rb @@ -63,7 +63,7 @@ EOS # 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 { candidates_exist_for_all_uninstalled? } 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 @@ -84,8 +84,8 @@ EOS def install_package(names, versions) name_versions_to_install = desired_name_versions.select { |n, v| lowercase_names(names).include?(n) } - name_nil_versions = name_versions_to_install.select { |n,v| v.nil? } - name_has_versions = name_versions_to_install.reject { |n,v| v.nil? } + name_nil_versions = name_versions_to_install.select { |n, v| v.nil? } + name_has_versions = name_versions_to_install.reject { |n, v| v.nil? } # choco does not support installing multiple packages with version pins name_has_versions.each do |name, version| @@ -106,8 +106,8 @@ EOS def upgrade_package(names, versions) name_versions_to_install = desired_name_versions.select { |n, v| lowercase_names(names).include?(n) } - name_nil_versions = name_versions_to_install.select { |n,v| v.nil? } - name_has_versions = name_versions_to_install.reject { |n,v| v.nil? } + name_nil_versions = name_versions_to_install.select { |n, v| v.nil? } + name_has_versions = name_versions_to_install.reject { |n, v| v.nil? } # choco does not support installing multiple packages with version pins name_has_versions.each do |name, version| @@ -220,7 +220,7 @@ EOS # @param args [String] variable number of string arguments # @return [String] nicely concatenated string or empty string def args_to_string(*args) - args.reject {|i| i.nil? || i == "" }.join(" ") + args.reject { |i| i.nil? || i == "" }.join(" ") end # Available packages in chocolatey as a Hash of names mapped to versions diff --git a/lib/chef/provider/package/dpkg.rb b/lib/chef/provider/package/dpkg.rb index f57b779ffa..a19e1b4650 100644 --- a/lib/chef/provider/package/dpkg.rb +++ b/lib/chef/provider/package/dpkg.rb @@ -145,14 +145,14 @@ class Chef # # @return [Boolean] True if all sources exist def source_files_exist? - resolved_source_array.all? {|s| s && ::File.exist?(s) } + resolved_source_array.all? { |s| s && ::File.exist?(s) } end # Helper to return all the nanes of the missing sources for error messages. # # @return [Array] Array of missing sources def missing_sources - resolved_source_array.select {|s| s.nil? || !::File.exist?(s) } + resolved_source_array.select { |s| s.nil? || !::File.exist?(s) } end def current_package_name_array @@ -187,14 +187,14 @@ class Chef def name_candidate_version @name_candidate_version ||= begin - Hash[name_pkginfo.map {|k, v| [k, v ? v.split("\t")[1].strip : nil] }] + Hash[name_pkginfo.map { |k, v| [k, v ? v.split("\t")[1].strip : nil] }] end end def name_package_name @name_package_name ||= begin - Hash[name_pkginfo.map {|k, v| [k, v ? v.split("\t")[0] : nil] }] + Hash[name_pkginfo.map { |k, v| [k, v ? v.split("\t")[0] : nil] }] end end @@ -219,7 +219,6 @@ class Chef def installing? [:install, :upgrade].include?(action) end - end end end diff --git a/lib/chef/provider/package/easy_install.rb b/lib/chef/provider/package/easy_install.rb index e4752cf3e7..7eab47f17c 100644 --- a/lib/chef/provider/package/easy_install.rb +++ b/lib/chef/provider/package/easy_install.rb @@ -24,7 +24,6 @@ class Chef class Provider class Package class EasyInstall < Chef::Provider::Package - provides :easy_install_package def install_check(name) @@ -32,10 +31,10 @@ class Chef begin # first check to see if we can import it - output = shell_out_with_timeout!("#{python_binary_path} -c \"import #{name}\"", :returns=>[0,1]).stderr + output = shell_out_with_timeout!("#{python_binary_path} -c \"import #{name}\"", :returns => [0, 1]).stderr if output.include? "ImportError" # then check to see if its on the path - output = shell_out_with_timeout!("#{python_binary_path} -c \"import sys; print sys.path\"", :returns=>[0,1]).stdout + output = shell_out_with_timeout!("#{python_binary_path} -c \"import sys; print sys.path\"", :returns => [0, 1]).stdout if output.downcase.include? "#{name.downcase}" check = true end @@ -75,9 +74,9 @@ class Chef output = shell_out_with_timeout!("#{python_binary_path} -c \"import #{module_name}; print #{module_name}.__version__\"").stdout package_version = output.strip rescue - output = shell_out_with_timeout!("#{python_binary_path} -c \"import sys; print sys.path\"", :returns=>[0,1]).stdout + output = shell_out_with_timeout!("#{python_binary_path} -c \"import sys; print sys.path\"", :returns => [0, 1]).stdout - output_array = output.gsub(/[\[\]]/,"").split(/\s*,\s*/) + output_array = output.gsub(/[\[\]]/, "").split(/\s*,\s*/) package_path = "" output_array.each do |entry| @@ -103,12 +102,12 @@ class Chef end def candidate_version - return @candidate_version if @candidate_version + return @candidate_version if @candidate_version # do a dry run to get the latest version - result = shell_out_with_timeout!("#{easy_install_binary_path} -n #{@new_resource.package_name}", :returns=>[0,1]) - @candidate_version = result.stdout[/(.*)Best match: (.*) (.*)$/, 3] - @candidate_version + result = shell_out_with_timeout!("#{easy_install_binary_path} -n #{@new_resource.package_name}", :returns => [0, 1]) + @candidate_version = result.stdout[/(.*)Best match: (.*) (.*)$/, 3] + @candidate_version end def install_package(name, version) @@ -126,7 +125,6 @@ class Chef def purge_package(name, version) remove_package(name, version) end - end end end diff --git a/lib/chef/provider/package/freebsd/base.rb b/lib/chef/provider/package/freebsd/base.rb index 81c27845ba..b1952e7472 100644 --- a/lib/chef/provider/package/freebsd/base.rb +++ b/lib/chef/provider/package/freebsd/base.rb @@ -27,7 +27,6 @@ class Chef class Provider class Package module Freebsd - module PortsHelper def supports_ports? ::File.exist?("/usr/ports/Makefile") @@ -57,8 +56,8 @@ class Chef def makefile_variable_value(variable, dir = nil) options = dir ? { :cwd => dir } : {} - make_v = shell_out_with_timeout!("make -V #{variable}", options.merge!(:env => nil, :returns => [0,1])) - make_v.exitstatus.zero? ? make_v.stdout.strip.split($\).first : nil # $\ is the line separator, i.e. newline. + make_v = shell_out_with_timeout!("make -V #{variable}", options.merge!(:env => nil, :returns => [0, 1])) + make_v.exitstatus.zero? ? make_v.stdout.strip.split($\).first : nil # $\ is the line separator, i.e. newline. end end @@ -82,7 +81,6 @@ class Chef @current_resource end end - end end end diff --git a/lib/chef/provider/package/freebsd/pkg.rb b/lib/chef/provider/package/freebsd/pkg.rb index 339693a3d5..70e87ab7ee 100644 --- a/lib/chef/provider/package/freebsd/pkg.rb +++ b/lib/chef/provider/package/freebsd/pkg.rb @@ -41,7 +41,7 @@ class Chef Chef::Log.debug("#{@new_resource} installed from: #{@new_resource.source}") when /^\// - shell_out_with_timeout!("pkg_add #{file_candidate_version_path}", :env => { "PKG_PATH" => @new_resource.source , "LC_ALL"=>nil}).status + shell_out_with_timeout!("pkg_add #{file_candidate_version_path}", :env => { "PKG_PATH" => @new_resource.source , "LC_ALL" => nil }).status Chef::Log.debug("#{@new_resource} installed from: #{@new_resource.source}") else @@ -72,7 +72,7 @@ class Chef end def current_installed_version - pkg_info = shell_out_with_timeout!("pkg_info -E \"#{package_name}*\"", :env => nil, :returns => [0,1]) + pkg_info = shell_out_with_timeout!("pkg_info -E \"#{package_name}*\"", :env => nil, :returns => [0, 1]) pkg_info.stdout[/^#{Regexp.escape(package_name)}-(.+)/, 1] end @@ -106,7 +106,6 @@ class Chef def port_path port_dir @new_resource.package_name end - end end end diff --git a/lib/chef/provider/package/freebsd/pkgng.rb b/lib/chef/provider/package/freebsd/pkgng.rb index e3fa0ad571..9b5601feed 100644 --- a/lib/chef/provider/package/freebsd/pkgng.rb +++ b/lib/chef/provider/package/freebsd/pkgng.rb @@ -23,7 +23,6 @@ class Chef class Package module Freebsd class Pkgng < Base - def install_package(name, version) unless @current_resource.version case @new_resource.source @@ -44,7 +43,7 @@ class Chef end def current_installed_version - pkg_info = shell_out_with_timeout!("pkg info \"#{@new_resource.package_name}\"", :env => nil, :returns => [0,70]) + pkg_info = shell_out_with_timeout!("pkg info \"#{@new_resource.package_name}\"", :env => nil, :returns => [0, 70]) pkg_info.stdout[/^Version +: (.+)$/, 1] end @@ -70,7 +69,6 @@ class Chef def repo_regex /(-r\s?\S+)\b/ end - end end end diff --git a/lib/chef/provider/package/freebsd/port.rb b/lib/chef/provider/package/freebsd/port.rb index 39b7b00988..3eb3c5ab01 100644 --- a/lib/chef/provider/package/freebsd/port.rb +++ b/lib/chef/provider/package/freebsd/port.rb @@ -35,9 +35,9 @@ class Chef def current_installed_version pkg_info = if @new_resource.supports_pkgng? - shell_out_with_timeout!("pkg info \"#{@new_resource.package_name}\"", :env => nil, :returns => [0,70]) + shell_out_with_timeout!("pkg info \"#{@new_resource.package_name}\"", :env => nil, :returns => [0, 70]) else - shell_out_with_timeout!("pkg_info -E \"#{@new_resource.package_name}*\"", :env => nil, :returns => [0,1]) + shell_out_with_timeout!("pkg_info -E \"#{@new_resource.package_name}*\"", :env => nil, :returns => [0, 1]) end pkg_info.stdout[/^#{Regexp.escape(@new_resource.package_name)}-(.+)/, 1] end diff --git a/lib/chef/provider/package/homebrew.rb b/lib/chef/provider/package/homebrew.rb index c032881e70..a7475ce44e 100644 --- a/lib/chef/provider/package/homebrew.rb +++ b/lib/chef/provider/package/homebrew.rb @@ -25,7 +25,6 @@ class Chef class Provider class Package class Homebrew < Chef::Provider::Package - provides :package, os: "darwin", override: true provides :homebrew_package @@ -130,7 +129,6 @@ class Chef output = shell_out_with_timeout!(command, :timeout => 1800, :user => homebrew_uid, :environment => { "HOME" => homebrew_user.dir, "RUBYOPT" => nil }) output.stdout.chomp end - end end end diff --git a/lib/chef/provider/package/ips.rb b/lib/chef/provider/package/ips.rb index dc83e4aa08..79ae6f93aa 100644 --- a/lib/chef/provider/package/ips.rb +++ b/lib/chef/provider/package/ips.rb @@ -26,7 +26,6 @@ class Chef class Provider class Package class Ips < Chef::Provider::Package - provides :package, platform: %w{openindiana opensolaris omnios solaris2} provides :ips_package, os: "solaris2" diff --git a/lib/chef/provider/package/macports.rb b/lib/chef/provider/package/macports.rb index c7ea71ac8c..b781c91eb5 100644 --- a/lib/chef/provider/package/macports.rb +++ b/lib/chef/provider/package/macports.rb @@ -2,7 +2,6 @@ class Chef class Provider class Package class Macports < Chef::Provider::Package - provides :package, os: "darwin" provides :macports_package @@ -81,6 +80,7 @@ class Chef end private + def get_response_from_command(command) output = nil status = shell_out_with_timeout(command) diff --git a/lib/chef/provider/package/openbsd.rb b/lib/chef/provider/package/openbsd.rb index 3e209bcf99..8855d0381d 100644 --- a/lib/chef/provider/package/openbsd.rb +++ b/lib/chef/provider/package/openbsd.rb @@ -29,7 +29,6 @@ class Chef class Provider class Package class Openbsd < Chef::Provider::Package - provides :package, os: "openbsd" provides :openbsd_package @@ -72,7 +71,7 @@ class Chef if parts = name.match(/^(.+?)--(.+)/) # use double-dash for stems with flavors, see man page for pkg_add name = parts[1] end - shell_out_with_timeout!("pkg_add -r #{name}#{version_string(version)}", :env => {"PKG_PATH" => pkg_path}).status + shell_out_with_timeout!("pkg_add -r #{name}#{version_string(version)}", :env => { "PKG_PATH" => pkg_path }).status Chef::Log.debug("#{new_resource.package_name} installed") end end @@ -92,7 +91,7 @@ class Chef else name = new_resource.package_name end - pkg_info = shell_out_with_timeout!("pkg_info -e \"#{name}->0\"", :env => nil, :returns => [0,1]) + pkg_info = shell_out_with_timeout!("pkg_info -e \"#{name}->0\"", :env => nil, :returns => [0, 1]) result = pkg_info.stdout[/^inst:#{Regexp.escape(name)}-(.+?)\s/, 1] Chef::Log.debug("installed_version of '#{new_resource.package_name}' is '#{result}'") result @@ -101,7 +100,7 @@ class Chef def candidate_version @candidate_version ||= begin results = [] - shell_out_with_timeout!("pkg_info -I \"#{new_resource.package_name}#{version_string(new_resource.version)}\"", :env => nil, :returns => [0,1]).stdout.each_line do |line| + shell_out_with_timeout!("pkg_info -I \"#{new_resource.package_name}#{version_string(new_resource.version)}\"", :env => nil, :returns => [0, 1]).stdout.each_line do |line| if parts = new_resource.package_name.match(/^(.+?)--(.+)/) results << line[/^#{Regexp.escape(parts[1])}-(.+?)\s/, 1] else @@ -129,7 +128,6 @@ class Chef def pkg_path ENV["PKG_PATH"] || "http://ftp.OpenBSD.org/pub/#{node.kernel.name}/#{node.kernel.release}/packages/#{node.kernel.machine}/" end - end end end diff --git a/lib/chef/provider/package/pacman.rb b/lib/chef/provider/package/pacman.rb index ad7db25f49..f9b8abcac1 100644 --- a/lib/chef/provider/package/pacman.rb +++ b/lib/chef/provider/package/pacman.rb @@ -24,7 +24,6 @@ class Chef class Provider class Package class Pacman < Chef::Provider::Package - provides :package, platform: "arch" provides :pacman_package, os: "linux" @@ -52,14 +51,14 @@ class Chef def candidate_version return @candidate_version if @candidate_version - repos = ["extra","core","community"] + repos = ["extra", "core", "community"] if(::File.exists?("/etc/pacman.conf")) pacman = ::File.read("/etc/pacman.conf") repos = pacman.scan(/\[(.+)\]/).flatten end - package_repos = repos.map {|r| Regexp.escape(r) }.join("|") + package_repos = repos.map { |r| Regexp.escape(r) }.join("|") status = shell_out_with_timeout("pacman -Sl") status.stdout.each_line do |line| @@ -80,7 +79,6 @@ class Chef end @candidate_version - end def install_package(name, version) @@ -98,7 +96,6 @@ class Chef def purge_package(name, version) remove_package(name, version) end - end end end diff --git a/lib/chef/provider/package/paludis.rb b/lib/chef/provider/package/paludis.rb index 51437025e1..5cd0151d12 100644 --- a/lib/chef/provider/package/paludis.rb +++ b/lib/chef/provider/package/paludis.rb @@ -23,7 +23,6 @@ class Chef class Provider class Package class Paludis < Chef::Provider::Package - provides :package, platform: "exherbo" provides :paludis_package, os: "linux" @@ -59,7 +58,7 @@ class Chef else pkg = "#{@new_resource.package_name}" end - shell_out!("cave -L warning resolve -x#{expand_options(@new_resource.options)} \"#{pkg}\"",:timeout => @new_resource.timeout) + shell_out!("cave -L warning resolve -x#{expand_options(@new_resource.options)} \"#{pkg}\"", :timeout => @new_resource.timeout) end def upgrade_package(name, version) @@ -79,7 +78,6 @@ class Chef def purge_package(name, version) remove_package(name, version) end - end end end diff --git a/lib/chef/provider/package/portage.rb b/lib/chef/provider/package/portage.rb index 4d99d75ca2..0696863a82 100644 --- a/lib/chef/provider/package/portage.rb +++ b/lib/chef/provider/package/portage.rb @@ -25,7 +25,6 @@ class Chef class Provider class Package class Portage < Chef::Provider::Package - provides :package, platform: "gentoo" provides :portage_package @@ -35,11 +34,11 @@ class Chef @current_resource = Chef::Resource::Package.new(@new_resource.name) @current_resource.package_name(@new_resource.package_name) - category, pkg = %r{^#{PACKAGE_NAME_PATTERN}$}.match(@new_resource.package_name)[1,2] + category, pkg = %r{^#{PACKAGE_NAME_PATTERN}$}.match(@new_resource.package_name)[1, 2] globsafe_category = category ? Chef::Util::PathHelper.escape_glob(category) : nil globsafe_pkg = Chef::Util::PathHelper.escape_glob(pkg) - possibilities = Dir["/var/db/pkg/#{globsafe_category || "*"}/#{globsafe_pkg}-*"].map {|d| d.sub(%r{/var/db/pkg/}, "") } + possibilities = Dir["/var/db/pkg/#{globsafe_category || "*"}/#{globsafe_pkg}-*"].map { |d| d.sub(%r{/var/db/pkg/}, "") } versions = possibilities.map do |entry| if(entry =~ %r{[^/]+/#{Regexp.escape(pkg)}\-(\d[\.\d]*((_(alpha|beta|pre|rc|p)\d*)*)?(-r\d+)?)}) [$&, $1] @@ -47,8 +46,8 @@ class Chef end.compact if versions.size > 1 - atoms = versions.map {|v| v.first }.sort - categories = atoms.map {|v| v.split("/")[0] }.uniq + atoms = versions.map { |v| v.first }.sort + categories = atoms.map { |v| v.split("/")[0] }.uniq if !category && categories.size > 1 raise Chef::Exceptions::Package, "Multiple packages found for #{@new_resource.package_name}: #{atoms.join(" ")}. Specify a category." end @@ -103,7 +102,6 @@ class Chef end @candidate_version - end def install_package(name, version) @@ -134,7 +132,6 @@ class Chef def purge_package(name, version) remove_package(name, version) end - end end end diff --git a/lib/chef/provider/package/rpm.rb b/lib/chef/provider/package/rpm.rb index c72c9559c8..16dd960c7f 100644 --- a/lib/chef/provider/package/rpm.rb +++ b/lib/chef/provider/package/rpm.rb @@ -24,7 +24,6 @@ class Chef class Provider class Package class Rpm < Chef::Provider::Package - provides :rpm_package, os: [ "linux", "aix" ] include Chef::Mixin::GetSourceFromPackage diff --git a/lib/chef/provider/package/rubygems.rb b/lib/chef/provider/package/rubygems.rb index b176114a15..b13505af01 100644 --- a/lib/chef/provider/package/rubygems.rb +++ b/lib/chef/provider/package/rubygems.rb @@ -47,7 +47,7 @@ class Chef # alternate value and overwrite it with the defaults. Gem.configuration - DEFAULT_UNINSTALLER_OPTS = {:ignore => true, :executables => true} + DEFAULT_UNINSTALLER_OPTS = { :ignore => true, :executables => true } ## # The paths where rubygems should search for installed gems. @@ -133,7 +133,7 @@ class Chef def candidate_version_from_file(gem_dependency, source) spec = spec_from_file(source) if spec.satisfies_requirement?(gem_dependency) - logger.debug {"#{@new_resource} found candidate gem version #{spec.version} from local gem package #{source}"} + logger.debug { "#{@new_resource} found candidate gem version #{spec.version} from local gem package #{source}" } spec.version else # This is probably going to end badly... @@ -189,7 +189,7 @@ class Chef # === Options # :sources rubygems servers to use # Other options are passed to Gem::DependencyInstaller.new - def install(gem_dependency, options={}) + def install(gem_dependency, options = {}) with_gem_sources(*options.delete(:sources)) do with_correct_verbosity do dependency_installer(options).install(gem_dependency) @@ -203,7 +203,7 @@ class Chef # Otherwise, all versions are uninstalled. # === Options # Options are passed to Gem::Uninstaller.new - def uninstall(gem_name, gem_version=nil, opts={}) + def uninstall(gem_name, gem_version = nil, opts = {}) gem_version ? opts[:version] = gem_version : opts[:all] = true with_correct_verbosity do uninstaller(gem_name, opts).uninstall @@ -218,11 +218,11 @@ class Chef yield end - def dependency_installer(opts={}) + def dependency_installer(opts = {}) Gem::DependencyInstaller.new(opts) end - def uninstaller(gem_name, opts={}) + def uninstaller(gem_name, opts = {}) Gem::Uninstaller.new(gem_name, DEFAULT_UNINSTALLER_OPTS.merge(opts)) end @@ -231,11 +231,9 @@ class Chef def logger Chef::Log.logger end - end class CurrentGemEnvironment < GemEnvironment - def gem_paths Gem.path end @@ -253,7 +251,6 @@ class Chef find_newest_remote_version(gem_dependency, *sources) end end - end class AlternateGemEnvironment < GemEnvironment @@ -343,7 +340,6 @@ class Chef end end end - end attr_reader :gem_env @@ -358,7 +354,7 @@ class Chef include Chef::Mixin::GetSourceFromPackage - def initialize(new_resource, run_context=nil) + def initialize(new_resource, run_context = nil) super @cleanup_gem_env = true if new_resource.gem_binary @@ -398,7 +394,7 @@ class Chef Chef::Log.debug("#{@new_resource} detected omnibus installation in #{RbConfig::CONFIG['bindir']}") # Omnibus installs to a static path because of linking on unix, find it. true - elsif RbConfig::CONFIG["bindir"].sub(/^[\w]:/, "") == "/opscode/chef/embedded/bin" + elsif RbConfig::CONFIG["bindir"].sub(/^[\w]:/, "") == "/opscode/chef/embedded/bin" Chef::Log.debug("#{@new_resource} detected omnibus installation in #{RbConfig::CONFIG['bindir']}") # windows, with the drive letter removed true @@ -436,7 +432,7 @@ class Chef # is the current version if !matching_installed_versions.empty? gemspec = matching_installed_versions.last - logger.debug { "#{@new_resource} found installed gem #{gemspec.name} version #{gemspec.version} matching #{gem_dependency}"} + logger.debug { "#{@new_resource} found installed gem #{gemspec.name} version #{gemspec.version} matching #{gem_dependency}" } gemspec # If no version matching the requirements exists, the latest installed # version is the current version. @@ -445,7 +441,7 @@ class Chef logger.debug { "#{@new_resource} newest installed version of gem #{gemspec.name} is #{gemspec.version}" } gemspec else - logger.debug { "#{@new_resource} no installed version found for #{gem_dependency}"} + logger.debug { "#{@new_resource} no installed version found for #{gem_dependency}" } nil end end @@ -519,7 +515,7 @@ class Chef elsif @new_resource.gem_binary.nil? @gem_env.install(@new_resource.source) else - install_via_gem_command(name,version) + install_via_gem_command(name, version) end true end @@ -538,9 +534,9 @@ class Chef src = @new_resource.source && " --source=#{@new_resource.source} --source=https://rubygems.org" end if !version.nil? && version.length > 0 - shell_out_with_timeout!("#{gem_binary_path} install #{name} -q --no-rdoc --no-ri -v \"#{version}\"#{src}#{opts}", :env=>nil) + shell_out_with_timeout!("#{gem_binary_path} install #{name} -q --no-rdoc --no-ri -v \"#{version}\"#{src}#{opts}", :env => nil) else - shell_out_with_timeout!("#{gem_binary_path} install \"#{name}\" -q --no-rdoc --no-ri #{src}#{opts}", :env=>nil) + shell_out_with_timeout!("#{gem_binary_path} install \"#{name}\" -q --no-rdoc --no-ri #{src}#{opts}", :env => nil) end end @@ -564,9 +560,9 @@ class Chef def uninstall_via_gem_command(name, version) if version - shell_out_with_timeout!("#{gem_binary_path} uninstall #{name} -q -x -I -v \"#{version}\"#{opts}", :env=>nil) + shell_out_with_timeout!("#{gem_binary_path} uninstall #{name} -q -x -I -v \"#{version}\"#{opts}", :env => nil) else - shell_out_with_timeout!("#{gem_binary_path} uninstall #{name} -q -x -I -a#{opts}", :env=>nil) + shell_out_with_timeout!("#{gem_binary_path} uninstall #{name} -q -x -I -a#{opts}", :env => nil) end end @@ -579,7 +575,6 @@ class Chef def opts expand_options(@new_resource.options) end - end end end diff --git a/lib/chef/provider/package/smartos.rb b/lib/chef/provider/package/smartos.rb index 5ef8ae2cbe..ba14f25aff 100644 --- a/lib/chef/provider/package/smartos.rb +++ b/lib/chef/provider/package/smartos.rb @@ -43,7 +43,7 @@ class Chef def check_package_state(name) Chef::Log.debug("#{@new_resource} checking package #{name}") version = nil - info = shell_out_with_timeout!("/opt/local/sbin/pkg_info", "-E", "#{name}*", :env => nil, :returns => [0,1]) + info = shell_out_with_timeout!("/opt/local/sbin/pkg_info", "-E", "#{name}*", :env => nil, :returns => [0, 1]) if info.stdout version = info.stdout[/^#{@new_resource.package_name}-(.+)/, 1] @@ -58,7 +58,7 @@ class Chef return @candidate_version if @candidate_version name = nil version = nil - pkg = shell_out_with_timeout!("/opt/local/bin/pkgin", "se", new_resource.package_name, :env => nil, :returns => [0,1]) + pkg = shell_out_with_timeout!("/opt/local/bin/pkgin", "se", new_resource.package_name, :env => nil, :returns => [0, 1]) pkg.stdout.each_line do |line| case line when /^#{new_resource.package_name}/ @@ -85,7 +85,6 @@ class Chef package = "#{name}" out = shell_out_with_timeout!("/opt/local/bin/pkgin", "-y", "remove", package, :env => nil) end - end end end diff --git a/lib/chef/provider/package/solaris.rb b/lib/chef/provider/package/solaris.rb index 1c393e6a20..3afa3e8e7a 100644 --- a/lib/chef/provider/package/solaris.rb +++ b/lib/chef/provider/package/solaris.rb @@ -24,7 +24,6 @@ class Chef class Provider class Package class Solaris < Chef::Provider::Package - include Chef::Mixin::GetSourceFromPackage provides :package, platform: "nexentacore" @@ -131,7 +130,6 @@ class Chef Chef::Log.debug("#{@new_resource} removed version #{@new_resource.version}") end end - end end end diff --git a/lib/chef/provider/package/windows.rb b/lib/chef/provider/package/windows.rb index c5aed43c9b..deac7364eb 100644 --- a/lib/chef/provider/package/windows.rb +++ b/lib/chef/provider/package/windows.rb @@ -79,7 +79,7 @@ class Chef if new_resource.installer_type new_resource.installer_type elsif source_location.nil? - inferred_registry_type + inferred_registry_type else basename = ::File.basename(source_location) file_extension = basename.split(".").last.downcase @@ -220,7 +220,7 @@ class Chef r.backup(false) if new_resource.remote_file_attributes - new_resource.remote_file_attributes.each do |(k,v)| + new_resource.remote_file_attributes.each do |(k, v)| r.send(k.to_sym, v) end end @@ -253,7 +253,6 @@ class Chef end end end - end end end diff --git a/lib/chef/provider/package/windows/msi.rb b/lib/chef/provider/package/windows/msi.rb index 62c3be1e25..ac771688e7 100644 --- a/lib/chef/provider/package/windows/msi.rb +++ b/lib/chef/provider/package/windows/msi.rb @@ -67,22 +67,22 @@ class Chef def install_package # We could use MsiConfigureProduct here, but we'll start off with msiexec Chef::Log.debug("#{new_resource} installing MSI package '#{new_resource.source}'") - shell_out!("msiexec /qn /i \"#{new_resource.source}\" #{expand_options(new_resource.options)}", {:timeout => new_resource.timeout, :returns => new_resource.returns}) + shell_out!("msiexec /qn /i \"#{new_resource.source}\" #{expand_options(new_resource.options)}", { :timeout => new_resource.timeout, :returns => new_resource.returns }) end def remove_package # We could use MsiConfigureProduct here, but we'll start off with msiexec if !new_resource.source.nil? && ::File.exist?(new_resource.source) Chef::Log.debug("#{new_resource} removing MSI package '#{new_resource.source}'") - shell_out!("msiexec /qn /x \"#{new_resource.source}\" #{expand_options(new_resource.options)}", {:timeout => new_resource.timeout, :returns => new_resource.returns}) + shell_out!("msiexec /qn /x \"#{new_resource.source}\" #{expand_options(new_resource.options)}", { :timeout => new_resource.timeout, :returns => new_resource.returns }) else uninstall_version = new_resource.version || installed_version uninstall_entries.select { |entry| [uninstall_version].flatten.include?(entry.display_version) } .map { |version| version.uninstall_string }.uniq.each do |uninstall_string| - Chef::Log.debug("#{new_resource} removing MSI package version using '#{uninstall_string}'") - uninstall_string += expand_options(new_resource.options) - uninstall_string += " /Q" unless uninstall_string =~ / \/Q\b/ - shell_out!(uninstall_string, {:timeout => new_resource.timeout, :returns => new_resource.returns}) + Chef::Log.debug("#{new_resource} removing MSI package version using '#{uninstall_string}'") + uninstall_string += expand_options(new_resource.options) + uninstall_string += " /Q" unless uninstall_string =~ / \/Q\b/ + shell_out!(uninstall_string, { :timeout => new_resource.timeout, :returns => new_resource.returns }) end end end diff --git a/lib/chef/provider/package/windows/registry_uninstall_entry.rb b/lib/chef/provider/package/windows/registry_uninstall_entry.rb index 952a0f76b9..43f40082f4 100644 --- a/lib/chef/provider/package/windows/registry_uninstall_entry.rb +++ b/lib/chef/provider/package/windows/registry_uninstall_entry.rb @@ -24,7 +24,6 @@ class Chef class Package class Windows class RegistryUninstallEntry - def self.find_entries(package_name) Chef::Log.debug("Finding uninstall entries for #{package_name}") entries = [] diff --git a/lib/chef/provider/package/yum.rb b/lib/chef/provider/package/yum.rb index a0629842f2..acb303cdea 100644 --- a/lib/chef/provider/package/yum.rb +++ b/lib/chef/provider/package/yum.rb @@ -27,13 +27,11 @@ class Chef class Provider class Package class Yum < Chef::Provider::Package - provides :package, platform_family: %w{rhel fedora} provides :yum_package, os: "linux" class RPMUtils class << self - # RPM::Version version_parse equivalent def version_parse(evr) return if evr.nil? @@ -63,7 +61,7 @@ class Chef end end - version = evr[lead,tail] + version = evr[lead, tail] if version.empty? version = nil end @@ -159,12 +157,12 @@ class Chef end # copy the segment but not the unmatched character that x_seg_pos will # refer to - x_comp = x[x_pos,x_seg_pos - x_pos] + x_comp = x[x_pos, x_seg_pos - x_pos] while (y_seg_pos <= y_pos_max) and isdigit(y[y_seg_pos]) y_seg_pos += 1 end - y_comp = y[y_pos,y_seg_pos - y_pos] + y_comp = y[y_pos, y_seg_pos - y_pos] else # we are comparing strings x_seg_is_num = false @@ -172,12 +170,12 @@ class Chef while (x_seg_pos <= x_pos_max) and isalpha(x[x_seg_pos]) x_seg_pos += 1 end - x_comp = x[x_pos,x_seg_pos - x_pos] + x_comp = x[x_pos, x_seg_pos - x_pos] while (y_seg_pos <= y_pos_max) and isalpha(y[y_seg_pos]) y_seg_pos += 1 end - y_comp = y[y_pos,y_seg_pos - y_pos] + y_comp = y[y_pos, y_seg_pos - y_pos] end # if y_seg_pos didn't advance in the above loop it means the segments are @@ -224,7 +222,6 @@ class Chef return -1 end end - end # self end # RPMUtils @@ -240,7 +237,7 @@ class Chef @r = args[2] else raise ArgumentError, "Expecting either 'epoch-version-release' or 'epoch, " + - "version, release'" + "version, release'" end end attr_reader :e, :v, :r @@ -286,7 +283,7 @@ class Chef # 2:1.2-1 == 2:1.2 # 2:1.2-1 == 2: # - def compare_versions(y, partial=false) + def compare_versions(y, partial = false) x = self # compare epoch @@ -344,12 +341,12 @@ class Chef e = args[1].to_i v = args[2] r = args[3] - @version = RPMVersion.new(e,v,r) + @version = RPMVersion.new(e, v, r) @a = args[4] @provides = args[5] else raise ArgumentError, "Expecting either 'name, epoch-version-release, arch, provides' " + - "or 'name, epoch, version, release, arch, provides'" + "or 'name, epoch, version, release, arch, provides'" end # We always have one, ourselves! @@ -429,11 +426,11 @@ class Chef e = args[1].to_i v = args[2] r = args[3] - @version = RPMVersion.new(e,v,r) + @version = RPMVersion.new(e, v, r) @flag = args[4] || :== else raise ArgumentError, "Expecting either 'name, epoch-version-release, flag' or " + - "'name, epoch, version, release, flag'" + "'name, epoch, version, release, flag'" end end attr_reader :name, :version, :flag @@ -690,15 +687,15 @@ class Chef when :installed reset_installed # fast - opts=" --installed" + opts = " --installed" when :all reset # medium - opts=" --options --installed-provides" + opts = " --options --installed-provides" when :provides reset # slow! - opts=" --options --all-provides" + opts = " --options --all-provides" else raise ArgumentError, "Unexpected value in next_refresh: #{@next_refresh}" end @@ -870,7 +867,7 @@ class Chef end # Check if a package-version.arch is available to install - def version_available?(package_name, desired_version, arch=nil) + def version_available?(package_name, desired_version, arch = nil) version(package_name, arch, true, false) do |v| return true if desired_version == v end @@ -879,7 +876,7 @@ class Chef end # Return the source repository for a package-version.arch - def package_repository(package_name, desired_version, arch=nil) + def package_repository(package_name, desired_version, arch = nil) package(package_name, arch, true, false) do |pkg| return pkg.repoid if desired_version == pkg.version.to_s end @@ -888,13 +885,13 @@ class Chef end # Return the latest available version for a package.arch - def available_version(package_name, arch=nil) + def available_version(package_name, arch = nil) version(package_name, arch, true, false) end alias :candidate_version :available_version # Return the currently installed version for a package.arch - def installed_version(package_name, arch=nil) + def installed_version(package_name, arch = nil) version(package_name, arch, false, true) end @@ -922,7 +919,7 @@ class Chef private - def version(package_name, arch=nil, is_available=false, is_installed=false) + def version(package_name, arch = nil, is_available = false, is_installed = false) package(package_name, arch, is_available, is_installed) do |pkg| if block_given? yield pkg.version.to_s @@ -939,7 +936,7 @@ class Chef end end - def package(package_name, arch=nil, is_available=false, is_installed=false) + def package(package_name, arch = nil, is_available = false, is_installed = false) refresh packages = @rpmdb[package_name] if packages @@ -983,7 +980,6 @@ class Chef return ret end - end # YumCache include Chef::Mixin::GetSourceFromPackage @@ -1049,7 +1045,7 @@ class Chef def yum_command(command) command = "#{yum_binary} #{command}" Chef::Log.debug("#{@new_resource}: yum command: \"#{command}\"") - status = shell_out_with_timeout(command, {:timeout => Chef::Config[:yum_timeout]}) + status = shell_out_with_timeout(command, { :timeout => Chef::Config[:yum_timeout] }) # This is fun: rpm can encounter errors in the %post/%postun scripts which aren't # considered fatal - meaning the rpm is still successfully installed. These issue @@ -1066,7 +1062,7 @@ class Chef if l =~ %r{^error: %(post|postun)\(.*\) scriptlet failed, exit status \d+$} Chef::Log.warn("#{@new_resource} caught non-fatal scriptlet issue: \"#{l}\". Can't trust yum exit status " + "so running install again to verify.") - status = shell_out_with_timeout(command, {:timeout => Chef::Config[:yum_timeout]}) + status = shell_out_with_timeout(command, { :timeout => Chef::Config[:yum_timeout] }) break end end @@ -1126,7 +1122,6 @@ class Chef end end - @current_resource = Chef::Resource::Package.new(@new_resource.name) @current_resource.package_name(@new_resource.package_name) @@ -1225,7 +1220,7 @@ class Chef else # we bail like yum when the package is older raise Chef::Exceptions::Package, "Installed package #{n}-#{current_version_array[idx]} is newer " + - "than candidate package #{n}-#{v}" + "than candidate package #{n}-#{v}" end end end @@ -1258,7 +1253,7 @@ class Chef yum_command("-d0 -e0 -y#{expand_options(@new_resource.options)} #{method} #{pkg_string}") else raise Chef::Exceptions::Package, "Version #{version} of #{name} not found. Did you specify both version " + - "and release? (version-release, e.g. 1.84-10.fc6)" + "and release? (version-release, e.g. 1.84-10.fc6)" end end @@ -1359,7 +1354,7 @@ class Chef # matching them up with an actual package so the standard resource handling can apply. # # There is currently no support for filename matching. - def parse_dependency(name,version) + def parse_dependency(name, version) # Transform the package_name into a requirement # If we are passed a version or a version constraint we have to assume it's a requirement first. If it can't be @@ -1412,10 +1407,9 @@ class Chef new_package_version = nil end - [new_package_name,new_package_version] + [new_package_name, new_package_version] end end - end end end diff --git a/lib/chef/provider/package/zypper.rb b/lib/chef/provider/package/zypper.rb index 5d42772a48..2441b46013 100644 --- a/lib/chef/provider/package/zypper.rb +++ b/lib/chef/provider/package/zypper.rb @@ -42,10 +42,10 @@ class Chef candidate_version = $1 Chef::Log.debug("#{new_resource} version #{$1}") when /^Installed: Yes$/ - is_installed=true + is_installed = true Chef::Log.debug("#{new_resource} is installed") when /^Status: out-of-date \(version (.+) installed\)$/ - current_version=$1 + current_version = $1 Chef::Log.debug("#{new_resource} out of date version #{$1}") end end diff --git a/lib/chef/provider/powershell_script.rb b/lib/chef/provider/powershell_script.rb index 77aaa080a9..5eb0e45f8d 100644 --- a/lib/chef/provider/powershell_script.rb +++ b/lib/chef/provider/powershell_script.rb @@ -22,7 +22,6 @@ require "chef/provider/windows_script" class Chef class Provider class PowershellScript < Chef::Provider::WindowsScript - provides :powershell_script, os: "windows" def initialize(new_resource, run_context) @@ -79,7 +78,7 @@ class Chef def validate_script_syntax! interpreter_arguments = default_interpreter_flags.join(" ") - Tempfile.open(["chef_powershell_script-user-code", ".ps1"]) do | user_script_file | + Tempfile.open(["chef_powershell_script-user-code", ".ps1"]) do |user_script_file| # Wrap the user's code in a PowerShell script block so that # it isn't executed. However, syntactically invalid script # in that block will still trigger a syntax error which is @@ -110,7 +109,7 @@ EOH # means a non-zero return and thus a syntactically invalid script. with_os_architecture(node, architecture: new_resource.architecture) do - shell_out!(validation_command, {returns: [0]}) + shell_out!(validation_command, { returns: [0] }) end end end @@ -146,7 +145,7 @@ EOH # executed, otherwise 0 or 1 based on whether $? is set to true # (success, where we return 0) or false (where we return 1). def wrapper_script -<<-EOH + <<-EOH # Chef Client wrapper for powershell_script resources # LASTEXITCODE can be uninitialized -- make it explictly 0 @@ -209,7 +208,6 @@ Write-Output $chefscriptresult exit $exitstatus EOH end - end end end diff --git a/lib/chef/provider/registry_key.rb b/lib/chef/provider/registry_key.rb index 3d3d2a01a4..9370009b63 100644 --- a/lib/chef/provider/registry_key.rb +++ b/lib/chef/provider/registry_key.rb @@ -28,7 +28,6 @@ require "chef/scan_access_control" require "chef/win32/registry" class Chef - class Provider class RegistryKey < Chef::Provider provides :registry_key @@ -72,22 +71,22 @@ 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 { registry.hive_exists?(@new_resource.key) } 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 { registry.key_exists?(@new_resource.key) } 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 { !registry.keys_missing?(@current_resource.key) || @new_resource.recursive } a.failure_message(Chef::Exceptions::Win32RegNoRecursive, "Intermediate keys missing but recursive is set to false") a.whyrun("Intermediate keys in #{@new_resource.key} go 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 { !registry.key_exists?(@new_resource.key) || !registry.has_subkeys?(@new_resource.key) || @new_resource.recursive } 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 @@ -149,7 +148,6 @@ class Chef end end end - end end end diff --git a/lib/chef/provider/remote_directory.rb b/lib/chef/provider/remote_directory.rb index 7479ef9e85..c85ef79998 100644 --- a/lib/chef/provider/remote_directory.rb +++ b/lib/chef/provider/remote_directory.rb @@ -106,7 +106,7 @@ class Chef if purge Dir.glob(::File.join(Chef::Util::PathHelper.escape_glob(path), "**", "*"), ::File::FNM_DOTMATCH).sort!.reverse!.each do |file| # skip '.' and '..' - next if [".",".."].include?(Pathname.new(file).basename().to_s) + next if [".", ".."].include?(Pathname.new(file).basename().to_s) # Clean the path. This is required because of the ::File.join file = Chef::Util::PathHelper.cleanpath(file) @@ -251,7 +251,7 @@ class Chef # Windows will handle inheritance. if dir == path rights.each do |r| - r = r.dup # do not update the new_resource + r = r.dup # do not update the new_resource permissions = r.delete(:permissions) principals = r.delete(:principals) res.rights(permissions, principals, r) @@ -275,7 +275,6 @@ class Chef alias_method :resource_for_directory, :directory_resource add_deprecation_warnings_for([:resource_for_directory]) - end end end diff --git a/lib/chef/provider/remote_file.rb b/lib/chef/provider/remote_file.rb index 9207e62ac6..83b267724d 100644 --- a/lib/chef/provider/remote_file.rb +++ b/lib/chef/provider/remote_file.rb @@ -47,7 +47,6 @@ class Chef return true if !@new_resource.source.nil? && @action != :create_if_missing false end - end end end diff --git a/lib/chef/provider/remote_file/cache_control_data.rb b/lib/chef/provider/remote_file/cache_control_data.rb index b100ebf4a0..f086e3bb79 100644 --- a/lib/chef/provider/remote_file/cache_control_data.rb +++ b/lib/chef/provider/remote_file/cache_control_data.rb @@ -28,7 +28,6 @@ require "chef/exceptions" class Chef class Provider class RemoteFile - # == CacheControlData # Implements per-uri storage of cache control data for a remote resource # along with a sanity check checksum of the file in question. @@ -51,7 +50,6 @@ class Chef # with new etag, mtime and checksum values in whatever format is # preferred by the protocol used. Then call #save to save the data to disk. class CacheControlData - def self.load_and_validate(uri, current_copy_checksum) ccdata = new(uri) ccdata.load @@ -177,10 +175,9 @@ class Chef def sanitized_cache_file_basename uri_sha2 = Chef::Digester.instance.generate_checksum(StringIO.new(uri)) - cache_file_basename(uri_sha2[0,32]) + cache_file_basename(uri_sha2[0, 32]) end - def sanitized_cache_file_basename_md5 # Old way of creating the file basename uri_md5 = Chef::Digester.instance.generate_md5_checksum(StringIO.new(uri)) diff --git a/lib/chef/provider/remote_file/content.rb b/lib/chef/provider/remote_file/content.rb index e44096428b..effc02c629 100644 --- a/lib/chef/provider/remote_file/content.rb +++ b/lib/chef/provider/remote_file/content.rb @@ -26,7 +26,6 @@ class Chef class Provider class RemoteFile class Content < Chef::FileContentManagement::ContentBase - private include Chef::Mixin::Uris @@ -74,7 +73,6 @@ class Chef def current_resource_matches_target_checksum? @new_resource.checksum && @current_resource.checksum && @current_resource.checksum =~ /^#{Regexp.escape(@new_resource.checksum)}/ end - end end end diff --git a/lib/chef/provider/remote_file/fetcher.rb b/lib/chef/provider/remote_file/fetcher.rb index dad73cf17f..c78e28b167 100644 --- a/lib/chef/provider/remote_file/fetcher.rb +++ b/lib/chef/provider/remote_file/fetcher.rb @@ -21,7 +21,6 @@ class Chef class Provider class RemoteFile class Fetcher - def self.for_resource(uri, new_resource, current_resource) if network_share?(uri) Chef::Provider::RemoteFile::NetworkFile.new(uri, new_resource, current_resource) @@ -48,7 +47,6 @@ class Chef false end end - end end end diff --git a/lib/chef/provider/remote_file/ftp.rb b/lib/chef/provider/remote_file/ftp.rb index 448acdb018..3462479387 100644 --- a/lib/chef/provider/remote_file/ftp.rb +++ b/lib/chef/provider/remote_file/ftp.rb @@ -26,7 +26,6 @@ class Chef class Provider class RemoteFile class FTP - attr_reader :uri attr_reader :new_resource attr_reader :current_resource @@ -176,7 +175,6 @@ class Chef @directories, @filename = directories, filename end - end end end diff --git a/lib/chef/provider/remote_file/http.rb b/lib/chef/provider/remote_file/http.rb index 0e44f06ca7..c44089d2e6 100644 --- a/lib/chef/provider/remote_file/http.rb +++ b/lib/chef/provider/remote_file/http.rb @@ -25,9 +25,7 @@ require "chef/provider/remote_file/cache_control_data" class Chef class Provider class RemoteFile - class HTTP - attr_reader :uri attr_reader :new_resource attr_reader :current_resource @@ -95,7 +93,7 @@ class Chef end def http_client_opts - opts={} + opts = {} # CHEF-3140 # 1. If it's already compressed, trying to compress it more will # probably be counter-productive. @@ -110,7 +108,6 @@ class Chef end opts end - end end end diff --git a/lib/chef/provider/remote_file/local_file.rb b/lib/chef/provider/remote_file/local_file.rb index b02d575999..93d8bb8afa 100644 --- a/lib/chef/provider/remote_file/local_file.rb +++ b/lib/chef/provider/remote_file/local_file.rb @@ -24,7 +24,6 @@ class Chef class Provider class RemoteFile class LocalFile - attr_reader :uri attr_reader :new_resource @@ -35,7 +34,7 @@ class Chef # CHEF-4472: Remove the leading slash from windows paths that we receive from a file:// URI def fix_windows_path(path) - path.gsub(/^\/([a-zA-Z]:)/,'\1') + path.gsub(/^\/([a-zA-Z]:)/, '\1') end def source_path @@ -53,7 +52,6 @@ class Chef tempfile.close if tempfile tempfile end - end end end diff --git a/lib/chef/provider/remote_file/network_file.rb b/lib/chef/provider/remote_file/network_file.rb index 44046132a9..193a9e09c6 100644 --- a/lib/chef/provider/remote_file/network_file.rb +++ b/lib/chef/provider/remote_file/network_file.rb @@ -24,7 +24,6 @@ class Chef class Provider class RemoteFile class NetworkFile - attr_reader :new_resource def initialize(source, new_resource, current_resource) @@ -41,7 +40,6 @@ class Chef tempfile.close if tempfile tempfile end - end end end diff --git a/lib/chef/provider/resource_update.rb b/lib/chef/provider/resource_update.rb index e069a8201c..af2bc688f6 100644 --- a/lib/chef/provider/resource_update.rb +++ b/lib/chef/provider/resource_update.rb @@ -1,7 +1,6 @@ class Chef class Provider - # { # "run_id" : "1000", # "resource" : { @@ -28,7 +27,6 @@ class Chef # } class ResourceUpdate - attr_accessor :type attr_accessor :name attr_accessor :duration #ms @@ -46,7 +44,6 @@ class Chef def updated_state_from_resource(resource) @final_properties = resource.to_hash end - end end end diff --git a/lib/chef/provider/route.rb b/lib/chef/provider/route.rb index d325c65d2a..3dd0e33cd1 100644 --- a/lib/chef/provider/route.rb +++ b/lib/chef/provider/route.rb @@ -22,208 +22,208 @@ require "chef/provider" require "ipaddr" class Chef::Provider::Route < Chef::Provider - include Chef::Mixin::Command - - provides :route - - attr_accessor :is_running - - MASK = {"0.0.0.0" => "0", - "128.0.0.0" => "1", - "192.0.0.0" => "2", - "224.0.0.0" => "3", - "240.0.0.0" => "4", - "248.0.0.0" => "5", - "252.0.0.0" => "6", - "254.0.0.0" => "7", - "255.0.0.0" => "8", - "255.128.0.0" => "9", - "255.192.0.0" => "10", - "255.224.0.0" => "11", - "255.240.0.0" => "12", - "255.248.0.0" => "13", - "255.252.0.0" => "14", - "255.254.0.0" => "15", - "255.255.0.0" => "16", - "255.255.128.0" => "17", - "255.255.192.0" => "18", - "255.255.224.0" => "19", - "255.255.240.0" => "20", - "255.255.248.0" => "21", - "255.255.252.0" => "22", - "255.255.254.0" => "23", - "255.255.255.0" => "24", - "255.255.255.128" => "25", - "255.255.255.192" => "26", - "255.255.255.224" => "27", - "255.255.255.240" => "28", - "255.255.255.248" => "29", - "255.255.255.252" => "30", - "255.255.255.254" => "31", - "255.255.255.255" => "32" } - - def hex2ip(hex_data) - # Cleanup hex data - hex_ip = hex_data.to_s.downcase.gsub(/[^0-9a-f]/, "") - - # Check hex data format (IP is a 32bit integer, so should be 8 chars long) - return nil if hex_ip.length != hex_data.length || hex_ip.length != 8 - - # Extract octets from hex data - octets = hex_ip.scan(/../).reverse.collect { |octet| [octet].pack("H2").unpack("C").first } - - # Validate IP - ip = octets.join(".") - begin - IPAddr.new(ip, Socket::AF_INET).to_s - rescue ArgumentError - Chef::Log.debug("Invalid IP address data: hex=#{hex_ip}, ip=#{ip}") - return nil - end - end - - def whyrun_supported? - true + include Chef::Mixin::Command + + provides :route + + attr_accessor :is_running + + MASK = { "0.0.0.0" => "0", + "128.0.0.0" => "1", + "192.0.0.0" => "2", + "224.0.0.0" => "3", + "240.0.0.0" => "4", + "248.0.0.0" => "5", + "252.0.0.0" => "6", + "254.0.0.0" => "7", + "255.0.0.0" => "8", + "255.128.0.0" => "9", + "255.192.0.0" => "10", + "255.224.0.0" => "11", + "255.240.0.0" => "12", + "255.248.0.0" => "13", + "255.252.0.0" => "14", + "255.254.0.0" => "15", + "255.255.0.0" => "16", + "255.255.128.0" => "17", + "255.255.192.0" => "18", + "255.255.224.0" => "19", + "255.255.240.0" => "20", + "255.255.248.0" => "21", + "255.255.252.0" => "22", + "255.255.254.0" => "23", + "255.255.255.0" => "24", + "255.255.255.128" => "25", + "255.255.255.192" => "26", + "255.255.255.224" => "27", + "255.255.255.240" => "28", + "255.255.255.248" => "29", + "255.255.255.252" => "30", + "255.255.255.254" => "31", + "255.255.255.255" => "32" } + + def hex2ip(hex_data) + # Cleanup hex data + hex_ip = hex_data.to_s.downcase.gsub(/[^0-9a-f]/, "") + + # Check hex data format (IP is a 32bit integer, so should be 8 chars long) + return nil if hex_ip.length != hex_data.length || hex_ip.length != 8 + + # Extract octets from hex data + octets = hex_ip.scan(/../).reverse.collect { |octet| [octet].pack("H2").unpack("C").first } + + # Validate IP + ip = octets.join(".") + begin + IPAddr.new(ip, Socket::AF_INET).to_s + rescue ArgumentError + Chef::Log.debug("Invalid IP address data: hex=#{hex_ip}, ip=#{ip}") + return nil end + end - def load_current_resource - self.is_running = false + def whyrun_supported? + true + end - # cidr or quad dot mask - if @new_resource.netmask - new_ip = IPAddr.new("#{@new_resource.target}/#{@new_resource.netmask}") - else - new_ip = IPAddr.new(@new_resource.target) - end - - # For linux, we use /proc/net/route file to read proc table info - if node[:os] == "linux" - route_file = ::File.open("/proc/net/route", "r") - - # Read all routes - while (line = route_file.gets) - # Get all the fields for a route - iface,destination,gateway,flags,refcnt,use,metric,mask,mtu,window,irtt = line.split - - # Convert hex-encoded values to quad-dotted notation (e.g. 0064A8C0 => 192.168.100.0) - destination = hex2ip(destination) - gateway = hex2ip(gateway) - mask = hex2ip(mask) - - # Skip formatting lines (header, etc) - next unless destination && gateway && mask - Chef::Log.debug("#{@new_resource} system has route: dest=#{destination} mask=#{mask} gw=#{gateway}") - - # check if what were trying to configure is already there - # use an ipaddr object with ip/mask this way we can have - # a new resource be in cidr format (i don't feel like - # expanding bitmask by hand. - # - running_ip = IPAddr.new("#{destination}/#{mask}") - Chef::Log.debug("#{@new_resource} new ip: #{new_ip.inspect} running ip: #{running_ip.inspect}") - self.is_running = true if running_ip == new_ip && gateway == @new_resource.gateway - end + def load_current_resource + self.is_running = false - route_file.close - end + # cidr or quad dot mask + if @new_resource.netmask + new_ip = IPAddr.new("#{@new_resource.target}/#{@new_resource.netmask}") + else + new_ip = IPAddr.new(@new_resource.target) end - def action_add - # check to see if load_current_resource found the route - if is_running - Chef::Log.debug("#{@new_resource} route already active - nothing to do") - else - command = generate_command(:add) - converge_by ("run #{ command } to add route") do - run_command( :command => command ) - Chef::Log.info("#{@new_resource} added") - end + # For linux, we use /proc/net/route file to read proc table info + if node[:os] == "linux" + route_file = ::File.open("/proc/net/route", "r") + + # Read all routes + while (line = route_file.gets) + # Get all the fields for a route + iface, destination, gateway, flags, refcnt, use, metric, mask, mtu, window, irtt = line.split + + # Convert hex-encoded values to quad-dotted notation (e.g. 0064A8C0 => 192.168.100.0) + destination = hex2ip(destination) + gateway = hex2ip(gateway) + mask = hex2ip(mask) + + # Skip formatting lines (header, etc) + next unless destination && gateway && mask + Chef::Log.debug("#{@new_resource} system has route: dest=#{destination} mask=#{mask} gw=#{gateway}") + + # check if what were trying to configure is already there + # use an ipaddr object with ip/mask this way we can have + # a new resource be in cidr format (i don't feel like + # expanding bitmask by hand. + # + running_ip = IPAddr.new("#{destination}/#{mask}") + Chef::Log.debug("#{@new_resource} new ip: #{new_ip.inspect} running ip: #{running_ip.inspect}") + self.is_running = true if running_ip == new_ip && gateway == @new_resource.gateway end - #for now we always write the file (ugly but its what it is) - generate_config + route_file.close end - - def action_delete - if is_running - command = generate_command(:delete) - converge_by ("run #{ command } to delete route ") do - run_command( :command => command ) - Chef::Log.info("#{@new_resource} removed") - end - else - Chef::Log.debug("#{@new_resource} route does not exist - nothing to do") + end + + def action_add + # check to see if load_current_resource found the route + if is_running + Chef::Log.debug("#{@new_resource} route already active - nothing to do") + else + command = generate_command(:add) + converge_by ("run #{ command } to add route") do + run_command( :command => command ) + Chef::Log.info("#{@new_resource} added") end + end + + #for now we always write the file (ugly but its what it is) + generate_config + end - #for now we always write the file (ugly but its what it is) - generate_config + def action_delete + if is_running + command = generate_command(:delete) + converge_by ("run #{ command } to delete route ") do + run_command( :command => command ) + Chef::Log.info("#{@new_resource} removed") + end + else + Chef::Log.debug("#{@new_resource} route does not exist - nothing to do") end - def generate_config - conf = Hash.new - case node[:platform] - when "centos", "redhat", "fedora" - # walk the collection - run_context.resource_collection.each do |resource| - if resource.is_a? Chef::Resource::Route - # default to eth0 - if resource.device - dev = resource.device - else - dev = "eth0" - end - - conf[dev] = String.new if conf[dev].nil? - case @action - when :add - conf[dev] << config_file_contents(:add, :target => resource.target, :netmask => resource.netmask, :gateway => resource.gateway) - when :delete - # need to do this for the case when the last route on an int - # is removed - conf[dev] << config_file_contents(:delete) - end + #for now we always write the file (ugly but its what it is) + generate_config + end + + def generate_config + conf = Hash.new + case node[:platform] + when "centos", "redhat", "fedora" + # walk the collection + run_context.resource_collection.each do |resource| + if resource.is_a? Chef::Resource::Route + # default to eth0 + if resource.device + dev = resource.device + else + dev = "eth0" end - end - conf.each do |k, v| - network_file_name = "/etc/sysconfig/network-scripts/route-#{k}" - converge_by ("write route route.#{k}\n#{conf[k]} to #{ network_file_name }") do - network_file = ::File.new(network_file_name, "w") - network_file.puts(conf[k]) - Chef::Log.debug("#{@new_resource} writing route.#{k}\n#{conf[k]}") - network_file.close + + conf[dev] = String.new if conf[dev].nil? + case @action + when :add + conf[dev] << config_file_contents(:add, :target => resource.target, :netmask => resource.netmask, :gateway => resource.gateway) + when :delete + # need to do this for the case when the last route on an int + # is removed + conf[dev] << config_file_contents(:delete) end end end - end - - def generate_command(action) - common_route_items = "" - common_route_items << "/#{MASK[@new_resource.netmask.to_s]}" if @new_resource.netmask - common_route_items << " via #{@new_resource.gateway} " if @new_resource.gateway - - case action - when :add - command = "ip route replace #{@new_resource.target}" - command << common_route_items - command << " dev #{@new_resource.device} " if @new_resource.device - when :delete - command = "ip route delete #{@new_resource.target}" - command << common_route_items + conf.each do |k, v| + network_file_name = "/etc/sysconfig/network-scripts/route-#{k}" + converge_by ("write route route.#{k}\n#{conf[k]} to #{ network_file_name }") do + network_file = ::File.new(network_file_name, "w") + network_file.puts(conf[k]) + Chef::Log.debug("#{@new_resource} writing route.#{k}\n#{conf[k]}") + network_file.close + end end - - return command + end + end + + def generate_command(action) + common_route_items = "" + common_route_items << "/#{MASK[@new_resource.netmask.to_s]}" if @new_resource.netmask + common_route_items << " via #{@new_resource.gateway} " if @new_resource.gateway + + case action + when :add + command = "ip route replace #{@new_resource.target}" + command << common_route_items + command << " dev #{@new_resource.device} " if @new_resource.device + when :delete + command = "ip route delete #{@new_resource.target}" + command << common_route_items end - def config_file_contents(action, options={}) - content = "" - case action - when :add - content << "#{options[:target]}" - content << "/#{options[:netmask]}" if options[:netmask] - content << " via #{options[:gateway]}" if options[:gateway] - content << "\n" - end - - return content + return command + end + + def config_file_contents(action, options = {}) + content = "" + case action + when :add + content << "#{options[:target]}" + content << "/#{options[:netmask]}" if options[:netmask] + content << " via #{options[:gateway]}" if options[:gateway] + content << "\n" end + + return content + end end diff --git a/lib/chef/provider/ruby_block.rb b/lib/chef/provider/ruby_block.rb index 0817b14044..ec079a9de0 100644 --- a/lib/chef/provider/ruby_block.rb +++ b/lib/chef/provider/ruby_block.rb @@ -38,7 +38,6 @@ class Chef end alias :action_create :action_run - end end end diff --git a/lib/chef/provider/script.rb b/lib/chef/provider/script.rb index 6ca4e9f6f3..b7ef9e5fc4 100644 --- a/lib/chef/provider/script.rb +++ b/lib/chef/provider/script.rb @@ -79,7 +79,6 @@ class Chef def unlink_script_file script_file && script_file.close! end - end end end diff --git a/lib/chef/provider/service.rb b/lib/chef/provider/service.rb index 95ff28e368..aa796136de 100644 --- a/lib/chef/provider/service.rb +++ b/lib/chef/provider/service.rb @@ -22,7 +22,6 @@ require "chef/provider" class Chef class Provider class Service < Chef::Provider - include Chef::Mixin::Command def supports @@ -62,13 +61,13 @@ class Chef end def define_resource_requirements - requirements.assert(:reload) do |a| - a.assertion { supports[:reload] || @new_resource.reload_command } - 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 - # alternative here. - end + requirements.assert(:reload) do |a| + a.assertion { supports[:reload] || @new_resource.reload_command } + 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 + # alternative here. + end end def action_enable @@ -183,7 +182,6 @@ class Chef end module ServicePriorityInit - # # Platform-specific versions # diff --git a/lib/chef/provider/service/aix.rb b/lib/chef/provider/service/aix.rb index 6f0eba7737..201f9ff5f9 100644 --- a/lib/chef/provider/service/aix.rb +++ b/lib/chef/provider/service/aix.rb @@ -90,6 +90,7 @@ class Chef end protected + def determine_current_status! Chef::Log.debug "#{@new_resource} using lssrc to check the status" begin @@ -126,4 +127,3 @@ class Chef end end end - diff --git a/lib/chef/provider/service/aixinit.rb b/lib/chef/provider/service/aixinit.rb index c6483c3f59..6b451d649a 100644 --- a/lib/chef/provider/service/aixinit.rb +++ b/lib/chef/provider/service/aixinit.rb @@ -57,14 +57,14 @@ 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 { |f| ::File.delete(f) } if @new_resource.priority.is_a? Integer create_symlink(2, "S", @new_resource.priority) elsif @new_resource.priority.is_a? Hash - @new_resource.priority.each do |level,o| - create_symlink(level,(o[0] == :start ? "S" : "K"),o[1]) + @new_resource.priority.each do |level, o| + create_symlink(level, (o[0] == :start ? "S" : "K"), o[1]) end else create_symlink(2, "S", "") @@ -75,9 +75,9 @@ class Chef 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) } if @new_resource.priority.is_a? Integer - create_symlink(2, "K",100 - @new_resource.priority) + create_symlink(2, "K", 100 - @new_resource.priority) elsif @new_resource.priority.is_a? Hash - @new_resource.priority.each do |level,o| + @new_resource.priority.each do |level, o| create_symlink(level, "K", 100 - o[1]) if o[0] == :stop end else diff --git a/lib/chef/provider/service/arch.rb b/lib/chef/provider/service/arch.rb index 66504390e8..fb03d98b49 100644 --- a/lib/chef/provider/service/arch.rb +++ b/lib/chef/provider/service/arch.rb @@ -19,7 +19,6 @@ require "chef/provider/service/init" class Chef::Provider::Service::Arch < Chef::Provider::Service::Init - provides :service, platform_family: "arch" def self.supports?(resource, action) @@ -32,8 +31,8 @@ class Chef::Provider::Service::Arch < Chef::Provider::Service::Init end def load_current_resource - raise Chef::Exceptions::Service, "Could not find /etc/rc.conf" unless ::File.exists?("/etc/rc.conf") - raise Chef::Exceptions::Service, "No DAEMONS found in /etc/rc.conf" unless ::File.read("/etc/rc.conf").match(/DAEMONS=\((.*)\)/m) + raise Chef::Exceptions::Service, "Could not find /etc/rc.conf" unless ::File.exists?("/etc/rc.conf") + raise Chef::Exceptions::Service, "No DAEMONS found in /etc/rc.conf" unless ::File.read("/etc/rc.conf").match(/DAEMONS=\((.*)\)/m) super @current_resource.enabled(daemons.include?(@current_resource.service_name)) @@ -50,7 +49,7 @@ class Chef::Provider::Service::Arch < Chef::Provider::Service::Init def daemons entries = [] if ::File.read("/etc/rc.conf").match(/DAEMONS=\((.*)\)/m) - entries += $1.gsub(/\\?[\r\n]/, " ").gsub(/# *[^ ]+/," ").split(" ") if $1.length > 0 + entries += $1.gsub(/\\?[\r\n]/, " ").gsub(/# *[^ ]+/, " ").split(" ") if $1.length > 0 end yield(entries) if block_given? @@ -114,5 +113,4 @@ class Chef::Provider::Service::Arch < Chef::Provider::Service::Init update_daemons(new_daemons) end end - end diff --git a/lib/chef/provider/service/debian.rb b/lib/chef/provider/service/debian.rb index e67f5ca95d..d4e8ae955c 100644 --- a/lib/chef/provider/service/debian.rb +++ b/lib/chef/provider/service/debian.rb @@ -55,18 +55,18 @@ class Chef requirements.assert(:all_actions) do |a| a.assertion { @priority_success } - a.failure_message Chef::Exceptions::Service, "/usr/sbin/update-rc.d -n -f #{current_resource.service_name} failed - #{@rcd_status.inspect}" + a.failure_message Chef::Exceptions::Service, "/usr/sbin/update-rc.d -n -f #{current_resource.service_name} failed - #{@rcd_status.inspect}" # 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.", "Assigning temporary priorities to continue.", "If this service is not properly installed prior to this point, this will fail."] do - temp_priorities = {"6"=>[:stop, "20"], - "0"=>[:stop, "20"], - "1"=>[:stop, "20"], - "2"=>[:start, "20"], - "3"=>[:start, "20"], - "4"=>[:start, "20"], - "5"=>[:start, "20"]} + temp_priorities = { "6" => [:stop, "20"], + "0" => [:stop, "20"], + "1" => [:stop, "20"], + "2" => [:start, "20"], + "3" => [:start, "20"], + "4" => [:start, "20"], + "5" => [:start, "20"] } current_resource.priority(temp_priorities) end end @@ -76,7 +76,6 @@ class Chef priority = {} @rcd_status = popen4("/usr/sbin/update-rc.d -n -f #{current_resource.service_name} remove") do |pid, stdin, stdout, stderr| - [stdout, stderr].each do |iop| iop.each_line do |line| if UPDATE_RC_D_PRIORITIES =~ line @@ -148,7 +147,6 @@ class Chef shell_out!("/usr/sbin/update-rc.d -f #{new_resource.service_name} remove") shell_out!("/usr/sbin/update-rc.d #{new_resource.service_name} defaults") end - end def disable_service diff --git a/lib/chef/provider/service/freebsd.rb b/lib/chef/provider/service/freebsd.rb index fc0743d5e4..6d67346642 100644 --- a/lib/chef/provider/service/freebsd.rb +++ b/lib/chef/provider/service/freebsd.rb @@ -24,7 +24,6 @@ class Chef class Provider class Service class Freebsd < Chef::Provider::Service::Init - attr_reader :enabled_state_found provides :service, os: [ "freebsd", "netbsd" ] @@ -51,7 +50,7 @@ class Chef Chef::Log.debug("#{current_resource} found at #{init_command}") @status_load_success = true - determine_current_status! # see Chef::Provider::Service::Simple + determine_current_status! # see Chef::Provider::Service::Simple determine_enabled_status! current_resource diff --git a/lib/chef/provider/service/gentoo.rb b/lib/chef/provider/service/gentoo.rb index 66f2f10f23..95ecf2e4bc 100644 --- a/lib/chef/provider/service/gentoo.rb +++ b/lib/chef/provider/service/gentoo.rb @@ -22,7 +22,6 @@ require "chef/mixin/command" require "chef/util/path_helper" class Chef::Provider::Service::Gentoo < Chef::Provider::Service::Init - provides :service, platform_family: "gentoo" def load_current_resource diff --git a/lib/chef/provider/service/init.rb b/lib/chef/provider/service/init.rb index dff627d016..3c6007b365 100644 --- a/lib/chef/provider/service/init.rb +++ b/lib/chef/provider/service/init.rb @@ -24,7 +24,6 @@ class Chef class Provider class Service class Init < Chef::Provider::Service::Simple - attr_accessor :init_command provides :service, os: "!windows" diff --git a/lib/chef/provider/service/insserv.rb b/lib/chef/provider/service/insserv.rb index 7f92ef1eb4..6b42b391a0 100644 --- a/lib/chef/provider/service/insserv.rb +++ b/lib/chef/provider/service/insserv.rb @@ -23,7 +23,6 @@ class Chef class Provider class Service class Insserv < Chef::Provider::Service::Init - provides :service, platform_family: %w{debian rhel fedora suse} do |node| Chef::Platform::ServiceHelpers.service_resource_providers.include?(:insserv) end diff --git a/lib/chef/provider/service/invokercd.rb b/lib/chef/provider/service/invokercd.rb index 9477afec48..6f69fbf06c 100644 --- a/lib/chef/provider/service/invokercd.rb +++ b/lib/chef/provider/service/invokercd.rb @@ -22,7 +22,6 @@ class Chef class Provider class Service class Invokercd < Chef::Provider::Service::Init - provides :service, platform_family: "debian", override: true do |node| Chef::Platform::ServiceHelpers.service_resource_providers.include?(:invokercd) end diff --git a/lib/chef/provider/service/macosx.rb b/lib/chef/provider/service/macosx.rb index 4206f29aef..e593ab4cab 100644 --- a/lib/chef/provider/service/macosx.rb +++ b/lib/chef/provider/service/macosx.rb @@ -27,7 +27,6 @@ class Chef class Provider class Service class Macosx < Chef::Provider::Service::Simple - provides :macosx_service, os: "darwin" provides :service, os: "darwin" @@ -83,7 +82,7 @@ class Chef end requirements.assert(:all_actions) do |a| - a.assertion {::File.exists?(@plist.to_s) } + a.assertion { ::File.exists?(@plist.to_s) } a.failure_message Chef::Exceptions::Service, "Could not find plist for #{@new_resource}" end diff --git a/lib/chef/provider/service/openbsd.rb b/lib/chef/provider/service/openbsd.rb index 4fc10cff5c..5d3c11d185 100644 --- a/lib/chef/provider/service/openbsd.rb +++ b/lib/chef/provider/service/openbsd.rb @@ -25,7 +25,6 @@ class Chef class Provider class Service class Openbsd < Chef::Provider::Service::Init - provides :service, os: "openbsd" include Chef::Mixin::ShellOut @@ -117,7 +116,7 @@ class Chef old_list = rc_conf_local.match(/^pkg_scripts="(.*)"/) old_list = old_list ? old_list[1].split(" ") : [] new_list = old_list - [new_resource.service_name] - update_rcl rc_conf_local.sub(/^pkg_scripts="(.*)"/, pkg_scripts="#{new_list.join(' ')}") + update_rcl rc_conf_local.sub(/^pkg_scripts="(.*)"/, pkg_scripts = "#{new_list.join(' ')}") end end end @@ -210,7 +209,6 @@ class Chef current_resource.enabled result end alias :is_enabled? :determine_enabled_status! - end end end diff --git a/lib/chef/provider/service/redhat.rb b/lib/chef/provider/service/redhat.rb index 58c8d4d30a..dcb338749e 100644 --- a/lib/chef/provider/service/redhat.rb +++ b/lib/chef/provider/service/redhat.rb @@ -22,7 +22,6 @@ class Chef class Provider class Service class Redhat < Chef::Provider::Service::Init - # @api private attr_accessor :service_missing # @api private @@ -75,7 +74,7 @@ class Chef super if ::File.exists?("/sbin/chkconfig") - chkconfig = shell_out!("/sbin/chkconfig --list #{current_resource.service_name}", :returns => [0,1]) + chkconfig = shell_out!("/sbin/chkconfig --list #{current_resource.service_name}", :returns => [0, 1]) unless run_levels.nil? or run_levels.empty? all_levels_match = true chkconfig.stdout.split(/\s+/)[1..-1].each do |level| diff --git a/lib/chef/provider/service/simple.rb b/lib/chef/provider/service/simple.rb index b954a118dd..f6b444e44e 100644 --- a/lib/chef/provider/service/simple.rb +++ b/lib/chef/provider/service/simple.rb @@ -24,7 +24,6 @@ class Chef class Provider class Service class Simple < Chef::Provider::Service - # this must be subclassed to be useful so does not directly implement :service attr_reader :status_load_success @@ -66,7 +65,7 @@ class Chef end requirements.assert(:restart) do |a| - a.assertion { @new_resource.restart_command || ( @new_resource.start_command && @new_resource.stop_command ) } + a.assertion { @new_resource.restart_command || ( @new_resource.start_command && @new_resource.stop_command ) } 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 @@ -109,6 +108,7 @@ class Chef end protected + def determine_current_status! if @new_resource.status_command Chef::Log.debug("#{@new_resource} you have specified a status command, running..") diff --git a/lib/chef/provider/service/solaris.rb b/lib/chef/provider/service/solaris.rb index b302441a60..404624de12 100644 --- a/lib/chef/provider/service/solaris.rb +++ b/lib/chef/provider/service/solaris.rb @@ -28,7 +28,7 @@ class Chef provides :service, os: "solaris2" - def initialize(new_resource, run_context=nil) + def initialize(new_resource, run_context = nil) super @init_command = "/usr/sbin/svcadm" @status_command = "/bin/svcs" @@ -110,7 +110,6 @@ class Chef end @current_resource end - end end end diff --git a/lib/chef/provider/service/systemd.rb b/lib/chef/provider/service/systemd.rb index e70576fea7..864b6fda15 100644 --- a/lib/chef/provider/service/systemd.rb +++ b/lib/chef/provider/service/systemd.rb @@ -21,7 +21,6 @@ require "chef/provider/service/simple" require "chef/mixin/which" class Chef::Provider::Service::Systemd < Chef::Provider::Service::Simple - include Chef::Mixin::Which provides :service, os: "linux" do |node| @@ -135,5 +134,4 @@ class Chef::Provider::Service::Systemd < Chef::Provider::Service::Simple end @systemctl_path end - end diff --git a/lib/chef/provider/service/upstart.rb b/lib/chef/provider/service/upstart.rb index 2aacdf3915..926b846c97 100644 --- a/lib/chef/provider/service/upstart.rb +++ b/lib/chef/provider/service/upstart.rb @@ -25,7 +25,6 @@ class Chef class Provider class Service class Upstart < Chef::Provider::Service::Simple - provides :service, platform_family: "debian", override: true do |node| Chef::Platform::ServiceHelpers.service_resource_providers.include?(:upstart) end @@ -89,7 +88,7 @@ class Chef end requirements.assert(:all_actions) do |a| - a.assertion { @config_file_found } + a.assertion { @config_file_found } # 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 @@ -130,7 +129,7 @@ class Chef # Get enabled/disabled state by reading job configuration file if ::File.exists?("#{@upstart_job_dir}/#{@new_resource.service_name}#{@upstart_conf_suffix}") Chef::Log.debug("#{@new_resource} found #{@upstart_job_dir}/#{@new_resource.service_name}#{@upstart_conf_suffix}") - ::File.open("#{@upstart_job_dir}/#{@new_resource.service_name}#{@upstart_conf_suffix}","r") do |file| + ::File.open("#{@upstart_job_dir}/#{@new_resource.service_name}#{@upstart_conf_suffix}", "r") do |file| while line = file.gets case line when /^start on/ @@ -235,7 +234,6 @@ class Chef end end end - end end end diff --git a/lib/chef/provider/service/windows.rb b/lib/chef/provider/service/windows.rb index 8c7c76df3f..2705aa5c02 100644 --- a/lib/chef/provider/service/windows.rb +++ b/lib/chef/provider/service/windows.rb @@ -45,7 +45,7 @@ class Chef::Provider::Service::Windows < Chef::Provider::Service START_PENDING = "start pending" STOP_PENDING = "stop pending" - TIMEOUT = 60 + TIMEOUT = 60 SERVICE_RIGHT = "SeServiceLogonRight" @@ -75,7 +75,7 @@ class Chef::Provider::Service::Windows < Chef::Provider::Service service_name: @new_resource.service_name, service_start_name: @new_resource.run_as_user, password: @new_resource.run_as_password, - }.reject { |k,v| v.nil? || v.length == 0 } + }.reject { |k, v| v.nil? || v.length == 0 } Win32::Service.configure(new_config) Chef::Log.info "#{@new_resource} configured with #{new_config.inspect}" @@ -238,6 +238,7 @@ class Chef::Provider::Service::Windows < Chef::Provider::Service end private + def grant_service_logon(username) begin Chef::ReservedNames::Win32::Security.add_account_right(canonicalize_username(username), SERVICE_RIGHT) diff --git a/lib/chef/provider/subversion.rb b/lib/chef/provider/subversion.rb index e8c25c1740..e66c6bb1fe 100644 --- a/lib/chef/provider/subversion.rb +++ b/lib/chef/provider/subversion.rb @@ -26,7 +26,6 @@ require "fileutils" class Chef class Provider class Subversion < Chef::Provider - provides :subversion SVN_INFO_PATTERN = /^([\w\s]+): (.+)$/ @@ -48,7 +47,7 @@ class Chef end def define_resource_requirements - requirements.assert(:all_actions) do |a| + requirements.assert(:all_actions) do |a| # 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) @@ -115,7 +114,7 @@ class Chef def export_command args = ["--force"] args << @new_resource.svn_arguments << verbose << authentication << - "-r#{revision_int}" << @new_resource.repository << @new_resource.destination + "-r#{revision_int}" << @new_resource.repository << @new_resource.destination c = scm :export, *args Chef::Log.info "#{@new_resource} exported #{@new_resource.repository} at revision #{@new_resource.revision} to #{@new_resource.destination}" c @@ -130,7 +129,7 @@ class Chef @new_resource.revision else command = scm(:info, @new_resource.repository, @new_resource.svn_info_args, authentication, "-r#{@new_resource.revision}") - svn_info = shell_out!(command, run_options(:cwd => cwd, :returns => [0,1])).stdout + svn_info = shell_out!(command, run_options(:cwd => cwd, :returns => [0, 1])).stdout extract_revision_info(svn_info) end @@ -142,7 +141,7 @@ class Chef def find_current_revision return nil unless ::File.exist?(::File.join(@new_resource.destination, ".svn")) command = scm(:info) - svn_info = shell_out!(command, run_options(:cwd => cwd, :returns => [0,1])).stdout + svn_info = shell_out!(command, run_options(:cwd => cwd, :returns => [0, 1])).stdout extract_revision_info(svn_info) end @@ -151,7 +150,7 @@ class Chef (!@current_resource.revision.nil?) && (revision_int.strip.to_i == @current_resource.revision.strip.to_i) end - def run_options(run_opts={}) + def run_options(run_opts = {}) run_opts[:user] = @new_resource.user if @new_resource.user run_opts[:group] = @new_resource.group if @new_resource.group run_opts[:timeout] = @new_resource.timeout if @new_resource.timeout @@ -201,7 +200,7 @@ class Chef end def target_dir_non_existent_or_empty? - !::File.exist?(@new_resource.destination) || Dir.entries(@new_resource.destination).sort == [".",".."] + !::File.exist?(@new_resource.destination) || Dir.entries(@new_resource.destination).sort == [".", ".."] end def svn_binary diff --git a/lib/chef/provider/template.rb b/lib/chef/provider/template.rb index e12d465353..a7eadc14e5 100644 --- a/lib/chef/provider/template.rb +++ b/lib/chef/provider/template.rb @@ -59,7 +59,6 @@ class Chef return true if !@new_resource.source.nil? && @action != :create_if_missing false end - end end end diff --git a/lib/chef/provider/template/content.rb b/lib/chef/provider/template/content.rb index acf200621d..410c0f6288 100644 --- a/lib/chef/provider/template/content.rb +++ b/lib/chef/provider/template/content.rb @@ -22,9 +22,7 @@ require "chef/file_content_management/content_base" class Chef class Provider class Template - class Content < Chef::FileContentManagement::ContentBase - include Chef::Mixin::Template def template_location diff --git a/lib/chef/provider/template_finder.rb b/lib/chef/provider/template_finder.rb index ede6103885..8101cecbd7 100644 --- a/lib/chef/provider/template_finder.rb +++ b/lib/chef/provider/template_finder.rb @@ -18,9 +18,7 @@ class Chef class Provider - class TemplateFinder - def initialize(run_context, cookbook_name, node) @run_context = run_context @cookbook_name = cookbook_name @@ -41,6 +39,7 @@ class Chef end protected + def template_source_name(name, options) if options[:source] options[:source] diff --git a/lib/chef/provider/user.rb b/lib/chef/provider/user.rb index 3b8fe61171..85bd674d8d 100644 --- a/lib/chef/provider/user.rb +++ b/lib/chef/provider/user.rb @@ -98,7 +98,7 @@ class Chef a.assertion { @shadow_lib_ok } 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. " + "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 } @@ -125,7 +125,6 @@ class Chef end def action_create - if !@user_exists converge_by("create user #{@new_resource.username}") do create_user diff --git a/lib/chef/provider/user/aix.rb b/lib/chef/provider/user/aix.rb index 019fe88a04..1ec09baad6 100644 --- a/lib/chef/provider/user/aix.rb +++ b/lib/chef/provider/user/aix.rb @@ -48,7 +48,7 @@ class Chef end raise Chef::Exceptions::User, "Cannot determine if #{@new_resource} is locked!" if lock_info.stdout.empty? - status = /\S+\s+account_locked=(\S+)/.match(lock_info.stdout) + status = /\S+\s+account_locked=(\S+)/.match(lock_info.stdout) if status && status[1] == "true" @locked = true else @@ -67,6 +67,7 @@ class Chef end private + def add_password if @current_resource.password != @new_resource.password && @new_resource.password Chef::Log.debug("#{@new_resource.username} setting password to #{@new_resource.password}") @@ -89,7 +90,6 @@ class Chef end end end - end end end diff --git a/lib/chef/provider/user/dscl.rb b/lib/chef/provider/user/dscl.rb index 995d3bf30b..90357bdc60 100644 --- a/lib/chef/provider/user/dscl.rb +++ b/lib/chef/provider/user/dscl.rb @@ -43,7 +43,6 @@ class Chef # # This provider only supports Mac OSX versions 10.7 and above class Dscl < Chef::Provider::User - attr_accessor :user_info attr_accessor :authentication_authority attr_accessor :password_shadow_conversion_algorithm @@ -109,7 +108,6 @@ in 'password', with the associated 'salt' and 'iterations'.") Mac OS X version 10.7. Please specify a SALTED-SHA512 shadow hash in 'password' attribute to set the \ user password using shadow hash.") end - end def load_current_resource @@ -145,7 +143,7 @@ user password using shadow hash.") # Convert the salt from Base64 encoding to hex before consuming them current_resource.salt(shadow_hash["SALTED-SHA512-PBKDF2"]["salt"].string.unpack("H*").first) else - raise(Chef::Exceptions::User,"Unknown shadow_hash format: #{shadow_hash.keys.join(' ')}") + raise(Chef::Exceptions::User, "Unknown shadow_hash format: #{shadow_hash.keys.join(' ')}") end end @@ -226,7 +224,7 @@ user password using shadow hash.") # Find the next available uid on the system. starting with 200 if `system` is set, # 500 otherwise. # - def get_free_uid(search_limit=1000) + def get_free_uid(search_limit = 1000) uid = nil base_uid = new_resource.system ? 200 : 500 next_uid_guess = base_uid @@ -308,7 +306,7 @@ user password using shadow hash.") def validate_home_dir_specification! unless new_resource.home =~ /^\// - raise(Chef::Exceptions::InvalidHomeDirectory,"invalid path spec for User: '#{new_resource.username}', home directory: '#{new_resource.home}'") + raise(Chef::Exceptions::InvalidHomeDirectory, "invalid path spec for User: '#{new_resource.username}', home directory: '#{new_resource.home}'") end end @@ -322,9 +320,9 @@ user password using shadow hash.") def ditto_home skel = "/System/Library/User Template/English.lproj" - raise(Chef::Exceptions::User,"can't find skel at: #{skel}") unless ::File.exists?(skel) + raise(Chef::Exceptions::User, "can't find skel at: #{skel}") unless ::File.exists?(skel) shell_out! "ditto '#{skel}' '#{new_resource.home}'" - ::FileUtils.chown_R(new_resource.username,new_resource.gid.to_s,new_resource.home) + ::FileUtils.chown_R(new_resource.username, new_resource.gid.to_s, new_resource.home) end def move_home @@ -332,10 +330,10 @@ user password using shadow hash.") src = current_resource.home FileUtils.mkdir_p(new_resource.home) - files = ::Dir.glob("#{Chef::Util::PathHelper.escape_glob(src)}/*", ::File::FNM_DOTMATCH) - ["#{src}/.","#{src}/.."] - ::FileUtils.mv(files,new_resource.home, :force => true) + files = ::Dir.glob("#{Chef::Util::PathHelper.escape_glob(src)}/*", ::File::FNM_DOTMATCH) - ["#{src}/.", "#{src}/.."] + ::FileUtils.mv(files, new_resource.home, :force => true) ::FileUtils.rmdir(src) - ::FileUtils.chown_R(new_resource.username,new_resource.gid.to_s,new_resource.home) + ::FileUtils.chown_R(new_resource.username, new_resource.gid.to_s, new_resource.home) end # @@ -384,7 +382,7 @@ user password using shadow hash.") # Prepares the password shadow info based on the platform version. # def prepare_password_shadow_info - shadow_info = { } + shadow_info = {} entropy = nil salt = nil iterations = nil @@ -420,7 +418,7 @@ user password using shadow hash.") ) end - pbkdf_info = { } + pbkdf_info = {} pbkdf_info["entropy"] = StringIO.new pbkdf_info["entropy"].string = entropy pbkdf_info["salt"] = StringIO.new @@ -465,7 +463,7 @@ user password using shadow hash.") # Unlocks the user # def unlock_user - auth_string = authentication_authority.gsub(/AuthenticationAuthority: /,"").gsub(/;DisabledUser;/,"").strip + auth_string = authentication_authority.gsub(/AuthenticationAuthority: /, "").gsub(/;DisabledUser;/, "").strip run_dscl("create /Users/#{new_resource.username} AuthenticationAuthority '#{auth_string}'") end @@ -655,16 +653,16 @@ user password using shadow hash.") def run_dscl(*args) result = shell_out("dscl . -#{args.join(' ')}") return "" if ( args.first =~ /^delete/ ) && ( result.exitstatus != 0 ) - raise(Chef::Exceptions::DsclCommandFailed,"dscl error: #{result.inspect}") unless result.exitstatus == 0 - raise(Chef::Exceptions::DsclCommandFailed,"dscl error: #{result.inspect}") if result.stdout =~ /No such key: / + raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") unless result.exitstatus == 0 + raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") if result.stdout =~ /No such key: / result.stdout end def run_plutil(*args) result = shell_out("plutil -#{args.join(' ')}") - raise(Chef::Exceptions::PlistUtilCommandFailed,"plutil error: #{result.inspect}") unless result.exitstatus == 0 + raise(Chef::Exceptions::PlistUtilCommandFailed, "plutil error: #{result.inspect}") unless result.exitstatus == 0 if result.stdout.encoding == Encoding::ASCII_8BIT - result.stdout.encode("utf-8", "binary", :undef => :replace, :invalid => :replace, :replace => "?") + result.stdout.encode("utf-8", "binary", :undef => :replace, :invalid => :replace, :replace => "?") else result.stdout end @@ -675,7 +673,7 @@ user password using shadow hash.") end def convert_to_binary(string) - string.unpack("a2"*(string.size/2)).collect { |i| i.hex.chr }.join + string.unpack("a2" * (string.size / 2)).collect { |i| i.hex.chr }.join end def salted_sha512?(string) @@ -684,7 +682,7 @@ user password using shadow hash.") def salted_sha512_password_match? # Salt is included in the first 4 bytes of shadow data - salt = current_resource.password.slice(0,8) + salt = current_resource.password.slice(0, 8) shadow = OpenSSL::Digest::SHA512.hexdigest(convert_to_binary(salt) + new_resource.password) current_resource.password == salt + shadow end @@ -704,7 +702,6 @@ user password using shadow hash.") OpenSSL::Digest::SHA512.new, ).unpack("H*").first == current_resource.password end - end end end diff --git a/lib/chef/provider/user/pw.rb b/lib/chef/provider/user/pw.rb index 8bb234700e..949a21790b 100644 --- a/lib/chef/provider/user/pw.rb +++ b/lib/chef/provider/user/pw.rb @@ -77,7 +77,7 @@ class Chef "uid" => "-u", "shell" => "-s", } - field_list.sort{ |a,b| a[0] <=> b[0] }.each do |field, option| + field_list.sort { |a, b| a[0] <=> b[0] }.each do |field, option| field_symbol = field.to_sym if @current_resource.send(field_symbol) != @new_resource.send(field_symbol) if @new_resource.send(field_symbol) diff --git a/lib/chef/provider/user/useradd.rb b/lib/chef/provider/user/useradd.rb index 4779dedd94..364c6366aa 100644 --- a/lib/chef/provider/user/useradd.rb +++ b/lib/chef/provider/user/useradd.rb @@ -55,7 +55,7 @@ class Chef def check_lock # we can get an exit code of 1 even when it's successful on # rhel/centos (redhat bug 578534). See additional error checks below. - passwd_s = shell_out!("passwd", "-S", new_resource.username, :returns => [0,1]) + passwd_s = shell_out!("passwd", "-S", new_resource.username, :returns => [0, 1]) if whyrun_mode? && passwd_s.stdout.empty? && passwd_s.stderr.match(/does not exist/) # if we're in whyrun mode and the user is not yet created we assume it would be return false @@ -156,7 +156,6 @@ class Chef def managing_home_dir? new_resource.manage_home || new_resource.supports[:manage_home] end - end end end diff --git a/lib/chef/provider/user/windows.rb b/lib/chef/provider/user/windows.rb index 0a7505ddc3..02ef01c5ed 100644 --- a/lib/chef/provider/user/windows.rb +++ b/lib/chef/provider/user/windows.rb @@ -26,10 +26,9 @@ class Chef class Provider class User class Windows < Chef::Provider::User - provides :user, os: "windows" - def initialize(new_resource,run_context) + def initialize(new_resource, run_context) super @net_user = Chef::Util::Windows::NetUser.new(@new_resource.username) end @@ -37,7 +36,7 @@ class Chef def load_current_resource if @new_resource.gid Chef::Log.warn("The 'gid' attribute is not implemented by the Windows platform. Please use the 'group' resource to assign a user to a group.") - end + end @current_resource = Chef::Resource::User.new(@new_resource.name) @current_resource.username(@new_resource.username) @@ -98,7 +97,7 @@ class Chef end def set_options - opts = {:name => @new_resource.username} + opts = { :name => @new_resource.username } field_list = { "comment" => "full_name", @@ -108,7 +107,7 @@ class Chef "password" => "password", } - field_list.sort{ |a,b| a[0] <=> b[0] }.each do |field, option| + field_list.sort { |a, b| a[0] <=> b[0] }.each do |field, option| field_symbol = field.to_sym if @current_resource.send(field_symbol) != @new_resource.send(field_symbol) if @new_resource.send(field_symbol) @@ -121,7 +120,6 @@ class Chef end opts end - end end end diff --git a/lib/chef/provider/windows_script.rb b/lib/chef/provider/windows_script.rb index e500e16c8b..c02110dff4 100644 --- a/lib/chef/provider/windows_script.rb +++ b/lib/chef/provider/windows_script.rb @@ -22,14 +22,13 @@ require "chef/mixin/windows_architecture_helper" class Chef class Provider class WindowsScript < Chef::Provider::Script - attr_reader :is_forced_32bit protected include Chef::Mixin::WindowsArchitectureHelper - def initialize( new_resource, run_context, script_extension="") + def initialize( new_resource, run_context, script_extension = "") super( new_resource, run_context ) @script_extension = script_extension diff --git a/lib/chef/provider_resolver.rb b/lib/chef/provider_resolver.rb index 1df473abbd..b2d99e494f 100644 --- a/lib/chef/provider_resolver.rb +++ b/lib/chef/provider_resolver.rb @@ -45,7 +45,6 @@ class Chef # registered list* is selected and returned. # class ProviderResolver - attr_reader :node attr_reader :resource attr_reader :action diff --git a/lib/chef/recipe.rb b/lib/chef/recipe.rb index 20032e5b6a..e246e3f387 100644 --- a/lib/chef/recipe.rb +++ b/lib/chef/recipe.rb @@ -17,7 +17,6 @@ # limitations under the License. # - require "chef/dsl/recipe" require "chef/dsl/data_query" require "chef/dsl/platform_introspection" @@ -35,7 +34,6 @@ class Chef # == Chef::Recipe # A Recipe object is the context in which Chef recipes are evaluated. class Recipe - include Chef::DSL::Recipe::FullDSL include Chef::Mixin::FromFile @@ -115,6 +113,5 @@ class Chef run_context.node.tags.delete(tag) end end - end end diff --git a/lib/chef/reserved_names.rb b/lib/chef/reserved_names.rb index 029cddac9a..6452593bce 100644 --- a/lib/chef/reserved_names.rb +++ b/lib/chef/reserved_names.rb @@ -1,5 +1,4 @@ class Chef - # This module exists to hide conflicting constant names from the DSL. # Hopefully we'll have a better/prettier/more sustainable solution in the # future, but for now this will fix a regression introduced in Chef 0.10.10 diff --git a/lib/chef/resource.rb b/lib/chef/resource.rb index 1791e4143e..a1caa42335 100644 --- a/lib/chef/resource.rb +++ b/lib/chef/resource.rb @@ -47,7 +47,6 @@ require "chef/mixin/powershell_out" class Chef class Resource - # # Generic User DSL (not resource-specific) # @@ -132,7 +131,7 @@ class Chef # used for notifications to this resource). # @param run_context The context of the Chef run. Corresponds to #run_context. # - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) name(name) unless name.nil? @run_context = run_context @noop = nil @@ -167,7 +166,7 @@ class Chef # @param arg [Array[Symbol], Symbol] A list of actions (e.g. `:create`) # @return [Array[Symbol]] the list of actions. # - def action(arg=nil) + def action(arg = nil) if arg arg = Array(arg).map(&:to_sym) arg.each do |action| @@ -240,14 +239,13 @@ class Chef # notifies :create, bar # end # - def notifies(action, resource_spec, timing=:delayed) + def notifies(action, resource_spec, timing = :delayed) # when using old-style resources(:template => "/foo.txt") style, you # could end up with multiple resources. validate_resource_spec!(resource_spec) resources = [ resource_spec ].flatten resources.each do |resource| - case timing.to_s when "delayed" notifies_delayed(action, resource) @@ -327,7 +325,7 @@ class Chef # subscribes :create, [ bar, baz ] # end # - def subscribes(action, resources, timing=:delayed) + def subscribes(action, resources, timing = :delayed) resources = [resources].flatten resources.each do |resource| if resource.is_a?(String) @@ -364,7 +362,7 @@ class Chef # @param opts [Hash] Options control the execution of the command # @param block [Proc] A ruby block to run. Ignored if a command is given. # - def only_if(command=nil, opts={}, &block) + def only_if(command = nil, opts = {}, &block) if command || block_given? @only_if << Conditional.only_if(self, command, opts, &block) end @@ -394,7 +392,7 @@ class Chef # @param opts [Hash] Options control the execution of the command # @param block [Proc] A ruby block to run. Ignored if a command is given. # - def not_if(command=nil, opts={}, &block) + def not_if(command = nil, opts = {}, &block) if command || block_given? @not_if << Conditional.not_if(self, command, opts, &block) end @@ -411,7 +409,7 @@ class Chef # @param arg [Integer] The number of retries. # @return [Integer] The number of retries. # - def retries(arg=nil) + def retries(arg = nil) set_or_return(:retries, arg, kind_of: Integer) end attr_writer :retries @@ -422,7 +420,7 @@ class Chef # @param arg [Integer] The number of seconds to wait between retries. # @return [Integer] The number of seconds to wait between retries. # - def retry_delay(arg=nil) + def retry_delay(arg = nil) set_or_return(:retry_delay, arg, kind_of: Integer) end attr_writer :retry_delay @@ -434,7 +432,7 @@ class Chef # @param arg [Boolean] Whether this resource is sensitive or not. # @return [Boolean] Whether this resource is sensitive or not. # - def sensitive(arg=nil) + def sensitive(arg = nil) set_or_return(:sensitive, arg, :kind_of => [ TrueClass, FalseClass ]) end attr_writer :sensitive @@ -468,7 +466,7 @@ class Chef # symbol/name. # @return [Class, Symbol, String] The Guard interpreter resource. # - def guard_interpreter(arg=nil) + def guard_interpreter(arg = nil) if arg.nil? @guard_interpreter || @default_guard_interpreter else @@ -535,7 +533,7 @@ class Chef # @param arg [Boolean] Whether to ignore failures. # @return Whether this resource will ignore failures. # - def ignore_failure(arg=nil) + def ignore_failure(arg = nil) set_or_return(:ignore_failure, arg, kind_of: [ TrueClass, FalseClass ]) end attr_writer :ignore_failure @@ -567,7 +565,7 @@ class Chef # # @raise Any error that occurs during the actual action. # - def run_action(action, notification_type=nil, notifying_resource=nil) + def run_action(action, notification_type = nil, notifying_resource = nil) # reset state in case of multiple actions on the same resource. @elapsed_time = 0 start_time = Time.now @@ -647,7 +645,7 @@ class Chef ivars.each do |ivar| if (value = instance_variable_get(ivar)) && !(value.respond_to?(:empty?) && value.empty?) value_string = value.respond_to?(:to_text) ? value.to_text : value.inspect - text << " #{ivar.to_s.sub(/^@/,'')} #{value_string}\n" + text << " #{ivar.to_s.sub(/^@/, '')} #{value_string}\n" end end [@not_if, @only_if].flatten.each do |conditional| @@ -692,7 +690,7 @@ class Chef end safe_ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS safe_ivars.each do |iv| - key = iv.to_s.sub(/^@/,"").to_sym + key = iv.to_s.sub(/^@/, "").to_sym next if result.has_key?(key) result[key] = instance_variable_get(iv) end @@ -701,7 +699,7 @@ class Chef def self.json_create(o) resource = self.new(o["instance_vars"]["@name"]) - o["instance_vars"].each do |k,v| + o["instance_vars"].each do |k, v| resource.instance_variable_set("@#{k}".to_sym, v) end resource @@ -730,7 +728,7 @@ class Chef # # @see Chef::Resource.action_class # - def provider(arg=nil) + def provider(arg = nil) klass = if arg.kind_of?(String) || arg.kind_of?(Symbol) lookup_provider_constant(arg) else @@ -739,6 +737,7 @@ class Chef set_or_return(:provider, klass, kind_of: [ Class ]) || self.class.action_class end + def provider=(arg) provider(arg) end @@ -791,7 +790,7 @@ class Chef # @raise [ArgumentError] If no arguments are passed and the resource has # more than one identity property. # - def self.identity_property(name=nil) + def self.identity_property(name = nil) result = identity_properties(*Array(name)) if result.size > 1 raise Chef::Exceptions::MultipleIdentityError, "identity_property cannot be called on an object with more than one identity property (#{result.map { |r| r.name }.join(", ")})." @@ -813,7 +812,7 @@ class Chef # @raise [ArgumentError] If no arguments are passed and the resource has # more than one identity property. # - def self.identity_attr(name=nil) + def self.identity_attr(name = nil) property = identity_property(name) return nil if !property property.name @@ -842,7 +841,7 @@ class Chef # have. # attr_accessor :allowed_actions - def allowed_actions(value=NOT_PASSED) + def allowed_actions(value = NOT_PASSED) if value != NOT_PASSED self.allowed_actions = value end @@ -900,7 +899,7 @@ class Chef def updated=(true_or_false) Chef::Log.warn("Chef::Resource#updated=(true|false) is deprecated. Please call #updated_by_last_action(true|false) instead.") Chef::Log.warn("Called from:") - caller[0..3].each {|line| Chef::Log.warn(line)} + caller[0..3].each { |line| Chef::Log.warn(line) } updated_by_last_action(true_or_false) @updated = true_or_false end @@ -927,13 +926,14 @@ class Chef # this resource. Default: {} # @return Hash{Symbol=>Boolean} An array of things this resource supports. # - def supports(args={}) + def supports(args = {}) if args.any? @supports = args else @supports end end + def supports=(args) supports(args) end @@ -977,7 +977,7 @@ class Chef # # @return [Symbol] The name of this resource type (e.g. `:execute`). # - def self.resource_name(name=NOT_PASSED) + def self.resource_name(name = NOT_PASSED) # Setter if name != NOT_PASSED remove_canonical_dsl @@ -996,6 +996,7 @@ class Chef end @resource_name end + def self.resource_name=(name) resource_name(name) end @@ -1029,7 +1030,7 @@ class Chef # # @deprecated Use `provides` on the provider, or `provider` on the resource, instead. # - def self.provider_base(arg=nil) + def self.provider_base(arg = nil) if arg Chef.log_deprecation("Resource.provider_base is deprecated and will be removed in Chef 13. Use provides on the provider, or provider on the resource, instead.") end @@ -1052,6 +1053,7 @@ class Chef end @allowed_actions |= actions.flatten end + def self.allowed_actions=(value) @allowed_actions = value.uniq end @@ -1069,7 +1071,7 @@ class Chef # # @return [Array] The default actions for the resource. # - def self.default_action(action_name=NOT_PASSED) + def self.default_action(action_name = NOT_PASSED) unless action_name.equal?(NOT_PASSED) @default_action = Array(action_name).map(&:to_sym) self.allowed_actions |= @default_action @@ -1083,6 +1085,7 @@ class Chef [:nothing] end end + def self.default_action=(action_name) default_action action_name end @@ -1313,6 +1316,7 @@ class Chef def self.sorted_descendants @@sorted_descendants ||= descendants.sort_by { |x| x.to_s } end + def self.inherited(child) super @@sorted_descendants = nil @@ -1324,7 +1328,6 @@ class Chef end end - # If an unknown method is invoked, determine whether the enclosing Provider's # lexical scope can fulfill the request. E.g. This happens when the Resource's # block invokes new_resource. @@ -1444,7 +1447,7 @@ class Chef end # ??? TODO Seems unused. Delete? - def noop(tf=nil) + def noop(tf = nil) if !tf.nil? raise ArgumentError, "noop must be true or false!" unless tf == true || tf == false @noop = tf @@ -1540,7 +1543,6 @@ class Chef Chef::Resource.const_set(class_name, resource_class) deprecated_constants[class_name.to_sym] = resource_class end - end def self.deprecated_constants @@ -1548,7 +1550,7 @@ class Chef end # @api private - def lookup_provider_constant(name, action=:nothing) + def lookup_provider_constant(name, action = :nothing) begin self.class.provider_base.const_get(convert_to_class_name(name.to_s)) rescue NameError => e diff --git a/lib/chef/resource/action_class.rb b/lib/chef/resource/action_class.rb index 275680ee2d..3d9f2f3e7c 100644 --- a/lib/chef/resource/action_class.rb +++ b/lib/chef/resource/action_class.rb @@ -36,7 +36,7 @@ class Chef # We clear desired state in the copy, because it is supposed to be actual state. # We keep identity properties and non-desired-state, which are assumed to be # "control" values like `recurse: true` - current_resource.class.properties.each do |name,property| + current_resource.class.properties.each do |name, property| if property.desired_state? && !property.identity? && !property.name_property? property.reset(current_resource) end diff --git a/lib/chef/resource/apt_package.rb b/lib/chef/resource/apt_package.rb index 069fefcb2b..400a968c24 100644 --- a/lib/chef/resource/apt_package.rb +++ b/lib/chef/resource/apt_package.rb @@ -26,7 +26,6 @@ class Chef provides :package, os: "linux", platform_family: [ "debian" ] property :default_release, String, desired_state: false - end end end diff --git a/lib/chef/resource/bash.rb b/lib/chef/resource/bash.rb index 4abaf629cf..8b0199896c 100644 --- a/lib/chef/resource/bash.rb +++ b/lib/chef/resource/bash.rb @@ -22,12 +22,10 @@ require "chef/provider/script" class Chef class Resource class Bash < Chef::Resource::Script - - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @interpreter = "bash" end - end end end diff --git a/lib/chef/resource/batch.rb b/lib/chef/resource/batch.rb index e6eed983f0..a595871d52 100644 --- a/lib/chef/resource/batch.rb +++ b/lib/chef/resource/batch.rb @@ -21,13 +21,11 @@ require "chef/resource/windows_script" class Chef class Resource class Batch < Chef::Resource::WindowsScript - provides :batch, os: "windows" - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super(name, run_context, nil, "cmd.exe") end - end end end diff --git a/lib/chef/resource/breakpoint.rb b/lib/chef/resource/breakpoint.rb index 040acc40a3..a9af4b3a3a 100644 --- a/lib/chef/resource/breakpoint.rb +++ b/lib/chef/resource/breakpoint.rb @@ -16,7 +16,6 @@ # limitations under the License. # - require "chef/resource" class Chef @@ -24,10 +23,9 @@ class Chef class Breakpoint < Chef::Resource default_action :break - def initialize(action="break", *args) + def initialize(action = "break", *args) super(caller.first, *args) end - end end end diff --git a/lib/chef/resource/chef_gem.rb b/lib/chef/resource/chef_gem.rb index d2f8f98aff..edc82efa5f 100644 --- a/lib/chef/resource/chef_gem.rb +++ b/lib/chef/resource/chef_gem.rb @@ -25,9 +25,9 @@ class Chef resource_name :chef_gem property :gem_binary, default: "#{RbConfig::CONFIG['bindir']}/gem", - callbacks: { - "The chef_gem resource is restricted to the current gem environment, use gem_package to install to other environments." => proc { |v| v == "#{RbConfig::CONFIG['bindir']}/gem" } - } + callbacks: { + "The chef_gem resource is restricted to the current gem environment, use gem_package to install to other environments." => proc { |v| v == "#{RbConfig::CONFIG['bindir']}/gem" } + } property :compile_time, [ true, false, nil ], default: lazy { Chef::Config[:chef_gem_compile_time] }, desired_state: false def after_created diff --git a/lib/chef/resource/chocolatey_package.rb b/lib/chef/resource/chocolatey_package.rb index 4b4a537e7f..3e2deff158 100644 --- a/lib/chef/resource/chocolatey_package.rb +++ b/lib/chef/resource/chocolatey_package.rb @@ -21,12 +21,11 @@ require "chef/resource/package" class Chef class Resource class ChocolateyPackage < Chef::Resource::Package - provides :chocolatey_package, os: "windows" allowed_actions :install, :upgrade, :remove, :uninstall, :purge, :reconfig - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @resource_name = :chocolatey_package end diff --git a/lib/chef/resource/conditional.rb b/lib/chef/resource/conditional.rb index 12fd55d572..cdb9f13c45 100644 --- a/lib/chef/resource/conditional.rb +++ b/lib/chef/resource/conditional.rb @@ -30,11 +30,11 @@ class Chef private :new end - def self.not_if(parent_resource, command=nil, command_opts={}, &block) + def self.not_if(parent_resource, command = nil, command_opts = {}, &block) new(:not_if, parent_resource, command, command_opts, &block) end - def self.only_if(parent_resource, command=nil, command_opts={}, &block) + def self.only_if(parent_resource, command = nil, command_opts = {}, &block) new(:only_if, parent_resource, command, command_opts, &block) end @@ -43,7 +43,7 @@ class Chef attr_reader :command_opts attr_reader :block - def initialize(positivity, parent_resource, command=nil, command_opts={}, &block) + def initialize(positivity, parent_resource, command = nil, command_opts = {}, &block) @positivity = positivity @command, @command_opts = command, command_opts @block = block @@ -55,7 +55,7 @@ class Chef def configure case @command - when String,Array + when String, Array @guard_interpreter = Chef::GuardInterpreter.for_resource(@parent_resource, @command, @command_opts) @block = nil when nil diff --git a/lib/chef/resource/conditional_action_not_nothing.rb b/lib/chef/resource/conditional_action_not_nothing.rb index 94b542e33e..9336caaa11 100644 --- a/lib/chef/resource/conditional_action_not_nothing.rb +++ b/lib/chef/resource/conditional_action_not_nothing.rb @@ -19,7 +19,6 @@ class Chef class Resource class ConditionalActionNotNothing - attr_reader :current_action def initialize(current_action) @@ -42,7 +41,6 @@ class Chef def to_text "not_if { action == :nothing }" end - end end end diff --git a/lib/chef/resource/cookbook_file.rb b/lib/chef/resource/cookbook_file.rb index 6f1da0aa01..557ca0e750 100644 --- a/lib/chef/resource/cookbook_file.rb +++ b/lib/chef/resource/cookbook_file.rb @@ -29,21 +29,20 @@ class Chef default_action :create - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @provider = Chef::Provider::CookbookFile @source = ::File.basename(name) @cookbook = nil end - def source(source_filename=nil) + def source(source_filename = nil) set_or_return(:source, source_filename, :kind_of => [ String, Array ]) end - def cookbook(cookbook_name=nil) + def cookbook(cookbook_name = nil) set_or_return(:cookbook, cookbook_name, :kind_of => String) end - end end end diff --git a/lib/chef/resource/cron.rb b/lib/chef/resource/cron.rb index e105cc94d8..0d0c130794 100644 --- a/lib/chef/resource/cron.rb +++ b/lib/chef/resource/cron.rb @@ -22,7 +22,6 @@ require "chef/resource" class Chef class Resource class Cron < Chef::Resource - identity_attr :command state_attrs :minute, :hour, :day, :month, :weekday, :user @@ -30,7 +29,7 @@ class Chef default_action :create allowed_actions :create, :delete - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @minute = "*" @hour = "*" @@ -47,7 +46,7 @@ class Chef @environment = {} end - def minute(arg=nil) + def minute(arg = nil) if arg.is_a?(Integer) converted_arg = arg.to_s else @@ -64,7 +63,7 @@ class Chef ) end - def hour(arg=nil) + def hour(arg = nil) if arg.is_a?(Integer) converted_arg = arg.to_s else @@ -81,7 +80,7 @@ class Chef ) end - def day(arg=nil) + def day(arg = nil) if arg.is_a?(Integer) converted_arg = arg.to_s else @@ -98,7 +97,7 @@ class Chef ) end - def month(arg=nil) + def month(arg = nil) if arg.is_a?(Integer) converted_arg = arg.to_s else @@ -115,7 +114,7 @@ class Chef ) end - def weekday(arg=nil) + def weekday(arg = nil) if arg.is_a?(Integer) converted_arg = arg.to_s else @@ -123,11 +122,11 @@ class Chef end begin error_message = "You provided '#{arg}' as a weekday, acceptable values are " - error_message << Provider::Cron::WEEKDAY_SYMBOLS.map {|sym| ":#{sym}"}.join(", ") + error_message << Provider::Cron::WEEKDAY_SYMBOLS.map { |sym| ":#{sym}" }.join(", ") error_message << " and a string in crontab format" if (arg.is_a?(Symbol) && !Provider::Cron::WEEKDAY_SYMBOLS.include?(arg)) || - (!arg.is_a?(Symbol) && integerize(arg) > 7) || - (!arg.is_a?(Symbol) && integerize(arg) < 0) + (!arg.is_a?(Symbol) && integerize(arg) > 7) || + (!arg.is_a?(Symbol) && integerize(arg) < 0) raise RangeError, error_message end rescue ArgumentError @@ -139,7 +138,7 @@ class Chef ) end - def time(arg=nil) + def time(arg = nil) set_or_return( :time, arg, @@ -147,7 +146,7 @@ class Chef ) end - def mailto(arg=nil) + def mailto(arg = nil) set_or_return( :mailto, arg, @@ -155,7 +154,7 @@ class Chef ) end - def path(arg=nil) + def path(arg = nil) set_or_return( :path, arg, @@ -163,7 +162,7 @@ class Chef ) end - def home(arg=nil) + def home(arg = nil) set_or_return( :home, arg, @@ -171,7 +170,7 @@ class Chef ) end - def shell(arg=nil) + def shell(arg = nil) set_or_return( :shell, arg, @@ -179,7 +178,7 @@ class Chef ) end - def command(arg=nil) + def command(arg = nil) set_or_return( :command, arg, @@ -187,7 +186,7 @@ class Chef ) end - def user(arg=nil) + def user(arg = nil) set_or_return( :user, arg, @@ -195,7 +194,7 @@ class Chef ) end - def environment(arg=nil) + def environment(arg = nil) set_or_return( :environment, arg, diff --git a/lib/chef/resource/csh.rb b/lib/chef/resource/csh.rb index b4bae13399..e0c5254a1d 100644 --- a/lib/chef/resource/csh.rb +++ b/lib/chef/resource/csh.rb @@ -22,12 +22,10 @@ require "chef/provider/script" class Chef class Resource class Csh < Chef::Resource::Script - - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @interpreter = "csh" end - end end end diff --git a/lib/chef/resource/deploy.rb b/lib/chef/resource/deploy.rb index 797e2a664a..db0e34c4f9 100644 --- a/lib/chef/resource/deploy.rb +++ b/lib/chef/resource/deploy.rb @@ -40,7 +40,6 @@ require "chef/resource/scm" class Chef class Resource - # Deploy: Deploy apps from a source control repository. # # Callbacks: @@ -51,7 +50,6 @@ class Chef # release directory. Callback files can contain chef code (resources, etc.) # class Deploy < Chef::Resource - identity_attr :repository state_attrs :deploy_to, :revision @@ -59,7 +57,7 @@ class Chef default_action :deploy allowed_actions :force_deploy, :deploy, :rollback - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @deploy_to = name @environment = nil @@ -67,8 +65,8 @@ class Chef @copy_exclude = [] @purge_before_symlink = %w{log tmp/pids public/system} @create_dirs_before_symlink = %w{tmp public config} - @symlink_before_migrate = {"config/database.yml" => "config/database.yml"} - @symlinks = {"system" => "public/system", "pids" => "tmp/pids", "log" => "log"} + @symlink_before_migrate = { "config/database.yml" => "config/database.yml" } + @symlinks = { "system" => "public/system", "pids" => "tmp/pids", "log" => "log" } @revision = "HEAD" @migrate = false @rollback_on_error = false @@ -99,7 +97,7 @@ class Chef @current_path ||= @deploy_to + "/current" end - def depth(arg=@shallow_clone ? 5 : nil) + def depth(arg = @shallow_clone ? 5 : nil) set_or_return( :depth, arg, @@ -108,7 +106,7 @@ class Chef end # note: deploy_to is your application "meta-root." - def deploy_to(arg=nil) + def deploy_to(arg = nil) set_or_return( :deploy_to, arg, @@ -116,7 +114,7 @@ class Chef ) end - def repo(arg=nil) + def repo(arg = nil) set_or_return( :repo, arg, @@ -125,7 +123,7 @@ class Chef end alias :repository :repo - def remote(arg=nil) + def remote(arg = nil) set_or_return( :remote, arg, @@ -133,7 +131,7 @@ class Chef ) end - def role(arg=nil) + def role(arg = nil) set_or_return( :role, arg, @@ -141,7 +139,7 @@ class Chef ) end - def restart_command(arg=nil, &block) + def restart_command(arg = nil, &block) arg ||= block set_or_return( :restart_command, @@ -151,7 +149,7 @@ class Chef end alias :restart :restart_command - def migrate(arg=nil) + def migrate(arg = nil) set_or_return( :migrate, arg, @@ -159,7 +157,7 @@ class Chef ) end - def migration_command(arg=nil) + def migration_command(arg = nil) set_or_return( :migration_command, arg, @@ -167,7 +165,7 @@ class Chef ) end - def rollback_on_error(arg=nil) + def rollback_on_error(arg = nil) set_or_return( :rollback_on_error, arg, @@ -175,7 +173,7 @@ class Chef ) end - def user(arg=nil) + def user(arg = nil) set_or_return( :user, arg, @@ -183,7 +181,7 @@ class Chef ) end - def group(arg=nil) + def group(arg = nil) set_or_return( :group, arg, @@ -191,7 +189,7 @@ class Chef ) end - def enable_submodules(arg=nil) + def enable_submodules(arg = nil) set_or_return( :enable_submodules, arg, @@ -199,7 +197,7 @@ class Chef ) end - def shallow_clone(arg=nil) + def shallow_clone(arg = nil) set_or_return( :shallow_clone, arg, @@ -207,7 +205,7 @@ class Chef ) end - def repository_cache(arg=nil) + def repository_cache(arg = nil) set_or_return( :repository_cache, arg, @@ -215,7 +213,7 @@ class Chef ) end - def copy_exclude(arg=nil) + def copy_exclude(arg = nil) set_or_return( :copy_exclude, arg, @@ -223,7 +221,7 @@ class Chef ) end - def revision(arg=nil) + def revision(arg = nil) set_or_return( :revision, arg, @@ -232,7 +230,7 @@ class Chef end alias :branch :revision - def git_ssh_wrapper(arg=nil) + def git_ssh_wrapper(arg = nil) set_or_return( :git_ssh_wrapper, arg, @@ -241,7 +239,7 @@ class Chef end alias :ssh_wrapper :git_ssh_wrapper - def svn_username(arg=nil) + def svn_username(arg = nil) set_or_return( :svn_username, arg, @@ -249,7 +247,7 @@ class Chef ) end - def svn_password(arg=nil) + def svn_password(arg = nil) set_or_return( :svn_password, arg, @@ -257,7 +255,7 @@ class Chef ) end - def svn_arguments(arg=nil) + def svn_arguments(arg = nil) set_or_return( :svn_arguments, arg, @@ -265,14 +263,14 @@ class Chef ) end - def svn_info_args(arg=nil) + def svn_info_args(arg = nil) set_or_return( :svn_arguments, arg, :kind_of => [ String ]) end - def scm_provider(arg=nil) + def scm_provider(arg = nil) klass = if arg.kind_of?(String) || arg.kind_of?(Symbol) lookup_provider_constant(arg) else @@ -291,7 +289,7 @@ class Chef Chef::Provider::Deploy end - def svn_force_export(arg=nil) + def svn_force_export(arg = nil) set_or_return( :svn_force_export, arg, @@ -299,11 +297,11 @@ class Chef ) end - def environment(arg=nil) + def environment(arg = nil) if arg.is_a?(String) Chef::Log.debug "Setting RAILS_ENV, RACK_ENV, and MERB_ENV to `#{arg}'" Chef::Log.warn "[DEPRECATED] please modify your deploy recipe or attributes to set the environment using a hash" - arg = {"RAILS_ENV"=>arg,"MERB_ENV"=>arg,"RACK_ENV"=>arg} + arg = { "RAILS_ENV" => arg, "MERB_ENV" => arg, "RACK_ENV" => arg } end set_or_return( :environment, @@ -313,7 +311,7 @@ class Chef end # The number of old release directories to keep around after cleanup - def keep_releases(arg=nil) + def keep_releases(arg = nil) [set_or_return( :keep_releases, arg, @@ -324,7 +322,7 @@ class Chef # SCM clone/checkout before symlinking. Use this to get rid of files and # directories you want to be shared between releases. # Default: ["log", "tmp/pids", "public/system"] - def purge_before_symlink(arg=nil) + def purge_before_symlink(arg = nil) set_or_return( :purge_before_symlink, arg, @@ -340,7 +338,7 @@ class Chef # then specify tmp here so that the tmp directory will exist when you # symlink the pids directory in to the current release. # Default: ["tmp", "public", "config"] - def create_dirs_before_symlink(arg=nil) + def create_dirs_before_symlink(arg = nil) set_or_return( :create_dirs_before_symlink, arg, @@ -354,7 +352,7 @@ class Chef # $shared/pids that you would like to symlink as $current_release/tmp/pids # you specify it as "pids" => "tmp/pids" # Default {"system" => "public/system", "pids" => "tmp/pids", "log" => "log"} - def symlinks(arg=nil) + def symlinks(arg = nil) set_or_return( :symlinks, arg, @@ -369,7 +367,7 @@ class Chef # For a rails/merb app, this is used to link in a known good database.yml # (with the production db password) before running migrate. # Default {"config/database.yml" => "config/database.yml"} - def symlink_before_migrate(arg=nil) + def symlink_before_migrate(arg = nil) set_or_return( :symlink_before_migrate, arg, @@ -378,30 +376,30 @@ class Chef end # Callback fires before migration is run. - def before_migrate(arg=nil, &block) + def before_migrate(arg = nil, &block) arg ||= block set_or_return(:before_migrate, arg, :kind_of => [Proc, String]) end # Callback fires before symlinking - def before_symlink(arg=nil, &block) + def before_symlink(arg = nil, &block) arg ||= block set_or_return(:before_symlink, arg, :kind_of => [Proc, String]) end # Callback fires before restart - def before_restart(arg=nil, &block) + def before_restart(arg = nil, &block) arg ||= block set_or_return(:before_restart, arg, :kind_of => [Proc, String]) end # Callback fires after restart - def after_restart(arg=nil, &block) + def after_restart(arg = nil, &block) arg ||= block set_or_return(:after_restart, arg, :kind_of => [Proc, String]) end - def additional_remotes(arg=nil) + def additional_remotes(arg = nil) set_or_return( :additional_remotes, arg, @@ -409,7 +407,7 @@ class Chef ) end - def enable_checkout(arg=nil) + def enable_checkout(arg = nil) set_or_return( :enable_checkout, arg, @@ -417,7 +415,7 @@ class Chef ) end - def checkout_branch(arg=nil) + def checkout_branch(arg = nil) set_or_return( :checkout_branch, arg, @@ -430,14 +428,13 @@ class Chef # timeout for SCM operations. The deploy resource must therefore support # a timeout method, but the timeout it describes is for SCM operations, # not the overall deployment. This is potentially confusing. - def timeout(arg=nil) + def timeout(arg = nil) set_or_return( :timeout, arg, :kind_of => Integer, ) end - end end end diff --git a/lib/chef/resource/deploy_revision.rb b/lib/chef/resource/deploy_revision.rb index 41046ec288..ad03014b69 100644 --- a/lib/chef/resource/deploy_revision.rb +++ b/lib/chef/resource/deploy_revision.rb @@ -18,7 +18,6 @@ class Chef class Resource - # Convenience class for using the deploy resource with the revision # deployment strategy (provider) class DeployRevision < Chef::Resource::Deploy @@ -26,6 +25,5 @@ class Chef class DeployBranch < Chef::Resource::DeployRevision end - end end diff --git a/lib/chef/resource/directory.rb b/lib/chef/resource/directory.rb index 1f0c4cdb51..71cd7e28f1 100644 --- a/lib/chef/resource/directory.rb +++ b/lib/chef/resource/directory.rb @@ -25,7 +25,6 @@ require "chef/mixin/securable" class Chef class Resource class Directory < Chef::Resource - identity_attr :path state_attrs :group, :mode, :owner @@ -35,13 +34,13 @@ class Chef default_action :create allowed_actions :create, :delete - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @path = name @recursive = false end - def recursive(arg=nil) + def recursive(arg = nil) set_or_return( :recursive, arg, @@ -49,14 +48,13 @@ class Chef ) end - def path(arg=nil) + def path(arg = nil) set_or_return( :path, arg, :kind_of => String, ) end - end end end diff --git a/lib/chef/resource/dsc_resource.rb b/lib/chef/resource/dsc_resource.rb index d1777e77d9..4a55ce1d70 100644 --- a/lib/chef/resource/dsc_resource.rb +++ b/lib/chef/resource/dsc_resource.rb @@ -52,7 +52,7 @@ class Chef @reboot_action = :nothing end - def resource(value=nil) + def resource(value = nil) if value @resource = value else @@ -60,7 +60,7 @@ class Chef end end - def module_name(value=nil) + def module_name(value = nil) if value @module_name = value else @@ -68,7 +68,7 @@ class Chef end end - def property(property_name, value=nil) + def property(property_name, value = nil) if not property_name.is_a?(Symbol) raise TypeError, "A property name of type Symbol must be specified, '#{property_name}' of type #{property_name.class} was given" end @@ -91,7 +91,7 @@ class Chef # If the set method of the DSC resource indicate that a reboot # is necessary, reboot_action provides the mechanism for a reboot to # be requested. - def reboot_action(value=nil) + def reboot_action(value = nil) if value @reboot_action = value else @@ -99,13 +99,14 @@ class Chef end end - def timeout(arg=nil) + def timeout(arg = nil) set_or_return( :timeout, arg, :kind_of => [ Integer ], ) end + private def value_of(value) diff --git a/lib/chef/resource/dsc_script.rb b/lib/chef/resource/dsc_script.rb index 633a98c456..a8eeeb1d4f 100644 --- a/lib/chef/resource/dsc_script.rb +++ b/lib/chef/resource/dsc_script.rb @@ -28,12 +28,12 @@ class Chef default_action :run - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @imports = {} end - def code(arg=nil) + def code(arg = nil) if arg && command raise ArgumentError, "Only one of 'code' and 'command' attributes may be specified" end @@ -47,7 +47,7 @@ class Chef ) end - def configuration_name(arg=nil) + def configuration_name(arg = nil) if arg && code raise ArgumentError, "Attribute `configuration_name` may not be set if `code` is set" end @@ -58,7 +58,7 @@ class Chef ) end - def command(arg=nil) + def command(arg = nil) if arg && code raise ArgumentError, "The 'code' and 'command' attributes may not be used together" end @@ -69,7 +69,7 @@ class Chef ) end - def configuration_data(arg=nil) + def configuration_data(arg = nil) if arg && configuration_data_script raise ArgumentError, "The 'configuration_data' and 'configuration_data_script' attributes may not be used together" end @@ -80,7 +80,7 @@ class Chef ) end - def configuration_data_script(arg=nil) + def configuration_data_script(arg = nil) if arg && configuration_data raise ArgumentError, "The 'configuration_data' and 'configuration_data_script' attributes may not be used together" end @@ -91,7 +91,7 @@ class Chef ) end - def imports(module_name=nil, *args) + def imports(module_name = nil, *args) if module_name @imports[module_name] ||= [] if args.length == 0 @@ -104,7 +104,7 @@ class Chef end end - def flags(arg=nil) + def flags(arg = nil) set_or_return( :flags, arg, @@ -112,7 +112,7 @@ class Chef ) end - def cwd(arg=nil) + def cwd(arg = nil) set_or_return( :cwd, arg, @@ -120,7 +120,7 @@ class Chef ) end - def environment(arg=nil) + def environment(arg = nil) set_or_return( :environment, arg, @@ -128,7 +128,7 @@ class Chef ) end - def timeout(arg=nil) + def timeout(arg = nil) set_or_return( :timeout, arg, diff --git a/lib/chef/resource/easy_install_package.rb b/lib/chef/resource/easy_install_package.rb index dc5073a6f7..0b433d17ac 100644 --- a/lib/chef/resource/easy_install_package.rb +++ b/lib/chef/resource/easy_install_package.rb @@ -26,7 +26,6 @@ class Chef property :easy_install_binary, String, desired_state: false property :python_binary, String, desired_state: false property :module_name, String, desired_state: false - end end end diff --git a/lib/chef/resource/env.rb b/lib/chef/resource/env.rb index a6caa3299a..05313136b3 100644 --- a/lib/chef/resource/env.rb +++ b/lib/chef/resource/env.rb @@ -20,7 +20,6 @@ class Chef class Resource class Env < Chef::Resource - identity_attr :key_name state_attrs :value @@ -30,14 +29,14 @@ class Chef default_action :create allowed_actions :create, :delete, :modify - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @key_name = name @value = nil @delim = nil end - def key_name(arg=nil) + def key_name(arg = nil) set_or_return( :key_name, arg, @@ -45,7 +44,7 @@ class Chef ) end - def value(arg=nil) + def value(arg = nil) set_or_return( :value, arg, @@ -53,7 +52,7 @@ class Chef ) end - def delim(arg=nil) + def delim(arg = nil) set_or_return( :delim, arg, diff --git a/lib/chef/resource/erl_call.rb b/lib/chef/resource/erl_call.rb index 607bcc0fae..830e02b71b 100644 --- a/lib/chef/resource/erl_call.rb +++ b/lib/chef/resource/erl_call.rb @@ -23,14 +23,13 @@ require "chef/provider/erl_call" class Chef class Resource class ErlCall < Chef::Resource - # erl_call : http://erlang.org/doc/man/erl_call.html identity_attr :code default_action :run - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @code = "q()." # your erlang code goes here @@ -40,7 +39,7 @@ class Chef @node_name = "chef@localhost" # the erlang node hostname end - def code(arg=nil) + def code(arg = nil) set_or_return( :code, arg, @@ -48,7 +47,7 @@ class Chef ) end - def cookie(arg=nil) + def cookie(arg = nil) set_or_return( :cookie, arg, @@ -56,7 +55,7 @@ class Chef ) end - def distributed(arg=nil) + def distributed(arg = nil) set_or_return( :distributed, arg, @@ -64,7 +63,7 @@ class Chef ) end - def name_type(arg=nil) + def name_type(arg = nil) set_or_return( :name_type, arg, @@ -72,14 +71,13 @@ class Chef ) end - def node_name(arg=nil) + def node_name(arg = nil) set_or_return( :node_name, arg, :kind_of => [ String ], ) end - end end end diff --git a/lib/chef/resource/execute.rb b/lib/chef/resource/execute.rb index 167720f09f..cf8ffda02b 100644 --- a/lib/chef/resource/execute.rb +++ b/lib/chef/resource/execute.rb @@ -23,7 +23,6 @@ require "chef/provider/execute" class Chef class Resource class Execute < Chef::Resource - identity_attr :command # The ResourceGuardInterpreter wraps a resource's guards in another resource. That inner resource @@ -34,7 +33,7 @@ class Chef default_action :run - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @command = name @backup = 5 @@ -52,7 +51,7 @@ class Chef @live_stream = false end - def umask(arg=nil) + def umask(arg = nil) set_or_return( :umask, arg, @@ -60,7 +59,7 @@ class Chef ) end - def command(arg=nil) + def command(arg = nil) set_or_return( :command, arg, @@ -68,7 +67,7 @@ class Chef ) end - def creates(arg=nil) + def creates(arg = nil) set_or_return( :creates, arg, @@ -76,7 +75,7 @@ class Chef ) end - def cwd(arg=nil) + def cwd(arg = nil) set_or_return( :cwd, arg, @@ -84,7 +83,7 @@ class Chef ) end - def environment(arg=nil) + def environment(arg = nil) set_or_return( :environment, arg, @@ -94,7 +93,7 @@ class Chef alias :env :environment - def group(arg=nil) + def group(arg = nil) set_or_return( :group, arg, @@ -102,14 +101,14 @@ class Chef ) end - def live_stream(arg=nil) + def live_stream(arg = nil) set_or_return( :live_stream, arg, :kind_of => [ TrueClass, FalseClass ]) end - def path(arg=nil) + def path(arg = nil) Chef::Log.warn "The 'path' attribute of 'execute' is not used by any provider in Chef 11 or Chef 12. Use 'environment' attribute to configure 'PATH'. This attribute will be removed in Chef 13." set_or_return( @@ -119,7 +118,7 @@ class Chef ) end - def returns(arg=nil) + def returns(arg = nil) set_or_return( :returns, arg, @@ -127,7 +126,7 @@ class Chef ) end - def timeout(arg=nil) + def timeout(arg = nil) set_or_return( :timeout, arg, @@ -135,7 +134,7 @@ class Chef ) end - def user(arg=nil) + def user(arg = nil) set_or_return( :user, arg, @@ -166,7 +165,6 @@ class Chef :user, :umask, ) - end end end diff --git a/lib/chef/resource/file.rb b/lib/chef/resource/file.rb index f2606f72f0..ac6dc5fbdb 100644 --- a/lib/chef/resource/file.rb +++ b/lib/chef/resource/file.rb @@ -58,7 +58,7 @@ class Chef property :manage_symlink_source, [ true, false ], desired_state: false property :verifications, Array, default: lazy { [] } - def verify(command=nil, opts={}, &block) + def verify(command = nil, opts = {}, &block) if ! (command.nil? || [String, Symbol].include?(command.class)) raise ArgumentError, "verify requires either a string, symbol, or a block" end diff --git a/lib/chef/resource/file/verification.rb b/lib/chef/resource/file/verification.rb index 1c00797668..2bf82406c4 100644 --- a/lib/chef/resource/file/verification.rb +++ b/lib/chef/resource/file/verification.rb @@ -23,7 +23,6 @@ require "chef/mixin/descendants_tracker" class Chef class Resource class File < Chef::Resource - # # See RFC 027 for a full specification # @@ -73,7 +72,7 @@ class Chef end def self.lookup(name) - c = descendants.find {|d| d.provides?(name) } + c = descendants.find { |d| d.provides?(name) } if c.nil? raise Chef::Exceptions::VerificationNotFound.new "No file verification for #{name} found." end @@ -86,7 +85,7 @@ class Chef @parent_resource = parent_resource end - def verify(path, opts={}) + def verify(path, opts = {}) Chef::Log.debug("Running verification[#{self}] on #{path}") if @block verify_block(path, opts) @@ -112,7 +111,7 @@ class Chef "%{file} is deprecated in verify command and will not be "\ "supported in Chef 13. Please use %{path} instead." ) if @command.include?("%{file}") - command = @command % {:file => path, :path => path} + command = @command % { :file => path, :path => path } interpreter = Chef::GuardInterpreter.for_resource(@parent_resource, command, @command_opts) interpreter.evaluate end diff --git a/lib/chef/resource/gem_package.rb b/lib/chef/resource/gem_package.rb index e095115356..4c400e5c28 100644 --- a/lib/chef/resource/gem_package.rb +++ b/lib/chef/resource/gem_package.rb @@ -35,7 +35,6 @@ class Chef # will be installed by shelling out to the gem command. Using a Hash of # options with an explicit gem_binary will result in undefined behavior. property :options, [ String, Hash, nil ], desired_state: false - end end end diff --git a/lib/chef/resource/git.rb b/lib/chef/resource/git.rb index 44d4c9b684..efbf13245b 100644 --- a/lib/chef/resource/git.rb +++ b/lib/chef/resource/git.rb @@ -21,13 +21,12 @@ require "chef/resource/scm" class Chef class Resource class Git < Chef::Resource::Scm - - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @additional_remotes = Hash[] end - def additional_remotes(arg=nil) + def additional_remotes(arg = nil) set_or_return( :additional_remotes, arg, diff --git a/lib/chef/resource/group.rb b/lib/chef/resource/group.rb index 6a53e0de22..8d3ac8d8e0 100644 --- a/lib/chef/resource/group.rb +++ b/lib/chef/resource/group.rb @@ -20,7 +20,6 @@ class Chef class Resource class Group < Chef::Resource - identity_attr :group_name state_attrs :members @@ -28,7 +27,7 @@ class Chef allowed_actions :create, :remove, :modify, :manage default_action :create - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @group_name = name @gid = nil @@ -38,7 +37,7 @@ class Chef @non_unique = false end - def group_name(arg=nil) + def group_name(arg = nil) set_or_return( :group_name, arg, @@ -46,7 +45,7 @@ class Chef ) end - def gid(arg=nil) + def gid(arg = nil) set_or_return( :gid, arg, @@ -54,7 +53,7 @@ class Chef ) end - def members(arg=nil) + def members(arg = nil) converted_members = arg.is_a?(String) ? [].push(arg) : arg set_or_return( :members, @@ -65,7 +64,7 @@ class Chef alias_method :users, :members - def excluded_members(arg=nil) + def excluded_members(arg = nil) converted_members = arg.is_a?(String) ? [].push(arg) : arg set_or_return( :excluded_members, @@ -74,8 +73,7 @@ class Chef ) end - - def append(arg=nil) + def append(arg = nil) set_or_return( :append, arg, @@ -83,7 +81,7 @@ class Chef ) end - def system(arg=nil) + def system(arg = nil) set_or_return( :system, arg, @@ -91,7 +89,7 @@ class Chef ) end - def non_unique(arg=nil) + def non_unique(arg = nil) set_or_return( :non_unique, arg, diff --git a/lib/chef/resource/homebrew_package.rb b/lib/chef/resource/homebrew_package.rb index c2d0a65c5b..020a3e9cc0 100644 --- a/lib/chef/resource/homebrew_package.rb +++ b/lib/chef/resource/homebrew_package.rb @@ -28,7 +28,6 @@ class Chef provides :package, os: "darwin" property :homebrew_user, [ String, Integer ] - end end end diff --git a/lib/chef/resource/http_request.rb b/lib/chef/resource/http_request.rb index a8299a9064..d7ac62bbd9 100644 --- a/lib/chef/resource/http_request.rb +++ b/lib/chef/resource/http_request.rb @@ -23,20 +23,19 @@ require "chef/provider/http_request" class Chef class Resource class HttpRequest < Chef::Resource - identity_attr :url default_action :get allowed_actions :get, :put, :post, :delete, :head, :options - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @message = name @url = nil @headers = {} end - def url(args=nil) + def url(args = nil) set_or_return( :url, args, @@ -44,7 +43,7 @@ class Chef ) end - def message(args=nil, &block) + def message(args = nil, &block) args = block if block_given? set_or_return( :message, @@ -53,14 +52,13 @@ class Chef ) end - def headers(args=nil) + def headers(args = nil) set_or_return( :headers, args, :kind_of => Hash, ) end - end end end diff --git a/lib/chef/resource/ifconfig.rb b/lib/chef/resource/ifconfig.rb index c751595380..3832edf752 100644 --- a/lib/chef/resource/ifconfig.rb +++ b/lib/chef/resource/ifconfig.rb @@ -22,7 +22,6 @@ require "chef/resource" class Chef class Resource class Ifconfig < Chef::Resource - identity_attr :device state_attrs :inet_addr, :mask @@ -30,7 +29,7 @@ class Chef default_action :add allowed_actions :add, :delete, :enable, :disable - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @target = name @hwaddr = nil @@ -46,7 +45,7 @@ class Chef @onparent = nil end - def target(arg=nil) + def target(arg = nil) set_or_return( :target, arg, @@ -54,7 +53,7 @@ class Chef ) end - def device(arg=nil) + def device(arg = nil) set_or_return( :device, arg, @@ -62,7 +61,7 @@ class Chef ) end - def hwaddr(arg=nil) + def hwaddr(arg = nil) set_or_return( :hwaddr, arg, @@ -70,7 +69,7 @@ class Chef ) end - def inet_addr(arg=nil) + def inet_addr(arg = nil) set_or_return( :inet_addr, arg, @@ -78,7 +77,7 @@ class Chef ) end - def bcast(arg=nil) + def bcast(arg = nil) set_or_return( :bcast, arg, @@ -86,7 +85,7 @@ class Chef ) end - def mask(arg=nil) + def mask(arg = nil) set_or_return( :mask, arg, @@ -94,7 +93,7 @@ class Chef ) end - def mtu(arg=nil) + def mtu(arg = nil) set_or_return( :mtu, arg, @@ -102,7 +101,7 @@ class Chef ) end - def metric(arg=nil) + def metric(arg = nil) set_or_return( :metric, arg, @@ -110,7 +109,7 @@ class Chef ) end - def onboot(arg=nil) + def onboot(arg = nil) set_or_return( :onboot, arg, @@ -118,7 +117,7 @@ class Chef ) end - def network(arg=nil) + def network(arg = nil) set_or_return( :network, arg, @@ -126,7 +125,7 @@ class Chef ) end - def bootproto(arg=nil) + def bootproto(arg = nil) set_or_return( :bootproto, arg, @@ -134,7 +133,7 @@ class Chef ) end - def onparent(arg=nil) + def onparent(arg = nil) set_or_return( :onparent, arg, @@ -142,6 +141,5 @@ class Chef ) end end - end end diff --git a/lib/chef/resource/ksh.rb b/lib/chef/resource/ksh.rb index 3e54b5e836..e1f3b8d500 100644 --- a/lib/chef/resource/ksh.rb +++ b/lib/chef/resource/ksh.rb @@ -21,12 +21,10 @@ require "chef/resource/script" class Chef class Resource class Ksh < Chef::Resource::Script - - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @interpreter = "ksh" end - end end end diff --git a/lib/chef/resource/link.rb b/lib/chef/resource/link.rb index c2d5aa102c..a85e9eb058 100644 --- a/lib/chef/resource/link.rb +++ b/lib/chef/resource/link.rb @@ -32,7 +32,7 @@ class Chef default_action :create allowed_actions :create, :delete - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) verify_links_supported! super @to = nil @@ -40,7 +40,7 @@ class Chef @target_file = name end - def to(arg=nil) + def to(arg = nil) set_or_return( :to, arg, @@ -48,7 +48,7 @@ class Chef ) end - def target_file(arg=nil) + def target_file(arg = nil) set_or_return( :target_file, arg, @@ -56,7 +56,7 @@ class Chef ) end - def link_type(arg=nil) + def link_type(arg = nil) real_arg = arg.kind_of?(String) ? arg.to_sym : arg set_or_return( :link_type, @@ -65,7 +65,7 @@ class Chef ) end - def group(arg=nil) + def group(arg = nil) set_or_return( :group, arg, @@ -73,7 +73,7 @@ class Chef ) end - def owner(arg=nil) + def owner(arg = nil) set_or_return( :owner, arg, @@ -87,6 +87,7 @@ class Chef end private + def verify_links_supported! # On certain versions of windows links are not supported. Make # sure we are not on such a platform. diff --git a/lib/chef/resource/log.rb b/lib/chef/resource/log.rb index 49f821b3f2..89c807b0dd 100644 --- a/lib/chef/resource/log.rb +++ b/lib/chef/resource/log.rb @@ -23,7 +23,6 @@ require "chef/provider/log" class Chef class Resource class Log < Chef::Resource - identity_attr :message default_action :write @@ -48,13 +47,13 @@ class Chef # name:: Message to log # collection:: Collection of included recipes # node:: Node where resource will be used - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @level = :info @message = name end - def message(arg=nil) + def message(arg = nil) set_or_return( :message, arg, @@ -63,14 +62,13 @@ class Chef end # Log level, one of :debug, :info, :warn, :error or :fatal - def level(arg=nil) + def level(arg = nil) set_or_return( :level, arg, :equal_to => [ :debug, :info, :warn, :error, :fatal ], ) end - end end end diff --git a/lib/chef/resource/lwrp_base.rb b/lib/chef/resource/lwrp_base.rb index 7dfe147341..95a5e5bb2f 100644 --- a/lib/chef/resource/lwrp_base.rb +++ b/lib/chef/resource/lwrp_base.rb @@ -29,15 +29,12 @@ require "chef/mixin/params_validate" # for DelayedEvaluator class Chef class Resource - # == Chef::Resource::LWRPBase # Base class for LWRP resources. Adds DSL sugar on top of Chef::Resource, # so attributes, default action, etc. can be defined with pleasing syntax. class LWRPBase < Resource - # Class methods class < String, ) end - end end end diff --git a/lib/chef/resource/mdadm.rb b/lib/chef/resource/mdadm.rb index 235cd86210..d51cc91964 100644 --- a/lib/chef/resource/mdadm.rb +++ b/lib/chef/resource/mdadm.rb @@ -22,7 +22,6 @@ require "chef/resource" class Chef class Resource class Mdadm < Chef::Resource - identity_attr :raid_device state_attrs :devices, :level, :chunk @@ -30,7 +29,7 @@ class Chef default_action :create allowed_actions :create, :assemble, :stop - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @chunk = 16 @@ -42,7 +41,7 @@ class Chef @raid_device = name end - def chunk(arg=nil) + def chunk(arg = nil) set_or_return( :chunk, arg, @@ -50,7 +49,7 @@ class Chef ) end - def devices(arg=nil) + def devices(arg = nil) set_or_return( :devices, arg, @@ -58,7 +57,7 @@ class Chef ) end - def exists(arg=nil) + def exists(arg = nil) set_or_return( :exists, arg, @@ -66,7 +65,7 @@ class Chef ) end - def level(arg=nil) + def level(arg = nil) set_or_return( :level, arg, @@ -74,7 +73,7 @@ class Chef ) end - def metadata(arg=nil) + def metadata(arg = nil) set_or_return( :metadata, arg, @@ -82,7 +81,7 @@ class Chef ) end - def bitmap(arg=nil) + def bitmap(arg = nil) set_or_return( :bitmap, arg, @@ -90,15 +89,13 @@ class Chef ) end - def raid_device(arg=nil) + def raid_device(arg = nil) set_or_return( :raid_device, arg, :kind_of => [ String ], ) end - - end end end diff --git a/lib/chef/resource/mount.rb b/lib/chef/resource/mount.rb index 9d0c0291f8..88a0a869db 100644 --- a/lib/chef/resource/mount.rb +++ b/lib/chef/resource/mount.rb @@ -22,7 +22,6 @@ require "chef/resource" class Chef class Resource class Mount < Chef::Resource - identity_attr :device state_attrs :mount_point, :device_type, :fstype, :username, :password, :domain @@ -30,7 +29,7 @@ class Chef default_action :mount allowed_actions :mount, :umount, :remount, :enable, :disable - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @mount_point = name @device = nil @@ -48,7 +47,7 @@ class Chef @domain = nil end - def mount_point(arg=nil) + def mount_point(arg = nil) set_or_return( :mount_point, arg, @@ -56,7 +55,7 @@ class Chef ) end - def device(arg=nil) + def device(arg = nil) set_or_return( :device, arg, @@ -64,7 +63,7 @@ class Chef ) end - def device_type(arg=nil) + def device_type(arg = nil) real_arg = arg.kind_of?(String) ? arg.to_sym : arg valid_devices = if RUBY_PLATFORM =~ /solaris/i [ :device ] @@ -78,7 +77,7 @@ class Chef ) end - def fsck_device(arg=nil) + def fsck_device(arg = nil) set_or_return( :fsck_device, arg, @@ -86,7 +85,7 @@ class Chef ) end - def fstype(arg=nil) + def fstype(arg = nil) set_or_return( :fstype, arg, @@ -94,7 +93,7 @@ class Chef ) end - def options(arg=nil) + def options(arg = nil) ret = set_or_return( :options, arg, @@ -108,7 +107,7 @@ class Chef end end - def dump(arg=nil) + def dump(arg = nil) set_or_return( :dump, arg, @@ -116,7 +115,7 @@ class Chef ) end - def pass(arg=nil) + def pass(arg = nil) set_or_return( :pass, arg, @@ -124,7 +123,7 @@ class Chef ) end - def mounted(arg=nil) + def mounted(arg = nil) set_or_return( :mounted, arg, @@ -132,7 +131,7 @@ class Chef ) end - def enabled(arg=nil) + def enabled(arg = nil) set_or_return( :enabled, arg, @@ -140,7 +139,7 @@ class Chef ) end - def supports(args={}) + def supports(args = {}) if args.is_a? Array args.each { |arg| @supports[arg] = true } elsif args.any? @@ -150,7 +149,7 @@ class Chef end end - def username(arg=nil) + def username(arg = nil) set_or_return( :username, arg, @@ -158,7 +157,7 @@ class Chef ) end - def password(arg=nil) + def password(arg = nil) set_or_return( :password, arg, @@ -166,7 +165,7 @@ class Chef ) end - def domain(arg=nil) + def domain(arg = nil) set_or_return( :domain, arg, @@ -181,7 +180,6 @@ class Chef def clear_fstype @fstype = nil end - end end end diff --git a/lib/chef/resource/ohai.rb b/lib/chef/resource/ohai.rb index b36cf32880..634b83537a 100644 --- a/lib/chef/resource/ohai.rb +++ b/lib/chef/resource/ohai.rb @@ -20,20 +20,19 @@ class Chef class Resource class Ohai < Chef::Resource - identity_attr :name state_attrs :plugin default_action :reload - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @name = name @plugin = nil end - def plugin(arg=nil) + def plugin(arg = nil) set_or_return( :plugin, arg, @@ -41,7 +40,7 @@ class Chef ) end - def name(arg=nil) + def name(arg = nil) set_or_return( :name, arg, diff --git a/lib/chef/resource/osx_profile.rb b/lib/chef/resource/osx_profile.rb index aa01fa2ac0..d93c945216 100644 --- a/lib/chef/resource/osx_profile.rb +++ b/lib/chef/resource/osx_profile.rb @@ -29,7 +29,7 @@ class Chef default_action :install allowed_actions :install, :remove - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @profile_name = name @profile = nil @@ -37,7 +37,7 @@ class Chef @path = nil end - def profile_name(arg=nil) + def profile_name(arg = nil) set_or_return( :profile_name, arg, @@ -45,7 +45,7 @@ class Chef ) end - def profile(arg=nil) + def profile(arg = nil) set_or_return( :profile, arg, @@ -53,7 +53,7 @@ class Chef ) end - def identifier(arg=nil) + def identifier(arg = nil) set_or_return( :identifier, arg, @@ -61,14 +61,13 @@ class Chef ) end - def path(arg=nil) + def path(arg = nil) set_or_return( :path, arg, :kind_of => [ String ], ) end - end end end diff --git a/lib/chef/resource/package.rb b/lib/chef/resource/package.rb index 32339e1a24..2b5729447b 100644 --- a/lib/chef/resource/package.rb +++ b/lib/chef/resource/package.rb @@ -41,7 +41,6 @@ class Chef property :response_file_variables, Hash, default: lazy { {} }, desired_state: false property :source, String, desired_state: false property :timeout, [ String, Integer ], desired_state: false - end end end diff --git a/lib/chef/resource/perl.rb b/lib/chef/resource/perl.rb index 783751aca4..3d630489b5 100644 --- a/lib/chef/resource/perl.rb +++ b/lib/chef/resource/perl.rb @@ -22,11 +22,10 @@ require "chef/provider/script" class Chef class Resource class Perl < Chef::Resource::Script - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @interpreter = "perl" end - end end end diff --git a/lib/chef/resource/portage_package.rb b/lib/chef/resource/portage_package.rb index 9814ccda56..8137ba4b14 100644 --- a/lib/chef/resource/portage_package.rb +++ b/lib/chef/resource/portage_package.rb @@ -22,11 +22,10 @@ class Chef class Resource class PortagePackage < Chef::Resource::Package resource_name :portage_package - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @provider = Chef::Provider::Package::Portage end - end end end diff --git a/lib/chef/resource/powershell_script.rb b/lib/chef/resource/powershell_script.rb index 891438eb01..e66db9fa55 100644 --- a/lib/chef/resource/powershell_script.rb +++ b/lib/chef/resource/powershell_script.rb @@ -22,12 +22,12 @@ class Chef class PowershellScript < Chef::Resource::WindowsScript provides :powershell_script, os: "windows" - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super(name, run_context, nil, "powershell.exe") @convert_boolean_return = false end - def convert_boolean_return(arg=nil) + def convert_boolean_return(arg = nil) set_or_return( :convert_boolean_return, arg, @@ -43,7 +43,7 @@ class Chef # guard context and recipe resource context will have the # same behavior. def self.get_default_attributes(opts) - {:convert_boolean_return => true} + { :convert_boolean_return => true } end end end diff --git a/lib/chef/resource/python.rb b/lib/chef/resource/python.rb index d2a7a4fc14..746f2b247b 100644 --- a/lib/chef/resource/python.rb +++ b/lib/chef/resource/python.rb @@ -21,11 +21,10 @@ require "chef/provider/script" class Chef class Resource class Python < Chef::Resource::Script - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @interpreter = "python" end - end end end diff --git a/lib/chef/resource/reboot.rb b/lib/chef/resource/reboot.rb index 2941294ff8..24d6e74157 100644 --- a/lib/chef/resource/reboot.rb +++ b/lib/chef/resource/reboot.rb @@ -26,7 +26,7 @@ class Chef class Reboot < Chef::Resource allowed_actions :request_reboot, :reboot_now, :cancel - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @provider = Chef::Provider::Reboot @@ -36,11 +36,11 @@ class Chef # no default action. end - def reason(arg=nil) + def reason(arg = nil) set_or_return(:reason, arg, :kind_of => String) end - def delay_mins(arg=nil) + def delay_mins(arg = nil) set_or_return(:delay_mins, arg, :kind_of => Fixnum) end end diff --git a/lib/chef/resource/registry_key.rb b/lib/chef/resource/registry_key.rb index eaa9a00de5..30e6a17759 100644 --- a/lib/chef/resource/registry_key.rb +++ b/lib/chef/resource/registry_key.rb @@ -59,7 +59,7 @@ class Chef # See lib/chef/resource_reporter.rb for more information. attr_reader :unscrubbed_values - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @architecture = :machine @recursive = false @@ -67,7 +67,7 @@ class Chef @values, @unscrubbed_values = [], [] end - def key(arg=nil) + def key(arg = nil) set_or_return( :key, arg, @@ -75,7 +75,7 @@ class Chef ) end - def values(arg=nil) + def values(arg = nil) if not arg.nil? if arg.is_a?(Hash) @values = [ arg ] @@ -90,7 +90,7 @@ class Chef raise ArgumentError, "Missing type key in RegistryKey values hash" unless v.has_key?(:type) raise ArgumentError, "Missing data key in RegistryKey values hash" unless v.has_key?(:data) v.each_key do |key| - raise ArgumentError, "Bad key #{key} in RegistryKey values hash" unless [:name,:type,:data].include?(key) + raise ArgumentError, "Bad key #{key} in RegistryKey values hash" unless [:name, :type, :data].include?(key) end raise ArgumentError, "Type of name => #{v[:name]} should be string" unless v[:name].is_a?(String) raise ArgumentError, "Type of type => #{v[:type]} should be symbol" unless v[:type].is_a?(Symbol) @@ -101,7 +101,7 @@ class Chef end end - def recursive(arg=nil) + def recursive(arg = nil) set_or_return( :recursive, arg, @@ -109,7 +109,7 @@ class Chef ) end - def architecture(arg=nil) + def architecture(arg = nil) set_or_return( :architecture, arg, @@ -138,7 +138,6 @@ class Chef unsafe_types = [:binary, :dword, :dword_big_endian, :qword] unsafe_types.include?(value[:type]) end - end end end diff --git a/lib/chef/resource/remote_directory.rb b/lib/chef/resource/remote_directory.rb index b7fbcaf3b3..6940dfd091 100644 --- a/lib/chef/resource/remote_directory.rb +++ b/lib/chef/resource/remote_directory.rb @@ -33,7 +33,7 @@ class Chef default_action :create allowed_actions :create, :create_if_missing, :delete - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @path = name @source = ::File.basename(name) @@ -53,8 +53,7 @@ class Chef rights_attribute(:files_rights) end - - def source(args=nil) + def source(args = nil) set_or_return( :source, args, @@ -62,7 +61,7 @@ class Chef ) end - def files_backup(arg=nil) + def files_backup(arg = nil) set_or_return( :files_backup, arg, @@ -70,7 +69,7 @@ class Chef ) end - def purge(arg=nil) + def purge(arg = nil) set_or_return( :purge, arg, @@ -78,7 +77,7 @@ class Chef ) end - def files_group(arg=nil) + def files_group(arg = nil) set_or_return( :files_group, arg, @@ -86,7 +85,7 @@ class Chef ) end - def files_mode(arg=nil) + def files_mode(arg = nil) set_or_return( :files_mode, arg, @@ -94,7 +93,7 @@ class Chef ) end - def files_owner(arg=nil) + def files_owner(arg = nil) set_or_return( :files_owner, arg, @@ -102,7 +101,7 @@ class Chef ) end - def overwrite(arg=nil) + def overwrite(arg = nil) set_or_return( :overwrite, arg, @@ -110,14 +109,13 @@ class Chef ) end - def cookbook(args=nil) + def cookbook(args = nil) set_or_return( :cookbook, args, :kind_of => String, ) end - end end end diff --git a/lib/chef/resource/remote_file.rb b/lib/chef/resource/remote_file.rb index 5fce1ee89a..1ab183cbf1 100644 --- a/lib/chef/resource/remote_file.rb +++ b/lib/chef/resource/remote_file.rb @@ -28,7 +28,7 @@ class Chef class RemoteFile < Chef::Resource::File include Chef::Mixin::Securable - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @source = [] @use_etag = true @@ -51,8 +51,8 @@ class Chef ret = set_or_return(:source, arg, { :callbacks => { - :validate_source => method(:validate_source) - }}) + :validate_source => method(:validate_source) + } }) if ret.is_a? String Array(ret) else @@ -65,14 +65,14 @@ class Chef nil elsif args[0].is_a?(Chef::DelayedEvaluator) && args.count == 1 args[0] - elsif args.any? {|a| a.is_a?(Chef::DelayedEvaluator)} && args.count > 1 + elsif args.any? { |a| a.is_a?(Chef::DelayedEvaluator) } && args.count > 1 raise Exceptions::InvalidRemoteFileURI, "Only 1 source argument allowed when using a lazy evaluator" else Array(args).flatten end end - def checksum(args=nil) + def checksum(args = nil) set_or_return( :checksum, args, @@ -88,7 +88,7 @@ class Chef use_last_modified(true_or_false) end - def use_etag(args=nil) + def use_etag(args = nil) set_or_return( :use_etag, args, @@ -98,7 +98,7 @@ class Chef alias :use_etags :use_etag - def use_last_modified(args=nil) + def use_last_modified(args = nil) set_or_return( :use_last_modified, args, @@ -106,7 +106,7 @@ class Chef ) end - def ftp_active_mode(args=nil) + def ftp_active_mode(args = nil) set_or_return( :ftp_active_mode, args, @@ -114,7 +114,7 @@ class Chef ) end - def headers(args=nil) + def headers(args = nil) set_or_return( :headers, args, @@ -143,7 +143,6 @@ class Chef rescue URI::InvalidURIError false end - end end end diff --git a/lib/chef/resource/resource_notification.rb b/lib/chef/resource/resource_notification.rb index ee90064a17..200f2161b9 100644 --- a/lib/chef/resource/resource_notification.rb +++ b/lib/chef/resource/resource_notification.rb @@ -21,7 +21,6 @@ require "chef/resource" class Chef class Resource class Notification - attr_accessor :resource, :action, :notifying_resource def initialize(resource, action, notifying_resource) @@ -116,7 +115,6 @@ is defined near #{resource.source_line} return false unless other.is_a?(self.class) other.resource == resource && other.action == action && other.notifying_resource == notifying_resource end - end end end diff --git a/lib/chef/resource/route.rb b/lib/chef/resource/route.rb index b817ed33e0..bbfbada674 100644 --- a/lib/chef/resource/route.rb +++ b/lib/chef/resource/route.rb @@ -29,7 +29,7 @@ class Chef default_action :add allowed_actions :add, :delete - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @target = name @netmask = nil @@ -44,7 +44,7 @@ class Chef @domain = nil end - def networking(arg=nil) + def networking(arg = nil) set_or_return( :networking, arg, @@ -52,7 +52,7 @@ class Chef ) end - def networking_ipv6(arg=nil) + def networking_ipv6(arg = nil) set_or_return( :networking_ipv6, arg, @@ -60,7 +60,7 @@ class Chef ) end - def hostname(arg=nil) + def hostname(arg = nil) set_or_return( :hostname, arg, @@ -68,7 +68,7 @@ class Chef ) end - def domainname(arg=nil) + def domainname(arg = nil) set_or_return( :domainname, arg, @@ -76,7 +76,7 @@ class Chef ) end - def domain(arg=nil) + def domain(arg = nil) set_or_return( :domain, arg, @@ -84,7 +84,7 @@ class Chef ) end - def target(arg=nil) + def target(arg = nil) set_or_return( :target, arg, @@ -92,7 +92,7 @@ class Chef ) end - def netmask(arg=nil) + def netmask(arg = nil) set_or_return( :netmask, arg, @@ -100,7 +100,7 @@ class Chef ) end - def gateway(arg=nil) + def gateway(arg = nil) set_or_return( :gateway, arg, @@ -108,7 +108,7 @@ class Chef ) end - def metric(arg=nil) + def metric(arg = nil) set_or_return( :metric, arg, @@ -116,7 +116,7 @@ class Chef ) end - def device(arg=nil) + def device(arg = nil) set_or_return( :device, arg, @@ -124,7 +124,7 @@ class Chef ) end - def route_type(arg=nil) + def route_type(arg = nil) real_arg = arg.kind_of?(String) ? arg.to_sym : arg set_or_return( :route_type, diff --git a/lib/chef/resource/rpm_package.rb b/lib/chef/resource/rpm_package.rb index fdb5913db5..1693bb38a4 100644 --- a/lib/chef/resource/rpm_package.rb +++ b/lib/chef/resource/rpm_package.rb @@ -26,7 +26,6 @@ class Chef provides :rpm_package, os: [ "linux", "aix" ] property :allow_downgrade, [ true, false ], default: false, desired_state: false - end end end diff --git a/lib/chef/resource/ruby.rb b/lib/chef/resource/ruby.rb index 0a7bec90a2..91805a1db6 100644 --- a/lib/chef/resource/ruby.rb +++ b/lib/chef/resource/ruby.rb @@ -22,7 +22,7 @@ require "chef/provider/script" class Chef class Resource class Ruby < Chef::Resource::Script - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @interpreter = "ruby" end diff --git a/lib/chef/resource/ruby_block.rb b/lib/chef/resource/ruby_block.rb index 48f297e6ec..7bb433b330 100644 --- a/lib/chef/resource/ruby_block.rb +++ b/lib/chef/resource/ruby_block.rb @@ -28,7 +28,7 @@ class Chef identity_attr :block_name - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @block_name = name end @@ -41,7 +41,7 @@ class Chef end end - def block_name(arg=nil) + def block_name(arg = nil) set_or_return( :block_name, arg, diff --git a/lib/chef/resource/scm.rb b/lib/chef/resource/scm.rb index 9f5c66378b..4ba31cd31b 100644 --- a/lib/chef/resource/scm.rb +++ b/lib/chef/resource/scm.rb @@ -16,7 +16,6 @@ # limitations under the License. # - require "chef/resource" class Chef @@ -29,7 +28,7 @@ class Chef default_action :sync allowed_actions :checkout, :export, :sync, :diff, :log - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @destination = name @enable_submodules = false @@ -42,7 +41,7 @@ class Chef @environment = nil end - def destination(arg=nil) + def destination(arg = nil) set_or_return( :destination, arg, @@ -50,7 +49,7 @@ class Chef ) end - def repository(arg=nil) + def repository(arg = nil) set_or_return( :repository, arg, @@ -58,7 +57,7 @@ class Chef ) end - def revision(arg=nil) + def revision(arg = nil) set_or_return( :revision, arg, @@ -66,7 +65,7 @@ class Chef ) end - def user(arg=nil) + def user(arg = nil) set_or_return( :user, arg, @@ -74,7 +73,7 @@ class Chef ) end - def group(arg=nil) + def group(arg = nil) set_or_return( :group, arg, @@ -82,7 +81,7 @@ class Chef ) end - def svn_username(arg=nil) + def svn_username(arg = nil) set_or_return( :svn_username, arg, @@ -90,7 +89,7 @@ class Chef ) end - def svn_password(arg=nil) + def svn_password(arg = nil) set_or_return( :svn_password, arg, @@ -98,7 +97,7 @@ class Chef ) end - def svn_arguments(arg=nil) + def svn_arguments(arg = nil) @svn_arguments, arg = nil, nil if arg == false set_or_return( :svn_arguments, @@ -107,7 +106,7 @@ class Chef ) end - def svn_info_args(arg=nil) + def svn_info_args(arg = nil) @svn_info_args, arg = nil, nil if arg == false set_or_return( :svn_info_args, @@ -116,7 +115,7 @@ class Chef end # Capistrano and git-deploy use ``shallow clone'' - def depth(arg=nil) + def depth(arg = nil) set_or_return( :depth, arg, @@ -124,7 +123,7 @@ class Chef ) end - def enable_submodules(arg=nil) + def enable_submodules(arg = nil) set_or_return( :enable_submodules, arg, @@ -132,7 +131,7 @@ class Chef ) end - def enable_checkout(arg=nil) + def enable_checkout(arg = nil) set_or_return( :enable_checkout, arg, @@ -140,7 +139,7 @@ class Chef ) end - def remote(arg=nil) + def remote(arg = nil) set_or_return( :remote, arg, @@ -148,7 +147,7 @@ class Chef ) end - def ssh_wrapper(arg=nil) + def ssh_wrapper(arg = nil) set_or_return( :ssh_wrapper, arg, @@ -156,7 +155,7 @@ class Chef ) end - def timeout(arg=nil) + def timeout(arg = nil) set_or_return( :timeout, arg, @@ -164,7 +163,7 @@ class Chef ) end - def checkout_branch(arg=nil) + def checkout_branch(arg = nil) set_or_return( :checkout_branch, arg, @@ -172,7 +171,7 @@ class Chef ) end - def environment(arg=nil) + def environment(arg = nil) set_or_return( :environment, arg, diff --git a/lib/chef/resource/script.rb b/lib/chef/resource/script.rb index c7748a7eb8..3c2c4501ea 100644 --- a/lib/chef/resource/script.rb +++ b/lib/chef/resource/script.rb @@ -26,7 +26,7 @@ class Chef # Chef-13: go back to using :name as the identity attr identity_attr :command - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super # Chef-13: the command variable should be initialized to nil @command = name @@ -36,7 +36,7 @@ class Chef @default_guard_interpreter = :default end - def command(arg=nil) + def command(arg = nil) unless arg.nil? # Chef-13: change this to raise if the user is trying to set a value here Chef::Log.warn "Specifying command attribute on a script resource is a coding error, use the 'code' attribute, or the execute resource" @@ -45,7 +45,7 @@ class Chef super end - def code(arg=nil) + def code(arg = nil) set_or_return( :code, arg, @@ -53,7 +53,7 @@ class Chef ) end - def interpreter(arg=nil) + def interpreter(arg = nil) set_or_return( :interpreter, arg, @@ -61,14 +61,13 @@ class Chef ) end - def flags(arg=nil) + def flags(arg = nil) set_or_return( :flags, arg, :kind_of => [ String ], ) end - end end end diff --git a/lib/chef/resource/service.rb b/lib/chef/resource/service.rb index 504fdac104..7e9143a29c 100644 --- a/lib/chef/resource/service.rb +++ b/lib/chef/resource/service.rb @@ -29,7 +29,7 @@ class Chef default_action :nothing allowed_actions :enable, :disable, :start, :stop, :restart, :reload - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @service_name = name @enabled = nil @@ -48,7 +48,7 @@ class Chef @supports = { :restart => nil, :reload => nil, :status => nil } end - def service_name(arg=nil) + def service_name(arg = nil) set_or_return( :service_name, arg, @@ -57,7 +57,7 @@ class Chef end # regex for match against ps -ef when !supports[:has_status] && status == nil - def pattern(arg=nil) + def pattern(arg = nil) set_or_return( :pattern, arg, @@ -66,7 +66,7 @@ class Chef end # command to call to start service - def start_command(arg=nil) + def start_command(arg = nil) set_or_return( :start_command, arg, @@ -75,7 +75,7 @@ class Chef end # command to call to stop service - def stop_command(arg=nil) + def stop_command(arg = nil) set_or_return( :stop_command, arg, @@ -84,7 +84,7 @@ class Chef end # command to call to get status of service - def status_command(arg=nil) + def status_command(arg = nil) set_or_return( :status_command, arg, @@ -93,7 +93,7 @@ class Chef end # command to call to restart service - def restart_command(arg=nil) + def restart_command(arg = nil) set_or_return( :restart_command, arg, @@ -101,7 +101,7 @@ class Chef ) end - def reload_command(arg=nil) + def reload_command(arg = nil) set_or_return( :reload_command, arg, @@ -114,7 +114,7 @@ class Chef # non-standard configurations setting this value will save having to # specify overrides for the start_command, stop_command and # restart_command attributes. - def init_command(arg=nil) + def init_command(arg = nil) set_or_return( :init_command, arg, @@ -123,7 +123,7 @@ class Chef end # if the service is enabled or not - def enabled(arg=nil) + def enabled(arg = nil) set_or_return( :enabled, arg, @@ -132,7 +132,7 @@ class Chef end # if the service is running or not - def running(arg=nil) + def running(arg = nil) set_or_return( :running, arg, @@ -150,7 +150,7 @@ class Chef # runlevel 2, stopped in 3 with priority 55 and no symlinks or # similar for other runlevels # - def priority(arg=nil) + def priority(arg = nil) set_or_return( :priority, arg, @@ -159,7 +159,7 @@ class Chef end # timeout only applies to the windows service manager - def timeout(arg=nil) + def timeout(arg = nil) set_or_return( :timeout, arg, @@ -167,7 +167,7 @@ class Chef ) end - def parameters(arg=nil) + def parameters(arg = nil) set_or_return( :parameters, arg, @@ -175,14 +175,14 @@ class Chef ) end - def run_levels(arg=nil) + def run_levels(arg = nil) set_or_return( :run_levels, arg, :kind_of => [ Array ] ) end - def supports(args={}) + def supports(args = {}) if args.is_a? Array args.each { |arg| @supports[arg] = true } elsif args.any? @@ -191,7 +191,6 @@ class Chef @supports end end - end end end diff --git a/lib/chef/resource/subversion.rb b/lib/chef/resource/subversion.rb index c391fdfd0f..9966614eeb 100644 --- a/lib/chef/resource/subversion.rb +++ b/lib/chef/resource/subversion.rb @@ -24,7 +24,7 @@ class Chef class Subversion < Chef::Resource::Scm allowed_actions :force_export - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @svn_arguments = "--no-auth-cache" @svn_info_args = "--no-auth-cache" @@ -36,7 +36,7 @@ class Chef "#{self} (#{defined_at}) had an error: #{e.class.name}: #{svn_password ? e.message.gsub(svn_password, "[hidden_password]") : e.message}" end - def svn_binary(arg=nil) + def svn_binary(arg = nil) set_or_return(:svn_binary, arg, :kind_of => [String]) end end diff --git a/lib/chef/resource/template.rb b/lib/chef/resource/template.rb index 9a1a69120d..0561025006 100644 --- a/lib/chef/resource/template.rb +++ b/lib/chef/resource/template.rb @@ -30,7 +30,7 @@ class Chef attr_reader :inline_helper_blocks attr_reader :inline_helper_modules - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @source = "#{::File.basename(name)}.erb" @cookbook = nil @@ -41,7 +41,7 @@ class Chef @helper_modules = [] end - def source(file=nil) + def source(file = nil) set_or_return( :source, file, @@ -49,7 +49,7 @@ class Chef ) end - def variables(args=nil) + def variables(args = nil) set_or_return( :variables, args, @@ -57,7 +57,7 @@ class Chef ) end - def cookbook(args=nil) + def cookbook(args = nil) set_or_return( :cookbook, args, @@ -65,7 +65,7 @@ class Chef ) end - def local(args=nil) + def local(args = nil) set_or_return( :local, args, @@ -160,7 +160,7 @@ class Chef # And in the template resource: # helpers(MyTemplateHelper) # The template code in the above example will work unmodified. - def helpers(module_name=nil,&block) + def helpers(module_name = nil, &block) if block_given? and !module_name.nil? raise Exceptions::ValidationFailed, "Passing both a module and block to #helpers is not supported. Call #helpers multiple times instead" @@ -171,8 +171,8 @@ class Chef elsif module_name.nil? raise Exceptions::ValidationFailed, "#helpers requires either a module name or inline module code as a block.\n" + - "e.g.: helpers do; helper_code; end;\n" + - "OR: helpers(MyHelpersModule)" + "e.g.: helpers do; helper_code; end;\n" + + "OR: helpers(MyHelpersModule)" else raise Exceptions::ValidationFailed, "Argument to #helpers must be a module. You gave #{module_name.inspect} (#{module_name.class})" @@ -209,7 +209,6 @@ class Chef Module.new(&module_body) end end - end end end diff --git a/lib/chef/resource/user.rb b/lib/chef/resource/user.rb index 4f11975d50..82bcba6e34 100644 --- a/lib/chef/resource/user.rb +++ b/lib/chef/resource/user.rb @@ -28,7 +28,7 @@ class Chef default_action :create allowed_actions :create, :remove, :modify, :manage, :lock, :unlock - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @username = name @comment = nil @@ -49,7 +49,7 @@ class Chef @salt = nil end - def username(arg=nil) + def username(arg = nil) set_or_return( :username, arg, @@ -57,7 +57,7 @@ class Chef ) end - def comment(arg=nil) + def comment(arg = nil) set_or_return( :comment, arg, @@ -65,7 +65,7 @@ class Chef ) end - def uid(arg=nil) + def uid(arg = nil) set_or_return( :uid, arg, @@ -73,7 +73,7 @@ class Chef ) end - def gid(arg=nil) + def gid(arg = nil) set_or_return( :gid, arg, @@ -83,7 +83,7 @@ class Chef alias_method :group, :gid - def home(arg=nil) + def home(arg = nil) set_or_return( :home, arg, @@ -91,7 +91,7 @@ class Chef ) end - def shell(arg=nil) + def shell(arg = nil) set_or_return( :shell, arg, @@ -99,7 +99,7 @@ class Chef ) end - def password(arg=nil) + def password(arg = nil) set_or_return( :password, arg, @@ -107,7 +107,7 @@ class Chef ) end - def salt(arg=nil) + def salt(arg = nil) set_or_return( :salt, arg, @@ -115,7 +115,7 @@ class Chef ) end - def iterations(arg=nil) + def iterations(arg = nil) set_or_return( :iterations, arg, @@ -123,7 +123,7 @@ class Chef ) end - def system(arg=nil) + def system(arg = nil) set_or_return( :system, arg, @@ -131,7 +131,7 @@ class Chef ) end - def manage_home(arg=nil) + def manage_home(arg = nil) set_or_return( :manage_home, arg, @@ -139,7 +139,7 @@ class Chef ) end - def force(arg=nil) + def force(arg = nil) set_or_return( :force, arg, @@ -147,14 +147,13 @@ class Chef ) end - def non_unique(arg=nil) + def non_unique(arg = nil) set_or_return( :non_unique, arg, :kind_of => [ TrueClass, FalseClass ], ) end - end end end diff --git a/lib/chef/resource/windows_package.rb b/lib/chef/resource/windows_package.rb index c718708e79..0e8dd39672 100644 --- a/lib/chef/resource/windows_package.rb +++ b/lib/chef/resource/windows_package.rb @@ -32,7 +32,7 @@ class Chef allowed_actions :install, :remove - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @source ||= source(@package_name) if @package_name.downcase.end_with?(".msi") end diff --git a/lib/chef/resource/windows_script.rb b/lib/chef/resource/windows_script.rb index 13905fc4ba..44f1d8d652 100644 --- a/lib/chef/resource/windows_script.rb +++ b/lib/chef/resource/windows_script.rb @@ -40,7 +40,7 @@ class Chef public - def architecture(arg=nil) + def architecture(arg = nil) assert_architecture_compatible!(arg) if ! arg.nil? result = set_or_return( :architecture, diff --git a/lib/chef/resource/windows_service.rb b/lib/chef/resource/windows_service.rb index ab49abc2c3..38ad504900 100644 --- a/lib/chef/resource/windows_service.rb +++ b/lib/chef/resource/windows_service.rb @@ -21,7 +21,6 @@ require "chef/resource/service" class Chef class Resource class WindowsService < Chef::Resource::Service - # Until #1773 is resolved, you need to manually specify the windows_service resource # to use action :configure_startup and attribute startup_type @@ -34,14 +33,14 @@ class Chef state_attrs :enabled, :running - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @startup_type = :automatic @run_as_user = "" @run_as_password = "" end - def startup_type(arg=nil) + def startup_type(arg = nil) # Set-Service arguments are automatic and manual # Win32::Service returns 'auto start' or 'demand start' respectively, which the provider currently uses set_or_return( @@ -51,7 +50,7 @@ class Chef ) end - def run_as_user(arg=nil) + def run_as_user(arg = nil) set_or_return( :run_as_user, arg, @@ -59,7 +58,7 @@ class Chef ) end - def run_as_password(arg=nil) + def run_as_password(arg = nil) set_or_return( :run_as_password, arg, diff --git a/lib/chef/resource/yum_package.rb b/lib/chef/resource/yum_package.rb index f2dd772d82..53b3cf3c55 100644 --- a/lib/chef/resource/yum_package.rb +++ b/lib/chef/resource/yum_package.rb @@ -41,7 +41,6 @@ class Chef } property :allow_downgrade, [ true, false ], default: false property :yum_binary, String - end end end diff --git a/lib/chef/resource_builder.rb b/lib/chef/resource_builder.rb index f3ca2e95ad..18f381c187 100644 --- a/lib/chef/resource_builder.rb +++ b/lib/chef/resource_builder.rb @@ -142,7 +142,6 @@ class Chef nil end end - end end diff --git a/lib/chef/resource_collection.rb b/lib/chef/resource_collection.rb index 369aacd29e..fd0fe933f9 100644 --- a/lib/chef/resource_collection.rb +++ b/lib/chef/resource_collection.rb @@ -45,7 +45,7 @@ class Chef # @param instance_name [String] If known, the recource name as used in the recipe, IE `vim` in `package 'vim'` # This method is meant to be the 1 insert method necessary in the future. It should support all known use cases # for writing into the ResourceCollection. - def insert(resource, opts={}) + def insert(resource, opts = {}) resource_type ||= opts[:resource_type] # Would rather use Ruby 2.x syntax, but oh well instance_name ||= opts[:instance_name] resource_list.insert(resource) @@ -78,12 +78,11 @@ class Chef # Read-only methods are simple to delegate - doing that below resource_list_methods = Enumerable.instance_methods + - [:iterator, :all_resources, :[], :each, :execute_each_resource, :each_index, :empty?] - - [:find] # find needs to run on the set + [:iterator, :all_resources, :[], :each, :execute_each_resource, :each_index, :empty?] - + [:find] # find needs to run on the set resource_set_methods = [:lookup, :find, :resources, :keys, :validate_lookup_spec!] def_delegators :resource_list, *resource_list_methods def_delegators :resource_set, *resource_set_methods - end end diff --git a/lib/chef/resource_collection/resource_collection_serialization.rb b/lib/chef/resource_collection/resource_collection_serialization.rb index b654644cd9..b119a89dfc 100644 --- a/lib/chef/resource_collection/resource_collection_serialization.rb +++ b/lib/chef/resource_collection/resource_collection_serialization.rb @@ -25,8 +25,8 @@ class Chef instance_vars[iv] = self.instance_variable_get(iv) end { - "json_class" => self.class.name, - "instance_vars" => instance_vars, + "json_class" => self.class.name, + "instance_vars" => instance_vars, } end @@ -41,7 +41,7 @@ class Chef module ClassMethods def json_create(o) collection = self.new() - o["instance_vars"].each do |k,v| + o["instance_vars"].each do |k, v| collection.instance_variable_set(k.to_sym, v) end collection diff --git a/lib/chef/resource_collection/resource_list.rb b/lib/chef/resource_collection/resource_list.rb index 20bfc7b5f0..8c13c0b19b 100644 --- a/lib/chef/resource_collection/resource_list.rb +++ b/lib/chef/resource_collection/resource_list.rb @@ -83,7 +83,6 @@ class Chef yield resource end end - end end end diff --git a/lib/chef/resource_collection/resource_set.rb b/lib/chef/resource_collection/resource_set.rb index 7bc980b6db..e347cf8465 100644 --- a/lib/chef/resource_collection/resource_set.rb +++ b/lib/chef/resource_collection/resource_set.rb @@ -40,7 +40,7 @@ class Chef @resources_by_key.keys end - def insert_as(resource, resource_type=nil, instance_name=nil) + def insert_as(resource, resource_type = nil, instance_name = nil) is_chef_resource!(resource) resource_type ||= resource.resource_name instance_name ||= resource.name @@ -124,7 +124,7 @@ class Chef else raise Chef::Exceptions::InvalidResourceSpecification, "The object `#{query_object.inspect}' is not valid for resource collection lookup. " + - "Use a String like `resource_type[resource_name]' or a Chef::Resource object" + "Use a String like `resource_type[resource_name]' or a Chef::Resource object" end end @@ -164,7 +164,6 @@ class Chef end return results end - end end end diff --git a/lib/chef/resource_collection/stepable_iterator.rb b/lib/chef/resource_collection/stepable_iterator.rb index c744ce7943..3c534079b8 100644 --- a/lib/chef/resource_collection/stepable_iterator.rb +++ b/lib/chef/resource_collection/stepable_iterator.rb @@ -18,7 +18,6 @@ class Chef class ResourceCollection class StepableIterator - def self.for_collection(new_collection) instance = new(new_collection) instance @@ -27,7 +26,7 @@ class Chef attr_accessor :collection attr_reader :position - def initialize(collection=[]) + def initialize(collection = []) @position = 0 @paused = false @collection = collection @@ -72,11 +71,11 @@ class Chef @position = 0 end - def skip_back(skips=1) + def skip_back(skips = 1) @position -= skips end - def skip_forward(skips=1) + def skip_forward(skips = 1) @position += skips end @@ -118,7 +117,6 @@ class Chef raise "42error: someone forgot to set @iterator_type, wtf?" end end - end end end diff --git a/lib/chef/resource_definition.rb b/lib/chef/resource_definition.rb index f6fe77a1fd..d541704ead 100644 --- a/lib/chef/resource_definition.rb +++ b/lib/chef/resource_definition.rb @@ -21,20 +21,19 @@ require "chef/mixin/params_validate" class Chef class ResourceDefinition - include Chef::Mixin::FromFile include Chef::Mixin::ParamsValidate attr_accessor :name, :params, :recipe, :node - def initialize(node=nil) + def initialize(node = nil) @name = nil @params = Hash.new @recipe = nil @node = node end - def define(resource_name, prototype_params=nil, &block) + def define(resource_name, prototype_params = nil, &block) unless resource_name.kind_of?(Symbol) raise ArgumentError, "You must use a symbol when defining a new resource!" end diff --git a/lib/chef/resource_definition_list.rb b/lib/chef/resource_definition_list.rb index ca3f46c4ea..22751249e4 100644 --- a/lib/chef/resource_definition_list.rb +++ b/lib/chef/resource_definition_list.rb @@ -29,7 +29,7 @@ class Chef @defines = Hash.new end - def define(resource_name, prototype_params=nil, &block) + def define(resource_name, prototype_params = nil, &block) @defines[resource_name] = ResourceDefinition.new @defines[resource_name].define(resource_name, prototype_params, &block) true diff --git a/lib/chef/resource_reporter.rb b/lib/chef/resource_reporter.rb index 19964c24cf..04fd00c103 100644 --- a/lib/chef/resource_reporter.rb +++ b/lib/chef/resource_reporter.rb @@ -25,7 +25,6 @@ require "chef/event_dispatch/base" class Chef class ResourceReporter < EventDispatch::Base - class ResourceReport < Struct.new(:new_resource, :current_resource, :action, @@ -121,8 +120,8 @@ class Chef if reporting_enabled? begin resource_history_url = "reports/nodes/#{node_name}/runs" - server_response = @rest_client.post(resource_history_url, {:action => :start, :run_id => run_id, - :start_time => start_time.to_s}, headers) + server_response = @rest_client.post(resource_history_url, { :action => :start, :run_id => run_id, + :start_time => start_time.to_s }, headers) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e handle_error_starting_run(e, resource_history_url) end @@ -232,7 +231,7 @@ class Chef Chef::Log.debug("Sending compressed run data...") # Since we're posting compressed data we can not directly call post which expects JSON begin - @rest_client.raw_request(:POST, resource_history_url, headers({"Content-Encoding" => "gzip"}), compressed_data) + @rest_client.raw_request(:POST, resource_history_url, headers({ "Content-Encoding" => "gzip" }), compressed_data) rescue StandardError => e if e.respond_to? :response Chef::FileCache.store("failed-reporting-data.json", Chef::JSONCompat.to_json_pretty(run_data), 0640) @@ -247,7 +246,7 @@ class Chef end def headers(additional_headers = {}) - options = {"X-Ops-Reporting-Protocol-Version" => PROTOCOL_VERSION} + options = { "X-Ops-Reporting-Protocol-Version" => PROTOCOL_VERSION } options.merge(additional_headers) end @@ -282,7 +281,7 @@ class Chef exception_data["class"] = exception.inspect exception_data["message"] = exception.message exception_data["backtrace"] = Chef::JSONCompat.to_json(exception.backtrace) - exception_data["description"] = @error_descriptions + exception_data["description"] = @error_descriptions run_data["data"]["exception"] = exception_data end run_data @@ -319,9 +318,8 @@ class Chef def encode_gzip(data) "".tap do |out| - Zlib::GzipWriter.wrap(StringIO.new(out)){|gz| gz << data } + Zlib::GzipWriter.wrap(StringIO.new(out)) { |gz| gz << data } end end - end end diff --git a/lib/chef/resource_resolver.rb b/lib/chef/resource_resolver.rb index d8fb7f6599..769272d637 100644 --- a/lib/chef/resource_resolver.rb +++ b/lib/chef/resource_resolver.rb @@ -47,7 +47,6 @@ class Chef new(node, resource_name, canonical: canonical).list end - include Chef::Mixin::ConvertToClassName # @api private diff --git a/lib/chef/rest.rb b/lib/chef/rest.rb index bf444ffe23..e46941e360 100644 --- a/lib/chef/rest.rb +++ b/lib/chef/rest.rb @@ -39,12 +39,10 @@ require "chef/platform/query_helpers" require "chef/http/remote_request_id" class Chef - # == Chef::REST # Chef's custom REST client with built-in JSON support and RSA signed header # authentication. class REST < HTTP - # Backwards compatibility for things that use # Chef::REST::RESTRequest or its constants RESTRequest = HTTP::HTTPRequest @@ -57,8 +55,7 @@ class Chef # all subsequent requests. For example, when initialized with a base url # http://localhost:4000, a call to +get_rest+ with 'nodes' will make an # HTTP GET request to http://localhost:4000/nodes - def initialize(url, client_name=Chef::Config[:node_name], signing_key_filename=Chef::Config[:client_key], options={}) - + def initialize(url, client_name = Chef::Config[:node_name], signing_key_filename = Chef::Config[:client_key], options = {}) Chef.log_deprecation("Chef::REST is deprecated. Please use Chef::ServerAPI, or investigate Ridley or ChefAPI.") signing_key_filename = nil if chef_zero_uri?(url) @@ -84,7 +81,6 @@ class Chef # because the order of middlewares is reversed when handling # responses. @middlewares << ValidateContentLength.new(options) - end def signing_key_filename @@ -115,7 +111,7 @@ class Chef # path:: The path to GET # raw:: Whether you want the raw body returned, or JSON inflated. Defaults # to JSON inflated. - def get(path, raw=false, headers={}) + def get(path, raw = false, headers = {}) if raw streaming_request(path, headers) else @@ -136,8 +132,8 @@ class Chef # If you rename the tempfile, it will not be deleted. # Beware that if the server streams infinite content, this method will # stream it until you run out of disk space. - def fetch(path, headers={}) - streaming_request(create_url(path), headers) {|tmp_file| yield tmp_file } + def fetch(path, headers = {}) + streaming_request(create_url(path), headers) { |tmp_file| yield tmp_file } end alias :api_request :request @@ -203,9 +199,8 @@ class Chef @decompressor.decompress_body(body) end - def authentication_headers(method, url, json_body=nil) + def authentication_headers(method, url, json_body = nil) authenticator.authentication_headers(method, url, json_body) end - end end diff --git a/lib/chef/role.rb b/lib/chef/role.rb index 22a4c9f01d..01f9411e6d 100644 --- a/lib/chef/role.rb +++ b/lib/chef/role.rb @@ -29,7 +29,6 @@ require "chef/search/query" class Chef class Role - include Chef::Mixin::FromFile include Chef::Mixin::ParamsValidate @@ -41,7 +40,7 @@ class Chef @description = "" @default_attributes = Mash.new @override_attributes = Mash.new - @env_run_lists = {"_default" => Chef::RunList.new} + @env_run_lists = { "_default" => Chef::RunList.new } @chef_server_rest = chef_server_rest end @@ -53,7 +52,7 @@ class Chef Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end - def name(arg=nil) + def name(arg = nil) set_or_return( :name, arg, @@ -61,7 +60,7 @@ class Chef ) end - def description(arg=nil) + def description(arg = nil) set_or_return( :description, arg, @@ -92,7 +91,7 @@ class Chef end # Per environment run lists - def env_run_lists(env_run_lists=nil) + def env_run_lists(env_run_lists = nil) if (!env_run_lists.nil?) unless env_run_lists.key?("_default") msg = "_default key is required in env_run_lists.\n" @@ -100,24 +99,23 @@ class Chef raise Chef::Exceptions::InvalidEnvironmentRunListSpecification, msg end @env_run_lists.clear - env_run_lists.each { |k,v| @env_run_lists[k] = Chef::RunList.new(*Array(v))} + env_run_lists.each { |k, v| @env_run_lists[k] = Chef::RunList.new(*Array(v)) } end @env_run_lists end alias :env_run_list :env_run_lists - def env_run_lists_add(env_run_lists=nil) + def env_run_lists_add(env_run_lists = nil) if (!env_run_lists.nil?) - env_run_lists.each { |k,v| @env_run_lists[k] = Chef::RunList.new(*Array(v))} + env_run_lists.each { |k, v| @env_run_lists[k] = Chef::RunList.new(*Array(v)) } end @env_run_lists end alias :env_run_list_add :env_run_lists_add - - def default_attributes(arg=nil) + def default_attributes(arg = nil) set_or_return( :default_attributes, arg, @@ -125,7 +123,7 @@ class Chef ) end - def override_attributes(arg=nil) + def override_attributes(arg = nil) set_or_return( :override_attributes, arg, @@ -184,7 +182,7 @@ class Chef # _default run_list is in 'run_list' for newer clients, and # 'recipes' for older clients. - env_run_list_hash = {"_default" => (o.has_key?("run_list") ? o["run_list"] : o["recipes"])} + env_run_list_hash = { "_default" => (o.has_key?("run_list") ? o["run_list"] : o["recipes"]) } # Clients before 0.10 do not include env_run_lists, so only # merge if it's there. @@ -197,7 +195,7 @@ class Chef end # Get the list of all roles from the API. - def self.list(inflate=false) + def self.list(inflate = false) if inflate response = Hash.new Chef::Search::Query.new.search(:role) do |n| @@ -276,6 +274,5 @@ class Chef raise Chef::Exceptions::RoleNotFound, "Role '#{name}' could not be loaded from disk" end - end end diff --git a/lib/chef/run_context.rb b/lib/chef/run_context.rb index 8b3f120deb..1c28f2bd85 100644 --- a/lib/chef/run_context.rb +++ b/lib/chef/run_context.rb @@ -28,7 +28,6 @@ require "chef/event_dispatch/events_output_stream" require "forwardable" class Chef - # == Chef::RunContext # Value object that loads and tracks the context of a Chef run class RunContext @@ -173,9 +172,9 @@ class Chef def initialize_child_state @audits = {} @resource_collection = Chef::ResourceCollection.new - @before_notification_collection = Hash.new {|h,k| h[k] = []} - @immediate_notification_collection = Hash.new {|h,k| h[k] = []} - @delayed_notification_collection = Hash.new {|h,k| h[k] = []} + @before_notification_collection = Hash.new { |h, k| h[k] = [] } + @immediate_notification_collection = Hash.new { |h, k| h[k] = [] } + @delayed_notification_collection = Hash.new { |h, k| h[k] = [] } end # @@ -322,7 +321,6 @@ including it from in that cookbook's metadata. ERROR_MESSAGE end - if loaded_fully_qualified_recipe?(cookbook_name, recipe_short_name) Chef::Log.debug("I am not loading #{recipe_name}, because I have already seen it.") false @@ -592,7 +590,6 @@ ERROR_MESSAGE end prepend Deprecated - # # A child run context. Delegates all root context calls to its parent. # diff --git a/lib/chef/run_context/cookbook_compiler.rb b/lib/chef/run_context/cookbook_compiler.rb index 57aa59881a..9b4f45787b 100644 --- a/lib/chef/run_context/cookbook_compiler.rb +++ b/lib/chef/run_context/cookbook_compiler.rb @@ -25,7 +25,6 @@ require "chef/resource_definition_list" class Chef class RunContext - # Implements the compile phase of the chef run by loading/eval-ing files # from cookbooks in the correct order and in the correct context. class CookbookCompiler @@ -165,7 +164,7 @@ class Chef def load_attributes_from_cookbook(cookbook_name) list_of_attr_files = files_in_cookbook_by_segment(cookbook_name, :attributes).dup - if default_file = list_of_attr_files.find {|path| File.basename(path) == "default.rb" } + if default_file = list_of_attr_files.find { |path| File.basename(path) == "default.rb" } list_of_attr_files.delete(default_file) load_attribute_file(cookbook_name.to_s, default_file) end @@ -224,7 +223,6 @@ class Chef raise end - def load_resource_definitions_from_cookbook(cookbook_name) files_in_cookbook_by_segment(cookbook_name, :definitions).each do |filename| begin @@ -258,7 +256,6 @@ class Chef ordered_cookbooks << cookbook end - def count_files_by_segment(segment) cookbook_collection.inject(0) do |count, cookbook_by_name| count + cookbook_by_name[1].segment_filenames(segment).size @@ -275,7 +272,7 @@ class Chef # +cookbook_name+ in lexical sort order. def each_cookbook_dep(cookbook_name, &block) cookbook = cookbook_collection[cookbook_name] - cookbook.metadata.dependencies.keys.sort.map{|x| x.to_sym}.each(&block) + cookbook.metadata.dependencies.keys.sort.map { |x| x.to_sym }.each(&block) end # Given a +recipe_name+, finds the file associated with the recipe. @@ -284,9 +281,6 @@ class Chef cookbook = cookbook_collection[cookbook_name] cookbook.recipe_filenames_by_name[recipe_short_name] end - - end - end end diff --git a/lib/chef/run_list.rb b/lib/chef/run_list.rb index 8b586f4077..021f7ecff8 100644 --- a/lib/chef/run_list.rb +++ b/lib/chef/run_list.rb @@ -47,13 +47,13 @@ class Chef end def role_names - @run_list_items.inject([]){|memo, run_list_item| memo << run_list_item.name if run_list_item.role? ; memo} + @run_list_items.inject([]) { |memo, run_list_item| memo << run_list_item.name if run_list_item.role? ; memo } end alias :roles :role_names def recipe_names - @run_list_items.inject([]){|memo, run_list_item| memo << run_list_item.name if run_list_item.recipe? ; memo} + @run_list_items.inject([]) { |memo, run_list_item| memo << run_list_item.name if run_list_item.recipe? ; memo } end alias :recipes :recipe_names @@ -130,7 +130,7 @@ class Chef end def remove(item) - @run_list_items.delete_if{|i| i == item} + @run_list_items.delete_if { |i| i == item } self end alias :delete :remove @@ -138,7 +138,7 @@ class Chef # Expands this run_list: recursively expand roles into their included # recipes. # Returns a RunListExpansion object. - def expand(environment, data_source="server", expansion_opts={}) + def expand(environment, data_source = "server", expansion_opts = {}) expansion = expansion_for_data_source(environment, data_source, expansion_opts) expansion.expand expansion @@ -153,7 +153,7 @@ class Chef item.kind_of?(RunListItem) ? item : parse_entry(item) end - def expansion_for_data_source(environment, data_source, opts={}) + def expansion_for_data_source(environment, data_source, opts = {}) case data_source.to_s when "disk" RunListExpansionFromDisk.new(environment, @run_list_items) @@ -161,6 +161,5 @@ class Chef RunListExpansionFromAPI.new(environment, @run_list_items, opts[:rest]) end end - end end diff --git a/lib/chef/run_list/run_list_expansion.rb b/lib/chef/run_list/run_list_expansion.rb index bac748096d..2a29839b35 100644 --- a/lib/chef/run_list/run_list_expansion.rb +++ b/lib/chef/run_list/run_list_expansion.rb @@ -29,7 +29,6 @@ class Chef # Abstract Base class for expanding a run list. Subclasses must handle # fetching roles from a data source by defining +fetch_role+ class RunListExpansion - attr_reader :run_list_items # A VersionedRecipeList of recipes. Populated only after #expand @@ -62,7 +61,7 @@ class Chef attr_reader :all_missing_roles attr_reader :role_errors - def initialize(environment, run_list_items, source=nil) + def initialize(environment, run_list_items, source = nil) @environment = environment @missing_roles_with_including_role = Array.new @@ -75,8 +74,8 @@ class Chef @recipes = Chef::RunList::VersionedRecipeList.new @applied_roles = {} - @run_list_trace = Hash.new {|h, key| h[key] = [] } - @better_run_list_trace = Hash.new {|h, key| h[key] = [] } + @run_list_trace = Hash.new { |h, key| h[key] = [] } + @better_run_list_trace = Hash.new { |h, key| h[key] = [] } @all_missing_roles = {} @role_errors = {} end @@ -140,7 +139,7 @@ class Chef end def errors - @missing_roles_with_including_role.map {|item| item.first } + @missing_roles_with_including_role.map { |item| item.first } end def to_json(*a) @@ -148,8 +147,8 @@ class Chef end def to_hash - seen_items = {:recipe => {}, :role => {}} - {:id => @environment, :run_list => convert_run_list_trace("top level", seen_items)} + seen_items = { :recipe => {}, :role => {} } + { :id => @environment, :run_list => convert_run_list_trace("top level", seen_items) } end private @@ -160,11 +159,10 @@ class Chef @applied_roles[role_name] = true end - def expand_run_list_items(items, included_by="top level") - + def expand_run_list_items(items, included_by = "top level") if entry = items.shift @run_list_trace[included_by.to_s] << entry.to_s - @better_run_list_trace[included_by.to_s] << entry + @better_run_list_trace[included_by.to_s] << entry case entry.type when :recipe @@ -186,33 +184,28 @@ class Chef seen_items[item.type][item.name] = true case item.type when :recipe - {:type => "recipe", :name => item.name, :version => item.version, :skipped => !!skipped} + { :type => "recipe", :name => item.name, :version => item.version, :skipped => !!skipped } when :role error = @role_errors[item.name] missing = @all_missing_roles[item.name] - {:type => :role, :name => item.name, :children => (missing || error || skipped) ? [] : convert_run_list_trace(item.to_s, seen_items), - :missing => missing, :error => error, :skipped => skipped} + { :type => :role, :name => item.name, :children => (missing || error || skipped) ? [] : convert_run_list_trace(item.to_s, seen_items), + :missing => missing, :error => error, :skipped => skipped } end end end - end - # Expand a run list from disk. Suitable for chef-solo class RunListExpansionFromDisk < RunListExpansion - def fetch_role(name, included_by) Chef::Role.from_disk(name) rescue Chef::Exceptions::RoleNotFound role_not_found(name, included_by) end - end # Expand a run list from the chef-server API. class RunListExpansionFromAPI < RunListExpansion - def rest @rest ||= (source || Chef::ServerAPI.new(Chef::Config[:chef_server_url])) end @@ -229,10 +222,6 @@ class Chef @role_errors[name] = e.to_s raise end - end - end end - - diff --git a/lib/chef/run_list/run_list_item.rb b/lib/chef/run_list/run_list_item.rb index 3e689eddef..4c81c2928a 100644 --- a/lib/chef/run_list/run_list_item.rb +++ b/lib/chef/run_list/run_list_item.rb @@ -25,7 +25,6 @@ class Chef attr_reader :name, :type, :version - def initialize(item) @version = nil case item @@ -89,11 +88,10 @@ class Chef end def assert_hash_is_valid_run_list_item!(item) - unless (item.key?("type")|| item.key?(:type)) && (item.key?("name") || item.key?(:name)) + unless (item.key?("type") || item.key?(:type)) && (item.key?("name") || item.key?(:name)) raise ArgumentError, "Initializing a #{self.class} from a hash requires that it have a 'type' and 'name' key" end end - end end end diff --git a/lib/chef/run_list/versioned_recipe_list.rb b/lib/chef/run_list/versioned_recipe_list.rb index 49622b8c43..b919b54db6 100644 --- a/lib/chef/run_list/versioned_recipe_list.rb +++ b/lib/chef/run_list/versioned_recipe_list.rb @@ -23,13 +23,12 @@ require "chef/version_constraint" class Chef class RunList class VersionedRecipeList < Array - def initialize super @versions = Hash.new end - def add_recipe(name, version=nil) + def add_recipe(name, version = nil) if version && @versions.has_key?(name) unless Chef::Version.new(@versions[name]) == Chef::Version.new(version) raise Chef::Exceptions::CookbookVersionConflict, "Run list requires #{name} at versions #{@versions[name]} and #{version}" @@ -40,7 +39,7 @@ class Chef end def with_versions - self.map {|recipe_name| {:name => recipe_name, :version => @versions[recipe_name]}} + self.map { |recipe_name| { :name => recipe_name, :version => @versions[recipe_name] } } end # Return an Array of Hashes, each of the form: diff --git a/lib/chef/run_lock.rb b/lib/chef/run_lock.rb index c4e2751391..040ea5a628 100644 --- a/lib/chef/run_lock.rb +++ b/lib/chef/run_lock.rb @@ -25,7 +25,6 @@ require "chef/exceptions" require "timeout" class Chef - # == Chef::RunLock # Provides an interface for acquiring and releasing a system-wide exclusive # lock. @@ -132,7 +131,7 @@ class Chef def create_lock # ensure the runlock_file path exists create_path(File.dirname(runlock_file)) - @runlock = File.open(runlock_file,"a+") + @runlock = File.open(runlock_file, "a+") end # @api private solely for race condition tests @@ -148,7 +147,7 @@ class Chef end # Flock will return 0 if it can acquire the lock otherwise it # will return false - if runlock.flock(File::LOCK_NB|File::LOCK_EX) == 0 + if runlock.flock(File::LOCK_NB | File::LOCK_EX) == 0 true else false diff --git a/lib/chef/run_status.rb b/lib/chef/run_status.rb index 58a6a43e3c..02e7a790f2 100644 --- a/lib/chef/run_status.rb +++ b/lib/chef/run_status.rb @@ -22,7 +22,6 @@ # are passed to any notification or exception handlers at the completion of a # Chef run. class Chef::RunStatus - attr_reader :events attr_reader :run_context @@ -113,7 +112,7 @@ class Chef::RunStatus :updated_resources => updated_resources, :exception => formatted_exception, :backtrace => backtrace, - :run_id => run_id} + :run_id => run_id } end # Returns a string of the format "ExceptionClass: message" or +nil+ if no @@ -121,5 +120,4 @@ class Chef::RunStatus def formatted_exception @exception && "#{@exception.class.name}: #{@exception.message}" end - end diff --git a/lib/chef/runner.rb b/lib/chef/runner.rb index a8cda86a6b..2c090f3fe0 100644 --- a/lib/chef/runner.rb +++ b/lib/chef/runner.rb @@ -27,7 +27,6 @@ class Chef # == Chef::Runner # This class is responsible for executing the steps in a Chef run. class Runner - attr_reader :run_context attr_reader :delayed_actions @@ -45,8 +44,7 @@ class Chef # Determine the appropriate provider for the given resource, then # execute it. - def run_action(resource, action, notification_type=nil, notifying_resource=nil) - + def run_action(resource, action, notification_type = nil, notifying_resource = nil) # If there are any before notifications, why-run the resource # and notify anyone who needs notifying # TODO cheffish has a bug where it passes itself instead of the run_context to us, so doesn't have before_notifications. Fix there, update dependency requirement, and remove this if statement. @@ -103,7 +101,7 @@ class Chef # Execute each resource. run_context.resource_collection.execute_each_resource do |resource| - Array(resource.action).each {|action| run_action(resource, action)} + Array(resource.action).each { |action| run_action(resource, action) } end rescue Exception => e @@ -117,7 +115,7 @@ class Chef private # Run all our :delayed actions - def run_delayed_notifications(error=nil) + def run_delayed_notifications(error = nil) collected_failures = Exceptions::MultipleFailures.new collected_failures.client_run_failure(error) unless error.nil? delayed_actions.each do |notification| diff --git a/lib/chef/scan_access_control.rb b/lib/chef/scan_access_control.rb index f55a106e6d..ff3ce81809 100644 --- a/lib/chef/scan_access_control.rb +++ b/lib/chef/scan_access_control.rb @@ -36,7 +36,6 @@ class Chef # TODO: figure out if all this works with OS X's negative uids # TODO: windows class ScanAccessControl - attr_reader :new_resource attr_reader :current_resource diff --git a/lib/chef/search/query.rb b/lib/chef/search/query.rb index 6041cafcf8..1e6ef02225 100644 --- a/lib/chef/search/query.rb +++ b/lib/chef/search/query.rb @@ -25,11 +25,10 @@ require "uri" class Chef class Search class Query - attr_accessor :rest attr_reader :config - def initialize(url=nil, config:Chef::Config) + def initialize(url = nil, config:Chef::Config) @config = config @url = url end @@ -40,7 +39,7 @@ class Chef # Backwards compatability for cookbooks. # This can be removed in Chef > 12. - def partial_search(type, query="*:*", *args, &block) + def partial_search(type, query = "*:*", *args, &block) Chef::Log.warn(<<-WARNDEP) DEPRECATED: The 'partial_search' API is deprecated and will be removed in future releases. Please use 'search' with a :filter_result argument to get @@ -80,7 +79,7 @@ WARNDEP # an example of the returned json may be: # {"ip_address":"127.0.0.1", "ruby_version": "1.9.3"} # - def search(type, query="*:*", *args, &block) + def search(type, query = "*:*", *args, &block) validate_type(type) args_h = hashify_args(*args) @@ -116,8 +115,8 @@ WARNDEP def validate_type(t) unless t.kind_of?(String) || t.kind_of?(Symbol) msg = "Invalid search object type #{t.inspect} (#{t.class}), must be a String or Symbol." + - "Usage: search(:node, QUERY[, OPTIONAL_ARGS])" + - " `knife search environment QUERY (options)`" + "Usage: search(:node, QUERY[, OPTIONAL_ARGS])" + + " `knife search environment QUERY (options)`" raise Chef::Exceptions::InvalidSearchQuery, msg end end @@ -174,7 +173,6 @@ WARNDEP response end - end end end diff --git a/lib/chef/server_api.rb b/lib/chef/server_api.rb index 3bfceacdd7..6b7d7daced 100644 --- a/lib/chef/server_api.rb +++ b/lib/chef/server_api.rb @@ -27,7 +27,6 @@ require "chef/http/validate_content_length" class Chef class ServerAPI < Chef::HTTP - def initialize(url = Chef::Config[:chef_server_url], options = {}) options[:client_name] ||= Chef::Config[:node_name] options[:signing_key_filename] ||= Chef::Config[:client_key] @@ -57,7 +56,7 @@ class Chef # Makes an HTTP request to +path+ with the given +method+, +headers+, and # +data+ (if applicable). Does not apply any middleware, besides that # needed for Authentication. - def raw_request(method, path, headers={}, data=false) + def raw_request(method, path, headers = {}, data = false) url = create_url(path) method, url, headers, data = Chef::HTTP::Authenticator.new(options).handle_request(method, url, headers, data) method, url, headers, data = Chef::HTTP::RemoteRequestID.new(options).handle_request(method, url, headers, data) diff --git a/lib/chef/shell.rb b/lib/chef/shell.rb index c877c1cbf3..11c4c67e8b 100644 --- a/lib/chef/shell.rb +++ b/lib/chef/shell.rb @@ -64,7 +64,6 @@ module Shell init(irb.context.main) - irb_conf[:IRB_RC].call(irb.context) if irb_conf[:IRB_RC] irb_conf[:MAIN_CONTEXT] = irb.context @@ -186,7 +185,7 @@ module Shell class Options include Mixlib::CLI - def self.footer(text=nil) + def self.footer(text = nil) @footer = text if text @footer end @@ -232,7 +231,7 @@ FOOTER :long => "--solo", :description => "chef-solo session", :boolean => true, - :proc => proc {Chef::Config[:solo] = true} + :proc => proc { Chef::Config[:solo] = true } option :client, :short => "-z", @@ -257,14 +256,14 @@ FOOTER :long => "--version", :description => "Show chef version", :boolean => true, - :proc => lambda {|v| puts "Chef: #{::Chef::VERSION}"}, + :proc => lambda { |v| puts "Chef: #{::Chef::VERSION}" }, :exit => 0 option :override_runlist, :short => "-o RunlistItem,RunlistItem...", :long => "--override-runlist RunlistItem,RunlistItem...", :description => "Replace current run list with specified items", - :proc => lambda { |items| items.split(",").map { |item| Chef::RunList::RunListItem.new(item) }} + :proc => lambda { |items| items.split(",").map { |item| Chef::RunList::RunListItem.new(item) } } def self.print_help instance = new @@ -317,7 +316,5 @@ FOOTER nil end end - end - end diff --git a/lib/chef/shell/ext.rb b/lib/chef/shell/ext.rb index 902de4ec04..b9269be881 100644 --- a/lib/chef/shell/ext.rb +++ b/lib/chef/shell/ext.rb @@ -28,19 +28,17 @@ require "chef/json_compat" module Shell module Extensions - Help = Struct.new(:cmd, :desc, :explanation) # Extensions to be included in every 'main' object in chef-shell. # These objects are extended with this module. module ObjectCoreExtensions - def ensure_session_select_defined # irb breaks if you prematurely define IRB::JobMangager # so these methods need to be defined at the latest possible time. unless jobs.respond_to?(:select_session_by_context) def jobs.select_session_by_context(&block) - @jobs.select { |job| block.call(job[1].context.main)} + @jobs.select { |job| block.call(job[1].context.main) } end end @@ -125,7 +123,7 @@ module Shell @explain = explain_text end - def subcommands(subcommand_help={}) + def subcommands(subcommand_help = {}) @subcommand_help = subcommand_help end @@ -141,7 +139,6 @@ module Shell end @subcommand_help = {} end - end module String @@ -197,7 +194,7 @@ module Shell prints a detailed explanation of the command if available, or the description if no explanation is available. E - def help(commmand=nil) + def help(commmand = nil) if commmand explain_command(commmand) else @@ -209,10 +206,10 @@ module Shell desc "prints information about chef" def version - puts "This is the chef-shell.\n" + - " Chef Version: #{::Chef::VERSION}\n" + - " http://www.chef.io/\n" + - " http://docs.chef.io/" + puts "This is the chef-shell.\n" + + " Chef Version: #{::Chef::VERSION}\n" + + " http://www.chef.io/\n" + + " http://docs.chef.io/" :ucanhaz_automation end alias :shell :version @@ -240,9 +237,9 @@ module Shell desc "returns an object to control a paused chef run" subcommands :resume => "resume the chef run", - :step => "run only the next resource", - :skip_back => "move back in the run list", - :skip_forward => "move forward in the run list" + :step => "run only the next resource", + :skip_back => "move back in the run list", + :skip_forward => "move forward in the run list" def chef_run Shell.session.resource_collection.iterator end @@ -295,7 +292,7 @@ module Shell end desc "pretty print the node's attributes" - def ohai(key=nil) + def ohai(key = nil) pp(key ? node.attribute[key] : node.attribute) end end @@ -394,17 +391,17 @@ module Shell This will strip the admin privileges from any client named after borat. E subcommands :all => "list all api clients", - :show => "load an api client by name", - :search => "search for API clients", - :transform => "edit all api clients via a code block and save them" + :show => "load an api client by name", + :search => "search for API clients", + :transform => "edit all api clients via a code block and save them" def clients @clients ||= Shell::ModelWrapper.new(Chef::ApiClient, :client) end desc "Find and edit cookbooks" subcommands :all => "list all cookbooks", - :show => "load a cookbook by name", - :transform => "edit all cookbooks via a code block and save them" + :show => "load a cookbook by name", + :transform => "edit all cookbooks via a code block and save them" def cookbooks @cookbooks ||= Shell::ModelWrapper.new(Chef::CookbookVersion) end @@ -456,9 +453,9 @@ module Shell This will assign the attribute to every node with a FQDN matching the regex. E subcommands :all => "list all nodes", - :show => "load a node by name", - :search => "search for nodes", - :transform => "edit all nodes via a code block and save them" + :show => "load a node by name", + :search => "search for nodes", + :transform => "edit all nodes via a code block and save them" def nodes @nodes ||= Shell::ModelWrapper.new(Chef::Node) end @@ -478,9 +475,9 @@ module Shell See the help for +nodes+ for more information about the subcommands. E subcommands :all => "list all roles", - :show => "load a role by name", - :search => "search for roles", - :transform => "edit all roles via a code block and save them" + :show => "load a role by name", + :search => "search for roles", + :transform => "edit all roles via a code block and save them" def roles @roles ||= Shell::ModelWrapper.new(Chef::Role) end @@ -504,9 +501,9 @@ module Shell E subcommands :all => "list all items in the data bag", - :show => "load a data bag item by id", - :search => "search for items in the data bag", - :transform => "edit all items via a code block and save them" + :show => "load a data bag item by id", + :search => "search for items in the data bag", + :transform => "edit all items via a code block and save them" def databags(databag_name) @named_databags_wrappers ||= {} @named_databags_wrappers[databag_name] ||= Shell::NamedDataBagWrapper.new(databag_name) @@ -527,9 +524,9 @@ module Shell See the help for +nodes+ for more information about the subcommands. E subcommands :all => "list all environments", - :show => "load an environment by name", - :search => "search for environments", - :transform => "edit all environments via a code block and save them" + :show => "load an environment by name", + :search => "search for environments", + :transform => "edit all environments via a code block and save them" def environments @environments ||= Shell::ModelWrapper.new(Chef::Environment) end @@ -538,7 +535,6 @@ module Shell def api @rest = Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end - end RecipeUIExtensions = Proc.new do @@ -572,7 +568,6 @@ module Shell recipe_obj.instance_eval(&ObjectUIExtensions) recipe_obj.instance_eval(&RecipeUIExtensions) end - end end diff --git a/lib/chef/shell/model_wrapper.rb b/lib/chef/shell/model_wrapper.rb index f9f9874401..b97e8155bb 100644 --- a/lib/chef/shell/model_wrapper.rb +++ b/lib/chef/shell/model_wrapper.rb @@ -21,12 +21,11 @@ require "chef/mixin/language" module Shell class ModelWrapper - include Chef::Mixin::ConvertToClassName attr_reader :model_symbol - def initialize(model_class, symbol=nil) + def initialize(model_class, symbol = nil) @model_class = model_class @model_symbol = symbol || convert_to_snake_case(model_class.name, "Chef").to_sym end @@ -79,8 +78,8 @@ module Shell # paper over inconsistencies in the model classes APIs, and return the objects # the user wanted instead of the URI=>object stuff def list_objects - objects = @model_class.method(:list).arity == 0? @model_class.list : @model_class.list(true) - objects.map { |obj| Array(obj).find {|o| o.kind_of?(@model_class)} } + objects = @model_class.method(:list).arity == 0 ? @model_class.list : @model_class.list(true) + objects.map { |obj| Array(obj).find { |o| o.kind_of?(@model_class) } } end def format_query(query) @@ -93,12 +92,10 @@ module Shell end class NamedDataBagWrapper < ModelWrapper - def initialize(databag_name) @model_symbol = @databag_name = databag_name end - alias :list :all def show(item) @@ -114,7 +111,5 @@ module Shell end all_items end - end - end diff --git a/lib/chef/shell/shell_session.rb b/lib/chef/shell/shell_session.rb index 431f9a8121..22f7eb8ad9 100644 --- a/lib/chef/shell/shell_session.rb +++ b/lib/chef/shell/shell_session.rb @@ -33,7 +33,7 @@ module Shell class ShellSession include Singleton - def self.session_type(type=nil) + def self.session_type(type = nil) @session_type = type if type @session_type end @@ -134,11 +134,9 @@ module Shell def rebuild_node raise "Not Implemented! :rebuild_node should be implemented by subclasses" end - end class StandAloneSession < ShellSession - session_type :standalone def rebuild_context @@ -156,11 +154,9 @@ module Shell @client.load_node @client.build_node end - end class SoloSession < ShellSession - session_type :solo def definitions @@ -188,11 +184,9 @@ module Shell @client.load_node @client.build_node end - end class ClientSession < SoloSession - session_type :client def save_node @@ -220,11 +214,9 @@ module Shell @client.load_node @client.build_node end - end class DoppelGangerClient < Chef::Client - attr_reader :node_name def initialize(node_name) @@ -244,7 +236,7 @@ module Shell Chef::Log.debug("Building node object for #{@node_name}") @node = Chef::Node.find_or_create(node_name) ohai_data = @ohai.data.merge(@node.automatic_attrs) - @node.consume_external_attrs(ohai_data,nil) + @node.consume_external_attrs(ohai_data, nil) @run_list_expansion = @node.expand!("server") @expanded_run_list_with_versions = @run_list_expansion.recipes.with_version_constraints_strings Chef::Log.info("Run List is [#{@node.run_list}]") @@ -254,13 +246,11 @@ module Shell def register @rest = Chef::ServerAPI.new(Chef::Config[:chef_server_url], :client_name => Chef::Config[:node_name], - :signing_key_filename => Chef::Config[:client_key]) + :signing_key_filename => Chef::Config[:client_key]) end - end class DoppelGangerSession < ClientSession - session_type "doppelganger client" def save_node @@ -293,7 +283,5 @@ module Shell @client.build_node @client.sync_cookbooks end - end - end diff --git a/lib/chef/shell_out.rb b/lib/chef/shell_out.rb index bf6018df52..3e82c339a9 100644 --- a/lib/chef/shell_out.rb +++ b/lib/chef/shell_out.rb @@ -2,10 +2,9 @@ require "mixlib/shellout" class Chef class ShellOut < Mixlib::ShellOut - def initialize(*args) Chef::Log.warn("Chef::ShellOut is deprecated, please use Mixlib::ShellOut") - called_from = caller[0..3].inject("Called from:\n") {|msg, trace_line| msg << " #{trace_line}\n" } + called_from = caller[0..3].inject("Called from:\n") { |msg, trace_line| msg << " #{trace_line}\n" } Chef::Log.warn(called_from) super end diff --git a/lib/chef/tasks/chef_repo.rake b/lib/chef/tasks/chef_repo.rake index 5d5d6640b9..543bd8d864 100644 --- a/lib/chef/tasks/chef_repo.rake +++ b/lib/chef/tasks/chef_repo.rake @@ -176,7 +176,6 @@ def deprecation_notice NOTICE: Chef Repository Rake Tasks Are Deprecated ************************************************* } - end def deprecated_cookbook_upload diff --git a/lib/chef/user.rb b/lib/chef/user.rb index 7791b56cb5..cdca8dafb5 100644 --- a/lib/chef/user.rb +++ b/lib/chef/user.rb @@ -36,7 +36,6 @@ require "chef/server_api" # should be removed once client support for Open Source Chef Server 11 expires. class Chef class User - include Chef::Mixin::FromFile include Chef::Mixin::ParamsValidate @@ -49,30 +48,30 @@ class Chef end def chef_rest_v0 - @chef_rest_v0 ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url], {:api_version => "0"}) + @chef_rest_v0 ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url], { :api_version => "0" }) end - def name(arg=nil) + def name(arg = nil) set_or_return(:name, arg, :regex => /^[a-z0-9\-_]+$/) end - def admin(arg=nil) + def admin(arg = nil) set_or_return(:admin, arg, :kind_of => [TrueClass, FalseClass]) end - def public_key(arg=nil) + def public_key(arg = nil) set_or_return(:public_key, arg, :kind_of => String) end - def private_key(arg=nil) + def private_key(arg = nil) set_or_return(:private_key, arg, :kind_of => String) end - def password(arg=nil) + def password(arg = nil) set_or_return(:password, arg, :kind_of => String) end @@ -97,21 +96,21 @@ class Chef end def create - payload = {:name => self.name, :admin => self.admin, :password => self.password } + payload = { :name => self.name, :admin => self.admin, :password => self.password } payload[:public_key] = public_key if public_key new_user = chef_rest_v0.post("users", payload) Chef::User.from_hash(self.to_hash.merge(new_user)) end - def update(new_key=false) - payload = {:name => name, :admin => admin} + def update(new_key = false) + payload = { :name => name, :admin => admin } payload[:private_key] = new_key if new_key payload[:password] = password if password updated_user = chef_rest_v0.put("users/#{name}", payload) Chef::User.from_hash(self.to_hash.merge(updated_user)) end - def save(new_key=false) + def save(new_key = false) begin create rescue Net::HTTPServerException => e @@ -159,8 +158,8 @@ class Chef Chef::User.from_json(json) end - def self.list(inflate=false) - response = Chef::ServerAPI.new(Chef::Config[:chef_server_url], {:api_version => "0"}).get("users") + def self.list(inflate = false) + response = Chef::ServerAPI.new(Chef::Config[:chef_server_url], { :api_version => "0" }).get("users") users = if response.is_a?(Array) transform_ohc_list_response(response) # OHC/OPC else @@ -177,7 +176,7 @@ class Chef end def self.load(name) - response = Chef::ServerAPI.new(Chef::Config[:chef_server_url], {:api_version => "0"}).get("users/#{name}") + response = Chef::ServerAPI.new(Chef::Config[:chef_server_url], { :api_version => "0" }).get("users/#{name}") Chef::User.from_hash(response) end diff --git a/lib/chef/user_v1.rb b/lib/chef/user_v1.rb index ba0253d50e..582e28af29 100644 --- a/lib/chef/user_v1.rb +++ b/lib/chef/user_v1.rb @@ -34,12 +34,11 @@ require "chef/server_api" # Exception: self.list is backwards compatible with OSC 11 class Chef class UserV1 - include Chef::Mixin::FromFile include Chef::Mixin::ParamsValidate include Chef::Mixin::ApiVersionRequestHandling - SUPPORTED_API_VERSIONS = [0,1] + SUPPORTED_API_VERSIONS = [0, 1] def initialize @username = nil @@ -55,59 +54,59 @@ class Chef end def chef_root_rest_v0 - @chef_root_rest_v0 ||= Chef::ServerAPI.new(Chef::Config[:chef_server_root], {:api_version => "0"}) + @chef_root_rest_v0 ||= Chef::ServerAPI.new(Chef::Config[:chef_server_root], { :api_version => "0" }) end def chef_root_rest_v1 - @chef_root_rest_v1 ||= Chef::ServerAPI.new(Chef::Config[:chef_server_root], {:api_version => "1"}) + @chef_root_rest_v1 ||= Chef::ServerAPI.new(Chef::Config[:chef_server_root], { :api_version => "1" }) end - def username(arg=nil) + def username(arg = nil) set_or_return(:username, arg, :regex => /^[a-z0-9\-_]+$/) end - def display_name(arg=nil) + def display_name(arg = nil) set_or_return(:display_name, arg, :kind_of => String) end - def first_name(arg=nil) + def first_name(arg = nil) set_or_return(:first_name, arg, :kind_of => String) end - def middle_name(arg=nil) + def middle_name(arg = nil) set_or_return(:middle_name, arg, :kind_of => String) end - def last_name(arg=nil) + def last_name(arg = nil) set_or_return(:last_name, arg, :kind_of => String) end - def email(arg=nil) + def email(arg = nil) set_or_return(:email, arg, :kind_of => String) end - def create_key(arg=nil) + def create_key(arg = nil) set_or_return(:create_key, arg, :kind_of => [TrueClass, FalseClass]) end - def public_key(arg=nil) + def public_key(arg = nil) set_or_return(:public_key, arg, :kind_of => String) end - def private_key(arg=nil) + def private_key(arg = nil) set_or_return(:private_key, arg, :kind_of => String) end - def password(arg=nil) + def password(arg = nil) set_or_return(:password, arg, :kind_of => String) end @@ -183,9 +182,9 @@ class Chef Chef::UserV1.from_hash(self.to_hash.merge(new_user)) end - def update(new_key=false) + def update(new_key = false) begin - payload = {:username => username} + payload = { :username => username } payload[:display_name] = display_name unless display_name.nil? payload[:first_name] = first_name unless first_name.nil? payload[:middle_name] = middle_name unless middle_name.nil? @@ -216,7 +215,7 @@ class Chef Chef::UserV1.from_hash(self.to_hash.merge(updated_user)) end - def save(new_key=false) + def save(new_key = false) begin create rescue Net::HTTPServerException => e @@ -231,7 +230,7 @@ class Chef # Note: remove after API v0 no longer supported by client (and knife command). def reregister begin - payload = self.to_hash.merge({"private_key" => true}) + payload = self.to_hash.merge({ "private_key" => true }) reregistered_self = chef_root_rest_v0.put("users/#{username}", payload) private_key(reregistered_self["private_key"]) # only V0 supported for reregister @@ -281,7 +280,7 @@ class Chef Chef::UserV1.from_json(json) end - def self.list(inflate=false) + def self.list(inflate = false) response = Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("users") users = if response.is_a?(Array) # EC 11 / CS 12 V0, V1 @@ -325,6 +324,5 @@ class Chef end private_class_method :transform_list_response - end end diff --git a/lib/chef/util/backup.rb b/lib/chef/util/backup.rb index e9b4ed2fe3..8bf2b3f25b 100644 --- a/lib/chef/util/backup.rb +++ b/lib/chef/util/backup.rb @@ -83,11 +83,11 @@ class Chef fn = Regexp.escape(::File.basename(path)) Dir.entries(::File.dirname(backup_path)).select do |f| !!(f =~ /\A#{fn}.chef-[0-9.]*\B/) - end.map {|f| ::File.join(::File.dirname(backup_path), f)} + end.map { |f| ::File.join(::File.dirname(backup_path), f) } end def sorted_backup_files - unsorted_backup_files.sort { |a,b| b <=> a } + unsorted_backup_files.sort { |a, b| b <=> a } end end end diff --git a/lib/chef/util/diff.rb b/lib/chef/util/diff.rb index bb1b4e2b95..1920198191 100644 --- a/lib/chef/util/diff.rb +++ b/lib/chef/util/diff.rb @@ -178,7 +178,6 @@ class Chef def encode_diff_for_json(diff_str) diff_str.encode!("UTF-8", :invalid => :replace, :undef => :replace, :replace => "?") end - end end end diff --git a/lib/chef/util/dsc/configuration_generator.rb b/lib/chef/util/dsc/configuration_generator.rb index bec9c69ff7..af9a71b246 100644 --- a/lib/chef/util/dsc/configuration_generator.rb +++ b/lib/chef/util/dsc/configuration_generator.rb @@ -70,7 +70,7 @@ class Chef::Util::DSC def get_merged_configuration_flags!(configuration_flags, configuration_name) merged_configuration_flags = { :outputpath => configuration_document_directory(configuration_name) } if configuration_flags - configuration_flags.map do | switch, value | + configuration_flags.map do |switch, value| if merged_configuration_flags.key?(switch.to_s.downcase.to_sym) raise ArgumentError, "The `flags` attribute for the dsc_script resource contained a command line switch :#{switch} that is disallowed." end @@ -114,7 +114,7 @@ Configuration '#{configuration_name}' def write_document_generation_script(code, configuration_name, imports) script_path = "#{@config_directory}/chef_dsc_config.ps1" - ::File.open(script_path, "wt") do | script | + ::File.open(script_path, "wt") do |script| script.write(configuration_code(code, configuration_name, imports)) end script_path @@ -122,7 +122,7 @@ Configuration '#{configuration_name}' def find_configuration_document(configuration_name) document_directory = configuration_document_directory(configuration_name) - document_file_name = ::Dir.entries(document_directory).find { | path | path =~ /.*.mof/ } + document_file_name = ::Dir.entries(document_directory).find { |path| path =~ /.*.mof/ } ::File.join(document_directory, document_file_name) if document_file_name end @@ -131,7 +131,7 @@ Configuration '#{configuration_name}' end def get_configuration_document(document_path) - ::File.open(document_path, "rb") do | file | + ::File.open(document_path, "rb") do |file| file.read end end diff --git a/lib/chef/util/dsc/lcm_output_parser.rb b/lib/chef/util/dsc/lcm_output_parser.rb index 8f62a27c8a..57fe0a760a 100644 --- a/lib/chef/util/dsc/lcm_output_parser.rb +++ b/lib/chef/util/dsc/lcm_output_parser.rb @@ -73,7 +73,7 @@ class Chef if current_resource[:name] resources.push(current_resource) end - current_resource = {:name => info} + current_resource = { :name => info } else Chef::Log.debug("Ignoring op_action #{op_action}: Read line #{line}") end @@ -108,8 +108,8 @@ class Chef # If the line looks like # What If: [machinename]: LCM: [op_action op_type] message # extract op_action, op_type, and message - operation, info = match.captures - op_action, op_type = operation.strip.split(" ").map {|m| m.downcase.to_sym} + operation, info = match.captures + op_action, op_type = operation.strip.split(" ").map { |m| m.downcase.to_sym } else op_action = op_type = :info if match = line.match(/^.*?:.*?: \s+(.*)/) @@ -129,7 +129,6 @@ class Chef end end private_class_method :build_resource_info - end end end diff --git a/lib/chef/util/dsc/local_configuration_manager.rb b/lib/chef/util/dsc/local_configuration_manager.rb index 6db8f40eae..3b4eaa92a9 100644 --- a/lib/chef/util/dsc/local_configuration_manager.rb +++ b/lib/chef/util/dsc/local_configuration_manager.rb @@ -111,7 +111,7 @@ EOH def save_configuration_document(configuration_document) ::FileUtils.mkdir_p(@configuration_path) - ::File.open(configuration_document_path, "wb") do | file | + ::File.open(configuration_document_path, "wb") do |file| file.write(configuration_document) end end @@ -121,7 +121,7 @@ EOH end def configuration_document_path - File.join(@configuration_path,"..mof") + File.join(@configuration_path, "..mof") end def clear_execution_time diff --git a/lib/chef/util/dsc/resource_info.rb b/lib/chef/util/dsc/resource_info.rb index 4a32451721..d6dfcff59a 100644 --- a/lib/chef/util/dsc/resource_info.rb +++ b/lib/chef/util/dsc/resource_info.rb @@ -2,25 +2,25 @@ class Chef class Util class DSC - class ResourceInfo - # The name is the text following [Start Set] - attr_reader :name + class ResourceInfo + # The name is the text following [Start Set] + attr_reader :name - # A list of all log messages between [Start Set] and [End Set]. - # Each line is an element in the list. - attr_reader :change_log + # A list of all log messages between [Start Set] and [End Set]. + # Each line is an element in the list. + attr_reader :change_log - def initialize(name, sets, change_log) - @name = name - @sets = sets - @change_log = change_log || [] - end + def initialize(name, sets, change_log) + @name = name + @sets = sets + @change_log = change_log || [] + end - # Does this resource change the state of the system? - def changes_state? - @sets - end + # Does this resource change the state of the system? + def changes_state? + @sets end + end end end end diff --git a/lib/chef/util/dsc/resource_store.rb b/lib/chef/util/dsc/resource_store.rb index df8cfa84ed..e0ad2eae6d 100644 --- a/lib/chef/util/dsc/resource_store.rb +++ b/lib/chef/util/dsc/resource_store.rb @@ -21,90 +21,88 @@ require "chef/util/powershell/cmdlet_result" require "chef/exceptions" class Chef -class Util -class DSC - class ResourceStore - - def self.instance - @@instance ||= ResourceStore.new.tap do |store| - store.send(:populate_cache) - end - end + class Util + class DSC + class ResourceStore + def self.instance + @@instance ||= ResourceStore.new.tap do |store| + store.send(:populate_cache) + end + end - def resources - @resources ||= [] - end + def resources + @resources ||= [] + end - def find(name, module_name=nil) - found = find_resources(name, module_name, resources) + def find(name, module_name = nil) + found = find_resources(name, module_name, resources) - # We don't have it, query for the resource...it might - # have been added since we last queried - if found.length == 0 - rs = query_resource(name) - add_resources(rs) - found = find_resources(name, module_name, rs) - end + # We don't have it, query for the resource...it might + # have been added since we last queried + if found.length == 0 + rs = query_resource(name) + add_resources(rs) + found = find_resources(name, module_name, rs) + end - found - end - - private + found + end - def add_resource(new_r) - count = resources.count do |r| - r["ResourceType"].casecmp(new_r["ResourceType"]) == 0 - end - if count == 0 - resources << new_r - end - end + private - def add_resources(rs) - rs.each do |r| - add_resource(r) - end - end + def add_resource(new_r) + count = resources.count do |r| + r["ResourceType"].casecmp(new_r["ResourceType"]) == 0 + end + if count == 0 + resources << new_r + end + end - def populate_cache - @resources = query_resources - end + def add_resources(rs) + rs.each do |r| + add_resource(r) + end + end - def find_resources(name, module_name, rs) - found = rs.find_all do |r| - name_matches = r["Name"].casecmp(name) == 0 - if name_matches - module_name == nil || (r["Module"] and r["Module"]["Name"].casecmp(module_name) == 0) - else - false + def populate_cache + @resources = query_resources end - end - end + def find_resources(name, module_name, rs) + found = rs.find_all do |r| + name_matches = r["Name"].casecmp(name) == 0 + if name_matches + module_name == nil || (r["Module"] and r["Module"]["Name"].casecmp(module_name) == 0) + else + false + end + end + end - # Returns a list of dsc resources - def query_resources - cmdlet = Chef::Util::Powershell::Cmdlet.new(nil, "get-dscresource", - :object) - result = cmdlet.run - result.return_value - end + # Returns a list of dsc resources + def query_resources + cmdlet = Chef::Util::Powershell::Cmdlet.new(nil, "get-dscresource", + :object) + result = cmdlet.run + result.return_value + end - # Returns a list of dsc resources matching the provided name - def query_resource(resource_name) - cmdlet = Chef::Util::Powershell::Cmdlet.new(nil, "get-dscresource #{resource_name}", - :object) - result = cmdlet.run - ret_val = result.return_value - if ret_val.nil? - [] - elsif ret_val.is_a? Array - ret_val - else - [ret_val] + # Returns a list of dsc resources matching the provided name + def query_resource(resource_name) + cmdlet = Chef::Util::Powershell::Cmdlet.new(nil, "get-dscresource #{resource_name}", + :object) + result = cmdlet.run + ret_val = result.return_value + if ret_val.nil? + [] + elsif ret_val.is_a? Array + ret_val + else + [ret_val] + end + end end end end end -end -end diff --git a/lib/chef/util/editor.rb b/lib/chef/util/editor.rb index 4073a0be70..fa4f0ec12e 100644 --- a/lib/chef/util/editor.rb +++ b/lib/chef/util/editor.rb @@ -89,4 +89,3 @@ class Chef end end end - diff --git a/lib/chef/util/file_edit.rb b/lib/chef/util/file_edit.rb index 5aa33fd169..ff0f789eee 100644 --- a/lib/chef/util/file_edit.rb +++ b/lib/chef/util/file_edit.rb @@ -21,7 +21,6 @@ require "fileutils" class Chef class Util class FileEdit - private attr_reader :editor, :original_pathname diff --git a/lib/chef/util/powershell/cmdlet.rb b/lib/chef/util/powershell/cmdlet.rb index d9b53f6c7c..6ab380c071 100644 --- a/lib/chef/util/powershell/cmdlet.rb +++ b/lib/chef/util/powershell/cmdlet.rb @@ -21,150 +21,150 @@ require "chef/mixin/windows_architecture_helper" require "chef/util/powershell/cmdlet_result" class Chef -class Util -class Powershell - class Cmdlet - def initialize(node, cmdlet, output_format=nil, output_format_options={}) - @output_format = output_format - @node = node - - case output_format - when nil - @json_format = false - when :json - @json_format = true - when :text - @json_format = false - when :object - @json_format = true - else - raise ArgumentError, "Invalid output format #{output_format} specified" - end - - @cmdlet = cmdlet - @output_format_options = output_format_options - end - - attr_reader :output_format + class Util + class Powershell + class Cmdlet + def initialize(node, cmdlet, output_format = nil, output_format_options = {}) + @output_format = output_format + @node = node + + case output_format + when nil + @json_format = false + when :json + @json_format = true + when :text + @json_format = false + when :object + @json_format = true + else + raise ArgumentError, "Invalid output format #{output_format} specified" + end - def run(switches={}, execution_options={}, *arguments) - streams = { :json => CmdletStream.new("json"), - :verbose => CmdletStream.new("verbose"), - } + @cmdlet = cmdlet + @output_format_options = output_format_options + end - arguments_string = arguments.join(" ") + attr_reader :output_format - switches_string = command_switches_string(switches) + def run(switches = {}, execution_options = {}, *arguments) + streams = { :json => CmdletStream.new("json"), + :verbose => CmdletStream.new("verbose"), + } - json_depth = 5 + arguments_string = arguments.join(" ") - if @json_format && @output_format_options.has_key?(:depth) - json_depth = @output_format_options[:depth] - end + switches_string = command_switches_string(switches) - json_command = @json_format ? " | convertto-json -compress -depth #{json_depth} "\ - "> #{streams[:json].path}" : "" - redirections = "4> '#{streams[:verbose].path}'" - command_string = "powershell.exe -executionpolicy bypass -noprofile -noninteractive "\ - "-command \"trap [Exception] {write-error -exception "\ - "($_.Exception.Message);exit 1};#{@cmdlet} #{switches_string} "\ - "#{arguments_string} #{redirections}"\ - "#{json_command}\";if ( ! $? ) { exit 1 }" + json_depth = 5 - augmented_options = {:returns => [0], :live_stream => false}.merge(execution_options) - command = Mixlib::ShellOut.new(command_string, augmented_options) + if @json_format && @output_format_options.has_key?(:depth) + json_depth = @output_format_options[:depth] + end - status = nil + json_command = @json_format ? " | convertto-json -compress -depth #{json_depth} "\ + "> #{streams[:json].path}" : "" + redirections = "4> '#{streams[:verbose].path}'" + command_string = "powershell.exe -executionpolicy bypass -noprofile -noninteractive "\ + "-command \"trap [Exception] {write-error -exception "\ + "($_.Exception.Message);exit 1};#{@cmdlet} #{switches_string} "\ + "#{arguments_string} #{redirections}"\ + "#{json_command}\";if ( ! $? ) { exit 1 }" - with_os_architecture(@node) do - status = command.run_command - end + augmented_options = { :returns => [0], :live_stream => false }.merge(execution_options) + command = Mixlib::ShellOut.new(command_string, augmented_options) - CmdletResult.new(status, streams, @output_format) - end + status = nil - def run!(switches={}, execution_options={}, *arguments) - result = run(switches, execution_options, arguments) + with_os_architecture(@node) do + status = command.run_command + end - if ! result.succeeded? - raise Chef::Exceptions::PowershellCmdletException, "Powershell Cmdlet failed: #{result.stderr}" - end + CmdletResult.new(status, streams, @output_format) + end - result - end + def run!(switches = {}, execution_options = {}, *arguments) + result = run(switches, execution_options, arguments) - protected + if ! result.succeeded? + raise Chef::Exceptions::PowershellCmdletException, "Powershell Cmdlet failed: #{result.stderr}" + end - include Chef::Mixin::WindowsArchitectureHelper + result + end - def validate_switch_name!(switch_parameter_name) - if !!(switch_parameter_name =~ /\A[A-Za-z]+[_a-zA-Z0-9]*\Z/) == false - raise ArgumentError, "`#{switch_parameter_name}` is not a valid PowerShell cmdlet switch parameter name" - end - end + protected - def escape_parameter_value(parameter_value) - parameter_value.gsub(/(`|'|"|#)/,'`\1') - end + include Chef::Mixin::WindowsArchitectureHelper - def escape_string_parameter_value(parameter_value) - "'#{escape_parameter_value(parameter_value)}'" - end + def validate_switch_name!(switch_parameter_name) + if !!(switch_parameter_name =~ /\A[A-Za-z]+[_a-zA-Z0-9]*\Z/) == false + raise ArgumentError, "`#{switch_parameter_name}` is not a valid PowerShell cmdlet switch parameter name" + end + end - def command_switches_string(switches) - command_switches = switches.map do | 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'" + def escape_parameter_value(parameter_value) + parameter_value.gsub(/(`|'|"|#)/, '`\1') end - validate_switch_name!(switch_name) - - switch_argument = "" - switch_present = true - - case switch_value - when Numeric - switch_argument = switch_value.to_s - when Float - switch_argument = switch_value.to_s - when FalseClass - switch_present = false - when TrueClass - when String - switch_argument = escape_string_parameter_value(switch_value) - else - raise ArgumentError, "Invalid argument type `#{switch_value.class}` specified for PowerShell switch `:#{switch_name}`. Arguments to PowerShell must be of type `String`, `Numeric`, `Float`, `FalseClass`, or `TrueClass`" + def escape_string_parameter_value(parameter_value) + "'#{escape_parameter_value(parameter_value)}'" end - switch_present ? ["-#{switch_name.to_s.downcase}", switch_argument].join(" ").strip : "" - end + def command_switches_string(switches) + command_switches = switches.map do |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 + + validate_switch_name!(switch_name) + + switch_argument = "" + switch_present = true + + case switch_value + when Numeric + switch_argument = switch_value.to_s + when Float + switch_argument = switch_value.to_s + when FalseClass + switch_present = false + when TrueClass + when String + switch_argument = escape_string_parameter_value(switch_value) + else + raise ArgumentError, "Invalid argument type `#{switch_value.class}` specified for PowerShell switch `:#{switch_name}`. Arguments to PowerShell must be of type `String`, `Numeric`, `Float`, `FalseClass`, or `TrueClass`" + end + + switch_present ? ["-#{switch_name.to_s.downcase}", switch_argument].join(" ").strip : "" + end - command_switches.join(" ") - end + command_switches.join(" ") + end - class CmdletStream - def initialize(name) - @filename = Dir::Tmpname.create(name) {} - ObjectSpace.define_finalizer(self, self.class.destroy(@filename)) - end + class CmdletStream + def initialize(name) + @filename = Dir::Tmpname.create(name) {} + ObjectSpace.define_finalizer(self, self.class.destroy(@filename)) + end - def path - @filename - end + def path + @filename + end - def read - if File.exist? @filename - File.open(@filename, "rb:bom|UTF-16LE") do |f| - f.read.encode("UTF-8") + def read + if File.exist? @filename + File.open(@filename, "rb:bom|UTF-16LE") do |f| + f.read.encode("UTF-8") + end + end end - end - end - def self.destroy(name) - proc { File.delete(name) if File.exists? name } + def self.destroy(name) + proc { File.delete(name) if File.exists? name } + end + end end end end end -end -end diff --git a/lib/chef/util/powershell/cmdlet_result.rb b/lib/chef/util/powershell/cmdlet_result.rb index 4f97658a58..82aef4da40 100644 --- a/lib/chef/util/powershell/cmdlet_result.rb +++ b/lib/chef/util/powershell/cmdlet_result.rb @@ -19,43 +19,43 @@ require "chef/json_compat" class Chef -class Util -class Powershell - class CmdletResult - attr_reader :output_format - - def initialize(status, streams, output_format) - @status = status - @output_format = output_format - @streams = streams - end + class Util + class Powershell + class CmdletResult + attr_reader :output_format - def stdout - @status.stdout - end - - def stderr - @status.stderr - end + def initialize(status, streams, output_format) + @status = status + @output_format = output_format + @streams = streams + end - def stream(name) - @streams[name].read - end + def stdout + @status.stdout + end - def return_value - if output_format == :object - Chef::JSONCompat.parse(stream(:json)) - elsif output_format == :json - stream(:json) - else - @status.stdout - end - end + def stderr + @status.stderr + end - def succeeded? - @succeeded = @status.status.exitstatus == 0 + def stream(name) + @streams[name].read + end + + def return_value + if output_format == :object + Chef::JSONCompat.parse(stream(:json)) + elsif output_format == :json + stream(:json) + else + @status.stdout + end + end + + def succeeded? + @succeeded = @status.status.exitstatus == 0 + end + end end end end -end -end diff --git a/lib/chef/util/selinux.rb b/lib/chef/util/selinux.rb index 46b4dfce36..06fd999faf 100644 --- a/lib/chef/util/selinux.rb +++ b/lib/chef/util/selinux.rb @@ -31,7 +31,6 @@ class Chef # without selinux utilities is not supported. # module Selinux - include Chef::Mixin::ShellOut include Chef::Mixin::Which @@ -71,7 +70,7 @@ class Chef def check_selinux_enabled? if selinuxenabled_path - cmd = shell_out!(selinuxenabled_path, :returns => [0,1]) + cmd = shell_out!(selinuxenabled_path, :returns => [0, 1]) case cmd.exitstatus when 1 return false @@ -86,7 +85,6 @@ class Chef return false end end - end end end diff --git a/lib/chef/util/windows/net_group.rb b/lib/chef/util/windows/net_group.rb index cfb06ed1f1..f120d60806 100644 --- a/lib/chef/util/windows/net_group.rb +++ b/lib/chef/util/windows/net_group.rb @@ -21,7 +21,6 @@ require "chef/win32/net" #wrapper around a subset of the NetGroup* APIs. class Chef::Util::Windows::NetGroup - private def groupname @@ -72,7 +71,6 @@ class Chef::Util::Windows::NetGroup rescue Chef::Exceptions::Win32APIError => e raise ArgumentError, e end - end def local_delete diff --git a/lib/chef/util/windows/net_use.rb b/lib/chef/util/windows/net_use.rb index 89b17a9687..b9c3ecc783 100644 --- a/lib/chef/util/windows/net_use.rb +++ b/lib/chef/util/windows/net_use.rb @@ -29,7 +29,7 @@ class Chef::Util::Windows::NetUse < Chef::Util::Windows end def to_ui2_struct(use_info) - use_info.inject({}) do |memo, (k,v)| + use_info.inject({}) do |memo, (k, v)| memo["ui2_#{k}".to_sym] = v memo end @@ -52,7 +52,7 @@ class Chef::Util::Windows::NetUse < Chef::Util::Windows end def from_use_info_struct(ui2_hash) - ui2_hash.inject({}) do |memo, (k,v)| + ui2_hash.inject({}) do |memo, (k, v)| memo[k.to_s.sub("ui2_", "").to_sym] = v memo end diff --git a/lib/chef/util/windows/net_user.rb b/lib/chef/util/windows/net_user.rb index 3c28ce6e22..b5bcdeb507 100644 --- a/lib/chef/util/windows/net_user.rb +++ b/lib/chef/util/windows/net_user.rb @@ -24,8 +24,8 @@ require "chef/win32/security" #wrapper around a subset of the NetUser* APIs. #nothing Chef specific, but not complete enough to be its own gem, so util for now. class Chef::Util::Windows::NetUser < Chef::Util::Windows - private + NetUser = Chef::ReservedNames::Win32::NetUser Security = Chef::ReservedNames::Win32::Security @@ -62,7 +62,7 @@ class Chef::Util::Windows::NetUser < Chef::Util::Windows } def transform_usri3(args) - args.inject({}) do |memo, (k,v)| + args.inject({}) do |memo, (k, v)| memo[USER_INFO_3_TRANSFORM[k]] = v memo end @@ -70,7 +70,7 @@ class Chef::Util::Windows::NetUser < Chef::Util::Windows def usri3_to_hash(usri3) t = USER_INFO_3_TRANSFORM.invert - usri3.inject({}) do |memo, (k,v)| + usri3.inject({}) do |memo, (k, v)| memo[t[k]] = v memo end @@ -128,7 +128,7 @@ class Chef::Util::Windows::NetUser < Chef::Util::Windows def update(args) user_modify do |user| - args.each do |key,val| + args.each do |key, val| user[key] = val end end diff --git a/lib/chef/version/platform.rb b/lib/chef/version/platform.rb index 426d3d9834..f2205ca5c8 100644 --- a/lib/chef/version/platform.rb +++ b/lib/chef/version/platform.rb @@ -19,10 +19,9 @@ require "chef/version_class" class Chef class Version class Platform < Chef::Version - protected - def parse(str="") + def parse(str = "") @major, @minor, @patch = case str.to_s when /^(\d+)\.(\d+)\.(\d+)$/ @@ -31,14 +30,13 @@ class Chef [ $1.to_i, $2.to_i, 0 ] when /^(\d+)$/ [ $1.to_i, 0, 0 ] - when /^(\d+).(\d+)-[a-z]+\d?(-p(\d+))?$/i # Match FreeBSD + when /^(\d+).(\d+)-[a-z]+\d?(-p(\d+))?$/i # Match FreeBSD [ $1.to_i, $2.to_i, ($4 ? $4.to_i : 0)] else msg = "'#{str}' does not match 'x.y.z', 'x.y' or 'x'" raise Chef::Exceptions::InvalidPlatformVersion.new( msg ) end end - end end end diff --git a/lib/chef/version_class.rb b/lib/chef/version_class.rb index b27a9cc421..64b0e1cb47 100644 --- a/lib/chef/version_class.rb +++ b/lib/chef/version_class.rb @@ -20,7 +20,7 @@ class Chef include Comparable attr_reader :major, :minor, :patch - def initialize(str="") + def initialize(str = "") parse(str) end @@ -53,7 +53,7 @@ class Chef protected - def parse(str="") + def parse(str = "") @major, @minor, @patch = case str.to_s when /^(\d+)\.(\d+)\.(\d+)$/ @@ -65,6 +65,5 @@ class Chef raise Chef::Exceptions::InvalidCookbookVersion.new( msg ) end end - end end diff --git a/lib/chef/version_constraint.rb b/lib/chef/version_constraint.rb index 25f5bd1a47..5312070b83 100644 --- a/lib/chef/version_constraint.rb +++ b/lib/chef/version_constraint.rb @@ -26,7 +26,7 @@ class Chef attr_reader :op, :version - def initialize(constraint_spec=DEFAULT_CONSTRAINT) + def initialize(constraint_spec = DEFAULT_CONSTRAINT) case constraint_spec when nil parse(DEFAULT_CONSTRAINT) @@ -46,7 +46,7 @@ class Chef else self.class::VERSION_CLASS.new(v.to_s) end - do_op(version) + do_op(version) end def inspect @@ -78,7 +78,7 @@ class Chef other_version.minor == @version.minor && other_version.patch >= @version.patch) end - else # should never happen + else # should never happen raise "bad op #{@op}" end end @@ -113,6 +113,5 @@ class Chef raise Chef::Exceptions::InvalidVersionConstraint, "'#{str}'" end end - end end diff --git a/lib/chef/version_constraint/platform.rb b/lib/chef/version_constraint/platform.rb index 29f4678bb5..d8763192bf 100644 --- a/lib/chef/version_constraint/platform.rb +++ b/lib/chef/version_constraint/platform.rb @@ -20,7 +20,6 @@ class Chef class VersionConstraint class Platform < Chef::VersionConstraint VERSION_CLASS = Chef::Version::Platform - end end end diff --git a/lib/chef/whitelist.rb b/lib/chef/whitelist.rb index ca4be38d7f..015b0cdc94 100644 --- a/lib/chef/whitelist.rb +++ b/lib/chef/whitelist.rb @@ -3,7 +3,6 @@ require "chef/exceptions" class Chef class Whitelist - # filter takes two arguments - the data you want to filter, and a whitelisted array # of keys you want included. You can capture a subtree of the data to filter by # providing a "/"-delimited string of keys. If some key includes "/"-characters, @@ -27,7 +26,7 @@ class Chef # }, # ["network/interfaces/eth0", ["filesystem", "/dev/disk"]]) # will capture the eth0 and /dev/disk subtrees. - def self.filter(data, whitelist=nil) + def self.filter(data, whitelist = nil) return data if whitelist.nil? new_data = {} @@ -81,6 +80,5 @@ class Chef end private_class_method :to_array - end end diff --git a/lib/chef/win32/api.rb b/lib/chef/win32/api.rb index e7cd3b5bd0..3e4811e12d 100644 --- a/lib/chef/win32/api.rb +++ b/lib/chef/win32/api.rb @@ -24,7 +24,6 @@ require "chef/exceptions" class Chef module ReservedNames::Win32 module API - # Attempts to use FFI's attach_function method to link a native Win32 # function into the calling module. If this fails a dummy method is # defined which when called, raises a helpful exception to the end-user. @@ -239,11 +238,10 @@ class Chef # In WinNT.h: host.typedef wchar_t WCHAR; #WINAPI: K, # Calling convention for system functions. WinDef.h: define WINAPI __stdcall host.typedef :ushort, :WORD # 16-bit unsigned integer. The range is 0 through 65535 decimal. - host.typedef :uint, :WPARAM # Message parameter. WinDef.h as follows: host.typedef UINT_PTR WPARAM; + host.typedef :uint, :WPARAM # Message parameter. WinDef.h as follows: host.typedef UINT_PTR WPARAM; end module Macros - ############################################### # winbase.h ############################################### @@ -368,7 +366,6 @@ class Chef def wtime_to_time(wtime) Time.at((wtime - WIN32_EPOC_MINUS_POSIX_EPOC) / 10000000) end - end end end diff --git a/lib/chef/win32/api/crypto.rb b/lib/chef/win32/api/crypto.rb index a2c44dcb42..72c50930b9 100644 --- a/lib/chef/win32/api/crypto.rb +++ b/lib/chef/win32/api/crypto.rb @@ -35,20 +35,19 @@ class Chef CRYPTPROTECT_AUDIT = 0x10 class CRYPT_INTEGER_BLOB < FFI::Struct - layout :cbData, :DWORD, # Count, in bytes, of data + layout :cbData, :DWORD, # Count, in bytes, of data :pbData, :pointer # Pointer to data buffer - def initialize(str=nil) + def initialize(str = nil) super(nil) if str self[:pbData] = FFI::MemoryPointer.from_string(str) self[:cbData] = str.bytesize end end - end safe_attach_function :CryptProtectData, [ - :PDATA_BLOB, + :PDATA_BLOB, :LPCWSTR, :PDATA_BLOB, :pointer, @@ -56,7 +55,6 @@ class Chef :DWORD, :PDATA_BLOB, ], :BOOL - end end end diff --git a/lib/chef/win32/api/error.rb b/lib/chef/win32/api/error.rb index 0b10fc6e3d..a714871c4f 100644 --- a/lib/chef/win32/api/error.rb +++ b/lib/chef/win32/api/error.rb @@ -178,7 +178,7 @@ class Chef ERROR_LOCK_FAILED = 167 ERROR_BUSY = 170 ERROR_CANCEL_VIOLATION = 173 - ERROR_ATOMIC_LOCKS_NOT_SUPPORTED= 174 + ERROR_ATOMIC_LOCKS_NOT_SUPPORTED = 174 ERROR_INVALID_SEGMENT_NUMBER = 180 ERROR_INVALID_CALLGATE = 181 @@ -446,7 +446,7 @@ class Chef ERROR_DOWNGRADE_DETECTED = 1265 ERROR_MACHINE_LOCKED = 1271 ERROR_CALLBACK_SUPPLIED_INVALID_DATA = 1273 - ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED= 1274 + ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED = 1274 ERROR_DRIVER_BLOCKED = 1275 ERROR_INVALID_IMPORT_OF_NON_DLL = 1276 ERROR_NOT_ALL_ASSIGNED = 1300 @@ -750,7 +750,7 @@ class Chef ERROR_NETLOGON_NOT_STARTED = 1792 ERROR_ACCOUNT_EXPIRED = 1793 ERROR_REDIRECTOR_HAS_OPEN_HANDLES = 1794 - ERROR_PRINTER_DRIVER_ALREADY_INSTALLED= 1795 + ERROR_PRINTER_DRIVER_ALREADY_INSTALLED = 1795 ERROR_UNKNOWN_PORT = 1796 ERROR_UNKNOWN_PRINTER_DRIVER = 1797 ERROR_UNKNOWN_PRINTPROCESSOR = 1798 @@ -824,9 +824,9 @@ class Chef ERROR_CONTEXT_EXPIRED = 1931 ERROR_PER_USER_TRUST_QUOTA_EXCEEDED = 1932 ERROR_ALL_USER_TRUST_QUOTA_EXCEEDED = 1933 - ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED= 1934 - ERROR_AUTHENTICATION_FIREWALL_FAILED = 1935 - ERROR_REMOTE_PRINT_CONNECTIONS_BLOCKED= 1936 + ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED = 1934 + ERROR_AUTHENTICATION_FIREWALL_FAILED = 1935 + ERROR_REMOTE_PRINT_CONNECTIONS_BLOCKED = 1936 ERROR_INVALID_PIXEL_FORMAT = 2000 ERROR_BAD_DRIVER = 2001 ERROR_INVALID_WINDOW_STYLE = 2002 @@ -915,7 +915,6 @@ UINT WINAPI SetErrorMode( ); =end safe_attach_function :SetErrorMode, [:UINT], :UINT - end end end diff --git a/lib/chef/win32/api/file.rb b/lib/chef/win32/api/file.rb index 992c595e9a..d2ce757222 100644 --- a/lib/chef/win32/api/file.rb +++ b/lib/chef/win32/api/file.rb @@ -163,7 +163,7 @@ class Chef (device_type << 16) | (access << 14) | (function << 2) | method end - FSCTL_GET_REPARSE_POINT = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS) + FSCTL_GET_REPARSE_POINT = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS) # Reparse point tags IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003 @@ -176,7 +176,7 @@ class Chef IO_REPARSE_TAG_SYMLINK = 0xA000000C IO_REPARSE_TAG_DFSR = 0x80000012 - MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16*1024 + MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16 * 1024 ############################################### # Win32 API Bindings @@ -238,7 +238,7 @@ typedef struct _WIN32_FIND_DATA { :n_file_size_low, :DWORD, :dw_reserved_0, :DWORD, :dw_reserved_1, :DWORD, - :c_file_name, [:BYTE, MAX_PATH*2], + :c_file_name, [:BYTE, MAX_PATH * 2], :c_alternate_file_name, [:BYTE, 14] end @@ -307,11 +307,12 @@ typedef struct _REPARSE_DATA_BUFFER { def substitute_name string_pointer = FFI::Pointer.new(pointer.address) + offset_of(:PathBuffer) + self[:SubstituteNameOffset] - string_pointer.read_wstring(self[:SubstituteNameLength]/2) + string_pointer.read_wstring(self[:SubstituteNameLength] / 2) end + def print_name string_pointer = FFI::Pointer.new(pointer.address) + offset_of(:PathBuffer) + self[:PrintNameOffset] - string_pointer.read_wstring(self[:PrintNameLength]/2) + string_pointer.read_wstring(self[:PrintNameLength] / 2) end end class REPARSE_DATA_BUFFER_MOUNT_POINT < FFI::Struct @@ -323,11 +324,12 @@ typedef struct _REPARSE_DATA_BUFFER { def substitute_name string_pointer = FFI::Pointer.new(pointer.address) + offset_of(:PathBuffer) + self[:SubstituteNameOffset] - string_pointer.read_wstring(self[:SubstituteNameLength]/2) + string_pointer.read_wstring(self[:SubstituteNameLength] / 2) end + def print_name string_pointer = FFI::Pointer.new(pointer.address) + offset_of(:PathBuffer) + self[:PrintNameOffset] - string_pointer.read_wstring(self[:PrintNameLength]/2) + string_pointer.read_wstring(self[:PrintNameLength] / 2) end end class REPARSE_DATA_BUFFER_GENERIC < FFI::Struct @@ -458,7 +460,6 @@ BOOL WINAPI DeviceIoControl( =end safe_attach_function :DeviceIoControl, [:HANDLE, :DWORD, :LPVOID, :DWORD, :LPVOID, :DWORD, :LPDWORD, :pointer], :BOOL - #BOOL WINAPI DeleteVolumeMountPoint( #_In_ LPCTSTR lpszVolumeMountPoint #); @@ -606,7 +607,7 @@ BOOL WINAPI VerQueryValue( if file_size == 0 Chef::ReservedNames::Win32::Error.raise! end - + version_info = FFI::MemoryPointer.new(file_size) unless GetFileVersionInfoW(file_name, 0, file_size, version_info) Chef::ReservedNames::Win32::Error.raise! @@ -614,7 +615,6 @@ BOOL WINAPI VerQueryValue( version_info end - end end end diff --git a/lib/chef/win32/api/installer.rb b/lib/chef/win32/api/installer.rb index e1be747245..caf7b23f59 100644 --- a/lib/chef/win32/api/installer.rb +++ b/lib/chef/win32/api/installer.rb @@ -32,7 +32,6 @@ class Chef # Win32 API Constants ############################################### - ############################################### # Win32 API Bindings ############################################### @@ -94,7 +93,7 @@ UINT MsiCloseHandle( msg << Chef::ReservedNames::Win32::Error.format_message(status) raise Chef::Exceptions::Package, msg end - + buffer_length = FFI::Buffer.new(:long).write_long(buffer_length.read_long + 1) buffer = 0.chr * buffer_length.read_long @@ -114,18 +113,18 @@ UINT MsiCloseHandle( # Opens a Microsoft Installer (MSI) file from an absolute path and returns a pointer to a handle # Remember to close the handle with msi_close_handle() def open_package(package_path) - # MsiOpenPackage expects a perfect absolute Windows path to the MSI + # MsiOpenPackage expects a perfect absolute Windows path to the MSI raise ArgumentError, "Provided path '#{package_path}' must be an absolute path" unless Pathname.new(package_path).absolute? pkg_ptr = FFI::MemoryPointer.new(:pointer, 4) status = msi_open_package(package_path, 1, pkg_ptr) case status - when 0 + when 0 # success else raise Chef::Exceptions::Package, "msi_open_package: unexpected status #{status}: #{Chef::ReservedNames::Win32::Error.format_message(status)}" end - return pkg_ptr + return pkg_ptr end # All installed product_codes should have a VersionString @@ -133,11 +132,11 @@ UINT MsiCloseHandle( def get_installed_version(product_code) version = 0.chr version_length = FFI::Buffer.new(:long).write_long(0) - + status = msi_get_product_info(product_code, "VersionString", version, version_length) - + return nil if status == 1605 # ERROR_UNKNOWN_PRODUCT (0x645) - + # We expect error ERROR_MORE_DATA (234) here because we passed a buffer length of 0 if status != 234 msg = "msi_get_product_info: product code '#{product_code}' returned unknown error #{status} when retrieving VersionString: " @@ -149,9 +148,9 @@ UINT MsiCloseHandle( version_length = FFI::Buffer.new(:long).write_long(version_length.read_long + 1) version = 0.chr * version_length.read_long - + status = msi_get_product_info(product_code, "VersionString", version, version_length) - + if status != 0 msg = "msi_get_product_info: product code '#{product_code}' returned unknown error #{status} when retrieving VersionString: " msg << Chef::ReservedNames::Win32::Error.format_message(status) diff --git a/lib/chef/win32/api/memory.rb b/lib/chef/win32/api/memory.rb index a00ac5fec8..f23cc0c063 100644 --- a/lib/chef/win32/api/memory.rb +++ b/lib/chef/win32/api/memory.rb @@ -98,7 +98,6 @@ UINT WINAPI LocalSize( safe_attach_function :realloc, [:pointer, :size_t], :pointer safe_attach_function :free, [:pointer], :void safe_attach_function :memcpy, [:pointer, :pointer, :size_t], :pointer - end end end diff --git a/lib/chef/win32/api/net.rb b/lib/chef/win32/api/net.rb index fdbe55579f..bec00f638a 100644 --- a/lib/chef/win32/api/net.rb +++ b/lib/chef/win32/api/net.rb @@ -90,7 +90,6 @@ class Chef end end - class USER_INFO_3 < FFI::Struct include StructHelpers layout :usri3_name, :LPWSTR, @@ -159,7 +158,6 @@ class Chef :ui2_domainname, :LMSTR end - #NET_API_STATUS NetLocalGroupAdd( #_In_ LPCWSTR servername, #_In_ DWORD level, diff --git a/lib/chef/win32/api/process.rb b/lib/chef/win32/api/process.rb index 3568b7e76c..8584e25f1d 100644 --- a/lib/chef/win32/api/process.rb +++ b/lib/chef/win32/api/process.rb @@ -35,7 +35,6 @@ class Chef safe_attach_function :GetProcessId, [ :HANDLE ], :DWORD safe_attach_function :CloseHandle, [ :HANDLE ], :BOOL safe_attach_function :IsWow64Process, [ :HANDLE, :PBOOL ], :BOOL - end end end diff --git a/lib/chef/win32/api/psapi.rb b/lib/chef/win32/api/psapi.rb index 9deb68d92e..5fe630b7e7 100644 --- a/lib/chef/win32/api/psapi.rb +++ b/lib/chef/win32/api/psapi.rb @@ -44,7 +44,6 @@ class Chef ffi_lib "psapi" safe_attach_function :GetProcessMemoryInfo, [ :HANDLE, :pointer, :DWORD ], :BOOL - end end end diff --git a/lib/chef/win32/api/registry.rb b/lib/chef/win32/api/registry.rb index 8f394ad12a..387551831e 100644 --- a/lib/chef/win32/api/registry.rb +++ b/lib/chef/win32/api/registry.rb @@ -44,8 +44,7 @@ class Chef # _In_opt_ LPCTSTR lpValueName # ); safe_attach_function :RegDeleteValueW, [ :HKEY, :LPCTSTR ], :LONG - end end end -end \ No newline at end of file +end diff --git a/lib/chef/win32/api/security.rb b/lib/chef/win32/api/security.rb index 61c65971be..380d2fe283 100644 --- a/lib/chef/win32/api/security.rb +++ b/lib/chef/win32/api/security.rb @@ -136,20 +136,10 @@ class Chef SYNCHRONIZE | 0x1FF FILE_GENERIC_READ = STANDARD_RIGHTS_READ | - FILE_READ_DATA | - FILE_READ_ATTRIBUTES | - FILE_READ_EA | - SYNCHRONIZE - FILE_GENERIC_WRITE = STANDARD_RIGHTS_WRITE | - FILE_WRITE_DATA | - FILE_WRITE_ATTRIBUTES | - FILE_WRITE_EA | - FILE_APPEND_DATA | - SYNCHRONIZE - FILE_GENERIC_EXECUTE = STANDARD_RIGHTS_EXECUTE | - FILE_READ_ATTRIBUTES | - FILE_EXECUTE | - SYNCHRONIZE + FILE_READ_DATA | FILE_READ_ATTRIBUTES | + FILE_READ_EA | SYNCHRONIZE + FILE_GENERIC_WRITE = STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE + FILE_GENERIC_EXECUTE = STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE # Access Token Rights (for OpenProcessToken) # Access Rights for Access-Token Objects (used in OpenProcessToken) TOKEN_ASSIGN_PRIMARY = 0x0001 @@ -173,9 +163,7 @@ class Chef SE_PRIVILEGE_REMOVED = 0X00000004 SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000 SE_PRIVILEGE_VALID_ATTRIBUTES = SE_PRIVILEGE_ENABLED_BY_DEFAULT | - SE_PRIVILEGE_ENABLED | - SE_PRIVILEGE_REMOVED | - SE_PRIVILEGE_USED_FOR_ACCESS + SE_PRIVILEGE_ENABLED | SE_PRIVILEGE_REMOVED | SE_PRIVILEGE_USED_FOR_ACCESS # Minimum size of a SECURITY_DESCRIPTOR. TODO: this is probably platform dependent. # Make it work on 64 bit. @@ -315,7 +303,6 @@ class Chef :SecurityDelegation, ] - # SECURITY_DESCRIPTOR is an opaque structure whose contents can vary. Pass the # pointer around and free it with LocalFree. # http://msdn.microsoft.com/en-us/library/windows/desktop/aa379561(v=vs.85).aspx @@ -384,7 +371,7 @@ class Chef :Privileges, LUID_AND_ATTRIBUTES def self.size_with_privileges(num_privileges) - offset_of(:Privileges) + LUID_AND_ATTRIBUTES.size*num_privileges + offset_of(:Privileges) + LUID_AND_ATTRIBUTES.size * num_privileges end def size_with_privileges @@ -431,7 +418,7 @@ class Chef safe_attach_function :GetAce, [ :pointer, :DWORD, :pointer ], :BOOL safe_attach_function :GetFileSecurityW, [:LPCWSTR, :DWORD, :pointer, :DWORD, :pointer], :BOOL safe_attach_function :GetLengthSid, [ :pointer ], :DWORD - safe_attach_function :GetNamedSecurityInfoW, [ :LPWSTR, :SE_OBJECT_TYPE, :DWORD, :pointer, :pointer, :pointer, :pointer, :pointer ], :DWORD + safe_attach_function :GetNamedSecurityInfoW, [ :LPWSTR, :SE_OBJECT_TYPE, :DWORD, :pointer, :pointer, :pointer, :pointer, :pointer ], :DWORD safe_attach_function :GetSecurityDescriptorControl, [ :pointer, :PWORD, :LPDWORD], :BOOL safe_attach_function :GetSecurityDescriptorDacl, [ :pointer, :LPBOOL, :pointer, :LPBOOL ], :BOOL safe_attach_function :GetSecurityDescriptorGroup, [ :pointer, :pointer, :LPBOOL], :BOOL @@ -466,7 +453,6 @@ class Chef safe_attach_function :SetSecurityDescriptorSacl, [ :pointer, :BOOL, :pointer, :BOOL ], :BOOL safe_attach_function :GetTokenInformation, [ :HANDLE, :TOKEN_INFORMATION_CLASS, :pointer, :DWORD, :PDWORD ], :BOOL safe_attach_function :LogonUserW, [:LPTSTR, :LPTSTR, :LPTSTR, :DWORD, :DWORD, :PHANDLE], :BOOL - end end end diff --git a/lib/chef/win32/api/unicode.rb b/lib/chef/win32/api/unicode.rb index 21ddde2865..2cc14fcd7a 100644 --- a/lib/chef/win32/api/unicode.rb +++ b/lib/chef/win32/api/unicode.rb @@ -128,7 +128,6 @@ int WideCharToMultiByte( ); =end safe_attach_function :WideCharToMultiByte, [:UINT, :DWORD, :LPCWSTR, :int, :LPSTR, :int, :LPCSTR, :LPBOOL], :int - end end end diff --git a/lib/chef/win32/crypto.rb b/lib/chef/win32/crypto.rb index 9832f9e67e..ae2af8c5b7 100644 --- a/lib/chef/win32/crypto.rb +++ b/lib/chef/win32/crypto.rb @@ -44,7 +44,6 @@ class Chef Chef::ReservedNames::Win32::Memory.local_free(data_blob[:pbData]) end end - end end end diff --git a/lib/chef/win32/file.rb b/lib/chef/win32/file.rb index a0aa34d481..e43bd4b3a0 100644 --- a/lib/chef/win32/file.rb +++ b/lib/chef/win32/file.rb @@ -125,8 +125,8 @@ class Chef if size == 0 Chef::ReservedNames::Win32::Error.raise! end - result = FFI::MemoryPointer.new :char, (size+1)*2 - if GetShortPathNameW(path, result, size+1) == 0 + result = FFI::MemoryPointer.new :char, (size + 1) * 2 + if GetShortPathNameW(path, result, size + 1) == 0 Chef::ReservedNames::Win32::Error.raise! end result.read_wstring(size) @@ -139,8 +139,8 @@ class Chef if size == 0 Chef::ReservedNames::Win32::Error.raise! end - result = FFI::MemoryPointer.new :char, (size+1)*2 - if GetLongPathNameW(path, result, size+1) == 0 + result = FFI::MemoryPointer.new :char, (size + 1) * 2 + if GetLongPathNameW(path, result, size + 1) == 0 Chef::ReservedNames::Win32::Error.raise! end result.read_wstring(size) @@ -199,7 +199,7 @@ class Chef def self.get_volume_name_for_volume_mount_point(mount_point) buffer = FFI::MemoryPointer.new(2, 128) - unless GetVolumeNameForVolumeMountPointW(wstring(mount_point), buffer, buffer.size/buffer.type_size) + unless GetVolumeNameForVolumeMountPointW(wstring(mount_point), buffer, buffer.size / buffer.type_size) Chef::ReservedNames::Win32::Error.raise! end buffer.read_wstring @@ -209,7 +209,6 @@ class Chef class << self alias :stat :info end - end end end diff --git a/lib/chef/win32/file/info.rb b/lib/chef/win32/file/info.rb index 010bf80079..bb8bfa0411 100644 --- a/lib/chef/win32/file/info.rb +++ b/lib/chef/win32/file/info.rb @@ -21,13 +21,11 @@ require "chef/win32/file" class Chef module ReservedNames::Win32 class File - # Objects of class Chef::ReservedNames::Win32::File::Stat encapsulate common status # information for Chef::ReservedNames::Win32::File objects. The information # is recorded at the moment the Chef::ReservedNames::Win32::File::Stat object is # created; changes made to the file after that point will not be reflected. class Info - include Chef::ReservedNames::Win32::API::File include Chef::ReservedNames::Win32::API @@ -92,8 +90,6 @@ class Chef wtime_to_time(make_uint64(file_time_struct[:dw_low_date_time], file_time_struct[:dw_high_date_time])) end - - end end end diff --git a/lib/chef/win32/file/version_info.rb b/lib/chef/win32/file/version_info.rb index 37cfd944e6..bd0287ff89 100644 --- a/lib/chef/win32/file/version_info.rb +++ b/lib/chef/win32/file/version_info.rb @@ -21,9 +21,7 @@ require "chef/win32/file" class Chef module ReservedNames::Win32 class File - class VersionInfo - include Chef::ReservedNames::Win32::API::File def initialize(file_name) @@ -75,7 +73,7 @@ class Chef end def to_hex(integer) - integer.to_s(16).rjust(4,"0") + integer.to_s(16).rjust(4, "0") end def get_version_info_string(string_key) diff --git a/lib/chef/win32/handle.rb b/lib/chef/win32/handle.rb index 3ebb6983c4..e47e3bb356 100644 --- a/lib/chef/win32/handle.rb +++ b/lib/chef/win32/handle.rb @@ -49,7 +49,6 @@ class Chef Chef::ReservedNames::Win32::Error.raise! end end - end end end diff --git a/lib/chef/win32/memory.rb b/lib/chef/win32/memory.rb index 49dcdfbd41..1c0df58813 100644 --- a/lib/chef/win32/memory.rb +++ b/lib/chef/win32/memory.rb @@ -95,7 +95,6 @@ class Chef def self.local_free_finalizer(pointer) proc { local_free(pointer) } end - end end end diff --git a/lib/chef/win32/net.rb b/lib/chef/win32/net.rb index 4ee278aa28..0454b17d49 100644 --- a/lib/chef/win32/net.rb +++ b/lib/chef/win32/net.rb @@ -40,7 +40,7 @@ class Chef usri3_priv: 0, usri3_home_dir: nil, usri3_comment: nil, - usri3_flags: UF_SCRIPT|UF_DONT_EXPIRE_PASSWD|UF_NORMAL_ACCOUNT, + usri3_flags: UF_SCRIPT | UF_DONT_EXPIRE_PASSWD | UF_NORMAL_ACCOUNT, usri3_script_path: nil, usri3_auth_flags: 0, usri3_full_name: nil, @@ -63,7 +63,7 @@ class Chef usri3_profile: nil, usri3_home_dir_drive: nil, usri3_password_expired: 0, - }.each do |(k,v)| + }.each do |(k, v)| s.set(k, v) end end @@ -254,7 +254,7 @@ class Chef end end - def self.net_use_del(server_name, use_name, force=:use_noforce) + def self.net_use_del(server_name, use_name, force = :use_noforce) server_name = wstring(server_name) use_name = wstring(use_name) force_const = case force @@ -296,8 +296,8 @@ class Chef buf = USE_INFO_2.new - ui2_hash.each do |(k,v)| - buf.set(k,v) + ui2_hash.each do |(k, v)| + buf.set(k, v) end rc = NetUseAdd(server_name, 2, buf, nil) diff --git a/lib/chef/win32/process.rb b/lib/chef/win32/process.rb index 76e526340b..2a209f6cfd 100644 --- a/lib/chef/win32/process.rb +++ b/lib/chef/win32/process.rb @@ -91,7 +91,6 @@ class Chef end memory_info end - end end end diff --git a/lib/chef/win32/registry.rb b/lib/chef/win32/registry.rb index 4113e5eb2b..2710fa7781 100644 --- a/lib/chef/win32/registry.rb +++ b/lib/chef/win32/registry.rb @@ -30,7 +30,6 @@ end class Chef class Win32 class Registry - if RUBY_PLATFORM =~ /mswin|mingw32|windows/ include Chef::ReservedNames::Win32::API::Registry extend Chef::ReservedNames::Win32::API::Registry @@ -42,7 +41,7 @@ class Chef attr_accessor :run_context attr_accessor :architecture - def initialize(run_context=nil, user_architecture=:machine) + def initialize(run_context = nil, user_architecture = :machine) @run_context = run_context self.architecture = user_architecture end @@ -56,7 +55,7 @@ class Chef 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| - reg.map { |name, type, data| {:name=>name, :type=>get_name_from_type(type), :data=>data} } + reg.map { |name, type, data| { :name => name, :type => get_name_from_type(type), :data => data } } end end @@ -175,7 +174,7 @@ class Chef key_exists!(key_path) hive, key = get_hive_and_key(key_path) hive.open(key, ::Win32::Registry::KEY_READ | registry_system_architecture) do |reg| - reg.each_key{ |key| return true } + reg.each_key { |key| return true } end return false end @@ -185,7 +184,7 @@ class Chef key_exists!(key_path) hive, key = get_hive_and_key(key_path) hive.open(key, ::Win32::Registry::KEY_READ | registry_system_architecture) do |reg| - reg.each_key{ |current_key| subkeys << current_key } + reg.each_key { |current_key| subkeys << current_key } end return subkeys end @@ -200,7 +199,7 @@ class Chef key_exists!(key_path) hive, key = get_hive_and_key(key_path) hive.open(key, ::Win32::Registry::KEY_READ | registry_system_architecture) do |reg| - return true if reg.any? {|val| safely_downcase(val) == safely_downcase(value[:name]) } + return true if reg.any? { |val| safely_downcase(val) == safely_downcase(value[:name]) } end return false end @@ -211,8 +210,8 @@ class Chef hive.open(key, ::Win32::Registry::KEY_READ | registry_system_architecture) do |reg| reg.each do |val_name, val_type, val_data| if safely_downcase(val_name) == safely_downcase(value[:name]) && - val_type == get_type_from_name(value[:type]) && - val_data == value[:data] + val_type == get_type_from_name(value[:type]) && + val_data == value[:data] return true end end @@ -273,7 +272,6 @@ class Chef private - def safely_downcase(val) if val.is_a? String return val.downcase @@ -367,7 +365,6 @@ class Chef hive_name = reg_path.shift key = reg_path.join("\\") end - end end end diff --git a/lib/chef/win32/security.rb b/lib/chef/win32/security.rb index 13b4604469..7fc3215786 100644 --- a/lib/chef/win32/security.rb +++ b/lib/chef/win32/security.rb @@ -235,7 +235,6 @@ class Chef SecurityDescriptor.new(security_descriptor_ptr) end - def self.get_named_security_info(path, type = :SE_FILE_OBJECT, info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION) security_descriptor = FFI::MemoryPointer.new :pointer hr = GetNamedSecurityInfoW(path.to_wstring, type, info, nil, nil, nil, nil, security_descriptor) @@ -385,7 +384,7 @@ class Chef end sid = FFI::MemoryPointer.new :char, sid_size.read_long - referenced_domain_name = FFI::MemoryPointer.new :char, (referenced_domain_name_size.read_long*2) + referenced_domain_name = FFI::MemoryPointer.new :char, (referenced_domain_name_size.read_long * 2) use = FFI::Buffer.new(:long).write_long(0) unless LookupAccountNameW(system_name, name.to_wstring, sid, sid_size, referenced_domain_name, referenced_domain_name_size, use) Chef::ReservedNames::Win32::Error.raise! @@ -406,8 +405,8 @@ class Chef Chef::ReservedNames::Win32::Error.raise! end - name = FFI::MemoryPointer.new :char, (name_size.read_long*2) - referenced_domain_name = FFI::MemoryPointer.new :char, (referenced_domain_name_size.read_long*2) + name = FFI::MemoryPointer.new :char, (name_size.read_long * 2) + referenced_domain_name = FFI::MemoryPointer.new :char, (referenced_domain_name_size.read_long * 2) use = FFI::Buffer.new(:long).write_long(0) unless LookupAccountSidW(system_name, sid, name, name_size, referenced_domain_name, referenced_domain_name_size, use) Chef::ReservedNames::Win32::Error.raise! @@ -425,7 +424,7 @@ class Chef Chef::ReservedNames::Win32::Error.raise! end - name = FFI::MemoryPointer.new :char, (name_size.read_long*2) + name = FFI::MemoryPointer.new :char, (name_size.read_long * 2) unless LookupPrivilegeNameW(system_name, luid, name, name_size) Chef::ReservedNames::Win32::Error.raise! end @@ -443,7 +442,7 @@ class Chef Chef::ReservedNames::Win32::Error.raise! end - display_name = FFI::MemoryPointer.new :char, (display_name_size.read_long*2) + display_name = FFI::MemoryPointer.new :char, (display_name_size.read_long * 2) unless LookupPrivilegeDisplayNameW(system_name, name.to_wstring, display_name, display_name_size, language_id) Chef::ReservedNames::Win32::Error.raise! end diff --git a/lib/chef/win32/security/ace.rb b/lib/chef/win32/security/ace.rb index d593513983..51fcc6af20 100644 --- a/lib/chef/win32/security/ace.rb +++ b/lib/chef/win32/security/ace.rb @@ -26,7 +26,6 @@ class Chef module ReservedNames::Win32 class Security class ACE - def initialize(pointer, owner = nil) if Chef::ReservedNames::Win32::API::Security::ACE_WITH_MASK_AND_SID.supports?(pointer.read_uchar) @struct = Chef::ReservedNames::Win32::API::Security::ACE_WITH_MASK_AND_SID.new pointer diff --git a/lib/chef/win32/security/acl.rb b/lib/chef/win32/security/acl.rb index 86c6e05bd2..38707b8a32 100644 --- a/lib/chef/win32/security/acl.rb +++ b/lib/chef/win32/security/acl.rb @@ -34,7 +34,7 @@ class Chef end def self.create(aces) - aces_size = aces.inject(0) { |sum,ace| sum + ace.size } + 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) } @@ -45,7 +45,7 @@ class Chef def ==(other) return false if length != other.length - 0.upto(length-1) do |i| + 0.upto(length - 1) do |i| return false if self[i] != other[i] end return true @@ -64,7 +64,7 @@ class Chef end def each - 0.upto(length-1) { |i| yield self[i] } + 0.upto(length - 1) { |i| yield self[i] } end def insert(index, *aces) @@ -96,7 +96,6 @@ class Chef end private_class_method :align_dword - end end end diff --git a/lib/chef/win32/security/securable_object.rb b/lib/chef/win32/security/securable_object.rb index aef1a72c8c..ade423bb28 100644 --- a/lib/chef/win32/security/securable_object.rb +++ b/lib/chef/win32/security/securable_object.rb @@ -24,7 +24,6 @@ class Chef module ReservedNames::Win32 class Security class SecurableObject - def initialize(path, type = :SE_FILE_OBJECT) @path = path @type = type diff --git a/lib/chef/win32/security/security_descriptor.rb b/lib/chef/win32/security/security_descriptor.rb index 8bfd8b8287..ba1aaa2f73 100644 --- a/lib/chef/win32/security/security_descriptor.rb +++ b/lib/chef/win32/security/security_descriptor.rb @@ -24,7 +24,6 @@ class Chef module ReservedNames::Win32 class Security class SecurityDescriptor - def initialize(pointer) @pointer = pointer end diff --git a/lib/chef/win32/security/sid.rb b/lib/chef/win32/security/sid.rb index 0219aa6eb1..4d2d252dd3 100644 --- a/lib/chef/win32/security/sid.rb +++ b/lib/chef/win32/security/sid.rb @@ -80,111 +80,147 @@ class Chef def self.Null SID.from_string_sid("S-1-0") end + def self.Nobody SID.from_string_sid("S-1-0-0") end + def self.World SID.from_string_sid("S-1-1") end + def self.Everyone SID.from_string_sid("S-1-1-0") end + def self.Local SID.from_string_sid("S-1-2") end + def self.Creator SID.from_string_sid("S-1-3") end + def self.CreatorOwner SID.from_string_sid("S-1-3-0") end + def self.CreatorGroup SID.from_string_sid("S-1-3-1") end + def self.CreatorOwnerServer SID.from_string_sid("S-1-3-2") end + def self.CreatorGroupServer SID.from_string_sid("S-1-3-3") end + def self.NonUnique SID.from_string_sid("S-1-4") end + def self.Nt SID.from_string_sid("S-1-5") end + def self.Dialup SID.from_string_sid("S-1-5-1") end + def self.Network SID.from_string_sid("S-1-5-2") end + def self.Batch SID.from_string_sid("S-1-5-3") end + def self.Interactive SID.from_string_sid("S-1-5-4") end + def self.Service SID.from_string_sid("S-1-5-6") end + def self.Anonymous SID.from_string_sid("S-1-5-7") end + def self.Proxy SID.from_string_sid("S-1-5-8") end + def self.EnterpriseDomainControllers SID.from_string_sid("S-1-5-9") end + def self.PrincipalSelf SID.from_string_sid("S-1-5-10") end + def self.AuthenticatedUsers SID.from_string_sid("S-1-5-11") end + def self.RestrictedCode SID.from_string_sid("S-1-5-12") end + def self.TerminalServerUsers SID.from_string_sid("S-1-5-13") end + def self.LocalSystem SID.from_string_sid("S-1-5-18") end + def self.NtLocal SID.from_string_sid("S-1-5-19") end + def self.NtNetwork SID.from_string_sid("S-1-5-20") end + def self.BuiltinAdministrators SID.from_string_sid("S-1-5-32-544") end + def self.BuiltinUsers SID.from_string_sid("S-1-5-32-545") end + def self.Guests SID.from_string_sid("S-1-5-32-546") end + def self.PowerUsers SID.from_string_sid("S-1-5-32-547") end + def self.AccountOperators SID.from_string_sid("S-1-5-32-548") end + def self.ServerOperators SID.from_string_sid("S-1-5-32-549") end + def self.PrintOperators SID.from_string_sid("S-1-5-32-550") end + def self.BackupOperators SID.from_string_sid("S-1-5-32-551") end + def self.Replicators SID.from_string_sid("S-1-5-32-552") end + def self.Administrators SID.from_string_sid("S-1-5-32-544") end @@ -192,9 +228,11 @@ class Chef def self.None SID.from_account("#{::ENV['COMPUTERNAME']}\\None") end + def self.Administrator SID.from_account("#{::ENV['COMPUTERNAME']}\\#{SID.admin_account_name}") end + def self.Guest SID.from_account("#{::ENV['COMPUTERNAME']}\\Guest") end diff --git a/lib/chef/win32/security/token.rb b/lib/chef/win32/security/token.rb index f8b6790d44..85689adbc0 100644 --- a/lib/chef/win32/security/token.rb +++ b/lib/chef/win32/security/token.rb @@ -25,7 +25,6 @@ class Chef module ReservedNames::Win32 class Security class Token - def initialize(handle) @handle = handle end diff --git a/lib/chef/win32/system.rb b/lib/chef/win32/system.rb index ec2e5d3457..75269dcb03 100755 --- a/lib/chef/win32/system.rb +++ b/lib/chef/win32/system.rb @@ -56,7 +56,6 @@ class Chef raise Win32APIError, "Failed to revert Wow64 file redirection" end end - end end end diff --git a/lib/chef/win32/unicode.rb b/lib/chef/win32/unicode.rb index a7509115c0..b0fcf6492d 100644 --- a/lib/chef/win32/unicode.rb +++ b/lib/chef/win32/unicode.rb @@ -40,13 +40,13 @@ module FFI last_char = nil while last_char != "\000\000" do length += 1 - last_char = self.get_bytes(0,length * 2)[-2..-1] + last_char = self.get_bytes(0, length * 2)[-2..-1] end num_wchars = length end - wide_to_utf8(self.get_bytes(0, num_wchars*2)) + wide_to_utf8(self.get_bytes(0, num_wchars * 2)) end end end diff --git a/lib/chef/win32/version.rb b/lib/chef/win32/version.rb index abd9916b3a..39a764b439 100644 --- a/lib/chef/win32/version.rb +++ b/lib/chef/win32/version.rb @@ -48,21 +48,21 @@ class Chef private_class_method :method_name_from_marketing_name WIN_VERSIONS = { - "Windows 10" => {:major => 10, :minor => 0, :callable => lambda{ |product_type, suite_mask| product_type == VER_NT_WORKSTATION }}, - "Windows Server 2016" => {:major => 10, :minor => 0, :callable => lambda {|product_type, suite_mask| product_type != VER_NT_WORKSTATION }}, - "Windows 8.1" => {:major => 6, :minor => 3, :callable => lambda{ |product_type, suite_mask| product_type == VER_NT_WORKSTATION }}, - "Windows Server 2012 R2" => {:major => 6, :minor => 3, :callable => lambda {|product_type, suite_mask| product_type != VER_NT_WORKSTATION }}, - "Windows 8" => {:major => 6, :minor => 2, :callable => lambda{ |product_type, suite_mask| product_type == VER_NT_WORKSTATION }}, - "Windows Server 2012" => {:major => 6, :minor => 2, :callable => lambda{ |product_type, suite_mask| product_type != VER_NT_WORKSTATION }}, - "Windows 7" => {:major => 6, :minor => 1, :callable => lambda{ |product_type, suite_mask| product_type == VER_NT_WORKSTATION }}, - "Windows Server 2008 R2" => {:major => 6, :minor => 1, :callable => lambda{ |product_type, suite_mask| product_type != VER_NT_WORKSTATION }}, - "Windows Server 2008" => {:major => 6, :minor => 0, :callable => lambda{ |product_type, suite_mask| product_type != VER_NT_WORKSTATION }}, - "Windows Vista" => {:major => 6, :minor => 0, :callable => lambda{ |product_type, suite_mask| product_type == VER_NT_WORKSTATION }}, - "Windows Server 2003 R2" => {:major => 5, :minor => 2, :callable => lambda{ |product_type, suite_mask| get_system_metrics(SM_SERVERR2) != 0 }}, - "Windows Home Server" => {:major => 5, :minor => 2, :callable => lambda{ |product_type, suite_mask| (suite_mask & VER_SUITE_WH_SERVER) == VER_SUITE_WH_SERVER }}, - "Windows Server 2003" => {:major => 5, :minor => 2, :callable => lambda{ |product_type, suite_mask| get_system_metrics(SM_SERVERR2) == 0 }}, - "Windows XP" => {:major => 5, :minor => 1}, - "Windows 2000" => {:major => 5, :minor => 0}, + "Windows 10" => { :major => 10, :minor => 0, :callable => lambda { |product_type, suite_mask| product_type == VER_NT_WORKSTATION } }, + "Windows Server 2016" => { :major => 10, :minor => 0, :callable => lambda { |product_type, suite_mask| product_type != VER_NT_WORKSTATION } }, + "Windows 8.1" => { :major => 6, :minor => 3, :callable => lambda { |product_type, suite_mask| product_type == VER_NT_WORKSTATION } }, + "Windows Server 2012 R2" => { :major => 6, :minor => 3, :callable => lambda { |product_type, suite_mask| product_type != VER_NT_WORKSTATION } }, + "Windows 8" => { :major => 6, :minor => 2, :callable => lambda { |product_type, suite_mask| product_type == VER_NT_WORKSTATION } }, + "Windows Server 2012" => { :major => 6, :minor => 2, :callable => lambda { |product_type, suite_mask| product_type != VER_NT_WORKSTATION } }, + "Windows 7" => { :major => 6, :minor => 1, :callable => lambda { |product_type, suite_mask| product_type == VER_NT_WORKSTATION } }, + "Windows Server 2008 R2" => { :major => 6, :minor => 1, :callable => lambda { |product_type, suite_mask| product_type != VER_NT_WORKSTATION } }, + "Windows Server 2008" => { :major => 6, :minor => 0, :callable => lambda { |product_type, suite_mask| product_type != VER_NT_WORKSTATION } }, + "Windows Vista" => { :major => 6, :minor => 0, :callable => lambda { |product_type, suite_mask| product_type == VER_NT_WORKSTATION } }, + "Windows Server 2003 R2" => { :major => 5, :minor => 2, :callable => lambda { |product_type, suite_mask| get_system_metrics(SM_SERVERR2) != 0 } }, + "Windows Home Server" => { :major => 5, :minor => 2, :callable => lambda { |product_type, suite_mask| (suite_mask & VER_SUITE_WH_SERVER) == VER_SUITE_WH_SERVER } }, + "Windows Server 2003" => { :major => 5, :minor => 2, :callable => lambda { |product_type, suite_mask| get_system_metrics(SM_SERVERR2) == 0 } }, + "Windows XP" => { :major => 5, :minor => 1 }, + "Windows 2000" => { :major => 5, :minor => 0 }, } def initialize @@ -88,12 +88,12 @@ class Chef marketing_names = Array.new # General Windows checks - WIN_VERSIONS.each do |k,v| + WIN_VERSIONS.each do |k, v| method_name = method_name_from_marketing_name(k) define_method(method_name) do (@major_version == v[:major]) && - (@minor_version == v[:minor]) && - (v[:callable] ? v[:callable].call(@product_type, @suite_mask) : true) + (@minor_version == v[:minor]) && + (v[:callable] ? v[:callable].call(@product_type, @suite_mask) : true) end marketing_names << [k, method_name] end @@ -129,7 +129,7 @@ class Chef # The operating system version is a string in the following form # that can be split into components based on the '.' delimiter: # MajorVersionNumber.MinorVersionNumber.BuildNumber - os_version.split(".").collect { | version_string | version_string.to_i } + os_version.split(".").collect { |version_string| version_string.to_i } end def get_version_ex @@ -152,7 +152,6 @@ class Chef # Windows Server 2003 datacenter sku = (ver_info[:w_suite_mask] & VER_SUITE_DATACENTER) ? PRODUCT_DATACENTER_SERVER : 0 end - end end end diff --git a/omnibus/config/projects/chef.rb b/omnibus/config/projects/chef.rb index 6a0f5eb96e..1dfd11edcd 100644 --- a/omnibus/config/projects/chef.rb +++ b/omnibus/config/projects/chef.rb @@ -33,7 +33,7 @@ else install_dir "#{default_root}/#{name}" end -override :bundler, version: "1.10.6" +override :bundler, version: "1.10.6" if windows? override :'ruby-windows', version: "2.0.0-p645" @@ -43,7 +43,7 @@ if windows? override :'ruby-windows-devkit', version: "4.5.2-20111229-1559" end else - override :ruby, version: "2.1.6" + override :ruby, version: "2.1.6" end ###### @@ -88,5 +88,5 @@ package :msi do wix_light_extension "WixUtilExtension" signing_identity "F74E1A68005E8A9C465C3D2FF7B41F3988F0EA09", machine_store: true parameters ChefLogDllPath: windows_safe_path(gem_path("chef-[0-9]*-mingw32/ext/win32-eventlog/chef-log.dll")), - ProjectLocationDir: project_location_dir + ProjectLocationDir: project_location_dir end diff --git a/spec/functional/audit/rspec_formatter_spec.rb b/spec/functional/audit/rspec_formatter_spec.rb index 209694ae70..0799c1e38a 100644 --- a/spec/functional/audit/rspec_formatter_spec.rb +++ b/spec/functional/audit/rspec_formatter_spec.rb @@ -50,5 +50,4 @@ describe Chef::Audit::RspecFormatter do runner.run end end - end diff --git a/spec/functional/audit/runner_spec.rb b/spec/functional/audit/runner_spec.rb index dcfa69c349..3a05ca5b99 100644 --- a/spec/functional/audit/runner_spec.rb +++ b/spec/functional/audit/runner_spec.rb @@ -29,7 +29,6 @@ require "tempfile" # so this isn't needed. In unit testing the Runner should be mocked appropriately. describe Chef::Audit::Runner do - # The functional tests must be run in a sub_process. Including Serverspec includes the Serverspec DSL - this # conflicts with our `package` DSL (among others) when we try to test `package` inside an RSpec example. # Our DSL leverages `method_missing` while the Serverspec DSL defines a method on the RSpec::Core::ExampleGroup. @@ -47,7 +46,6 @@ describe Chef::Audit::Runner do end describe "#run" do - let(:audits) { {} } let(:run_context) { instance_double(Chef::RunContext, :events => events, :audits => audits) } let(:control_group_name) { "control_group_name" } @@ -63,7 +61,7 @@ describe Chef::Audit::Runner do expect(2 - 2).to eq(0) end end - { control_group_name => Struct.new(:args, :block).new([control_group_name], should_pass)} + { control_group_name => Struct.new(:args, :block).new([control_group_name], should_pass) } end end @@ -74,7 +72,7 @@ describe Chef::Audit::Runner do expect(2 - 1).to eq(0) end end - { control_group_name => Struct.new(:args, :block).new([control_group_name], should_fail)} + { control_group_name => Struct.new(:args, :block).new([control_group_name], should_fail) } end end @@ -115,7 +113,5 @@ describe Chef::Audit::Runner do end end end - end - end diff --git a/spec/functional/dsl/reboot_pending_spec.rb b/spec/functional/dsl/reboot_pending_spec.rb index 6f600ca325..c7a93c6822 100644 --- a/spec/functional/dsl/reboot_pending_spec.rb +++ b/spec/functional/dsl/reboot_pending_spec.rb @@ -22,7 +22,7 @@ require "spec_helper" describe Chef::DSL::RebootPending, :windows_only do def run_ohai - node.consume_external_attrs(OHAI_SYSTEM.data,{}) + node.consume_external_attrs(OHAI_SYSTEM.data, {}) end let(:node) { Chef::Node.new } @@ -98,7 +98,7 @@ describe Chef::DSL::RebootPending, :windows_only do describe "when there is nothing to indicate a reboot is pending" do it "should return false" do - skip "reboot pending" if @any_flag.any? { |_,v| v == true } + skip "reboot pending" if @any_flag.any? { |_, v| v == true } expect(recipe.reboot_pending?).to be_falsey end end diff --git a/spec/functional/dsl/registry_helper_spec.rb b/spec/functional/dsl/registry_helper_spec.rb index 885615b6d7..9ac94c26e6 100644 --- a/spec/functional/dsl/registry_helper_spec.rb +++ b/spec/functional/dsl/registry_helper_spec.rb @@ -20,7 +20,6 @@ require "chef/dsl/registry_helper" require "spec_helper" describe Chef::Resource::RegistryKey, :windows_only do - before (:all) do ::Win32::Registry::HKEY_CURRENT_USER.create "Software\\Root" ::Win32::Registry::HKEY_CURRENT_USER.create "Software\\Root\\Branch" @@ -31,7 +30,7 @@ describe Chef::Resource::RegistryKey, :windows_only do events = Chef::EventDispatch::Dispatcher.new node = Chef::Node.new - node.consume_external_attrs(OHAI_SYSTEM.data,{}) + node.consume_external_attrs(OHAI_SYSTEM.data, {}) run_context = Chef::RunContext.new(node, {}, events) @resource = Chef::Resource.new("foo", run_context) end @@ -42,7 +41,7 @@ describe Chef::Resource::RegistryKey, :windows_only do end it "returns true if registry has specified value" do values = @resource.registry_get_values("HKCU\\Software\\Root") - expect(values.include?({:name=>"RootType1",:type=>:string,:data=>"fibrous"})).to eq(true) + expect(values.include?({ :name => "RootType1", :type => :string, :data => "fibrous" })).to eq(true) end it "returns true if specified registry_has_subkey" do expect(@resource.registry_has_subkeys?("HKCU\\Software\\Root")).to eq(true) @@ -52,10 +51,10 @@ describe Chef::Resource::RegistryKey, :windows_only do expect(subkeys.include?("Branch")).to eq(true) end it "returns true if registry_value_exists" do - expect(@resource.registry_value_exists?("HKCU\\Software\\Root", {:name=>"RootType1", :type=>:string, :data=>"fibrous"})).to eq(true) + expect(@resource.registry_value_exists?("HKCU\\Software\\Root", { :name => "RootType1", :type => :string, :data => "fibrous" })).to eq(true) end it "returns true if data_value_exists" do - expect(@resource.registry_data_exists?("HKCU\\Software\\Root", {:name=>"RootType1", :type=>:string, :data=>"fibrous"})).to eq(true) + expect(@resource.registry_data_exists?("HKCU\\Software\\Root", { :name => "RootType1", :type => :string, :data => "fibrous" })).to eq(true) end end end diff --git a/spec/functional/event_loggers/windows_eventlog_spec.rb b/spec/functional/event_loggers/windows_eventlog_spec.rb index 0f59e64f25..d0bf218257 100644 --- a/spec/functional/event_loggers/windows_eventlog_spec.rb +++ b/spec/functional/event_loggers/windows_eventlog_spec.rb @@ -26,7 +26,7 @@ end describe Chef::EventLoggers::WindowsEventLogger, :windows_only, :not_supported_on_win2k3 do def rand - random.rand(1<<32).to_s + random.rand(1 << 32).to_s end let(:random) { Random.new } @@ -36,10 +36,10 @@ describe Chef::EventLoggers::WindowsEventLogger, :windows_only, :not_supported_o let(:logger) { Chef::EventLoggers::WindowsEventLogger.new } let(:flags) { nil } let(:node) { nil } - let(:run_status) { double("Run Status", {run_id: run_id, elapsed_time: elapsed_time }) } + let(:run_status) { double("Run Status", { run_id: run_id, elapsed_time: elapsed_time }) } let(:event_log) { EventLog.new("Application") } let!(:offset) { event_log.read_last_event.record_number } - let(:mock_exception) { double("Exception", {message: rand, backtrace: [rand, rand]})} + let(:mock_exception) { double("Exception", { message: rand, backtrace: [rand, rand] }) } it "is available" do expect(Chef::EventLoggers::WindowsEventLogger.available?).to be_truthy @@ -97,5 +97,4 @@ describe Chef::EventLoggers::WindowsEventLogger, :windows_only, :not_supported_o e.string_inserts[4].include?(mock_exception.backtrace[1]) end).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 d3fc6bcd37..6b9d76d0d4 100644 --- a/spec/functional/file_content_management/deploy_strategies_spec.rb +++ b/spec/functional/file_content_management/deploy_strategies_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" shared_examples_for "a content deploy strategy" do - def normalize_mode(mode_int) ( mode_int & 07777).to_s(8) end @@ -38,9 +37,7 @@ shared_examples_for "a content deploy strategy" do let(:content_deployer) { described_class.new } let(:target_file_path) { File.join(sandbox_dir, "cp-deploy-strategy-target-file.txt") } - describe "creating the file" do - ## # UNIX Context let(:default_mode) { normalize_mode(0666 & ~File.umask) } @@ -69,7 +66,7 @@ shared_examples_for "a content deploy strategy" do def ace_inherits?(ace) flags = ace.flags - (flags & masks::OBJECT_INHERIT_ACE) !=0 + (flags & masks::OBJECT_INHERIT_ACE) != 0 end let(:parent_inheritable_aces) do @@ -103,7 +100,6 @@ shared_examples_for "a content deploy strategy" do end describe "updating the file" do - let(:staging_dir) { Dir.mktmpdir } let(:staging_file_content) { "this is the expected content" } @@ -155,7 +151,6 @@ shared_examples_for "a content deploy strategy" do end context "when the owner of the target file is not the owner of the staging file", :requires_root do - before do File.chown(1337, 1337, target_file_path) end @@ -167,14 +162,11 @@ shared_examples_for "a content deploy strategy" do expect(unix_invariant_properies(original_info)).to eq(unix_invariant_properies(updated_info)) end - end - end end describe Chef::FileContentManagement::Deploy::Cp do - let(:unix_invariants) do [ :uid, @@ -193,11 +185,9 @@ describe Chef::FileContentManagement::Deploy::Cp do end it_should_behave_like "a content deploy strategy" - end describe Chef::FileContentManagement::Deploy::MvUnix, :unix_only do - let(:unix_invariants) do [ :uid, @@ -213,9 +203,7 @@ end class Chef::FileContentManagement::Deploy::MvWindows ; end describe Chef::FileContentManagement::Deploy::MvWindows, :windows_only do - context "when a file has no sacl" do - let(:security_descriptor_invariants) do [ :owner, @@ -226,5 +214,4 @@ describe Chef::FileContentManagement::Deploy::MvWindows, :windows_only do it_should_behave_like "a content deploy strategy" end - end diff --git a/spec/functional/knife/cookbook_delete_spec.rb b/spec/functional/knife/cookbook_delete_spec.rb index 1757b22842..d915962ced 100644 --- a/spec/functional/knife/cookbook_delete_spec.rb +++ b/spec/functional/knife/cookbook_delete_spec.rb @@ -44,7 +44,7 @@ describe Chef::Knife::CookbookDelete do before do @knife.name_args = %w{no-such-cookbook} - @api.get("/cookbooks/no-such-cookbook", 404, Chef::JSONCompat.to_json({"error"=>"dear Tim, no. -Sent from my iPad"})) + @api.get("/cookbooks/no-such-cookbook", 404, Chef::JSONCompat.to_json({ "error" => "dear Tim, no. -Sent from my iPad" })) end around do |ex| @@ -62,16 +62,15 @@ describe Chef::Knife::CookbookDelete do it "logs an error and exits" do allow(@knife.ui).to receive(:stderr).and_return(log_output) - expect {@knife.run}.to raise_error(SystemExit) + expect { @knife.run }.to raise_error(SystemExit) expect(log_output.string).to match(/Cannot find a cookbook named no-such-cookbook to delete/) end - end context "when there is only one version of a cookbook" do before do @knife.name_args = %w{obsolete-cookbook} - @cookbook_list = {"obsolete-cookbook" => { "versions" => ["version" => "1.0.0"]} } + @cookbook_list = { "obsolete-cookbook" => { "versions" => ["version" => "1.0.0"] } } @api.get("/cookbooks/obsolete-cookbook", 200, Chef::JSONCompat.to_json(@cookbook_list)) end @@ -104,9 +103,7 @@ describe Chef::Knife::CookbookDelete do expect(stdout.string).to match(/#{Regexp.escape('Are you sure you want to purge files')}/) expect(stdout.string).to match(/#{Regexp.escape('Do you really want to delete obsolete-cookbook version 1.0.0? (Y/N)')}/) expect(cb100_deleted).to be_truthy - end - end context "when there are several versions of a cookbook" do @@ -114,7 +111,7 @@ describe Chef::Knife::CookbookDelete do @knife.name_args = %w{obsolete-cookbook} versions = ["1.0.0", "1.1.0", "1.2.0"] with_version = lambda { |version| { "version" => version } } - @cookbook_list = {"obsolete-cookbook" => { "versions" => versions.map(&with_version) } } + @cookbook_list = { "obsolete-cookbook" => { "versions" => versions.map(&with_version) } } @api.get("/cookbooks/obsolete-cookbook", 200, Chef::JSONCompat.to_json(@cookbook_list)) end @@ -161,7 +158,5 @@ describe Chef::Knife::CookbookDelete do expect(cb110_deleted).to be_truthy expect(cb120_deleted).to be_truthy end - end - end diff --git a/spec/functional/knife/exec_spec.rb b/spec/functional/knife/exec_spec.rb index 62e3a4c214..c755812460 100644 --- a/spec/functional/knife/exec_spec.rb +++ b/spec/functional/knife/exec_spec.rb @@ -44,12 +44,11 @@ describe Chef::Knife::Exec do it "executes a script in the context of the chef-shell main context" do @node = Chef::Node.new @node.name("ohai-world") - response = {"rows" => [@node],"start" => 0,"total" => 1} + response = { "rows" => [@node], "start" => 0, "total" => 1 } @api.get(%r{^/search/node}, 200, Chef::JSONCompat.to_json(response)) code = "$output.puts nodes.all" @knife.config[:exec] = code @knife.run expect($output.string).to match(%r{node\[ohai-world\]}) end - end diff --git a/spec/functional/knife/smoke_test.rb b/spec/functional/knife/smoke_test.rb index 8681a01873..dfb7bec611 100644 --- a/spec/functional/knife/smoke_test.rb +++ b/spec/functional/knife/smoke_test.rb @@ -19,7 +19,6 @@ require "spec_helper" describe "knife smoke tests" do - # Since our specs load all code, there could be a case where knife does not # run correctly b/c of a missing require, but is not caught by other tests. # @@ -31,7 +30,7 @@ describe "knife smoke tests" do knife_cmd.error! expect(knife_cmd.stdout).to include(Chef::VERSION) end - + it "can run and show help" do knife_path = File.expand_path("../../bin/knife", CHEF_SPEC_DATA) knife_cmd = Mixlib::ShellOut.new("#{knife_path} --help") diff --git a/spec/functional/knife/ssh_spec.rb b/spec/functional/knife/ssh_spec.rb index e516590905..d7bd43cd8c 100644 --- a/spec/functional/knife/ssh_spec.rb +++ b/spec/functional/knife/ssh_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "tiny_server" describe Chef::Knife::Ssh do - before(:all) do Chef::Knife::Ssh.load_deps @server = TinyServer::Manager.new @@ -262,7 +261,7 @@ describe Chef::Knife::Ssh do end end - def setup_knife(params=[]) + def setup_knife(params = []) @knife = Chef::Knife::Ssh.new(params) # We explicitly avoid running #configure_chef, which would read a knife.rb # if available, but #merge_configs (which is called by #configure_chef) is @@ -280,5 +279,4 @@ describe Chef::Knife::Ssh do %({"total":1, "start":0, "rows":[{"name":"i-xxxxxxxx", "json_class":"Chef::Node", "automatic":{"fqdn":"the.fqdn", "ec2":{"public_hostname":"the_public_hostname"}},"recipes":[]}]}) } end - end diff --git a/spec/functional/mixin/shell_out_spec.rb b/spec/functional/mixin/shell_out_spec.rb index edbfaa9ec8..48f6b7d912 100644 --- a/spec/functional/mixin/shell_out_spec.rb +++ b/spec/functional/mixin/shell_out_spec.rb @@ -36,9 +36,9 @@ describe Chef::Mixin::ShellOut do describe "when environment['LC_ALL'] is set" do it "should use the option's setting" do cmd = if windows? - shell_out_with_systems_locale("echo %LC_ALL%", :environment => {"LC_ALL" => "POSIX"}) + shell_out_with_systems_locale("echo %LC_ALL%", :environment => { "LC_ALL" => "POSIX" }) else - shell_out_with_systems_locale("echo $LC_ALL", :environment => {"LC_ALL" => "POSIX"}) + shell_out_with_systems_locale("echo $LC_ALL", :environment => { "LC_ALL" => "POSIX" }) end expect(cmd.stdout.chomp).to eq "POSIX" diff --git a/spec/functional/notifications_spec.rb b/spec/functional/notifications_spec.rb index ec6e514836..372f2619d4 100644 --- a/spec/functional/notifications_spec.rb +++ b/spec/functional/notifications_spec.rb @@ -1,7 +1,6 @@ require "spec_helper" require "chef/recipe" - # The goal of these tests is to make sure that loading resources from a file creates the necessary notifications. # Then once converge has started, both immediate and delayed notifications are called as the resources are converged. # We want to do this WITHOUT actually converging any resources - we don't want to take time changing the system, @@ -11,7 +10,6 @@ require "chef/recipe" # This test is extremely fragile since it mocks MANY different systems at once - any of them changes, this test # breaks describe "Notifications" do - # We always pretend we are on OSx because that has a specific provider (HomebrewProvider) so it # tests the translation from Provider => HomebrewProvider let(:node) { @@ -136,7 +134,7 @@ describe "Notifications" do expect(actions).to eq [ # First it runs why-run to check if the resource would update - { resource: log_resource.to_s, action: :write, why_run: true }, + { resource: log_resource.to_s, action: :write, why_run: true }, # Then it does NOT run the before action # Then it runs the actual action { resource: log_resource.to_s, action: :write }, @@ -166,7 +164,6 @@ describe "Notifications" do end describe "when one resource is defined lazily" do - it "subscribes to a resource defined in a ruby block" do r = recipe t = self @@ -224,16 +221,14 @@ describe "Notifications" do runner.converge end - end # Mocks having the provider run successfully and update the resource - def update_action(resource, times=1) + def update_action(resource, times = 1) p = Chef::Provider.new(resource, run_context) expect(resource).to receive(:provider_for_action).exactly(times).times.and_return(p) expect(p).to receive(:run_action).exactly(times).times { resource.updated_by_last_action(true) } end - end 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 e567c0b876..3aec76fb3f 100755 --- a/spec/functional/provider/remote_file/cache_control_data_spec.rb +++ b/spec/functional/provider/remote_file/cache_control_data_spec.rb @@ -20,15 +20,14 @@ require "spec_helper" require "uri" describe Chef::Provider::RemoteFile::CacheControlData do - before do - @original_config = Chef::Config.hash_dup + @original_config = Chef::Config.hash_dup end after do - Chef::Config.configuration = @original_config if @original_config + Chef::Config.configuration = @original_config if @original_config end - + before(:each) do Chef::Config[:file_cache_path] = Dir.mktmpdir end @@ -38,9 +37,8 @@ describe Chef::Provider::RemoteFile::CacheControlData do end let(:uri) { URI.parse("http://www.bing.com/robots.txt") } - - describe "when the cache control data save method is invoked" do + describe "when the cache control data save method is invoked" do subject(:cache_control_data) do Chef::Provider::RemoteFile::CacheControlData.load_and_validate(uri, file_checksum) end @@ -66,7 +64,7 @@ describe Chef::Provider::RemoteFile::CacheControlData do saved_cache_control_data = Chef::Provider::RemoteFile::CacheControlData.load_and_validate(uri, file_checksum) expect(saved_cache_control_data.etag).to eq(cache_control_data.etag) expect(saved_cache_control_data.mtime).to eq(cache_control_data.mtime) - expect(saved_cache_control_data.checksum).to eq(cache_control_data.checksum) + expect(saved_cache_control_data.checksum).to eq(cache_control_data.checksum) end # Cover the very long remote file path case -- see CHEF-4422 where @@ -91,11 +89,8 @@ describe Chef::Provider::RemoteFile::CacheControlData do saved_cache_control_data = Chef::Provider::RemoteFile::CacheControlData.load_and_validate(uri, file_checksum) expect(saved_cache_control_data.etag).to eq(cache_control_data.etag) expect(saved_cache_control_data.mtime).to eq(cache_control_data.mtime) - expect(saved_cache_control_data.checksum).to eq(cache_control_data.checksum) + expect(saved_cache_control_data.checksum).to eq(cache_control_data.checksum) end - end end - end - diff --git a/spec/functional/provider/whyrun_safe_ruby_block_spec.rb b/spec/functional/provider/whyrun_safe_ruby_block_spec.rb index b68193e8b9..892e1080db 100644 --- a/spec/functional/provider/whyrun_safe_ruby_block_spec.rb +++ b/spec/functional/provider/whyrun_safe_ruby_block_spec.rb @@ -43,7 +43,7 @@ describe Chef::Resource::WhyrunSafeRubyBlock do 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 { |action| new_resource.run_action(action) } expect($evil_global_evil_laugh).to eq(:mwahahaha) expect(new_resource).to be_updated end diff --git a/spec/functional/rebooter_spec.rb b/spec/functional/rebooter_spec.rb index 4b77c40e91..5be7325083 100644 --- a/spec/functional/rebooter_spec.rb +++ b/spec/functional/rebooter_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Platform::Rebooter do - let(:reboot_info) do { :delay_mins => 5, @@ -51,7 +50,6 @@ describe Chef::Platform::Rebooter do let(:rebooter) { Chef::Platform::Rebooter } describe '#reboot_if_needed!' do - it 'should not call #shell_out! when reboot has not been requested' do expect(rebooter).to receive(:shell_out!).exactly(0).times expect(rebooter).to receive(:reboot_if_needed!).once.and_call_original @@ -59,7 +57,6 @@ describe Chef::Platform::Rebooter do end describe 'calling #shell_out! to reboot' do - before(:each) do run_context.request_reboot(reboot_info) end diff --git a/spec/functional/resource/aix_service_spec.rb b/spec/functional/resource/aix_service_spec.rb index fe71f10cb3..6f71ad71ae 100755 --- a/spec/functional/resource/aix_service_spec.rb +++ b/spec/functional/resource/aix_service_spec.rb @@ -22,7 +22,6 @@ require "functional/resource/base" require "chef/mixin/shell_out" shared_examples "src service" do - include Chef::Mixin::ShellOut def service_should_be_started @@ -73,7 +72,6 @@ shared_examples "src service" do end describe Chef::Resource::Service, :requires_root, :aix_only do - include Chef::Mixin::ShellOut def get_user_id @@ -94,7 +92,6 @@ describe Chef::Resource::Service, :requires_root, :aix_only do shell_out!("rmssys -s ctestsys") end - let(:new_resource) do new_resource = Chef::Resource::Service.new("ctestsys", run_context) new_resource diff --git a/spec/functional/resource/aixinit_service_spec.rb b/spec/functional/resource/aixinit_service_spec.rb index 63c9cf618a..4d60712cbd 100755 --- a/spec/functional/resource/aixinit_service_spec.rb +++ b/spec/functional/resource/aixinit_service_spec.rb @@ -23,7 +23,6 @@ require "chef/mixin/shell_out" require "fileutils" describe Chef::Resource::Service, :requires_root, :aix_only do - include Chef::Mixin::ShellOut # Platform specific validation routines. @@ -39,7 +38,7 @@ describe Chef::Resource::Service, :requires_root, :aix_only do def valide_symlinks(expected_output, run_level = nil, status = nil, priority = nil) directory = [] if priority.is_a? Hash - priority.each do |level,o| + priority.each do |level, o| directory << "/etc/rc.d/rc#{level}.d/#{(o[0] == :start ? 'S' : 'K')}#{o[1]}#{new_resource.service_name}" end directory @@ -59,7 +58,7 @@ describe Chef::Resource::Service, :requires_root, :aix_only do let(:new_resource) do new_resource = Chef::Resource::Service.new("chefinittest", run_context) new_resource.provider Chef::Provider::Service::AixInit - new_resource.supports({:status => true, :restart => true, :reload => true}) + new_resource.supports({ :status => true, :restart => true, :reload => true }) new_resource end @@ -70,7 +69,7 @@ describe Chef::Resource::Service, :requires_root, :aix_only do before(:all) do File.delete("/etc/rc.d/init.d/chefinittest") if File.exists?("/etc/rc.d/init.d/chefinittest") - FileUtils.cp("#{File.join(File.dirname(__FILE__), "/../assets/chefinittest")}", "/etc/rc.d/init.d/chefinittest") + FileUtils.cp("#{File.join(File.dirname(__FILE__), "/../assets/chefinittest")}", "/etc/rc.d/init.d/chefinittest") end after(:all) do @@ -126,11 +125,10 @@ describe Chef::Resource::Service, :requires_root, :aix_only do end describe "enable service" do - context "when the service doesn't set a priority" do it "creates symlink with status S" do new_resource.run_action(:enable) - valide_symlinks(["/etc/rc.d/rc2.d/Schefinittest"],2,"S") + valide_symlinks(["/etc/rc.d/rc2.d/Schefinittest"], 2, "S") end end @@ -141,25 +139,24 @@ describe Chef::Resource::Service, :requires_root, :aix_only do it "creates a symlink with status S and a priority" do new_resource.run_action(:enable) - valide_symlinks(["/etc/rc.d/rc2.d/S75chefinittest"], 2,"S",75) + valide_symlinks(["/etc/rc.d/rc2.d/S75chefinittest"], 2, "S", 75) end end context "when the service sets complex priorities (hash)" do before do - priority = {2 => [:start, 20], 3 => [:stop, 10]} + priority = { 2 => [:start, 20], 3 => [:stop, 10] } new_resource.priority(priority) end it "create symlink with status start (S) or stop (K) and a priority " do new_resource.run_action(:enable) - valide_symlinks(["/etc/rc.d/rc2.d/S20chefinittest", "/etc/rc.d/rc3.d/K10chefinittest"], 2,"S",new_resource.priority) + valide_symlinks(["/etc/rc.d/rc2.d/S20chefinittest", "/etc/rc.d/rc3.d/K10chefinittest"], 2, "S", new_resource.priority) end end end describe "disable_service" do - context "when the service doesn't set a priority" do before do File.symlink("/etc/rc.d/init.d/chefinittest", "/etc/rc.d/rc2.d/Schefinittest") @@ -171,7 +168,7 @@ describe Chef::Resource::Service, :requires_root, :aix_only do it "creates symlink with status K" do new_resource.run_action(:disable) - valide_symlinks(["/etc/rc.d/rc2.d/Kchefinittest"], 2,"K") + valide_symlinks(["/etc/rc.d/rc2.d/Kchefinittest"], 2, "K") end end @@ -187,13 +184,13 @@ describe Chef::Resource::Service, :requires_root, :aix_only do it "creates a symlink with status K and a priority" do new_resource.run_action(:disable) - valide_symlinks(["/etc/rc.d/rc2.d/K25chefinittest"], 2,"K",25) + valide_symlinks(["/etc/rc.d/rc2.d/K25chefinittest"], 2, "K", 25) end end context "when the service sets complex priorities (hash)" do before do - @priority = {2 => [:stop, 20], 3 => [:start, 10]} + @priority = { 2 => [:stop, 20], 3 => [:start, 10] } new_resource.priority(@priority) File.symlink("/etc/rc.d/init.d/chefinittest", "/etc/rc.d/rc2.d/Schefinittest") end @@ -204,7 +201,7 @@ describe Chef::Resource::Service, :requires_root, :aix_only do it "create symlink with status stop (K) and a priority " do new_resource.run_action(:disable) - valide_symlinks(["/etc/rc.d/rc2.d/K80chefinittest"], 2,"K",80) + valide_symlinks(["/etc/rc.d/rc2.d/K80chefinittest"], 2, "K", 80) end end end diff --git a/spec/functional/resource/base.rb b/spec/functional/resource/base.rb index 40d178479b..38175e81c0 100644 --- a/spec/functional/resource/base.rb +++ b/spec/functional/resource/base.rb @@ -16,7 +16,6 @@ # limitations under the License. # - def run_context @run_context ||= begin node = Chef::Node.new @@ -27,4 +26,3 @@ def run_context Chef::RunContext.new(node, {}, events) end end - diff --git a/spec/functional/resource/batch_spec.rb b/spec/functional/resource/batch_spec.rb index e4fc6420c7..424c546d94 100644 --- a/spec/functional/resource/batch_spec.rb +++ b/spec/functional/resource/batch_spec.rb @@ -26,5 +26,4 @@ describe Chef::Resource::WindowsScript::Batch, :windows_only do let (:architecture_command) { "@echo %PROCESSOR_ARCHITECTURE%" } it_behaves_like "a Windows script running on Windows" - end diff --git a/spec/functional/resource/bff_spec.rb b/spec/functional/resource/bff_spec.rb index 326340606d..3a1d5840e8 100644 --- a/spec/functional/resource/bff_spec.rb +++ b/spec/functional/resource/bff_spec.rb @@ -39,7 +39,6 @@ describe Chef::Resource::BffPackage, :requires_root, :external => ohai[:platform !::File.exists?("/usr/PkgA/bin/acommand") end - before(:all) do @pkg_name = "PkgA.rte" @pkg_path = "/tmp/PkgA.1.0.0.0.bff" @@ -119,4 +118,3 @@ describe Chef::Resource::BffPackage, :requires_root, :external => ohai[:platform end end end - diff --git a/spec/functional/resource/chocolatey_package_spec.rb b/spec/functional/resource/chocolatey_package_spec.rb index 7cbaaf0d6b..e442008060 100644 --- a/spec/functional/resource/chocolatey_package_spec.rb +++ b/spec/functional/resource/chocolatey_package_spec.rb @@ -31,7 +31,7 @@ describe Chef::Resource::ChocolateyPackage, :windows_only do let(:package_name) { "test-A" } let(:package_list) { proc { powershell_out!("choco list -lo -r #{Array(package_name).join(' ')}").stdout.chomp } } let(:package_source) { File.join(CHEF_SPEC_ASSETS, "chocolatey_feed") } - + subject do new_resource = Chef::Resource::ChocolateyPackage.new("test choco package", run_context) new_resource.package_name package_name @@ -80,13 +80,13 @@ describe Chef::Resource::ChocolateyPackage, :windows_only do it "raises if package is not found" do subject.package_name "blah" - expect{ subject.run_action(:install) }.to raise_error Chef::Exceptions::Package + expect { subject.run_action(:install) }.to raise_error Chef::Exceptions::Package end - it "raises if package version is not found" do + it "raises if package version is not found" do subject.version "3.0" - expect{ subject.run_action(:install) }.to raise_error Chef::Exceptions::Package - end + expect { subject.run_action(:install) }.to raise_error Chef::Exceptions::Package + end end context "upgrading a package" do @@ -121,4 +121,4 @@ describe Chef::Resource::ChocolateyPackage, :windows_only do expect(package_list.call).to eq("") end end -end \ No newline at end of file +end diff --git a/spec/functional/resource/cookbook_file_spec.rb b/spec/functional/resource/cookbook_file_spec.rb index cd678e5e13..6e008bdcc1 100644 --- a/spec/functional/resource/cookbook_file_spec.rb +++ b/spec/functional/resource/cookbook_file_spec.rb @@ -76,6 +76,5 @@ describe Chef::Resource::CookbookFile do after do FileUtils.rm_r(windows_non_temp_dir) if Chef::Platform.windows? && File.exists?(windows_non_temp_dir) end - end end diff --git a/spec/functional/resource/cron_spec.rb b/spec/functional/resource/cron_spec.rb index 8c12b6e867..1ce1c6b1e9 100644 --- a/spec/functional/resource/cron_spec.rb +++ b/spec/functional/resource/cron_spec.rb @@ -22,7 +22,6 @@ require "functional/resource/base" require "chef/mixin/shell_out" describe Chef::Resource::Cron, :requires_root, :unix_only do - include Chef::Mixin::ShellOut # Platform specific validation routines. @@ -108,7 +107,7 @@ describe Chef::Resource::Cron, :requires_root, :unix_only do describe "create action with various attributes", :external => exclude_solaris do def create_and_validate_with_attribute(resource, attribute, value) if ohai[:platform] == "aix" - expect {resource.run_action(:create)}.to raise_error(Chef::Exceptions::Cron, /Aix cron entry does not support environment variables. Please set them in script and use script in cron./) + expect { resource.run_action(:create) }.to raise_error(Chef::Exceptions::Cron, /Aix cron entry does not support environment variables. Please set them in script and use script in cron./) else resource.run_action(:create) # Verify if the cron is created successfully @@ -167,6 +166,5 @@ describe Chef::Resource::Cron, :requires_root, :unix_only do new_resource.user "1-really-really-invalid-user-name" cron_create_should_raise_exception end - end end diff --git a/spec/functional/resource/deploy_revision_spec.rb b/spec/functional/resource/deploy_revision_spec.rb index 184c1cd017..e43ddc69df 100644 --- a/spec/functional/resource/deploy_revision_spec.rb +++ b/spec/functional/resource/deploy_revision_spec.rb @@ -21,7 +21,6 @@ require "tmpdir" # Deploy relies heavily on symlinks, so it doesn't work on windows. describe Chef::Resource::DeployRevision, :unix_only => true do - let(:file_cache_path) { Dir.mktmpdir } let(:deploy_directory) { Dir.mktmpdir } @@ -271,7 +270,6 @@ describe Chef::Resource::DeployRevision, :unix_only => true do it "is not marked updated" do expect(deploy_to_latest_rev).not_to be_updated_by_last_action end - end describe "again with force_deploy" do @@ -289,7 +287,6 @@ describe Chef::Resource::DeployRevision, :unix_only => true do it "is marked updated" do expect(deploy_to_latest_rev).to be_updated_by_last_action end - end describe "again to a new revision" do @@ -311,7 +308,6 @@ describe Chef::Resource::DeployRevision, :unix_only => true do it "leaves the old copy of the app around for rollback" do expect(File).to exist(File.join(deploy_directory, "releases", previous_rev)) end - end describe "back to a previously deployed revision (implicit rollback)" do @@ -375,7 +371,6 @@ describe Chef::Resource::DeployRevision, :unix_only => true do it "all_releases after rollback should be the same as after the first deploy" do expect(@previous_rev_again_all_releases).to eq(@previous_rev_all_releases) end - end describe "back to a previously deployed revision where resource rev == previous revision (explicit rollback)" do @@ -492,12 +487,10 @@ describe Chef::Resource::DeployRevision, :unix_only => true do it "all_releases after rollback should be the same as after the first deploy" do expect(@fifth_deploy_all_releases).to eq(@first_deploy_all_releases) end - end # CHEF-3435 describe "to a deploy_to path that does not yet exist" do - let(:top_level_tmpdir) { Dir.mktmpdir } # override top level deploy_directory let block with one that is two @@ -527,12 +520,10 @@ describe Chef::Resource::DeployRevision, :unix_only => true do end the_app_is_deployed_at_revision(:latest_rev) - end end context "when deploying an app with inline recipe callbacks" do - # Use closures to capture and mutate this variable. This allows us to track # ordering of operations. callback_order = [] @@ -633,13 +624,11 @@ describe Chef::Resource::DeployRevision, :unix_only => true do expect(File).to exist(rel_path("current/tmp/before_restart.txt")) expect(File).to exist(rel_path("current/tmp/after_restart.txt")) end - end context "when deploying an app with migrations" do let(:deploy_with_migration) do basic_deploy_resource.dup.tap do |r| - # Need this so we can call methods from this test inside the inline # recipe callbacks spec_context = self @@ -652,7 +641,6 @@ describe Chef::Resource::DeployRevision, :unix_only => true do # miration command gets run r.migration_command shell_restart_command("migration") r.before_migrate do - # inline recipe callbacks don't cwd, so you have to get the release # directory as a local and "capture" it in the closure. current_release = release_path @@ -680,7 +668,6 @@ describe Chef::Resource::DeployRevision, :unix_only => true do cwd current_release end end - end end @@ -707,9 +694,7 @@ describe Chef::Resource::DeployRevision, :unix_only => true do end context "when a previously deployed application has been nuked" do - shared_examples_for "a redeployed application" do - it "should redeploy the application" do expect(File).to be_directory(rel_path("releases")) expect(File).to be_directory(rel_path("shared")) @@ -728,7 +713,6 @@ describe Chef::Resource::DeployRevision, :unix_only => true do # deployment dir, deploy resource should detect that and nullify its cache. context "by removing the entire deploy directory" do - before do deploy_to_latest_rev.dup.run_action(:deploy) FileUtils.rm_rf(deploy_directory) @@ -736,11 +720,9 @@ describe Chef::Resource::DeployRevision, :unix_only => true do end include_examples "a redeployed application" - end context "by removing the current/ directory" do - before do deploy_to_latest_rev.dup.run_action(:deploy) FileUtils.rm(rel_path("current")) @@ -748,14 +730,11 @@ describe Chef::Resource::DeployRevision, :unix_only => true do end include_examples "a redeployed application" - end end context "when a deployment fails" do - shared_examples_for "a recovered deployment" do - it "should redeploy the application" do expect(File).to be_directory(rel_path("releases")) expect(File).to be_directory(rel_path("shared")) @@ -790,7 +769,6 @@ describe Chef::Resource::DeployRevision, :unix_only => true do end [:before_migrate, :before_symlink, :before_restart, :after_restart].each do |callback| - context "in the `#{callback}' callback" do before do expect { deploy_that_fails.run_action(:deploy) }.to raise_error(Exception, %r{I am a failed deploy}) @@ -799,19 +777,16 @@ describe Chef::Resource::DeployRevision, :unix_only => true do let(:deploy_that_fails) do resource = deploy_to_latest_rev.dup - errant_callback = lambda {|x| raise Exception, "I am a failed deploy" } + errant_callback = lambda { |x| raise Exception, "I am a failed deploy" } resource.send(callback, &errant_callback) resource end include_examples "a recovered deployment" - end - end context "in the service restart step" do - let(:deploy_that_fails) do resource = deploy_to_latest_rev.dup resource.restart_command("RUBYOPT=\"\" ruby -e 'exit 1'") @@ -827,7 +802,6 @@ describe Chef::Resource::DeployRevision, :unix_only => true do end context "when cloning the app code" do - class BadTimeScmProvider def initialize(new_resource, run_context) end @@ -859,10 +833,9 @@ describe Chef::Resource::DeployRevision, :unix_only => true do end context "and then is deployed to a different revision" do - let(:deploy_that_fails) do resource = deploy_to_previous_rev.dup - resource.after_restart {|x| raise Exception, "I am a failed deploy" } + resource.after_restart { |x| raise Exception, "I am a failed deploy" } resource end @@ -874,8 +847,6 @@ describe Chef::Resource::DeployRevision, :unix_only => true do it "removes the unsuccessful deploy after a later successful deploy" do expect(::File).not_to exist(File.join(deploy_directory, "releases", previous_rev)) end - end - end end diff --git a/spec/functional/resource/directory_spec.rb b/spec/functional/resource/directory_spec.rb index 0c1345d57f..3109f74c7b 100644 --- a/spec/functional/resource/directory_spec.rb +++ b/spec/functional/resource/directory_spec.rb @@ -39,5 +39,4 @@ describe Chef::Resource::Directory do it_behaves_like "a directory resource" it_behaves_like "a securable resource with reporting" - end diff --git a/spec/functional/resource/dpkg_package_spec.rb b/spec/functional/resource/dpkg_package_spec.rb index 3a09faf0d6..d65256231b 100644 --- a/spec/functional/resource/dpkg_package_spec.rb +++ b/spec/functional/resource/dpkg_package_spec.rb @@ -33,7 +33,7 @@ describe Chef::Resource::DpkgPackage, :requires_root, :debian_family_only, arch: Chef::RunContext.new(node, {}, events) } - let(:dpkg_package) { Chef::Resource::DpkgPackage.new(test1_0, run_context)} + let(:dpkg_package) { Chef::Resource::DpkgPackage.new(test1_0, run_context) } before(:each) do shell_out("dpkg -P chef-integration-test chef-integration-test2") @@ -45,7 +45,7 @@ describe Chef::Resource::DpkgPackage, :requires_root, :debian_family_only, arch: dpkg_package.package_name name end - def should_be_purged_or_removed(package, action=nil) + def should_be_purged_or_removed(package, action = nil) status = shell_out("dpkg -s #{package}") output = status.stdout + status.stderr if action.nil? || action == :purge @@ -318,7 +318,7 @@ describe Chef::Resource::DpkgPackage, :requires_root, :debian_family_only, arch: set_dpkg_package_name "chef-integration-test2" dpkg_package.run_action(action) expect(dpkg_package).not_to be_updated_by_last_action - shell_out!("dpkg -s chef-integration-test2") # its still 'installed' + shell_out!("dpkg -s chef-integration-test2") # its still 'installed' end end diff --git a/spec/functional/resource/dsc_resource_spec.rb b/spec/functional/resource/dsc_resource_spec.rb index f2c943f21d..4373535fd1 100644 --- a/spec/functional/resource/dsc_resource_spec.rb +++ b/spec/functional/resource/dsc_resource_spec.rb @@ -52,7 +52,7 @@ describe Chef::Resource::DscResource, :windows_powershell_dsc_only do context "with a valid dsc resource" do let(:tmp_file_name) { Dir::Tmpname.create("tmpfile") {} } - let(:test_text) { "'\"!@#$%^&*)(}{][\u2713~n"} + let(:test_text) { "'\"!@#$%^&*)(}{][\u2713~n" } before do new_resource.resource :File @@ -85,6 +85,5 @@ describe Chef::Resource::DscResource, :windows_powershell_dsc_only do expect(reresource).not_to be_updated end end - end end diff --git a/spec/functional/resource/dsc_script_spec.rb b/spec/functional/resource/dsc_script_spec.rb index cb8d73f746..987cdbdf67 100644 --- a/spec/functional/resource/dsc_script_spec.rb +++ b/spec/functional/resource/dsc_script_spec.rb @@ -38,7 +38,7 @@ describe Chef::Resource::DscScript, :windows_powershell_dsc_only do data_suffix = data ? "_config_data" : "" extension = data ? "psd1" : "ps1" script_path = "#{@temp_dir}/dsc_functional_test#{data_suffix}.#{extension}" - ::File.open(script_path, "wt") do | script | + ::File.open(script_path, "wt") do |script| script.write(script_code) end script_path @@ -68,7 +68,7 @@ describe Chef::Resource::DscScript, :windows_powershell_dsc_only do node = Chef::Node.new node.automatic["platform"] = "windows" node.automatic["platform_version"] = "6.1" - node.automatic["kernel"][:machine] = :x86_64 # Only 64-bit architecture is supported + node.automatic["kernel"][:machine] = :x86_64 # Only 64-bit architecture is supported node.automatic[:languages][:powershell][:version] = "4.0" empty_events = Chef::EventDispatch::Dispatcher.new Chef::RunContext.new(node, {}, empty_events) @@ -83,7 +83,7 @@ describe Chef::Resource::DscScript, :windows_powershell_dsc_only do let(:test_registry_data2) { "LL928" } let(:reg_key_name_param_name) { "testregkeyname" } let(:reg_key_value_param_name) { "testregvaluename" } - let(:registry_embedded_parameters) { "$#{reg_key_name_param_name} = '#{test_registry_key}';$#{reg_key_value_param_name} = '#{test_registry_value}'"} + let(:registry_embedded_parameters) { "$#{reg_key_name_param_name} = '#{test_registry_key}';$#{reg_key_value_param_name} = '#{test_registry_value}'" } let(:dsc_reg_code) { <<-EOH #{registry_embedded_parameters} Registry "ChefRegKey" @@ -105,21 +105,20 @@ EOH let(:dsc_user_prefix) { "dsc" } let(:dsc_user_suffix) { "chefx" } - let(:dsc_user) {"#{dsc_user_prefix}_usr_#{dsc_user_suffix}" } + let(:dsc_user) { "#{dsc_user_prefix}_usr_#{dsc_user_suffix}" } let(:dsc_user_prefix_env_var_name) { "dsc_user_env_prefix" } let(:dsc_user_suffix_env_var_name) { "dsc_user_env_suffix" } - let(:dsc_user_prefix_env_code) { "$env:#{dsc_user_prefix_env_var_name}"} - let(:dsc_user_suffix_env_code) { "$env:#{dsc_user_suffix_env_var_name}"} + let(:dsc_user_prefix_env_code) { "$env:#{dsc_user_prefix_env_var_name}" } + let(:dsc_user_suffix_env_code) { "$env:#{dsc_user_suffix_env_var_name}" } let(:dsc_user_prefix_param_name) { "dsc_user_prefix_param" } let(:dsc_user_suffix_param_name) { "dsc_user_suffix_param" } - let(:dsc_user_prefix_param_code) { "$#{dsc_user_prefix_param_name}"} - let(:dsc_user_suffix_param_code) { "$#{dsc_user_suffix_param_name}"} - let(:dsc_user_env_code) { "\"$(#{dsc_user_prefix_env_code})_usr_$(#{dsc_user_suffix_env_code})\""} - let(:dsc_user_param_code) { "\"$(#{dsc_user_prefix_param_code})_usr_$(#{dsc_user_suffix_param_code})\""} + let(:dsc_user_prefix_param_code) { "$#{dsc_user_prefix_param_name}" } + let(:dsc_user_suffix_param_code) { "$#{dsc_user_suffix_param_name}" } + let(:dsc_user_env_code) { "\"$(#{dsc_user_prefix_env_code})_usr_$(#{dsc_user_suffix_env_code})\"" } + let(:dsc_user_param_code) { "\"$(#{dsc_user_prefix_param_code})_usr_$(#{dsc_user_suffix_param_code})\"" } let(:config_flags) { nil } let(:config_params) { <<-EOH - [CmdletBinding()] param ( @@ -157,7 +156,7 @@ EOH } let(:dsc_user_config_data) { -<<-EOH + <<-EOH @{ AllNodes = @( @{ @@ -220,7 +219,7 @@ EOH expect(dsc_test_resource.registry_key_exists?(test_registry_key)).to eq(false) dsc_test_resource.run_action(:run) expect(dsc_test_resource.registry_key_exists?(test_registry_key)).to eq(true) - expect(dsc_test_resource.registry_value_exists?(test_registry_key, {:name => test_registry_value, :type => :string, :data => test_registry_data})).to eq(true) + expect(dsc_test_resource.registry_value_exists?(test_registry_key, { :name => test_registry_value, :type => :string, :data => test_registry_data })).to eq(true) end it_should_behave_like "a dsc_script resource with configuration affected by cwd" @@ -243,12 +242,12 @@ EOH let(:dsc_code) { dsc_environment_config } it "should not raise an exception if the cwd is not etc" do dsc_test_resource.cwd(dsc_environment_no_fail_not_etc_directory) - expect {dsc_test_resource.run_action(:run)}.not_to raise_error + expect { dsc_test_resource.run_action(:run) }.not_to raise_error end it "should raise an exception if the cwd is etc" do dsc_test_resource.cwd(dsc_environment_fail_etc_directory) - expect {dsc_test_resource.run_action(:run)}.to raise_error(Chef::Exceptions::PowershellCmdletException) + expect { dsc_test_resource.run_action(:run) }.to raise_error(Chef::Exceptions::PowershellCmdletException) begin dsc_test_resource.run_action(:run) rescue Chef::Exceptions::PowershellCmdletException => e @@ -266,7 +265,6 @@ EOH shared_examples_for "a dsc_script without configuration data that takes parameters" do context "when configuration data is not specified" do - before(:each) do test_key_resource = Chef::Resource::RegistryKey.new(test_registry_key, dsc_test_run_context) test_key_resource.recursive(true) @@ -280,7 +278,7 @@ EOH end let(:test_registry_data) { test_registry_data1 } - let(:dsc_parameterized_env_param_value) { "val" + Random::rand.to_s } + let(:dsc_parameterized_env_param_value) { "val" + Random::rand.to_s } it "should have a default value of nil for the configuration_data attribute" do expect(dsc_test_resource.configuration_data).to eql(nil) @@ -296,11 +294,11 @@ EOH it "should set a registry key according to parameters passed to the configuration" do dsc_test_resource.configuration_name(config_name_value) - dsc_test_resource.flags({:"#{reg_key_name_param_name}" => test_registry_key, :"#{reg_key_value_param_name}" => test_registry_value}) + dsc_test_resource.flags({ :"#{reg_key_name_param_name}" => test_registry_key, :"#{reg_key_value_param_name}" => test_registry_value }) expect(dsc_test_resource.registry_key_exists?(test_registry_key)).to eq(false) dsc_test_resource.run_action(:run) expect(dsc_test_resource.registry_key_exists?(test_registry_key)).to eq(true) - expect(dsc_test_resource.registry_value_exists?(test_registry_key, {:name => test_registry_value, :type => :string, :data => test_registry_data})).to eq(true) + expect(dsc_test_resource.registry_value_exists?(test_registry_key, { :name => test_registry_value, :type => :string, :data => test_registry_data })).to eq(true) end end end @@ -320,12 +318,12 @@ EOH if configuration_data_attribute == "configuration_data_script" config_data_value = create_config_script_from_code(dsc_user_config_data, "", true) end - dsc_test_resource.environment({dsc_user_prefix_env_var_name => dsc_user_prefix, - dsc_user_suffix_env_var_name => dsc_user_suffix}) + dsc_test_resource.environment({ dsc_user_prefix_env_var_name => dsc_user_prefix, + dsc_user_suffix_env_var_name => dsc_user_suffix }) dsc_test_resource.send(configuration_data_attribute, config_data_value) dsc_test_resource.flags(config_flags) expect(user_exists?(dsc_user)).to eq(false) - expect {dsc_test_resource.run_action(:run)}.not_to raise_error + expect { dsc_test_resource.run_action(:run) }.not_to raise_error expect(user_exists?(dsc_user)).to eq(true) end end @@ -333,9 +331,9 @@ EOH shared_examples_for "a dsc_script with configuration data that takes parameters" do let(:dsc_user_code) { dsc_user_param_code } let(:config_param_section) { config_params } - let(:config_flags) {{:"#{dsc_user_prefix_param_name}" => "#{dsc_user_prefix}", :"#{dsc_user_suffix_param_name}" => "#{dsc_user_suffix}"}} + let(:config_flags) { { :"#{dsc_user_prefix_param_name}" => "#{dsc_user_prefix}", :"#{dsc_user_suffix_param_name}" => "#{dsc_user_suffix}" } } it "does not directly contain the user name" do - configuration_script_content = ::File.open(dsc_test_resource.command) do | file | + configuration_script_content = ::File.open(dsc_test_resource.command) do |file| file.read end expect(configuration_script_content.include?(dsc_user)).to be(false) @@ -347,7 +345,7 @@ EOH let(:dsc_user_code) { dsc_user_env_code } it "does not directly contain the user name" do - configuration_script_content = ::File.open(dsc_test_resource.command) do | file | + configuration_script_content = ::File.open(dsc_test_resource.command) do |file| file.read end expect(configuration_script_content.include?(dsc_user)).to be(false) @@ -385,7 +383,7 @@ EOH before(:each) do delete_user(dsc_user) - dsc_test_run_context.node.consume_external_attrs(OHAI_SYSTEM.data,{}) + dsc_test_run_context.node.consume_external_attrs(OHAI_SYSTEM.data, {}) end let(:configuration_data_path) { 'C:\\configurationdata.psd1' } @@ -422,12 +420,12 @@ if($cert -eq $null) { } lcm -thumbprint $cert.thumbprint -set-dsclocalconfigurationmanager -path ./LCM +set-dsclocalconfigurationmanager -path ./LCM $ConfigurationData = @" @{ -AllNodes = @( - @{ - NodeName = "localhost"; +AllNodes = @( + @{ + NodeName = "localhost"; CertificateID = '$($cert.thumbprint)'; }; ); diff --git a/spec/functional/resource/env_spec.rb b/spec/functional/resource/env_spec.rb index 91fa860cd7..16481b9b23 100755 --- a/spec/functional/resource/env_spec.rb +++ b/spec/functional/resource/env_spec.rb @@ -90,7 +90,7 @@ describe Chef::Resource::Env, :windows_only do expect(ENV[chef_env_test_lower_case]).to eq(nil) test_resource.key_name(chef_env_test_lower_case) test_resource.value(env_value1) - expect {test_resource.run_action(:modify) }.to raise_error(Chef::Exceptions::Env) + expect { test_resource.run_action(:modify) }.to raise_error(Chef::Exceptions::Env) end it "should modify an existing variable's value to a new value" do @@ -127,7 +127,7 @@ describe Chef::Resource::Env, :windows_only do context "when using PATH" do let(:random_name) { Time.now.to_i } - let(:env_val) { "#{env_value_expandable}_#{random_name}"} + let(:env_val) { "#{env_value_expandable}_#{random_name}" } let!(:path_before) { test_resource.provider_for_action(test_resource.action).env_value("PATH") || "" } let!(:env_path_before) { ENV["PATH"] } @@ -148,7 +148,6 @@ describe Chef::Resource::Env, :windows_only do ENV["PATH"] = env_path_before end end - end context "when the delete action is invoked" do @@ -165,7 +164,7 @@ describe Chef::Resource::Env, :windows_only do expect(ENV[chef_env_test_lower_case]).to eq(nil) test_resource.key_name(chef_env_test_lower_case) test_resource.value(env_value1) - expect{test_resource.run_action(:delete)}.not_to raise_error + expect { test_resource.run_action(:delete) }.not_to raise_error expect(ENV[chef_env_test_lower_case]).to eq(nil) end diff --git a/spec/functional/resource/execute_spec.rb b/spec/functional/resource/execute_spec.rb index 1ceeb70590..1f2c793461 100644 --- a/spec/functional/resource/execute_spec.rb +++ b/spec/functional/resource/execute_spec.rb @@ -87,9 +87,9 @@ describe Chef::Resource::Execute do describe "when parent resource sets :environment" do before do resource.environment({ - "SAWS_SECRET" => "supersecret", - "SAWS_KEY" => "qwerty", - },) + "SAWS_SECRET" => "supersecret", + "SAWS_KEY" => "qwerty", + },) end it "guard inherits :environment value from resource and runs" do diff --git a/spec/functional/resource/file_spec.rb b/spec/functional/resource/file_spec.rb index d7ca34ecb8..d78b0f63cc 100644 --- a/spec/functional/resource/file_spec.rb +++ b/spec/functional/resource/file_spec.rb @@ -25,7 +25,7 @@ describe Chef::Resource::File do let(:file_base) { "file_spec" } let(:expected_content) { "Don't fear the ruby." } - def create_resource(opts={}) + def create_resource(opts = {}) events = Chef::EventDispatch::Dispatcher.new node = Chef::Node.new run_context = Chef::RunContext.new(node, {}, events) @@ -86,7 +86,6 @@ describe Chef::Resource::File do end end - describe "when using backup" do before do Chef::Config[:file_backup_path] = CHEF_SPEC_BACKUP_PATH @@ -108,7 +107,6 @@ describe Chef::Resource::File do resource_without_content.run_action(:create) expect(Dir.glob(backup_glob).length).to eq(1) end - end # github issue 1842. diff --git a/spec/functional/resource/git_spec.rb b/spec/functional/resource/git_spec.rb index 8710b22f31..779de02090 100644 --- a/spec/functional/resource/git_spec.rb +++ b/spec/functional/resource/git_spec.rb @@ -62,7 +62,7 @@ describe Chef::Resource::Git do let(:v1_tag) { "9b73fb5e316bfaff7b822b0ccb3e1e08f9885085" } let(:rev_foo) { "ed181b3419b6f489bedab282348162a110d6d3a1" } let(:rev_testing) { "972d153654503bccec29f630c5dd369854a561e8" } - let(:rev_head) { "d294fbfd05aa7709ad9a9b8ef6343b17d355bf5f"} + let(:rev_head) { "d294fbfd05aa7709ad9a9b8ef6343b17d355bf5f" } let(:git_user_config) do <<-E @@ -76,7 +76,7 @@ E 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+") { |f| f.print(git_user_config) } Chef::Config[:file_cache_path] = file_cache_path end @@ -254,6 +254,5 @@ E :returns => [0]).stdout.strip expect(head_rev).to eq(rev_head) end - end end diff --git a/spec/functional/resource/group_spec.rb b/spec/functional/resource/group_spec.rb index cb460fe7b4..063b5d9004 100644 --- a/spec/functional/resource/group_spec.rb +++ b/spec/functional/resource/group_spec.rb @@ -334,7 +334,7 @@ downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ" } invalid_resource = group_resource.dup invalid_resource.members(["Jack"]) invalid_resource.excluded_members(["Jack"]) - expect { invalid_resource.run_action(:create)}.to raise_error(Chef::Exceptions::ConflictingMembersInGroup) + expect { invalid_resource.run_action(:create) }.to raise_error(Chef::Exceptions::ConflictingMembersInGroup) end end end @@ -361,7 +361,7 @@ downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ" } end describe "group modify action", :not_supported_on_solaris do - let(:spec_members){ ["mnou5sdz", "htulrvwq", "x4c3g1lu"] } + let(:spec_members) { ["mnou5sdz", "htulrvwq", "x4c3g1lu"] } let(:included_members) { [spec_members[0], spec_members[1]] } let(:excluded_members) { [spec_members[2]] } let(:tested_action) { :modify } @@ -379,7 +379,7 @@ downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ" } describe "when running on Windows", :windows_only do describe "when members are Active Directory domain identities", :windows_domain_joined_only do let(:computer_domain) { ohai[:kernel]["cs_info"]["domain"].split(".")[0] } - let(:spec_members){ ["#{computer_domain}\\Domain Admins", "#{computer_domain}\\Domain Users", "#{computer_domain}\\Domain Computers"] } + let(:spec_members) { ["#{computer_domain}\\Domain Admins", "#{computer_domain}\\Domain Users", "#{computer_domain}\\Domain Computers"] } include_examples "correct group management" end @@ -389,7 +389,7 @@ downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ" } end describe "group manage action", :not_supported_on_solaris do - let(:spec_members){ ["mnou5sdz", "htulrvwq", "x4c3g1lu"] } + let(:spec_members) { ["mnou5sdz", "htulrvwq", "x4c3g1lu"] } let(:included_members) { [spec_members[0], spec_members[1]] } let(:excluded_members) { [spec_members[2]] } let(:tested_action) { :manage } @@ -416,7 +416,7 @@ downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ" } describe "running on windows", :windows_only do describe "when members are Windows domain identities", :windows_domain_joined_only do let(:computer_domain) { ohai[:kernel]["cs_info"]["domain"].split(".")[0] } - let(:spec_members){ ["#{computer_domain}\\Domain Admins", "#{computer_domain}\\Domain Users", "#{computer_domain}\\Domain Computers"] } + let(:spec_members) { ["#{computer_domain}\\Domain Admins", "#{computer_domain}\\Domain Users", "#{computer_domain}\\Domain Computers"] } include_examples "correct group management" end @@ -430,15 +430,15 @@ downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ" } let(:excluded_members) { ["x4c3g1lu"] } it ":manage should raise an error" do - expect {group_resource.run_action(:manage) }.to raise_error + expect { group_resource.run_action(:manage) }.to raise_error end it ":modify should raise an error" do - expect {group_resource.run_action(:modify) }.to raise_error + expect { group_resource.run_action(:modify) }.to raise_error end it ":create should raise an error" do - expect {group_resource.run_action(:create) }.to raise_error + expect { group_resource.run_action(:create) }.to raise_error end end @@ -450,11 +450,11 @@ downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ" } end it ":manage should raise an error" do - expect {group_resource.run_action(:manage) }.to raise_error + expect { group_resource.run_action(:manage) }.to raise_error end it ":modify should raise an error" do - expect {group_resource.run_action(:modify) }.to raise_error + expect { group_resource.run_action(:modify) }.to raise_error end end end diff --git a/spec/functional/resource/link_spec.rb b/spec/functional/resource/link_spec.rb index cfb20f0c69..786df979f5 100644 --- a/spec/functional/resource/link_spec.rb +++ b/spec/functional/resource/link_spec.rb @@ -25,7 +25,7 @@ end describe Chef::Resource::Link do let(:file_base) { "file_spec" } - let(:expect_updated?) {true} + let(:expect_updated?) { true } # We create the files in a different directory than tmp to exercise # different file deployment strategies more completely. @@ -83,6 +83,7 @@ describe Chef::Resource::Link do File.symlink(a, b) end end + def symlink?(file) if windows? Chef::ReservedNames::Win32::File.symlink?(file) @@ -90,6 +91,7 @@ describe Chef::Resource::Link do File.symlink?(file) end end + def readlink(file) if windows? Chef::ReservedNames::Win32::File.readlink(file) @@ -97,6 +99,7 @@ describe Chef::Resource::Link do File.readlink(file) end end + def link(a, b) if windows? Chef::ReservedNames::Win32::File.link(a, b) @@ -263,7 +266,6 @@ describe Chef::Resource::Link do end context "is symbolic" do - context "when the link destination is a file" do before(:each) do File.open(to, "w") do |file| @@ -354,9 +356,11 @@ describe Chef::Resource::Link do def allowed_acl(sid, expected_perms) [ ACE.access_allowed(sid, expected_perms[:specific]) ] end + def denied_acl(sid, expected_perms) [ ACE.access_denied(sid, expected_perms[:specific]) ] end + def parent_inheritable_acls dummy_file_path = File.join(test_file_dir, "dummy_file") FileUtils.touch(dummy_file_path) @@ -602,7 +606,7 @@ describe Chef::Resource::Link do describe "when not supported on platform", :win2k3_only do it "raises error" do - expect {resource}.to raise_error(Chef::Exceptions::Win32APIFunctionNotImplemented) + expect { resource }.to raise_error(Chef::Exceptions::Win32APIFunctionNotImplemented) end end end diff --git a/spec/functional/resource/ohai_spec.rb b/spec/functional/resource/ohai_spec.rb index ff7666392a..9ce989d8df 100644 --- a/spec/functional/resource/ohai_spec.rb +++ b/spec/functional/resource/ohai_spec.rb @@ -45,7 +45,7 @@ describe Chef::Resource::Ohai do end describe "when reloading all plugins" do - let(:ohai_resource) { Chef::Resource::Ohai.new("reload all", run_context)} + let(:ohai_resource) { Chef::Resource::Ohai.new("reload all", run_context) } it_behaves_like "reloaded :uptime" end @@ -57,7 +57,6 @@ describe Chef::Resource::Ohai do r } - it_behaves_like "reloaded :uptime" end end diff --git a/spec/functional/resource/package_spec.rb b/spec/functional/resource/package_spec.rb index 499b2d6b78..c29523c24a 100644 --- a/spec/functional/resource/package_spec.rb +++ b/spec/functional/resource/package_spec.rb @@ -87,16 +87,15 @@ module AptServer end metadata = { :unix_only => true, - :requires_root => true, - :provider => {:package => Chef::Provider::Package::Apt}, - :arch => "x86_64" # test packages are 64bit + :requires_root => true, + :provider => { :package => Chef::Provider::Package::Apt }, + :arch => "x86_64" # test packages are 64bit } describe Chef::Resource::Package, metadata do include Chef::Mixin::ShellOut context "with a remote package source" do - include AptServer before(:all) do @@ -112,7 +111,6 @@ describe Chef::Resource::Package, metadata do shell_out!("apt-get clean") end - after do shell_out!("dpkg -r chef-integration-test") shell_out("dpkg --clear-avail") @@ -192,11 +190,9 @@ describe Chef::Resource::Package, metadata do package_resource.run_action(:install) end.to raise_error(Mixlib::ShellOut::ShellCommandFailed) end - end describe "when preseeding the install" do - let(:file_cache_path) { Dir.mktmpdir } before do @@ -210,7 +206,6 @@ describe Chef::Resource::Package, metadata do end context "with a preseed file" do - let(:package_resource) do r = base_resource r.cookbook_name = "preseed" @@ -226,7 +221,6 @@ describe Chef::Resource::Package, metadata do end context "and the preseed file exists and is up-to-date" do - before do # Code here is duplicated from the implementation. Not great, but # it should at least fail if the code gets out of sync. @@ -242,13 +236,10 @@ describe Chef::Resource::Package, metadata do expect(cmd.stdout).to include("chef-integration-test/sample-var: INVALID") expect(package_resource).to be_updated_by_last_action end - end - end context "with a preseed template" do - # NOTE: in the fixtures, there is also a cookbook_file named # "preseed-template.seed". This implicitly tests that templates are # preferred over cookbook_files when both are present. @@ -287,13 +278,11 @@ describe Chef::Resource::Package, metadata do expect(package_resource).to be_updated_by_last_action end end - end end # installing w/ preseed end # when package not installed context "and the desired version of the package is installed" do - before do v_1_1_package = File.expand_path("apt/chef-integration-test_1.1-1_amd64.deb", CHEF_SPEC_DATA) shell_out!("dpkg -i #{v_1_1_package}") @@ -325,14 +314,13 @@ describe Chef::Resource::Package, metadata do # un chef-integration-test (no description available) def pkg_should_be_removed # will raise if exit code != 0,1 - pkg_check = shell_out!("dpkg -l chef-integration-test", :returns => [0,1]) + pkg_check = shell_out!("dpkg -l chef-integration-test", :returns => [0, 1]) if pkg_check.exitstatus == 0 expect(pkg_check.stdout).to match(/un[\s]+chef-integration-test/) end end - it "removes the package for action :remove" do package_resource.run_action(:remove) pkg_should_be_removed @@ -344,7 +332,6 @@ describe Chef::Resource::Package, metadata do pkg_should_be_removed expect(package_resource).to be_updated_by_last_action end - end context "and an older version of the package is installed" do @@ -380,9 +367,6 @@ describe Chef::Resource::Package, metadata do expect(package_resource).to be_updated_by_last_action end end - end - end - end diff --git a/spec/functional/resource/powershell_script_spec.rb b/spec/functional/resource/powershell_script_spec.rb index 2d9e1458a7..e8613becc5 100644 --- a/spec/functional/resource/powershell_script_spec.rb +++ b/spec/functional/resource/powershell_script_spec.rb @@ -20,7 +20,6 @@ require "chef/platform/query_helpers" require "spec_helper" describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do - include_context Chef::Resource::WindowsScript let (:architecture_command) { "echo $env:PROCESSOR_ARCHITECTURE" } @@ -164,7 +163,7 @@ describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do it "returns 1 if the last command was a cmdlet that failed and was preceded by an unsuccessfully executed non-cmdlet Windows binary" do pending "powershell.exe always exits with 0 on nano" if Chef::Platform.windows_nano_server? - resource.code([arbitrary_nonzero_process_exit_code_content,cmdlet_exit_code_not_found_content].join(";")) + resource.code([arbitrary_nonzero_process_exit_code_content, cmdlet_exit_code_not_found_content].join(";")) resource.returns(arbitrary_nonzero_process_exit_code) resource.run_action(:run) end @@ -325,7 +324,7 @@ configuration LCM it "raises an error when executing a script with a 32-bit process on Windows Nano Server", :windows_nano_only do resource.code(processor_architecture_script_content + " | out-file -encoding ASCII #{script_output_path}") - expect{ resource.architecture(:i386) }.to raise_error(Chef::Exceptions::Win32ArchitectureIncorrect, + expect { resource.architecture(:i386) }.to raise_error(Chef::Exceptions::Win32ArchitectureIncorrect, "cannot execute script with requested architecture 'i386' on Windows Nano Server") end end @@ -342,22 +341,22 @@ configuration LCM end it "evaluates a succeeding not_if block using cmd.exe as false by default" do - resource.not_if "exit /b 0" + resource.not_if "exit /b 0" expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a failing not_if block using cmd.exe as true by default" do - resource.not_if "exit /b 2" + resource.not_if "exit /b 2" expect(resource.should_skip?(:run)).to be_falsey end it "evaluates an succeeding only_if block using cmd.exe as true by default" do - resource.only_if "exit /b 0" + resource.only_if "exit /b 0" expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a failing only_if block using cmd.exe as false by default" do - resource.only_if "exit /b 2" + resource.only_if "exit /b 2" expect(resource.should_skip?(:run)).to be_truthy end end @@ -375,7 +374,6 @@ configuration LCM end context "with powershell_script as the guard_interpreter" do - it "has a guard_interpreter attribute set to :powershell_script" do expect(resource.guard_interpreter).to eq(:powershell_script) end @@ -383,77 +381,77 @@ configuration LCM it "evaluates a powershell $false for a not_if block as true" do pending "powershell.exe always exits with $true on nano" if Chef::Platform.windows_nano_server? - resource.not_if "$false" + resource.not_if "$false" expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a powershell $true for a not_if block as false" do - resource.not_if "$true" + resource.not_if "$true" expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a powershell $false for an only_if block as false" do pending "powershell.exe always exits with $true on nano" if Chef::Platform.windows_nano_server? - resource.only_if "$false" + resource.only_if "$false" expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a powershell $true for a only_if block as true" do - resource.only_if "$true" + resource.only_if "$true" expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a not_if block using powershell.exe" do - resource.not_if "exit([int32](![System.Environment]::CommandLine.Contains('powershell.exe')))" + resource.not_if "exit([int32](![System.Environment]::CommandLine.Contains('powershell.exe')))" expect(resource.should_skip?(:run)).to be_truthy end it "evaluates an only_if block using powershell.exe" do - resource.only_if "exit([int32](![System.Environment]::CommandLine.Contains('powershell.exe')))" + resource.only_if "exit([int32](![System.Environment]::CommandLine.Contains('powershell.exe')))" expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a non-zero powershell exit status for not_if as true" do pending "powershell.exe always exits with 0 on nano" if Chef::Platform.windows_nano_server? - resource.not_if "exit 37" + resource.not_if "exit 37" expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a zero powershell exit status for not_if as false" do - resource.not_if "exit 0" + resource.not_if "exit 0" expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a failed executable exit status for not_if as false" do pending "powershell.exe always exits with success on nano" if Chef::Platform.windows_nano_server? - resource.not_if windows_process_exit_code_not_found_content + resource.not_if windows_process_exit_code_not_found_content expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a successful executable exit status for not_if as true" do - resource.not_if windows_process_exit_code_success_content + resource.not_if windows_process_exit_code_success_content expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a failed executable exit status for only_if as false" do pending "powershell.exe always exits with success on nano" if Chef::Platform.windows_nano_server? - resource.only_if windows_process_exit_code_not_found_content + resource.only_if windows_process_exit_code_not_found_content expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a successful executable exit status for only_if as true" do - resource.only_if windows_process_exit_code_success_content + resource.only_if windows_process_exit_code_success_content expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a failed cmdlet exit status for not_if as true" do pending "powershell.exe always exits with success on nano" if Chef::Platform.windows_nano_server? - resource.not_if "throw 'up'" + resource.not_if "throw 'up'" expect(resource.should_skip?(:run)).to be_falsey end @@ -465,44 +463,44 @@ configuration LCM it "evaluates a failed cmdlet exit status for only_if as false" do pending "powershell.exe always exits with success on nano" if Chef::Platform.windows_nano_server? - resource.only_if "throw 'up'" + resource.only_if "throw 'up'" expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a successful cmdlet exit status for only_if as true" do - resource.only_if "cd ." + resource.only_if "cd ." expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a not_if block using the cwd guard parameter" do custom_cwd = "#{ENV['SystemRoot']}\\system32\\drivers\\etc" - resource.not_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')", :cwd => custom_cwd + resource.not_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')", :cwd => custom_cwd expect(resource.should_skip?(:run)).to be_truthy end it "evaluates an only_if block using the cwd guard parameter" do custom_cwd = "#{ENV['SystemRoot']}\\system32\\drivers\\etc" - resource.only_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')", :cwd => custom_cwd + resource.only_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')", :cwd => custom_cwd expect(resource.should_skip?(:run)).to be_falsey end it "inherits cwd from the parent resource for only_if" do custom_cwd = "#{ENV['SystemRoot']}\\system32\\drivers\\etc" resource.cwd custom_cwd - resource.only_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')" + resource.only_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')" expect(resource.should_skip?(:run)).to be_falsey end it "inherits cwd from the parent resource for not_if" do custom_cwd = "#{ENV['SystemRoot']}\\system32\\drivers\\etc" resource.cwd custom_cwd - resource.not_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')" + resource.not_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')" expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a 64-bit resource with a 64-bit guard and interprets boolean false as zero status code", :windows64_only do resource.architecture :x86_64 - resource.only_if "exit [int32]($env:PROCESSOR_ARCHITECTURE -ne 'AMD64')" + resource.only_if "exit [int32]($env:PROCESSOR_ARCHITECTURE -ne 'AMD64')" expect(resource.should_skip?(:run)).to be_falsey end @@ -510,19 +508,19 @@ configuration LCM pending "powershell.exe always exits with 0 on nano" if Chef::Platform.windows_nano_server? resource.architecture :x86_64 - resource.only_if "exit [int32]($env:PROCESSOR_ARCHITECTURE -eq 'AMD64')" + resource.only_if "exit [int32]($env:PROCESSOR_ARCHITECTURE -eq 'AMD64')" expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a 32-bit resource with a 32-bit guard and interprets boolean false as zero status code", :not_supported_on_nano do resource.architecture :i386 - resource.only_if "exit [int32]($env:PROCESSOR_ARCHITECTURE -ne 'X86')" + resource.only_if "exit [int32]($env:PROCESSOR_ARCHITECTURE -ne 'X86')" expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a 32-bit resource with a 32-bit guard and interprets boolean true as nonzero status code", :not_supported_on_nano do resource.architecture :i386 - resource.only_if "exit [int32]($env:PROCESSOR_ARCHITECTURE -eq 'X86')" + resource.only_if "exit [int32]($env:PROCESSOR_ARCHITECTURE -eq 'X86')" expect(resource.should_skip?(:run)).to be_truthy end @@ -530,7 +528,7 @@ configuration LCM pending "powershell.exe always exits with 0 on nano" if Chef::Platform.windows_nano_server? resource.convert_boolean_return true - resource.only_if "$false" + resource.only_if "$false" expect(resource.should_skip?(:run)).to be_truthy end @@ -538,53 +536,53 @@ configuration LCM pending "powershell.exe always exits with 0 on nano" if Chef::Platform.windows_nano_server? resource.convert_boolean_return true - resource.not_if "$false" + resource.not_if "$false" expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a simple boolean true as 0 status code when convert_boolean_return is true for only_if" do resource.convert_boolean_return true - resource.only_if "$true" + resource.only_if "$true" expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a simple boolean true as 0 status code when convert_boolean_return is true for not_if" do resource.convert_boolean_return true - resource.not_if "$true" + resource.not_if "$true" expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a 32-bit resource with a 32-bit guard and interprets boolean false as zero status code using convert_boolean_return for only_if", :not_supported_on_nano do resource.convert_boolean_return true resource.architecture :i386 - resource.only_if "$env:PROCESSOR_ARCHITECTURE -eq 'X86'" + resource.only_if "$env:PROCESSOR_ARCHITECTURE -eq 'X86'" expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a 32-bit resource with a 32-bit guard and interprets boolean false as zero status code using convert_boolean_return for not_if", :not_supported_on_nano do resource.convert_boolean_return true resource.architecture :i386 - resource.not_if "$env:PROCESSOR_ARCHITECTURE -ne 'X86'" + resource.not_if "$env:PROCESSOR_ARCHITECTURE -ne 'X86'" expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a 32-bit resource with a 32-bit guard and interprets boolean true as nonzero status code using convert_boolean_return for only_if", :not_supported_on_nano do resource.convert_boolean_return true resource.architecture :i386 - resource.only_if "$env:PROCESSOR_ARCHITECTURE -ne 'X86'" + resource.only_if "$env:PROCESSOR_ARCHITECTURE -ne 'X86'" expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a 32-bit resource with a 32-bit guard and interprets boolean true as nonzero status code using convert_boolean_return for not_if", :not_supported_on_nano do resource.convert_boolean_return true resource.architecture :i386 - resource.not_if "$env:PROCESSOR_ARCHITECTURE -eq 'X86'" + resource.not_if "$env:PROCESSOR_ARCHITECTURE -eq 'X86'" expect(resource.should_skip?(:run)).to be_truthy end it "raises an error when a 32-bit guard is used on Windows Nano Server", :windows_nano_only do resource.only_if "$true", :architecture => :i386 - expect{resource.run_action(:run)}.to raise_error( + expect { resource.run_action(:run) }.to raise_error( Chef::Exceptions::Win32ArchitectureIncorrect, /cannot execute script with requested architecture 'i386' on Windows Nano Server/) end diff --git a/spec/functional/resource/reboot_spec.rb b/spec/functional/resource/reboot_spec.rb index 3cf7f58e55..55ee63aba9 100644 --- a/spec/functional/resource/reboot_spec.rb +++ b/spec/functional/resource/reboot_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::Reboot do - let(:expected) do { :delay_mins => 5, diff --git a/spec/functional/resource/registry_spec.rb b/spec/functional/resource/registry_spec.rb index 9d7de1f183..ef629b56ff 100644 --- a/spec/functional/resource/registry_spec.rb +++ b/spec/functional/resource/registry_spec.rb @@ -27,21 +27,20 @@ describe Chef::Resource::RegistryKey, :unix_only do node = Chef::Node.new ohai = Ohai::System.new ohai.all_plugins - node.consume_external_attrs(ohai.data,{}) + node.consume_external_attrs(ohai.data, {}) run_context = Chef::RunContext.new(node, {}, events) @resource = Chef::Resource::RegistryKey.new("HKCU\\Software", run_context) end context "when load_current_resource is run on a non-windows node" do it "throws an exception because you don't have a windows registry (derp)" do @resource.key("HKCU\\Software\\Opscode") - @resource.values([{:name=>"Color", :type=>:string, :data=>"Orange"}]) - expect{@resource.run_action(:create)}.to raise_error(Chef::Exceptions::Win32NotWindows) + @resource.values([{ :name => "Color", :type => :string, :data => "Orange" }]) + expect { @resource.run_action(:create) }.to raise_error(Chef::Exceptions::Win32NotWindows) end end end describe Chef::Resource::RegistryKey, :windows_only, :broken => true do - # parent and key must be single keys, not paths let(:parent) { "Opscode" } let(:child) { "Whatever" } @@ -98,7 +97,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do @node = Chef::Node.new ohai = Ohai::System.new ohai.all_plugins - @node.consume_external_attrs(ohai.data,{}) + @node.consume_external_attrs(ohai.data, {}) @run_context = Chef::RunContext.new(@node, {}, @events) @new_resource = Chef::Resource::RegistryKey.new(resource_name, @run_context) @@ -113,8 +112,8 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do @rest_client = double("Chef::ServerAPI (mock)") allow(@rest_client).to receive(:create_url).and_return("reports/nodes/windowsbox/runs/#{@run_id}"); - allow(@rest_client).to receive(:raw_http_request).and_return({"result"=>"ok"}); - allow(@rest_client).to receive(:post_rest).and_return({"uri"=>"https://example.com/reports/nodes/windowsbox/runs/#{@run_id}"}); + allow(@rest_client).to receive(:raw_http_request).and_return({ "result" => "ok" }); + allow(@rest_client).to receive(:post_rest).and_return({ "uri" => "https://example.com/reports/nodes/windowsbox/runs/#{@run_id}" }); @resource_reporter = Chef::ResourceReporter.new(@rest_client) @events.register(@resource_reporter) @@ -122,7 +121,6 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do @resource_reporter.run_started(@run_status) @run_id = @resource_reporter.run_id - @new_resource.cookbook_name = "monkey" @cookbook_version = double("Cookbook::Version", :version => "1.2.3") allow(@new_resource).to receive(:cookbook_version).and_return(@cookbook_version) @@ -138,76 +136,76 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do end it "creates registry key, value if the key is missing" do @new_resource.key(reg_child) - @new_resource.values([{:name=>"Color", :type=>:string, :data=>"Orange"}]) + @new_resource.values([{ :name => "Color", :type => :string, :data => "Orange" }]) @new_resource.run_action(:create) expect(@registry.key_exists?(reg_child)).to eq(true) - expect(@registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(true) + expect(@registry.data_exists?(reg_child, { :name => "Color", :type => :string, :data => "Orange" })).to eq(true) end it "does not create the key if it already exists with same value, type and data" do @new_resource.key(reg_child) - @new_resource.values([{:name=>"Color", :type=>:string, :data=>"Orange"}]) + @new_resource.values([{ :name => "Color", :type => :string, :data => "Orange" }]) @new_resource.run_action(:create) expect(@registry.key_exists?(reg_child)).to eq(true) - expect(@registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(true) + expect(@registry.data_exists?(reg_child, { :name => "Color", :type => :string, :data => "Orange" })).to eq(true) end it "creates a value if it does not exist" do @new_resource.key(reg_child) - @new_resource.values([{:name=>"Mango", :type=>:string, :data=>"Yellow"}]) + @new_resource.values([{ :name => "Mango", :type => :string, :data => "Yellow" }]) @new_resource.run_action(:create) - expect(@registry.data_exists?(reg_child, {:name=>"Mango", :type=>:string, :data=>"Yellow"})).to eq(true) + expect(@registry.data_exists?(reg_child, { :name => "Mango", :type => :string, :data => "Yellow" })).to eq(true) end it "modifies the data if the key and value exist and type matches" do @new_resource.key(reg_child) - @new_resource.values([{:name=>"Color", :type=>:string, :data=>"Not just Orange - OpscodeOrange!"}]) + @new_resource.values([{ :name => "Color", :type => :string, :data => "Not just Orange - OpscodeOrange!" }]) @new_resource.run_action(:create) - expect(@registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Not just Orange - OpscodeOrange!"})).to eq(true) + expect(@registry.data_exists?(reg_child, { :name => "Color", :type => :string, :data => "Not just Orange - OpscodeOrange!" })).to eq(true) end it "modifys the type if the key and value exist and the type does not match" do @new_resource.key(reg_child) - @new_resource.values([{:name=>"Color", :type=>:multi_string, :data=>["Not just Orange - OpscodeOrange!"]}]) + @new_resource.values([{ :name => "Color", :type => :multi_string, :data => ["Not just Orange - OpscodeOrange!"] }]) @new_resource.run_action(:create) - expect(@registry.data_exists?(reg_child, {:name=>"Color", :type=>:multi_string, :data=>["Not just Orange - OpscodeOrange!"]})).to eq(true) + expect(@registry.data_exists?(reg_child, { :name => "Color", :type => :multi_string, :data => ["Not just Orange - OpscodeOrange!"] })).to eq(true) end it "creates subkey if parent exists" do @new_resource.key(reg_child + '\OpscodeTest') - @new_resource.values([{:name=>"Chef", :type=>:multi_string, :data=>["OpscodeOrange", "Rules"]}]) + @new_resource.values([{ :name => "Chef", :type => :multi_string, :data => ["OpscodeOrange", "Rules"] }]) @new_resource.recursive(false) @new_resource.run_action(:create) expect(@registry.key_exists?(reg_child + '\OpscodeTest')).to eq(true) - expect(@registry.value_exists?(reg_child + '\OpscodeTest', {:name=>"Chef", :type=>:multi_string, :data=>["OpscodeOrange", "Rules"]})).to eq(true) + expect(@registry.value_exists?(reg_child + '\OpscodeTest', { :name => "Chef", :type => :multi_string, :data => ["OpscodeOrange", "Rules"] })).to eq(true) end it "gives error if action create and parent does not exist and recursive is set to false" do @new_resource.key(reg_child + '\Missing1\Missing2') - @new_resource.values([{:name=>"OC", :type=>:string, :data=>"MissingData"}]) + @new_resource.values([{ :name => "OC", :type => :string, :data => "MissingData" }]) @new_resource.recursive(false) - expect{@new_resource.run_action(:create)}.to raise_error(Chef::Exceptions::Win32RegNoRecursive) + expect { @new_resource.run_action(:create) }.to raise_error(Chef::Exceptions::Win32RegNoRecursive) end it "creates missing keys if action create and parent does not exist and recursive is set to true" do @new_resource.key(reg_child + '\Missing1\Missing2') - @new_resource.values([{:name=>"OC", :type=>:string, :data=>"MissingData"}]) + @new_resource.values([{ :name => "OC", :type => :string, :data => "MissingData" }]) @new_resource.recursive(true) @new_resource.run_action(:create) expect(@registry.key_exists?(reg_child + '\Missing1\Missing2')).to eq(true) - expect(@registry.value_exists?(reg_child + '\Missing1\Missing2', {:name=>"OC", :type=>:string, :data=>"MissingData"})).to eq(true) + expect(@registry.value_exists?(reg_child + '\Missing1\Missing2', { :name => "OC", :type => :string, :data => "MissingData" })).to eq(true) end it "creates key with multiple value as specified" do @new_resource.key(reg_child) - @new_resource.values([{:name=>"one", :type=>:string, :data=>"1"},{:name=>"two", :type=>:string, :data=>"2"},{:name=>"three", :type=>:string, :data=>"3"}]) + @new_resource.values([{ :name => "one", :type => :string, :data => "1" }, { :name => "two", :type => :string, :data => "2" }, { :name => "three", :type => :string, :data => "3" }]) @new_resource.recursive(true) @new_resource.run_action(:create) @@ -226,12 +224,12 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do end it "creates a key in a 32-bit registry that is not viewable in 64-bit" do @new_resource.key(reg_child + '\Atraxi' ) - @new_resource.values([{:name=>"OC", :type=>:string, :data=>"Data"}]) + @new_resource.values([{ :name => "OC", :type => :string, :data => "Data" }]) @new_resource.recursive(true) @new_resource.architecture(:i386) @new_resource.run_action(:create) @registry.architecture = :i386 - expect(@registry.data_exists?(reg_child + '\Atraxi', {:name=>"OC", :type=>:string, :data=>"Data"})).to eq(true) + expect(@registry.data_exists?(reg_child + '\Atraxi', { :name => "OC", :type => :string, :data => "Data" })).to eq(true) @registry.architecture = :x86_64 expect(@registry.key_exists?(reg_child + '\Atraxi')).to eq(false) end @@ -239,7 +237,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do it "prepares the reporting data for action :create" do @new_resource.key(reg_child + '\Ood') - @new_resource.values([{:name=>"ReportingVal1", :type=>:string, :data=>"report1"},{:name=>"ReportingVal2", :type=>:string, :data=>"report2"}]) + @new_resource.values([{ :name => "ReportingVal1", :type => :string, :data => "report1" }, { :name => "ReportingVal2", :type => :string, :data => "report2" }]) @new_resource.recursive(true) @new_resource.run_action(:create) @report = @resource_reporter.prepare_run_data @@ -248,8 +246,8 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do expect(@report["resources"][0]["type"]).to eq("registry_key") expect(@report["resources"][0]["name"]).to eq(resource_name) expect(@report["resources"][0]["id"]).to eq(reg_child + '\Ood') - expect(@report["resources"][0]["after"][:values]).to eq([{:name=>"ReportingVal1", :type=>:string, :data=>"report1"}, - {:name=>"ReportingVal2", :type=>:string, :data=>"report2"}]) + expect(@report["resources"][0]["after"][:values]).to eq([{ :name => "ReportingVal1", :type => :string, :data => "report1" }, + { :name => "ReportingVal2", :type => :string, :data => "report2" }]) expect(@report["resources"][0]["before"][:values]).to eq([]) expect(@report["resources"][0]["result"]).to eq("create") expect(@report["status"]).to eq("success") @@ -263,7 +261,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do it "does not throw an exception if the keys do not exist but recursive is set to false" do @new_resource.key(reg_child + '\Slitheen\Raxicoricofallapatorius') - @new_resource.values([{:name=>"BriskWalk",:type=>:string,:data=>"is good for health"}]) + @new_resource.values([{ :name => "BriskWalk", :type => :string, :data => "is good for health" }]) @new_resource.recursive(false) @new_resource.run_action(:create) # should not raise_error expect(@registry.key_exists?(reg_child + '\Slitheen')).to eq(false) @@ -271,7 +269,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do end it "does not create key if the action is create" do @new_resource.key(reg_child + '\Slitheen') - @new_resource.values([{:name=>"BriskWalk",:type=>:string,:data=>"is good for health"}]) + @new_resource.values([{ :name => "BriskWalk", :type => :string, :data => "is good for health" }]) @new_resource.recursive(false) @new_resource.run_action(:create) expect(@registry.key_exists?(reg_child + '\Slitheen')).to eq(false) @@ -286,61 +284,61 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do it "creates registry key, value if the key is missing" do @new_resource.key(reg_child) - @new_resource.values([{:name=>"Color", :type=>:string, :data=>"Orange"}]) + @new_resource.values([{ :name => "Color", :type => :string, :data => "Orange" }]) @new_resource.run_action(:create_if_missing) expect(@registry.key_exists?(reg_parent)).to eq(true) expect(@registry.key_exists?(reg_child)).to eq(true) - expect(@registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(true) + expect(@registry.data_exists?(reg_child, { :name => "Color", :type => :string, :data => "Orange" })).to eq(true) end it "does not create the key if it already exists with same value, type and data" do @new_resource.key(reg_child) - @new_resource.values([{:name=>"Color", :type=>:string, :data=>"Orange"}]) + @new_resource.values([{ :name => "Color", :type => :string, :data => "Orange" }]) @new_resource.run_action(:create_if_missing) expect(@registry.key_exists?(reg_child)).to eq(true) - expect(@registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(true) + expect(@registry.data_exists?(reg_child, { :name => "Color", :type => :string, :data => "Orange" })).to eq(true) end it "creates a value if it does not exist" do @new_resource.key(reg_child) - @new_resource.values([{:name=>"Mango", :type=>:string, :data=>"Yellow"}]) + @new_resource.values([{ :name => "Mango", :type => :string, :data => "Yellow" }]) @new_resource.run_action(:create_if_missing) - expect(@registry.data_exists?(reg_child, {:name=>"Mango", :type=>:string, :data=>"Yellow"})).to eq(true) + expect(@registry.data_exists?(reg_child, { :name => "Mango", :type => :string, :data => "Yellow" })).to eq(true) end it "creates subkey if parent exists" do @new_resource.key(reg_child + '\Pyrovile') - @new_resource.values([{:name=>"Chef", :type=>:multi_string, :data=>["OpscodeOrange", "Rules"]}]) + @new_resource.values([{ :name => "Chef", :type => :multi_string, :data => ["OpscodeOrange", "Rules"] }]) @new_resource.recursive(false) @new_resource.run_action(:create_if_missing) expect(@registry.key_exists?(reg_child + '\Pyrovile')).to eq(true) - expect(@registry.value_exists?(reg_child + '\Pyrovile', {:name=>"Chef", :type=>:multi_string, :data=>["OpscodeOrange", "Rules"]})).to eq(true) + expect(@registry.value_exists?(reg_child + '\Pyrovile', { :name => "Chef", :type => :multi_string, :data => ["OpscodeOrange", "Rules"] })).to eq(true) end it "gives error if action create and parent does not exist and recursive is set to false" do @new_resource.key(reg_child + '\Sontaran\Sontar') - @new_resource.values([{:name=>"OC", :type=>:string, :data=>"MissingData"}]) + @new_resource.values([{ :name => "OC", :type => :string, :data => "MissingData" }]) @new_resource.recursive(false) - expect{@new_resource.run_action(:create_if_missing)}.to raise_error(Chef::Exceptions::Win32RegNoRecursive) + expect { @new_resource.run_action(:create_if_missing) }.to raise_error(Chef::Exceptions::Win32RegNoRecursive) end it "creates missing keys if action create and parent does not exist and recursive is set to true" do @new_resource.key(reg_child + '\Sontaran\Sontar') - @new_resource.values([{:name=>"OC", :type=>:string, :data=>"MissingData"}]) + @new_resource.values([{ :name => "OC", :type => :string, :data => "MissingData" }]) @new_resource.recursive(true) @new_resource.run_action(:create_if_missing) expect(@registry.key_exists?(reg_child + '\Sontaran\Sontar')).to eq(true) - expect(@registry.value_exists?(reg_child + '\Sontaran\Sontar', {:name=>"OC", :type=>:string, :data=>"MissingData"})).to eq(true) + expect(@registry.value_exists?(reg_child + '\Sontaran\Sontar', { :name => "OC", :type => :string, :data => "MissingData" })).to eq(true) end it "creates key with multiple value as specified" do @new_resource.key(reg_child + '\Adipose') - @new_resource.values([{:name=>"one", :type=>:string, :data=>"1"},{:name=>"two", :type=>:string, :data=>"2"},{:name=>"three", :type=>:string, :data=>"3"}]) + @new_resource.values([{ :name => "one", :type => :string, :data => "1" }, { :name => "two", :type => :string, :data => "2" }, { :name => "three", :type => :string, :data => "3" }]) @new_resource.recursive(true) @new_resource.run_action(:create_if_missing) @@ -351,7 +349,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do it "prepares the reporting data for :create_if_missing" do @new_resource.key(reg_child + '\Judoon') - @new_resource.values([{:name=>"ReportingVal3", :type=>:string, :data=>"report3"}]) + @new_resource.values([{ :name => "ReportingVal3", :type => :string, :data => "report3" }]) @new_resource.recursive(true) @new_resource.run_action(:create_if_missing) @report = @resource_reporter.prepare_run_data @@ -360,7 +358,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do expect(@report["resources"][0]["type"]).to eq("registry_key") expect(@report["resources"][0]["name"]).to eq(resource_name) expect(@report["resources"][0]["id"]).to eq(reg_child + '\Judoon') - expect(@report["resources"][0]["after"][:values]).to eq([{:name=>"ReportingVal3", :type=>:string, :data=>"report3"}]) + expect(@report["resources"][0]["after"][:values]).to eq([{ :name => "ReportingVal3", :type => :string, :data => "report3" }]) expect(@report["resources"][0]["before"][:values]).to eq([]) expect(@report["resources"][0]["result"]).to eq("create_if_missing") expect(@report["status"]).to eq("success") @@ -374,7 +372,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do it "does not throw an exception if the keys do not exist but recursive is set to false" do @new_resource.key(reg_child + '\Zygons\Zygor') - @new_resource.values([{:name=>"BriskWalk",:type=>:string,:data=>"is good for health"}]) + @new_resource.values([{ :name => "BriskWalk", :type => :string, :data => "is good for health" }]) @new_resource.recursive(false) @new_resource.run_action(:create_if_missing) # should not raise_error expect(@registry.key_exists?(reg_child + '\Zygons')).to eq(false) @@ -382,7 +380,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do end it "does nothing if the action is create_if_missing" do @new_resource.key(reg_child + '\Zygons') - @new_resource.values([{:name=>"BriskWalk",:type=>:string,:data=>"is good for health"}]) + @new_resource.values([{ :name => "BriskWalk", :type => :string, :data => "is good for health" }]) @new_resource.recursive(false) @new_resource.run_action(:create_if_missing) expect(@registry.key_exists?(reg_child + '\Zygons')).to eq(false) @@ -399,7 +397,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do it "takes no action if the specified key path does not exist in the system" do expect(@registry.key_exists?(reg_parent + '\Osirian')).to eq(false) - @new_resource.key(reg_parent+ '\Osirian') + @new_resource.key(reg_parent + '\Osirian') @new_resource.recursive(false) @new_resource.run_action(:delete) @@ -407,53 +405,53 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do end it "takes no action if the key exists but the value does not" do - expect(@registry.data_exists?(reg_parent + '\Opscode', {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(true) + expect(@registry.data_exists?(reg_parent + '\Opscode', { :name => "Color", :type => :string, :data => "Orange" })).to eq(true) @new_resource.key(reg_parent + '\Opscode') - @new_resource.values([{:name=>"LooksLike", :type=>:multi_string, :data=>["SeattleGrey", "OCOrange"]}]) + @new_resource.values([{ :name => "LooksLike", :type => :multi_string, :data => ["SeattleGrey", "OCOrange"] }]) @new_resource.recursive(false) @new_resource.run_action(:delete) - expect(@registry.data_exists?(reg_parent + '\Opscode', {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(true) + expect(@registry.data_exists?(reg_parent + '\Opscode', { :name => "Color", :type => :string, :data => "Orange" })).to eq(true) end it "deletes only specified values under a key path" do @new_resource.key(reg_parent + '\Opscode') - @new_resource.values([{:name=>"Opscode", :type=>:multi_string, :data=>["Seattle", "Washington"]}, {:name=>"AKA", :type=>:string, :data=>"OC"}]) + @new_resource.values([{ :name => "Opscode", :type => :multi_string, :data => ["Seattle", "Washington"] }, { :name => "AKA", :type => :string, :data => "OC" }]) @new_resource.recursive(false) @new_resource.run_action(:delete) - expect(@registry.data_exists?(reg_parent + '\Opscode', {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(true) - expect(@registry.value_exists?(reg_parent + '\Opscode', {:name=>"AKA", :type=>:string, :data=>"OC"})).to eq(false) - expect(@registry.value_exists?(reg_parent + '\Opscode', {:name=>"Opscode", :type=>:multi_string, :data=>["Seattle", "Washington"]})).to eq(false) + expect(@registry.data_exists?(reg_parent + '\Opscode', { :name => "Color", :type => :string, :data => "Orange" })).to eq(true) + expect(@registry.value_exists?(reg_parent + '\Opscode', { :name => "AKA", :type => :string, :data => "OC" })).to eq(false) + expect(@registry.value_exists?(reg_parent + '\Opscode', { :name => "Opscode", :type => :multi_string, :data => ["Seattle", "Washington"] })).to eq(false) end it "it deletes the values with the same name irrespective of it type and data" do @new_resource.key(reg_parent + '\Opscode') - @new_resource.values([{:name=>"Color", :type=>:multi_string, :data=>["Black", "Orange"]}]) + @new_resource.values([{ :name => "Color", :type => :multi_string, :data => ["Black", "Orange"] }]) @new_resource.recursive(false) @new_resource.run_action(:delete) - expect(@registry.value_exists?(reg_parent + '\Opscode', {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(false) + expect(@registry.value_exists?(reg_parent + '\Opscode', { :name => "Color", :type => :string, :data => "Orange" })).to eq(false) end it "prepares the reporting data for action :delete" do @new_resource.key(reg_parent + '\ReportKey') - @new_resource.values([{:name=>"ReportVal4", :type=>:string, :data=>"report4"},{:name=>"ReportVal5", :type=>:string, :data=>"report5"}]) + @new_resource.values([{ :name => "ReportVal4", :type => :string, :data => "report4" }, { :name => "ReportVal5", :type => :string, :data => "report5" }]) @new_resource.recursive(true) @new_resource.run_action(:delete) @report = @resource_reporter.prepare_run_data - expect(@registry.value_exists?(reg_parent + '\ReportKey', [{:name=>"ReportVal4", :type=>:string, :data=>"report4"},{:name=>"ReportVal5", :type=>:string, :data=>"report5"}])).to eq(false) + expect(@registry.value_exists?(reg_parent + '\ReportKey', [{ :name => "ReportVal4", :type => :string, :data => "report4" }, { :name => "ReportVal5", :type => :string, :data => "report5" }])).to eq(false) expect(@report["action"]).to eq("end") expect(@report["resources"].count).to eq(1) expect(@report["resources"][0]["type"]).to eq("registry_key") expect(@report["resources"][0]["name"]).to eq(resource_name) expect(@report["resources"][0]["id"]).to eq(reg_parent + '\ReportKey') - expect(@report["resources"][0]["before"][:values]).to eq([{:name=>"ReportVal4", :type=>:string, :data=>"report4"}, - {:name=>"ReportVal5", :type=>:string, :data=>"report5"}]) + expect(@report["resources"][0]["before"][:values]).to eq([{ :name => "ReportVal4", :type => :string, :data => "report4" }, + { :name => "ReportVal5", :type => :string, :data => "report5" }]) #Not testing for after values to match since after -> new_resource values. expect(@report["resources"][0]["result"]).to eq("delete") expect(@report["status"]).to eq("success") @@ -466,7 +464,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do end it "does nothing if the action is delete" do @new_resource.key(reg_parent + '\OpscodeWhyRun') - @new_resource.values([{:name=>"BriskWalk",:type=>:string,:data=>"is good for health"}]) + @new_resource.values([{ :name => "BriskWalk", :type => :string, :data => "is good for health" }]) @new_resource.recursive(false) @new_resource.run_action(:delete) @@ -502,7 +500,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do it "raises an exception if the key has subkeys and recursive == false" do @new_resource.key(reg_parent) @new_resource.recursive(false) - expect{@new_resource.run_action(:delete_key)}.to raise_error(Chef::Exceptions::Win32RegNoRecursive) + expect { @new_resource.run_action(:delete_key) }.to raise_error(Chef::Exceptions::Win32RegNoRecursive) end it "ignores the values under a key" do @@ -544,13 +542,13 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do it "does not throw an exception if the key has subkeys but recursive is set to false" do @new_resource.key(reg_parent + '\OpscodeWhyRun') - @new_resource.values([{:name=>"BriskWalk",:type=>:string,:data=>"is good for health"}]) + @new_resource.values([{ :name => "BriskWalk", :type => :string, :data => "is good for health" }]) @new_resource.recursive(false) @new_resource.run_action(:delete_key) end it "does nothing if the action is delete_key" do @new_resource.key(reg_parent + '\OpscodeWhyRun') - @new_resource.values([{:name=>"BriskWalk",:type=>:string,:data=>"is good for health"}]) + @new_resource.values([{ :name => "BriskWalk", :type => :string, :data => "is good for health" }]) @new_resource.recursive(false) @new_resource.run_action(:delete_key) diff --git a/spec/functional/resource/remote_directory_spec.rb b/spec/functional/resource/remote_directory_spec.rb index 8e01464e86..008622064c 100644 --- a/spec/functional/resource/remote_directory_spec.rb +++ b/spec/functional/resource/remote_directory_spec.rb @@ -73,7 +73,6 @@ describe Chef::Resource::RemoteDirectory do it_behaves_like "a securable resource with reporting" context "when creating the remote directory with purging disabled" do - context "and the directory does not yet exist" do before do resource.run_action(:create) @@ -123,7 +122,6 @@ describe Chef::Resource::RemoteDirectory do it "is not marked as updated by last action" do expect(resource_second_pass).not_to be_updated_by_last_action end - end describe "with overwrite disabled" do @@ -136,8 +134,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") { |f| f.puts "santa is real" } + File.open(modified_subdir_file, "a") { |f| f.puts "so is rudolph" } modified_file_checksum = sha256_checksum(modified_file) modified_subdir_file_checksum = sha256_checksum(modified_subdir_file) @@ -163,7 +161,6 @@ describe Chef::Resource::RemoteDirectory do expect(File).to exist(file_path) end end - end context "and there are extraneous files in the directory" do @@ -213,8 +210,6 @@ describe Chef::Resource::RemoteDirectory do it "is marked as updated by last action" do expect(resource).to be_updated_by_last_action end - end end - end diff --git a/spec/functional/resource/remote_file_spec.rb b/spec/functional/resource/remote_file_spec.rb index 876467d490..b1b4231003 100644 --- a/spec/functional/resource/remote_file_spec.rb +++ b/spec/functional/resource/remote_file_spec.rb @@ -92,11 +92,9 @@ describe Chef::Resource::RemoteFile do it_behaves_like "a securable resource with reporting" end - end context "when fetching files over HTTPS" do - before(:all) do cert_text = File.read(File.expand_path("ssl/chef-rspec.cert", CHEF_SPEC_DATA)) cert = OpenSSL::X509::Certificate.new(cert_text) @@ -120,7 +118,6 @@ describe Chef::Resource::RemoteFile do let(:expected_content) { binread(nyan_uncompressed_filename) } it_behaves_like "a file resource" - end context "when dealing with content length checking" do @@ -232,7 +229,7 @@ describe Chef::Resource::RemoteFile do end it "should not create the file" do - expect{ resource.run_action(:create) }.to raise_error + expect { resource.run_action(:create) }.to raise_error expect(File).not_to exist(path) end end diff --git a/spec/functional/resource/template_spec.rb b/spec/functional/resource/template_spec.rb index 6ce4a3cc3d..5857f05049 100644 --- a/spec/functional/resource/template_spec.rb +++ b/spec/functional/resource/template_spec.rb @@ -19,9 +19,8 @@ require "spec_helper" describe Chef::Resource::Template do - def binread(file) - File.open(file,"rb") {|f| f.read } + File.open(file, "rb") { |f| f.read } end include_context Chef::Resource::File @@ -73,7 +72,7 @@ describe Chef::Resource::Template do end it "creates the template with the rendered content using a local erb file when the :create action is run" do - resource.source(File.expand_path(File.join(CHEF_SPEC_DATA,"cookbooks","openldap","templates","default","openldap_stuff.conf.erb"))) + resource.source(File.expand_path(File.join(CHEF_SPEC_DATA, "cookbooks", "openldap", "templates", "default", "openldap_stuff.conf.erb"))) resource.cookbook(nil) resource.local(true) resource.run_action(:create) @@ -82,7 +81,6 @@ describe Chef::Resource::Template do end describe "when the template resource defines helper methods" do - include_context "diff disabled" let(:resource) do @@ -141,11 +139,9 @@ describe Chef::Resource::Template do end it_behaves_like "a template with helpers" - end context "using a module from a library" do - module ExampleModule def helper_method "value from helper method" @@ -157,10 +153,8 @@ describe Chef::Resource::Template do end it_behaves_like "a template with helpers" - end context "using a module from a library referencing @node" do - module ExampleModuleReferencingATNode def helper_method @node[:helper_test_attr] @@ -174,7 +168,6 @@ describe Chef::Resource::Template do end it_behaves_like "a template with helpers" - end context "using helpers with partial templates" do @@ -184,7 +177,6 @@ describe Chef::Resource::Template do end it_behaves_like "a template with helpers" - end end @@ -208,5 +200,4 @@ describe Chef::Resource::Template do end end end - end diff --git a/spec/functional/resource/user/dscl_spec.rb b/spec/functional/resource/user/dscl_spec.rb index 37f6047dfc..1eec89d10e 100644 --- a/spec/functional/resource/user/dscl_spec.rb +++ b/spec/functional/resource/user/dscl_spec.rb @@ -194,5 +194,4 @@ c5adbbac718b7eb99463a7b679571e0f\ end end end - end diff --git a/spec/functional/resource/user/useradd_spec.rb b/spec/functional/resource/user/useradd_spec.rb index ab16a1672f..add7792b10 100644 --- a/spec/functional/resource/user/useradd_spec.rb +++ b/spec/functional/resource/user/useradd_spec.rb @@ -31,23 +31,21 @@ def user_provider_for_platform end metadata = { :unix_only => true, - :requires_root => true, - :not_supported_on_mac_osx => true, - :provider => {:user => user_provider_for_platform}, + :requires_root => true, + :not_supported_on_mac_osx => true, + :provider => { :user => user_provider_for_platform }, } describe Chef::Provider::User::Useradd, metadata do - include Chef::Mixin::ShellOut - # Utility code for /etc/passwd interaction, avoid any caching of user records: PwEntry = Struct.new(:name, :passwd, :uid, :gid, :gecos, :home, :shell) class UserNotFound < StandardError; end def pw_entry - passwd_file = File.open("/etc/passwd", "rb") {|f| f.read} + passwd_file = File.open("/etc/passwd", "rb") { |f| f.read } matcher = /^#{Regexp.escape(username)}.+$/ if passwd_entry = passwd_file.scan(matcher).first PwEntry.new(*passwd_entry.split(":")) @@ -59,9 +57,9 @@ describe Chef::Provider::User::Useradd, metadata do def etc_shadow case ohai[:platform] when "aix" - File.open("/etc/security/passwd") {|f| f.read } + File.open("/etc/security/passwd") { |f| f.read } else - File.open("/etc/shadow") {|f| f.read } + File.open("/etc/shadow") { |f| f.read } end end @@ -104,7 +102,7 @@ describe Chef::Provider::User::Useradd, metadata do while max_retries > 0 begin pw_entry # will raise if the user doesn't exist - status = shell_out!("userdel", "-r", username, :returns => [0,8,12]) + status = shell_out!("userdel", "-r", username, :returns => [0, 8, 12]) # Error code 8 during userdel indicates that the user is logged in. # This occurs randomly because the accounts daemon holds a lock due to which userdel fails. @@ -160,21 +158,19 @@ describe Chef::Provider::User::Useradd, metadata do let(:expected_shadow) do if ohai[:platform] == "aix" - expected_shadow = "cf-test" # For aix just check user entry in shadow file + expected_shadow = "cf-test" # For aix just check user entry in shadow file else expected_shadow = "cf-test:$1$RRa/wMM/$XltKfoX5ffnexVF4dHZZf/" end end describe "action :create" do - context "when the user does not exist beforehand" do before do user_resource.run_action(:create) expect(user_resource).to be_updated_by_last_action end - it "ensures the user exists" do expect(pw_entry.name).to eq(username) end @@ -186,7 +182,6 @@ describe Chef::Provider::User::Useradd, metadata do # default algorithm for the definition of the user's home directory. context "and the username contains a single quote", skip: quote_in_username_unsupported? do - let(:username) { "t'bilisi" } it "ensures the user exists" do @@ -194,7 +189,6 @@ describe Chef::Provider::User::Useradd, metadata do end end - context "when uid is set" do # Should verify uid not in use... let(:uid) { 1999 } @@ -296,7 +290,7 @@ describe Chef::Provider::User::Useradd, metadata do # Ubuntu 13.04 system, these are commented out, so we'll look at # UID_MIN to find the lower limit of the non-system-user range, and # use that value in our assertions. - login_defs = File.open("/etc/login.defs", "rb") {|f| f.read } + login_defs = File.open("/etc/login.defs", "rb") { |f| f.read } uid_min_scan = /^UID_MIN\s+(\d+)/ login_defs.match(uid_min_scan)[1] end @@ -309,7 +303,6 @@ describe Chef::Provider::User::Useradd, metadata do end # when the user does not exist beforehand context "when the user already exists" do - let(:expect_updated?) { true } let(:existing_uid) { nil } @@ -455,12 +448,10 @@ describe Chef::Provider::User::Useradd, metadata do end end - it "ensures the password is set" do password_should_be_set expect(etc_shadow).to include(expected_shadow) end - end context "and the password is updated" do @@ -484,7 +475,6 @@ describe Chef::Provider::User::Useradd, metadata do end end - it "ensures the password is set to the desired value" do password_should_be_set expect(etc_shadow).to include(expected_shadow) @@ -510,7 +500,6 @@ describe Chef::Provider::User::Useradd, metadata do it "does not modify the user at all" do end end - end # when the user already exists end # action :create @@ -518,7 +507,7 @@ describe Chef::Provider::User::Useradd, metadata do let(:user_locked_context?) { false } def shadow_entry - etc_shadow.lines.select {|l| l.include?(username) }.first + etc_shadow.lines.select { |l| l.include?(username) }.first end def shadow_password @@ -578,7 +567,6 @@ describe Chef::Provider::User::Useradd, metadata do end context "when the user exists" do - include_context "user exists for lock/unlock" before do @@ -596,7 +584,6 @@ describe Chef::Provider::User::Useradd, metadata do end end - it "locks the user's password" do user_account_should_be_locked end @@ -629,7 +616,6 @@ describe Chef::Provider::User::Useradd, metadata do end context "when the user exists" do - include_context "user exists for lock/unlock" before do @@ -642,7 +628,6 @@ describe Chef::Provider::User::Useradd, metadata do end context "and has no password" do - # TODO: platform_family should be setup in spec_helper w/ tags if %w{suse opensuse}.include?(OHAI_SYSTEM["platform_family"]) # suse gets this right: @@ -701,5 +686,4 @@ describe Chef::Provider::User::Useradd, metadata do end end end # action :unlock - end diff --git a/spec/functional/resource/windows_package_spec.rb b/spec/functional/resource/windows_package_spec.rb index 02559bcd97..bc508dc526 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 { subject.version("8.0.56336") } it "removes specified version" do subject.run_action(:remove) @@ -127,7 +127,7 @@ describe Chef::Resource::WindowsPackage, :windows_only, :volatile do let(:pkg_name) { "Ultra Defragmenter" } let(:pkg_path) { "http://iweb.dl.sourceforge.net/project/ultradefrag/stable-release/6.1.1/ultradefrag-6.1.1.bin.amd64.exe" } let(:pkg_checksum) { "11d53ed4c426c8c867ad43f142b7904226ffd9938c02e37086913620d79e3c09" } - + it "finds the correct installer type" do subject.run_action(:install) expect(subject.provider_for_action(:install).installer_type).to eq(:nsis) @@ -164,5 +164,5 @@ describe Chef::Resource::WindowsPackage, :windows_only, :volatile do subject.run_action(:remove) expect(subject).to be_updated_by_last_action end - end -end \ No newline at end of file + end +end diff --git a/spec/functional/resource/windows_service_spec.rb b/spec/functional/resource/windows_service_spec.rb index 6e19998995..5554454ea9 100644 --- a/spec/functional/resource/windows_service_spec.rb +++ b/spec/functional/resource/windows_service_spec.rb @@ -23,9 +23,9 @@ describe Chef::Resource::WindowsService, :windows_only, :system_windows_service_ include_context "using Win32::Service" - let(:username) { "service_spec_user"} - let(:qualified_username) { "#{ENV['COMPUTERNAME']}\\#{username}"} - let(:password) { "1a2b3c4X!&narf"} + let(:username) { "service_spec_user" } + let(:qualified_username) { "#{ENV['COMPUTERNAME']}\\#{username}" } + let(:password) { "1a2b3c4X!&narf" } let(:user_resource) { r = Chef::Resource::User.new(username, run_context) @@ -40,17 +40,16 @@ describe Chef::Resource::WindowsService, :windows_only, :system_windows_service_ } let(:service_params) { - id = "#{$$}_#{rand(1000)}" test_service.merge( { - run_as_user: qualified_username, - run_as_password: password, - service_name: "spec_service_#{id}", - service_display_name: "windows_service spec #{id}}", - service_description: "Test service for running the windows_service functional spec.", - service_file_path: global_service_file_path, - }, ) + run_as_user: qualified_username, + run_as_password: password, + service_name: "spec_service_#{id}", + service_display_name: "windows_service spec #{id}}", + service_description: "Test service for running the windows_service functional spec.", + service_file_path: global_service_file_path, + }, ) } let(:manager) { diff --git a/spec/functional/run_lock_spec.rb b/spec/functional/run_lock_spec.rb index 8680816d13..3fa0856a2c 100644 --- a/spec/functional/run_lock_spec.rb +++ b/spec/functional/run_lock_spec.rb @@ -19,10 +19,8 @@ require File.expand_path("../../spec_helper", __FILE__) require "chef/client" describe Chef::RunLock do - # This behavior works on windows, but the tests use fork :( describe "when locking the chef-client run", :unix_only => true do - ## # Lockfile location and helpers @@ -31,15 +29,16 @@ describe Chef::RunLock do "/tmp/#{Kernel.rand(Time.now.to_i + Process.pid)}" end - let(:lockfile){ "#{random_temp_root}/this/long/path/does/not/exist/chef-client-running.pid" } + 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) { 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) } - def log_event(message, time=Time.now.strftime("%H:%M:%S.%L")) + def log_event(message, time = Time.now.strftime("%H:%M:%S.%L")) events << [ message, time ] end + def events @events ||= [] end @@ -289,7 +288,6 @@ describe Chef::RunLock do expect(run_lock.test).to eq(false) Process.waitpid2(p1) end - end # diff --git a/spec/functional/shell_spec.rb b/spec/functional/shell_spec.rb index a2c44bd949..4d397e3c6e 100644 --- a/spec/functional/shell_spec.rb +++ b/spec/functional/shell_spec.rb @@ -23,14 +23,13 @@ require "chef/shell" require "chef/mixin/command/unix" describe Shell do - # chef-shell's unit tests are by necessity very mock-heavy, and frequently do # not catch cases where chef-shell fails to boot because of changes in # chef/client.rb describe "smoke tests", :unix_only => true do include Chef::Mixin::Command::Unix - TIMEOUT=300 + TIMEOUT = 300 def read_until(io, expected_value) start = Time.new @@ -43,7 +42,7 @@ describe Shell do end if Time.new - start > TIMEOUT raise "did not read expected value `#{expected_value}' within #{TIMEOUT}s\n" + - "Buffer so far: `#{buffer}'" + "Buffer so far: `#{buffer}'" end end buffer diff --git a/spec/functional/tiny_server_spec.rb b/spec/functional/tiny_server_spec.rb index 9540234ba6..bec3ffaedb 100644 --- a/spec/functional/tiny_server_spec.rb +++ b/spec/functional/tiny_server_spec.rb @@ -26,7 +26,7 @@ describe TinyServer::API do end it "is a Singleton" do - expect {TinyServer::API.new}.to raise_error + expect { TinyServer::API.new }.to raise_error end it "clears the router" do @@ -39,28 +39,27 @@ describe TinyServer::API do @api.get("/foo/bar", 200, "hello foobar") # WEBrick gives you the full URI with host, Thin only gave the part after scheme+host+port response = @api.call("REQUEST_METHOD" => "GET", "REQUEST_URI" => "http://localhost:1974/foo/bar") - expect(response).to eq([200, {"Content-Type" => "application/json"}, [ "hello foobar" ]]) + expect(response).to eq([200, { "Content-Type" => "application/json" }, [ "hello foobar" ]]) end it "creates a route for a request with a block" do block_called = false @api.get("/bar/baz", 200) { block_called = true; "hello barbaz" } 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(response).to eq([200, { "Content-Type" => "application/json" }, [ "hello barbaz" ]]) expect(block_called).to be_truthy end it "returns debugging info for 404s" do response = @api.call("REQUEST_METHOD" => "GET", "REQUEST_URI" => "/no_such_thing") expect(response[0]).to eq(404) - expect(response[1]).to eq({"Content-Type" => "application/json"}) + expect(response[1]).to eq({ "Content-Type" => "application/json" }) expect(response[2]).to be_a_kind_of(Array) response_obj = Chef::JSONCompat.from_json(response[2].first) expect(response_obj["message"]).to eq("no data matches the request for /no_such_thing") - expect(response_obj["available_routes"]).to eq({"GET"=>[], "PUT"=>[], "POST"=>[], "DELETE"=>[]}) - expect(response_obj["request"]).to eq({"REQUEST_METHOD"=>"GET", "REQUEST_URI"=>"/no_such_thing"}) + expect(response_obj["available_routes"]).to eq({ "GET" => [], "PUT" => [], "POST" => [], "DELETE" => [] }) + expect(response_obj["request"]).to eq({ "REQUEST_METHOD" => "GET", "REQUEST_URI" => "/no_such_thing" }) end - end describe TinyServer::Manager do diff --git a/spec/functional/util/powershell/cmdlet_spec.rb b/spec/functional/util/powershell/cmdlet_spec.rb index 741d8a78d4..6ddbea2f42 100644 --- a/spec/functional/util/powershell/cmdlet_spec.rb +++ b/spec/functional/util/powershell/cmdlet_spec.rb @@ -19,18 +19,18 @@ require "chef/json_compat" require File.expand_path("../../../../spec_helper", __FILE__) -describe Chef::Util::Powershell::Cmdlet, :windows_powershell_dsc_only do +describe Chef::Util::Powershell::Cmdlet, :windows_powershell_dsc_only do before(:all) do @node = Chef::Node.new @node.consume_external_attrs(OHAI_SYSTEM.data, {}) end let(:cmd_output_format) { :text } - let(:simple_cmdlet) { Chef::Util::Powershell::Cmdlet.new(@node, "get-childitem", cmd_output_format, {:depth => 2}) } + let(:simple_cmdlet) { Chef::Util::Powershell::Cmdlet.new(@node, "get-childitem", cmd_output_format, { :depth => 2 }) } let(:invalid_cmdlet) { Chef::Util::Powershell::Cmdlet.new(@node, "get-idontexist", cmd_output_format) } - let(:cmdlet_get_item_requires_switch_or_argument) { Chef::Util::Powershell::Cmdlet.new(@node, "get-item", cmd_output_format, {:depth => 2}) } - let(:cmdlet_alias_requires_switch_or_argument) { Chef::Util::Powershell::Cmdlet.new(@node, "alias", cmd_output_format, {:depth => 2}) } + let(:cmdlet_get_item_requires_switch_or_argument) { Chef::Util::Powershell::Cmdlet.new(@node, "get-item", cmd_output_format, { :depth => 2 }) } + let(:cmdlet_alias_requires_switch_or_argument) { Chef::Util::Powershell::Cmdlet.new(@node, "alias", cmd_output_format, { :depth => 2 }) } let(:etc_directory) { "#{ENV['systemroot']}\\system32\\drivers\\etc" } - let(:architecture_cmdlet) { Chef::Util::Powershell::Cmdlet.new(@node, "$env:PROCESSOR_ARCHITECTURE")} + let(:architecture_cmdlet) { Chef::Util::Powershell::Cmdlet.new(@node, "$env:PROCESSOR_ARCHITECTURE") } it "executes a simple process" do result = simple_cmdlet.run @@ -38,11 +38,11 @@ describe Chef::Util::Powershell::Cmdlet, :windows_powershell_dsc_only do end it "#run does not raise a PowershellCmdletException exception if the command cannot be executed" do - expect {invalid_cmdlet.run}.not_to raise_error + expect { invalid_cmdlet.run }.not_to raise_error end it "#run! raises a PowershellCmdletException exception if the command cannot be executed" do - expect {invalid_cmdlet.run!}.to raise_error(Chef::Exceptions::PowershellCmdletException) + expect { invalid_cmdlet.run! }.to raise_error(Chef::Exceptions::PowershellCmdletException) end it "executes a 64-bit command on a 64-bit OS, 32-bit otherwise" do @@ -58,17 +58,17 @@ describe Chef::Util::Powershell::Cmdlet, :windows_powershell_dsc_only do end it "passes command line switches to the command" do - result = cmdlet_alias_requires_switch_or_argument.run({:name => "ls"}) + result = cmdlet_alias_requires_switch_or_argument.run({ :name => "ls" }) expect(result.succeeded?).to eq(true) end it "passes command line arguments to the command" do - result = cmdlet_alias_requires_switch_or_argument.run({},{},"ls") + result = cmdlet_alias_requires_switch_or_argument.run({}, {}, "ls") expect(result.succeeded?).to eq(true) end it "passes command line arguments and switches to the command" do - result = cmdlet_get_item_requires_switch_or_argument.run({:path => etc_directory},{}," | select-object -property fullname | format-table -hidetableheaders") + result = cmdlet_get_item_requires_switch_or_argument.run({ :path => etc_directory }, {}, " | select-object -property fullname | format-table -hidetableheaders") expect(result.succeeded?).to eq(true) returned_directory = result.return_value returned_directory.strip! @@ -76,7 +76,7 @@ describe Chef::Util::Powershell::Cmdlet, :windows_powershell_dsc_only do end it "passes execution options to the command" do - result = cmdlet_get_item_requires_switch_or_argument.run({},{:cwd => etc_directory},". | select-object -property fullname | format-table -hidetableheaders") + result = cmdlet_get_item_requires_switch_or_argument.run({}, { :cwd => etc_directory }, ". | select-object -property fullname | format-table -hidetableheaders") expect(result.succeeded?).to eq(true) returned_directory = result.return_value returned_directory.strip! @@ -86,16 +86,16 @@ describe Chef::Util::Powershell::Cmdlet, :windows_powershell_dsc_only do context "when returning json" do let(:cmd_output_format) { :json } it "returns json format data" do - result = cmdlet_alias_requires_switch_or_argument.run({},{},"ls") + result = cmdlet_alias_requires_switch_or_argument.run({}, {}, "ls") expect(result.succeeded?).to eq(true) - expect(lambda{Chef::JSONCompat.parse(result.return_value)}).not_to raise_error + expect(lambda { Chef::JSONCompat.parse(result.return_value) }).not_to raise_error end end context "when returning Ruby objects" do let(:cmd_output_format) { :object } it "returns object format data" do - result = simple_cmdlet.run({},{:cwd => etc_directory}, "hosts") + result = simple_cmdlet.run({}, { :cwd => etc_directory }, "hosts") expect(result.succeeded?).to eq(true) data = result.return_value expect(data["Name"]).to eq("hosts") @@ -105,7 +105,7 @@ describe Chef::Util::Powershell::Cmdlet, :windows_powershell_dsc_only do context "when constructor is given invalid arguments" do let(:cmd_output_format) { :invalid } it "throws an exception if an invalid format is passed to the constructor" do - expect(lambda{simple_cmdlet}).to raise_error + expect(lambda { simple_cmdlet }).to raise_error end end end diff --git a/spec/functional/version_spec.rb b/spec/functional/version_spec.rb index a45c25ff8c..26ecd2cc59 100644 --- a/spec/functional/version_spec.rb +++ b/spec/functional/version_spec.rb @@ -31,5 +31,4 @@ describe "Chef Versions" do expect(shell_out!("ruby #{File.join("bin", binary)} -v", :cwd => chef_dir).stdout.chomp).to include("Chef: #{Chef::VERSION}") end end - end diff --git a/spec/functional/win32/crypto_spec.rb b/spec/functional/win32/crypto_spec.rb index b12193ced0..75a8bfbd24 100644 --- a/spec/functional/win32/crypto_spec.rb +++ b/spec/functional/win32/crypto_spec.rb @@ -25,7 +25,7 @@ describe "Chef::ReservedNames::Win32::Crypto", :windows_only do describe '#encrypt' do before(:all) do new_node = Chef::Node.new - new_node.consume_external_attrs(OHAI_SYSTEM.data,{}) + new_node.consume_external_attrs(OHAI_SYSTEM.data, {}) events = Chef::EventDispatch::Dispatcher.new diff --git a/spec/functional/win32/registry_spec.rb b/spec/functional/win32/registry_spec.rb index 5818d7c7e5..9cb5b76d80 100644 --- a/spec/functional/win32/registry_spec.rb +++ b/spec/functional/win32/registry_spec.rb @@ -21,7 +21,6 @@ require "spec_helper" require "chef/win32/registry" describe "Chef::Win32::Registry", :windows_only do - before(:all) do #Create a registry item ::Win32::Registry::HKEY_CURRENT_USER.create "Software\\Root" @@ -41,7 +40,7 @@ describe "Chef::Win32::Registry", :windows_only do #Create the node with ohai data events = Chef::EventDispatch::Dispatcher.new @node = Chef::Node.new - @node.consume_external_attrs(OHAI_SYSTEM.data,{}) + @node.consume_external_attrs(OHAI_SYSTEM.data, {}) @run_context = Chef::RunContext.new(@node, {}, events) #Create a registry object that has access ot the node previously created @@ -81,7 +80,7 @@ describe "Chef::Win32::Registry", :windows_only do end it "throws an exception if the hive does not exist" do - expect {@registry.key_exists?("JKLM\\Software\\Branch\\Flower")}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect { @registry.key_exists?("JKLM\\Software\\Branch\\Flower") }.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end end @@ -91,95 +90,95 @@ describe "Chef::Win32::Registry", :windows_only do end it "throws an exception if the key path does not exist" do - expect {@registry.key_exists!("HKCU\\Software\\Branch\\Flower")}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { @registry.key_exists!("HKCU\\Software\\Branch\\Flower") }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "throws an exception if the hive does not exist" do - expect {@registry.key_exists!("JKLM\\Software\\Branch\\Flower")}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect { @registry.key_exists!("JKLM\\Software\\Branch\\Flower") }.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end end describe "value_exists?" do it "throws an exception if the hive does not exist" do - expect {@registry.value_exists?("JKLM\\Software\\Branch\\Flower", {:name=>"Petals"})}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect { @registry.value_exists?("JKLM\\Software\\Branch\\Flower", { :name => "Petals" }) }.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end it "throws an exception if the key does not exist" do - expect {@registry.value_exists?("HKCU\\Software\\Branch\\Flower", {:name=>"Petals"})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { @registry.value_exists?("HKCU\\Software\\Branch\\Flower", { :name => "Petals" }) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "returns true if the value exists" do - expect(@registry.value_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals"})).to eq(true) + expect(@registry.value_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Petals" })).to eq(true) end it "returns true if the value exists with a case mismatch on the value name" do - expect(@registry.value_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"petals"})).to eq(true) + expect(@registry.value_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "petals" })).to eq(true) end it "returns false if the value does not exist" do - expect(@registry.value_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"FOOBAR"})).to eq(false) + expect(@registry.value_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "FOOBAR" })).to eq(false) end end describe "value_exists!" do it "throws an exception if the hive does not exist" do - expect {@registry.value_exists!("JKLM\\Software\\Branch\\Flower", {:name=>"Petals"})}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect { @registry.value_exists!("JKLM\\Software\\Branch\\Flower", { :name => "Petals" }) }.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end it "throws an exception if the key does not exist" do - expect {@registry.value_exists!("HKCU\\Software\\Branch\\Flower", {:name=>"Petals"})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { @registry.value_exists!("HKCU\\Software\\Branch\\Flower", { :name => "Petals" }) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "returns true if the value exists" do - expect(@registry.value_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals"})).to eq(true) + expect(@registry.value_exists!("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Petals" })).to eq(true) end it "returns true if the value exists with a case mismatch on the value name" do - expect(@registry.value_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"petals"})).to eq(true) + expect(@registry.value_exists!("HKCU\\Software\\Root\\Branch\\Flower", { :name => "petals" })).to eq(true) end it "throws an exception if the value does not exist" do - expect {@registry.value_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"FOOBAR"})}.to raise_error(Chef::Exceptions::Win32RegValueMissing) + expect { @registry.value_exists!("HKCU\\Software\\Root\\Branch\\Flower", { :name => "FOOBAR" }) }.to raise_error(Chef::Exceptions::Win32RegValueMissing) end end describe "data_exists?" do it "throws an exception if the hive does not exist" do - expect {@registry.data_exists?("JKLM\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect { @registry.data_exists?("JKLM\\Software\\Branch\\Flower", { :name => "Petals", :type => :multi_string, :data => ["Pink", "Delicate"] }) }.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end it "throws an exception if the key does not exist" do - expect {@registry.data_exists?("HKCU\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { @registry.data_exists?("HKCU\\Software\\Branch\\Flower", { :name => "Petals", :type => :multi_string, :data => ["Pink", "Delicate"] }) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "returns true if all the data matches" do - expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Petals", :type => :multi_string, :data => ["Pink", "Delicate"] })).to eq(true) end it "returns true if all the data matches with a case mismatch on the data name" do - expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "petals", :type => :multi_string, :data => ["Pink", "Delicate"] })).to eq(true) end it "returns false if the name does not exist" do - expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"slateP", :type=>:multi_string, :data=>["Pink", "Delicate"]})).to eq(false) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "slateP", :type => :multi_string, :data => ["Pink", "Delicate"] })).to eq(false) end it "returns false if the types do not match" do - expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:string, :data=>"Pink"})).to eq(false) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Petals", :type => :string, :data => "Pink" })).to eq(false) end it "returns false if the data does not match" do - expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Mauve", "Delicate"]})).to eq(false) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Petals", :type => :multi_string, :data => ["Mauve", "Delicate"] })).to eq(false) end end describe "data_exists!" do it "throws an exception if the hive does not exist" do - expect {@registry.data_exists!("JKLM\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect { @registry.data_exists!("JKLM\\Software\\Branch\\Flower", { :name => "Petals", :type => :multi_string, :data => ["Pink", "Delicate"] }) }.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end it "throws an exception if the key does not exist" do - expect {@registry.data_exists!("HKCU\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { @registry.data_exists!("HKCU\\Software\\Branch\\Flower", { :name => "Petals", :type => :multi_string, :data => ["Pink", "Delicate"] }) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "returns true if all the data matches" do - expect(@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})).to eq(true) + expect(@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Petals", :type => :multi_string, :data => ["Pink", "Delicate"] })).to eq(true) end it "returns true if all the data matches with a case mismatch on the data name" do - expect(@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})).to eq(true) + expect(@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", { :name => "petals", :type => :multi_string, :data => ["Pink", "Delicate"] })).to eq(true) end it "throws an exception if the name does not exist" do - expect {@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"slateP", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.to raise_error(Chef::Exceptions::Win32RegDataMissing) + expect { @registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", { :name => "slateP", :type => :multi_string, :data => ["Pink", "Delicate"] }) }.to raise_error(Chef::Exceptions::Win32RegDataMissing) end it "throws an exception if the types do not match" do - expect {@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:string, :data=>"Pink"})}.to raise_error(Chef::Exceptions::Win32RegDataMissing) + expect { @registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Petals", :type => :string, :data => "Pink" }) }.to raise_error(Chef::Exceptions::Win32RegDataMissing) end it "throws an exception if the data does not match" do - expect {@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Mauve", "Delicate"]})}.to raise_error(Chef::Exceptions::Win32RegDataMissing) + expect { @registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Petals", :type => :multi_string, :data => ["Mauve", "Delicate"] }) }.to raise_error(Chef::Exceptions::Win32RegDataMissing) end end @@ -187,85 +186,85 @@ describe "Chef::Win32::Registry", :windows_only do it "returns all values for a key if it exists" do values = @registry.get_values("HKCU\\Software\\Root") expect(values).to be_an_instance_of Array - expect(values).to eq([{:name=>"RootType1", :type=>:string, :data=>"fibrous"}, - {:name=>"Roots", :type=>:multi_string, :data=>["strong roots", "healthy tree"]}]) + expect(values).to eq([{ :name => "RootType1", :type => :string, :data => "fibrous" }, + { :name => "Roots", :type => :multi_string, :data => ["strong roots", "healthy tree"] }]) end it "throws an exception if the key does not exist" do - expect {@registry.get_values("HKCU\\Software\\Branch\\Flower")}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { @registry.get_values("HKCU\\Software\\Branch\\Flower") }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "throws an exception if the hive does not exist" do - expect {@registry.get_values("JKLM\\Software\\Branch\\Flower")}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect { @registry.get_values("JKLM\\Software\\Branch\\Flower") }.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end end describe "set_value" do it "updates a value if the key, value exist and type matches and value different" do - expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})).to eq(true) - expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})).to eq(true) + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Petals", :type => :multi_string, :data => ["Yellow", "Changed Color"] })).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Petals", :type => :multi_string, :data => ["Yellow", "Changed Color"] })).to eq(true) end it "updates a value if the type does match and the values are different" do - expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:string, :data=>"Yellow"})).to eq(true) - expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:string, :data=>"Yellow"})).to eq(true) - expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})).to eq(false) + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Petals", :type => :string, :data => "Yellow" })).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Petals", :type => :string, :data => "Yellow" })).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Petals", :type => :multi_string, :data => ["Yellow", "Changed Color"] })).to eq(false) end it "creates a value if key exists and value does not" do - expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Stamen", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})).to eq(true) - expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Stamen", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})).to eq(true) + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Stamen", :type => :multi_string, :data => ["Yellow", "Changed Color"] })).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Stamen", :type => :multi_string, :data => ["Yellow", "Changed Color"] })).to eq(true) end it "does nothing if data,type and name parameters for the value are same" do - expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Stamen", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})).to eq(false) - expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Stamen", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})).to eq(true) + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Stamen", :type => :multi_string, :data => ["Yellow", "Changed Color"] })).to eq(false) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "Stamen", :type => :multi_string, :data => ["Yellow", "Changed Color"] })).to eq(true) end it "throws an exception if the key does not exist" do - expect {@registry.set_value("HKCU\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { @registry.set_value("HKCU\\Software\\Branch\\Flower", { :name => "Petals", :type => :multi_string, :data => ["Yellow", "Changed Color"] }) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "throws an exception if the hive does not exist" do - expect {@registry.set_value("JKLM\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect { @registry.set_value("JKLM\\Software\\Root\\Branch\\Flower", { :name => "Petals", :type => :multi_string, :data => ["Yellow", "Changed Color"] }) }.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end # we are validating that the data gets .to_i called on it when type is a :dword it "casts an integer string given as a dword into an integer" do - expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBe32767", :type=>:dword, :data=>"32767"})).to eq(true) - expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBe32767", :type=>:dword, :data=>32767})).to eq(true) + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", { :name => "ShouldBe32767", :type => :dword, :data => "32767" })).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "ShouldBe32767", :type => :dword, :data => 32767 })).to eq(true) end it "casts a nonsense string given as a dword into zero" do - expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBeZero", :type=>:dword, :data=>"whatdoesthisdo"})).to eq(true) - expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBeZero", :type=>:dword, :data=>0})).to eq(true) + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", { :name => "ShouldBeZero", :type => :dword, :data => "whatdoesthisdo" })).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "ShouldBeZero", :type => :dword, :data => 0 })).to eq(true) end it "throws an exception when trying to cast an array to an int for a dword" do - expect {@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldThrow", :type=>:dword, :data=>["one","two"]})}.to raise_error + expect { @registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", { :name => "ShouldThrow", :type => :dword, :data => ["one", "two"] }) }.to raise_error end # we are validating that the data gets .to_s called on it when type is a :string it "stores the string representation of an array into a string if you pass it an array" do - expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBePainful", :type=>:string, :data=>["one","two"]})).to eq(true) - expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBePainful", :type=>:string, :data=>'["one", "two"]'})).to eq(true) + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", { :name => "ShouldBePainful", :type => :string, :data => ["one", "two"] })).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "ShouldBePainful", :type => :string, :data => '["one", "two"]' })).to eq(true) end it "stores the string representation of a number into a string if you pass it an number" do - expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBe65535", :type=>:string, :data=>65535})).to eq(true) - expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBe65535", :type=>:string, :data=>"65535"})).to eq(true) + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", { :name => "ShouldBe65535", :type => :string, :data => 65535 })).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { :name => "ShouldBe65535", :type => :string, :data => "65535" })).to eq(true) end # we are validating that the data gets .to_a called on it when type is a :multi_string it "throws an exception when a multi-string is passed a number" do - expect {@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldThrow", :type=>:multi_string, :data=>65535})}.to raise_error + expect { @registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", { :name => "ShouldThrow", :type => :multi_string, :data => 65535 }) }.to raise_error end it "throws an exception when a multi-string is passed a string" do - expect {@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBeWat", :type=>:multi_string, :data=>"foo"})}.to raise_error + expect { @registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", { :name => "ShouldBeWat", :type => :multi_string, :data => "foo" }) }.to raise_error end end @@ -280,7 +279,7 @@ describe "Chef::Win32::Registry", :windows_only do end it "throws an exception if the path has missing keys but recursive set to false" do - expect {@registry.create_key("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", false)}.to raise_error(Chef::Exceptions::Win32RegNoRecursive) + expect { @registry.create_key("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", false) }.to raise_error(Chef::Exceptions::Win32RegNoRecursive) expect(@registry.key_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker")).to eq(false) end @@ -295,7 +294,7 @@ describe "Chef::Win32::Registry", :windows_only do end it "throws an exception of the hive does not exist" do - expect {@registry.create_key("JKLM\\Software\\Root\\Trunk\\Peck\\Woodpecker", false)}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect { @registry.create_key("JKLM\\Software\\Root\\Trunk\\Peck\\Woodpecker", false) }.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end end @@ -308,21 +307,21 @@ describe "Chef::Win32::Registry", :windows_only do end it "deletes values if the value exists" do - expect(@registry.delete_value("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"})).to eq(true) - expect(@registry.value_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"})).to eq(false) + expect(@registry.delete_value("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", { :name => "Peter", :type => :string, :data => "Tiny" })).to eq(true) + expect(@registry.value_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", { :name => "Peter", :type => :string, :data => "Tiny" })).to eq(false) end it "does nothing if value does not exist" do - expect(@registry.delete_value("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"})).to eq(true) - expect(@registry.value_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"})).to eq(false) + expect(@registry.delete_value("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", { :name => "Peter", :type => :string, :data => "Tiny" })).to eq(true) + expect(@registry.value_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", { :name => "Peter", :type => :string, :data => "Tiny" })).to eq(false) end it "throws an exception if the key does not exist?" do - expect {@registry.delete_value("HKCU\\Software\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { @registry.delete_value("HKCU\\Software\\Trunk\\Peck\\Woodpecker", { :name => "Peter", :type => :string, :data => "Tiny" }) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "throws an exception if the hive does not exist" do - expect {@registry.delete_value("JKLM\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"})}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect { @registry.delete_value("JKLM\\Software\\Root\\Trunk\\Peck\\Woodpecker", { :name => "Peter", :type => :string, :data => "Tiny" }) }.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end end @@ -359,7 +358,7 @@ describe "Chef::Win32::Registry", :windows_only do end it "throws an exception if the hive does not exist" do - expect {@registry.delete_key("JKLM\\Software\\Root\\Branch\\Flower", false)}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect { @registry.delete_key("JKLM\\Software\\Root\\Branch\\Flower", false) }.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end end @@ -375,11 +374,11 @@ describe "Chef::Win32::Registry", :windows_only do end it "throws an exception if the hive was missing" do - expect {@registry.has_subkeys?("LMNO\\Software\\Root")}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect { @registry.has_subkeys?("LMNO\\Software\\Root") }.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end it "throws an exception if the key is missing" do - expect {@registry.has_subkeys?("HKCU\\Software\\Root\\Trunk\\Red")}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { @registry.has_subkeys?("HKCU\\Software\\Root\\Trunk\\Red") }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "returns true if the key has subkeys" do @@ -394,16 +393,16 @@ describe "Chef::Win32::Registry", :windows_only do describe "get_subkeys" do it "throws an exception if the key is missing" do - expect {@registry.get_subkeys("HKCU\\Software\\Trunk\\Red")}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { @registry.get_subkeys("HKCU\\Software\\Trunk\\Red") }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "throws an exception if the hive does not exist" do - expect {@registry.get_subkeys("JKLM\\Software\\Root")}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect { @registry.get_subkeys("JKLM\\Software\\Root") }.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end it "returns the array of subkeys for a given key" do subkeys = @registry.get_subkeys("HKCU\\Software\\Root") reg_subkeys = [] ::Win32::Registry::HKEY_CURRENT_USER.open("Software\\Root", Win32::Registry::KEY_ALL_ACCESS) do |reg| - reg.each_key{|name| reg_subkeys << name} + reg.each_key { |name| reg_subkeys << name } end expect(reg_subkeys).to eq(subkeys) end @@ -422,7 +421,7 @@ describe "Chef::Win32::Registry", :windows_only do context "registry constructor" do it "throws an exception if requested architecture is 64bit but running on 32bit" do - expect {Chef::Win32::Registry.new(@run_context, :x86_64)}.to raise_error(Chef::Exceptions::Win32RegArchitectureIncorrect) + expect { Chef::Win32::Registry.new(@run_context, :x86_64) }.to raise_error(Chef::Exceptions::Win32RegArchitectureIncorrect) end it "can correctly set the requested architecture to 32-bit" do @@ -440,7 +439,7 @@ describe "Chef::Win32::Registry", :windows_only do context "architecture setter" do it "throws an exception if requested architecture is 64bit but running on 32bit" do - expect {@registry.architecture = :x86_64}.to raise_error(Chef::Exceptions::Win32RegArchitectureIncorrect) + expect { @registry.architecture = :x86_64 }.to raise_error(Chef::Exceptions::Win32RegArchitectureIncorrect) end it "sets the requested architecture to :machine if passed :machine" do @@ -545,58 +544,58 @@ describe "Chef::Win32::Registry", :windows_only do describe "key_exists?" do it "does not find 64-bit keys in the 32-bit registry" do - @registry.architecture=:i386 + @registry.architecture = :i386 expect(@registry.key_exists?("HKLM\\Software\\Root\\Mauve")).to eq(false) end it "finds 32-bit keys in the 32-bit registry" do - @registry.architecture=:i386 + @registry.architecture = :i386 expect(@registry.key_exists?("HKLM\\Software\\Root\\Poosh")).to eq(true) end it "does not find 32-bit keys in the 64-bit registry" do - @registry.architecture=:x86_64 + @registry.architecture = :x86_64 expect(@registry.key_exists?("HKLM\\Software\\Root\\Mauve")).to eq(true) end it "finds 64-bit keys in the 64-bit registry" do - @registry.architecture=:x86_64 + @registry.architecture = :x86_64 expect(@registry.key_exists?("HKLM\\Software\\Root\\Poosh")).to eq(false) end end describe "value_exists?" do it "does not find 64-bit values in the 32-bit registry" do - @registry.architecture=:i386 - expect{@registry.value_exists?("HKLM\\Software\\Root\\Mauve", {:name=>"Alert"})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + @registry.architecture = :i386 + expect { @registry.value_exists?("HKLM\\Software\\Root\\Mauve", { :name => "Alert" }) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "finds 32-bit values in the 32-bit registry" do - @registry.architecture=:i386 - expect(@registry.value_exists?("HKLM\\Software\\Root\\Poosh", {:name=>"Status"})).to eq(true) + @registry.architecture = :i386 + expect(@registry.value_exists?("HKLM\\Software\\Root\\Poosh", { :name => "Status" })).to eq(true) end it "does not find 32-bit values in the 64-bit registry" do - @registry.architecture=:x86_64 - expect(@registry.value_exists?("HKLM\\Software\\Root\\Mauve", {:name=>"Alert"})).to eq(true) + @registry.architecture = :x86_64 + expect(@registry.value_exists?("HKLM\\Software\\Root\\Mauve", { :name => "Alert" })).to eq(true) end it "finds 64-bit values in the 64-bit registry" do - @registry.architecture=:x86_64 - expect{@registry.value_exists?("HKLM\\Software\\Root\\Poosh", {:name=>"Status"})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + @registry.architecture = :x86_64 + expect { @registry.value_exists?("HKLM\\Software\\Root\\Poosh", { :name => "Status" }) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end end describe "data_exists?" do it "does not find 64-bit keys in the 32-bit registry" do - @registry.architecture=:i386 - expect{@registry.data_exists?("HKLM\\Software\\Root\\Mauve", {:name=>"Alert", :type=>:string, :data=>"Universal"})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + @registry.architecture = :i386 + expect { @registry.data_exists?("HKLM\\Software\\Root\\Mauve", { :name => "Alert", :type => :string, :data => "Universal" }) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "finds 32-bit keys in the 32-bit registry" do - @registry.architecture=:i386 - expect(@registry.data_exists?("HKLM\\Software\\Root\\Poosh", {:name=>"Status", :type=>:string, :data=>"Lost"})).to eq(true) + @registry.architecture = :i386 + expect(@registry.data_exists?("HKLM\\Software\\Root\\Poosh", { :name => "Status", :type => :string, :data => "Lost" })).to eq(true) end it "does not find 32-bit keys in the 64-bit registry" do - @registry.architecture=:x86_64 - expect(@registry.data_exists?("HKLM\\Software\\Root\\Mauve", {:name=>"Alert", :type=>:string, :data=>"Universal"})).to eq(true) + @registry.architecture = :x86_64 + expect(@registry.data_exists?("HKLM\\Software\\Root\\Mauve", { :name => "Alert", :type => :string, :data => "Universal" })).to eq(true) end it "finds 64-bit keys in the 64-bit registry" do - @registry.architecture=:x86_64 - expect{@registry.data_exists?("HKLM\\Software\\Root\\Poosh", {:name=>"Status", :type=>:string, :data=>"Lost"})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + @registry.architecture = :x86_64 + expect { @registry.data_exists?("HKLM\\Software\\Root\\Poosh", { :name => "Status", :type => :string, :data => "Lost" }) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end end @@ -617,7 +616,6 @@ describe "Chef::Win32::Registry", :windows_only do expect(@registry.key_exists?("HKLM\\Software\\Root\\Trunk\\Blue")).to eq(false) end end - end end end diff --git a/spec/functional/win32/security_spec.rb b/spec/functional/win32/security_spec.rb index abf6b42e10..c4951f375c 100644 --- a/spec/functional/win32/security_spec.rb +++ b/spec/functional/win32/security_spec.rb @@ -70,7 +70,7 @@ describe "Chef::Win32::Security", :windows_only do let(:desired_access) { Chef::ReservedNames::Win32::Security::FILE_GENERIC_READ } it "should check if the provided token has the desired access" do - expect(Chef::ReservedNames::Win32::Security.access_check(security_descriptor, + expect(Chef::ReservedNames::Win32::Security.access_check(security_descriptor, token, desired_access, mapping)).to be true end end @@ -85,7 +85,7 @@ describe "Chef::Win32::Security", :windows_only do let(:token_rights) { Chef::ReservedNames::Win32::Security::TOKEN_ALL_ACCESS } it "can duplicate a token" do - expect{ token.duplicate_token(:SecurityImpersonation) }.not_to raise_error + expect { token.duplicate_token(:SecurityImpersonation) }.not_to raise_error end end @@ -93,7 +93,7 @@ describe "Chef::Win32::Security", :windows_only do let(:token_rights) { Chef::ReservedNames::Win32::Security::TOKEN_READ } it "raises an exception when trying to duplicate" do - expect{ token.duplicate_token(:SecurityImpersonation) }.to raise_error(Chef::Exceptions::Win32APIError) + expect { token.duplicate_token(:SecurityImpersonation) }.to raise_error(Chef::Exceptions::Win32APIError) end end end diff --git a/spec/functional/win32/service_manager_spec.rb b/spec/functional/win32/service_manager_spec.rb index b2bf04ed0c..b9af05a5f1 100644 --- a/spec/functional/win32/service_manager_spec.rb +++ b/spec/functional/win32/service_manager_spec.rb @@ -34,7 +34,6 @@ end # describe "Chef::Application::WindowsServiceManager", :windows_only, :system_windows_service_gem_only, :appveyor_only do - include_context "using Win32::Service" context "with invalid service definition" do @@ -101,8 +100,8 @@ describe "Chef::Application::WindowsServiceManager", :windows_only, :system_wind end it "install => should say service already exists" do - service_manager.run(["-a", "install"]) - expect(@service_manager_output.grep(/already exists/).length).to be > 0 + service_manager.run(["-a", "install"]) + expect(@service_manager_output.grep(/already exists/).length).to be > 0 end context "and service is stopped" do @@ -133,7 +132,6 @@ describe "Chef::Application::WindowsServiceManager", :windows_only, :system_wind expect(test_service_state).to eq("stopped") end - ["pause", "resume"].each do |action| it "#{action} => should raise error" do expect { service_manager.run(["-a", action]) }.to raise_error(SystemCallError) @@ -211,9 +209,8 @@ describe "Chef::Application::WindowsServiceManager", :windows_only, :system_wind end it "start should raise an error" do - expect {service_manager.run(["-a", "start"])}.to raise_error(::Win32::Service::Error) + expect { service_manager.run(["-a", "start"]) }.to raise_error(::Win32::Service::Error) end - end end end diff --git a/spec/functional/win32/versions_spec.rb b/spec/functional/win32/versions_spec.rb index 345df303a4..e0d679cf39 100644 --- a/spec/functional/win32/versions_spec.rb +++ b/spec/functional/win32/versions_spec.rb @@ -23,7 +23,6 @@ end describe "Chef::ReservedNames::Win32::Version", :windows_only, :not_supported_on_win2k3 do before do - wmi = WmiLite::Wmi.new host = wmi.first_of("Win32_OperatingSystem") @@ -52,7 +51,7 @@ describe "Chef::ReservedNames::Win32::Version", :windows_only, :not_supported_on def for_each_windows_version(&block) @version.methods.each do |method_name| - if Chef::ReservedNames::Win32::Version::WIN_VERSIONS.keys.find { | key | method_name.to_s == Chef::ReservedNames::Win32::Version.send(:method_name_from_marketing_name,key) } + if Chef::ReservedNames::Win32::Version::WIN_VERSIONS.keys.find { |key| method_name.to_s == Chef::ReservedNames::Win32::Version.send(:method_name_from_marketing_name, key) } yield method_name end end diff --git a/spec/integration/client/client_spec.rb b/spec/integration/client/client_spec.rb index 24ce69ac03..9609731162 100644 --- a/spec/integration/client/client_spec.rb +++ b/spec/integration/client/client_spec.rb @@ -3,17 +3,15 @@ require "chef/mixin/shell_out" require "tiny_server" require "tmpdir" - describe "chef-client" do - def recipes_filename File.join(CHEF_SPEC_DATA, "recipes.tgz") end - def start_tiny_server(server_opts={}) + def start_tiny_server(server_opts = {}) @server = TinyServer::Manager.new(server_opts) @server.start - @api = TinyServer::API.instance + @api = TinyServer::API.instance @api.clear # # trivial endpoints @@ -48,7 +46,7 @@ describe "chef-client" do # cf. CHEF-4914 let(:chef_client) { "ruby '#{chef_dir}/chef-client' --minimal-ohai" } - let(:critical_env_vars) { %w{PATH RUBYOPT BUNDLE_GEMFILE GEM_PATH}.map {|o| "#{o}=#{ENV[o]}"} .join(" ") } + let(:critical_env_vars) { %w{PATH RUBYOPT BUNDLE_GEMFILE GEM_PATH}.map { |o| "#{o}=#{ENV[o]}" } .join(" ") } when_the_repository "has a cookbook with a no-op recipe" do before { file "cookbooks/x/recipes/default.rb", "" } @@ -119,7 +117,6 @@ EOM # FATAL: Configuration error NoMethodError: undefined method `xxx' for nil:NilClass expect(result.stdout).to include("xxx") end - end it "should complete with success" do @@ -244,7 +241,6 @@ EOM expect(IO.read(path_to("tempfile.txt"))).to eq("1") end - end it "should complete with success when passed the -z flag" do @@ -435,7 +431,6 @@ EOM end when_the_repository "has a cookbook with only an audit recipe" do - before do file "config/client.rb", < "::1"} } + let(:chef_zero_opts) { { :host => "::1" } } let(:validation_pem) do <<-END_VALIDATION_PEM @@ -73,7 +73,6 @@ END_CLIENT_RB basic_config_file end - let(:chef_dir) { File.join(File.dirname(__FILE__), "..", "..", "..", "bin") } let(:chef_client_cmd) { %Q{ruby '#{chef_dir}/chef-client' --minimal-ohai -c "#{path_to('config/client.rb')}" -lwarn} } @@ -85,10 +84,9 @@ END_CLIENT_RB # Some Solaris test platforms are too old for IPv6. These tests should not # otherwise be platform dependent, so exclude solaris when_the_chef_server "is running on IPv6", :not_supported_on_solaris, :not_supported_on_gce do - when_the_repository "has a cookbook with a no-op recipe" do before do - cookbook "noop", "1.0.0", { }, "recipes" => {"default.rb" => "#raise 'foo'"} + cookbook "noop", "1.0.0", {}, "recipes" => { "default.rb" => "#raise 'foo'" } file "config/client.rb", client_rb_content file "config/validator.pem", validation_pem end @@ -97,13 +95,11 @@ END_CLIENT_RB result = shell_out("#{chef_client_cmd} -o 'noop::default'", :cwd => chef_dir) result.error! end - end when_the_repository "has a cookbook that hits server APIs" do - before do - recipe=<<-END_RECIPE + recipe = <<-END_RECIPE actual_item = data_bag_item("expect_bag", "expect_item") if actual_item.key?("expect_key") and actual_item["expect_key"] == "expect_value" Chef::Log.info "lookin good" @@ -115,9 +111,9 @@ END_CLIENT_RB END_RECIPE - data_bag("expect_bag", { "expect_item" => {"expect_key" => "expect_value"} }) + data_bag("expect_bag", { "expect_item" => { "expect_key" => "expect_value" } }) - cookbook "api-smoke-test", "1.0.0", { }, "recipes" => {"default.rb" => recipe} + cookbook "api-smoke-test", "1.0.0", {}, "recipes" => { "default.rb" => recipe } end before do @@ -129,7 +125,6 @@ END_CLIENT_RB result = shell_out("#{chef_client_cmd} -o 'api-smoke-test::default'", :cwd => chef_dir) result.error! end - end end end diff --git a/spec/integration/knife/chef_fs_data_store_spec.rb b/spec/integration/knife/chef_fs_data_store_spec.rb index e9a2ea4824..df7e2b78fd 100644 --- a/spec/integration/knife/chef_fs_data_store_spec.rb +++ b/spec/integration/knife/chef_fs_data_store_spec.rb @@ -146,7 +146,6 @@ EOM knife("delete -z /roles/x.json").should_succeed "Deleted /roles/x.json\n" knife("list -z -Rfp /roles").should_succeed "" end - end context "GET /TYPE/NAME" do @@ -173,13 +172,12 @@ EOM it "knife show -z /roles/x.json works" do knife("show -z /roles/x.json").should_succeed( /"x"/ ) end - end context "PUT /TYPE/NAME" do before do file "empty.json", {} - file "dummynode.json", { "name" => "x", "chef_environment" => "rspec" , "json_class" => "Chef::Node", "normal" => {"foo" => "bar"}} + file "dummynode.json", { "name" => "x", "chef_environment" => "rspec" , "json_class" => "Chef::Node", "normal" => { "foo" => "bar" } } file "rolestuff.json", '{"description":"hi there","name":"x"}' file "cookbooks_to_upload/x/metadata.rb", cookbook_x_100_metadata_rb end @@ -234,7 +232,7 @@ EOM context "POST /TYPE/NAME" do before do file "empty.json", { "name" => "z" } - file "dummynode.json", { "name" => "z", "chef_environment" => "rspec" , "json_class" => "Chef::Node", "normal" => {"foo" => "bar"}} + file "dummynode.json", { "name" => "z", "chef_environment" => "rspec" , "json_class" => "Chef::Node", "normal" => { "foo" => "bar" } } file "empty_x.json", { "name" => "x" } file "empty_id.json", { "id" => "z" } file "rolestuff.json", '{"description":"hi there","name":"x"}' @@ -352,7 +350,6 @@ EOM it "knife delete -z /roles/x.json fails with an error" do knife("delete -z /roles/x.json").should_fail "ERROR: /roles/x.json: No such file or directory\n" end - end context "GET /TYPE/NAME" do @@ -379,7 +376,6 @@ EOM it "knife show -z /roles/x.json fails with an error" do knife("show -z /roles/x.json").should_fail "ERROR: /roles/x.json: No such file or directory\n" end - end context "PUT /TYPE/NAME" do @@ -406,7 +402,6 @@ EOM it "knife raw -z -i empty.json -m PUT /roles/x fails with 404" do knife("raw -z -i #{path_to('empty.json')} -m PUT /roles/x").should_fail( /404/ ) end - end end end @@ -479,7 +474,7 @@ EOM context "PUT /TYPE/NAME" do before do file "empty.json", {} - file "dummynode.json", { "name" => "x", "chef_environment" => "rspec" , "json_class" => "Chef::Node", "normal" => {"foo" => "bar"}} + file "dummynode.json", { "name" => "x", "chef_environment" => "rspec" , "json_class" => "Chef::Node", "normal" => { "foo" => "bar" } } file "rolestuff.json", '{"description":"hi there","name":"x"}' file "cookbooks_to_upload/x/metadata.rb", cookbook_x_100_metadata_rb end @@ -505,7 +500,7 @@ EOM context "POST /TYPE/NAME" do before do file "empty.json", { "name" => "z" } - file "dummynode.json", { "name" => "z", "chef_environment" => "rspec" , "json_class" => "Chef::Node", "normal" => {"foo" => "bar"}} + file "dummynode.json", { "name" => "z", "chef_environment" => "rspec" , "json_class" => "Chef::Node", "normal" => { "foo" => "bar" } } file "empty_x.json", { "name" => "x" } file "empty_id.json", { "id" => "z" } file "rolestuff.json", '{"description":"hi there","name":"x"}' diff --git a/spec/integration/knife/cookbook_api_ipv6_spec.rb b/spec/integration/knife/cookbook_api_ipv6_spec.rb index 3126c93a1c..ed6a92c73c 100644 --- a/spec/integration/knife/cookbook_api_ipv6_spec.rb +++ b/spec/integration/knife/cookbook_api_ipv6_spec.rb @@ -23,7 +23,7 @@ describe "Knife cookbook API integration with IPv6", :workstation, :not_supporte include Chef::Mixin::ShellOut when_the_chef_server "is bound to IPv6" do - let(:chef_zero_opts) { {:host => "::1"} } + let(:chef_zero_opts) { { :host => "::1" } } let(:client_key) do <<-END_VALIDATION_PEM @@ -69,10 +69,8 @@ END_VALIDATION_PEM # Some Solaris test platforms are too old for IPv6. These tests should not # otherwise be platform dependent, so exclude solaris context "and the chef_server_url contains an IPv6 literal", :not_supported_on_solaris do - # This provides helper functions we need such as #path_to() when_the_repository "has the cookbook to be uploaded" do - let(:knife_rb_content) do <<-END_CLIENT_RB chef_server_url "http://[::1]:8900" @@ -102,10 +100,9 @@ END_CLIENT_RB it "downloads the cookbook" do shell_out!("knife cookbook download apache2 #{knife_config_flag} -d #{cache_path}", :cwd => chef_dir) - expect(Dir["#{cache_path}/*"].map {|entry| File.basename(entry)}).to include("apache2-0.0.1") + expect(Dir["#{cache_path}/*"].map { |entry| File.basename(entry) }).to include("apache2-0.0.1") end end - end end end diff --git a/spec/integration/knife/delete_spec.rb b/spec/integration/knife/delete_spec.rb index 9f2accdbfa..d8cb8d950f 100644 --- a/spec/integration/knife/delete_spec.rb +++ b/spec/integration/knife/delete_spec.rb @@ -916,7 +916,7 @@ EOM when_the_chef_server "has an earlier version for the cookbook" do before do - cookbook "x", "1.0.0", { "onlyin1.0.0.rb" => ""} + cookbook "x", "1.0.0", { "onlyin1.0.0.rb" => "" } cookbook "x", "0.9.9", { "onlyin0.9.9.rb" => "hi" } end diff --git a/spec/integration/knife/diff_spec.rb b/spec/integration/knife/diff_spec.rb index 3cc2518915..d88163b12b 100644 --- a/spec/integration/knife/diff_spec.rb +++ b/spec/integration/knife/diff_spec.rb @@ -63,7 +63,6 @@ EOM end when_the_repository "has an identical copy of each thing" do - before do file "clients/chef-validator.json", { "validator" => true, "public_key" => ChefZero::PUBLIC_KEY } file "clients/chef-webui.json", { "admin" => true, "public_key" => ChefZero::PUBLIC_KEY } @@ -174,7 +173,7 @@ EOM when_the_chef_server "has a later version for the cookbook" do before do - cookbook "x", "1.0.0", { "onlyin1.0.0.rb" => ""} + cookbook "x", "1.0.0", { "onlyin1.0.0.rb" => "" } cookbook "x", "1.0.1", { "onlyin1.0.1.rb" => "" } end @@ -470,7 +469,7 @@ EOM when_the_chef_server "has a later version for the cookbook" do before do - cookbook "x", "1.0.0", { "onlyin1.0.0.rb" => ""} + cookbook "x", "1.0.0", { "onlyin1.0.0.rb" => "" } cookbook "x", "1.0.1", { "onlyin1.0.1.rb" => "" } end diff --git a/spec/integration/knife/download_spec.rb b/spec/integration/knife/download_spec.rb index ec322ca01c..d2bd820b60 100644 --- a/spec/integration/knife/download_spec.rb +++ b/spec/integration/knife/download_spec.rb @@ -25,7 +25,6 @@ describe "knife download", :workstation do context "without versioned cookbooks" do when_the_chef_server "has one of each thing" do - before do client "x", {} cookbook "x", "1.0.0" @@ -489,7 +488,7 @@ EOM when_the_chef_server "has an earlier version for the cookbook" do before do - cookbook "x", "1.0.0", { "onlyin1.0.0.rb" => ""} + cookbook "x", "1.0.0", { "onlyin1.0.0.rb" => "" } cookbook "x", "0.9.9", { "onlyin0.9.9.rb" => "hi" } end @@ -986,7 +985,7 @@ EOM when_the_chef_server "has an earlier version for the cookbook" do before do - cookbook "x", "1.0.0", { "onlyin1.0.0.rb" => ""} + cookbook "x", "1.0.0", { "onlyin1.0.0.rb" => "" } cookbook "x", "0.9.9", { "onlyin0.9.9.rb" => "hi" } end @@ -1070,7 +1069,6 @@ EOM when_the_repository "is empty" do it "knife download /cookbooks/x signs all requests" do - # Check that BasicClient.request() always gets called with X-OPS-USERID original_new = Chef::HTTP::BasicClient.method(:new) expect(Chef::HTTP::BasicClient).to receive(:new) { |args| @@ -1254,8 +1252,8 @@ EOM file "members.json", [ "bar" ] file "nodes/x.json", {} file "org.json", { "full_name" => "Something" } - file "policies/x-1.0.0.json", { } - file "policies/blah-1.0.0.json", { } + file "policies/x-1.0.0.json", {} + file "policies/blah-1.0.0.json", {} file "policy_groups/x.json", { "policies" => { "x" => { "revision_id" => "1.0.0" }, "blah" => { "revision_id" => "1.0.0" } } } file "roles/x.json", {} end diff --git a/spec/integration/knife/raw_spec.rb b/spec/integration/knife/raw_spec.rb index 8d3499617c..9078bf09a1 100644 --- a/spec/integration/knife/raw_spec.rb +++ b/spec/integration/knife/raw_spec.rb @@ -186,7 +186,7 @@ EOM before :each do Chef::Config.chef_server_url = "http://localhost:9018" app = lambda do |env| - [200, {"Content-Type" => "application/json" }, ['{ "x": "y", "a": "b" }'] ] + [200, { "Content-Type" => "application/json" }, ['{ "x": "y", "a": "b" }'] ] end @raw_server, @raw_server_thread = start_app_server(app, 9018) end @@ -216,7 +216,7 @@ EOM before :each do Chef::Config.chef_server_url = "http://localhost:9018" app = lambda do |env| - [200, {"Content-Type" => "text" }, ['{ "x": "y", "a": "b" }'] ] + [200, { "Content-Type" => "text" }, ['{ "x": "y", "a": "b" }'] ] end @raw_server, @raw_server_thread = start_app_server(app, 9018) end diff --git a/spec/integration/knife/redirection_spec.rb b/spec/integration/knife/redirection_spec.rb index 9febfc0ce5..29c1ee6ffb 100644 --- a/spec/integration/knife/redirection_spec.rb +++ b/spec/integration/knife/redirection_spec.rb @@ -34,7 +34,7 @@ describe "redirection", :workstation do real_chef_server_url = Chef::Config.chef_server_url Chef::Config.chef_server_url = "http://localhost:9018" app = lambda do |env| - [302, {"Content-Type" => "text","Location" => "#{real_chef_server_url}#{env['PATH_INFO']}" }, ["302 found"] ] + [302, { "Content-Type" => "text", "Location" => "#{real_chef_server_url}#{env['PATH_INFO']}" }, ["302 found"] ] end @redirector_server, @redirector_server_thread = start_app_server(app, 9018) end diff --git a/spec/integration/knife/show_spec.rb b/spec/integration/knife/show_spec.rb index a1de48e121..ed4802fef9 100644 --- a/spec/integration/knife/show_spec.rb +++ b/spec/integration/knife/show_spec.rb @@ -129,7 +129,7 @@ EOM before do environment "x", { "default_attributes" => { "foo" => "bar" }, - "cookbook_versions" => { "blah" => "= 1.0.0"}, + "cookbook_versions" => { "blah" => "= 1.0.0" }, "override_attributes" => { "x" => "y" }, "description" => "woo", "name" => "x", diff --git a/spec/integration/knife/upload_spec.rb b/spec/integration/knife/upload_spec.rb index 2ecbd4e64a..882101130f 100644 --- a/spec/integration/knife/upload_spec.rb +++ b/spec/integration/knife/upload_spec.rb @@ -26,9 +26,7 @@ describe "knife upload", :workstation do include KnifeSupport context "without versioned cookbooks" do - when_the_chef_server "has one of each thing" do - before do client "x", {} cookbook "x", "1.0.0" @@ -80,14 +78,13 @@ Deleted extra entry /roles/x.json (purge is on) Deleted extra entry /users/admin.json (purge is on) Deleted extra entry /users/x.json (purge is on) EOM - knife("diff --name-status /").should_succeed < true, "public_key" => ChefZero::PUBLIC_KEY } file "clients/chef-webui.json", { "admin" => true, "public_key" => ChefZero::PUBLIC_KEY } @@ -268,7 +265,6 @@ EOM when_the_chef_server "is empty" do when_the_repository "has a data bag item" do - before do file "data_bags/x/y.json", { "foo" => "bar" } end @@ -292,7 +288,6 @@ EOM end when_the_repository "has a data bag item with keys chef_type and data_bag" do - before do file "data_bags/x/y.json", { "chef_type" => "aaa", "data_bag" => "bbb" } end @@ -329,7 +324,6 @@ EOM end when_the_chef_server "has three data bag items" do - before do data_bag "x", { "deleted" => {}, "modified" => {}, "unmodified" => {} } end @@ -402,7 +396,6 @@ EOM knife("diff --name-status /data_bags").should_succeed "" end context "when cwd is the /data_bags directory" do - before do cwd "data_bags" end @@ -435,7 +428,6 @@ EOM # upload of a file is designed not to work at present. Make sure that is the # case. when_the_chef_server "has a cookbook" do - before do cookbook "x", "1.0.0", { "z.rb" => "" } end @@ -468,7 +460,6 @@ EOM end end when_the_repository "has a missing file for the cookbook" do - before do file "cookbooks/x/metadata.rb", cb_metadata("x", "1.0.0") end @@ -481,7 +472,6 @@ EOM end end when_the_repository "has an extra file for the cookbook" do - before do file "cookbooks/x/metadata.rb", cb_metadata("x", "1.0.0") file "cookbooks/x/z.rb", "" @@ -518,7 +508,6 @@ EOM end when_the_repository "has an update to said cookbook" do - before do file "cookbooks/frozencook/metadata.rb", cb_metadata("frozencook", "1.0.0", "# This is different") end @@ -565,7 +554,7 @@ EOM when_the_chef_server "has an earlier version for the cookbook" do before do - cookbook "x", "1.0.0", { "onlyin1.0.0.rb" => ""} + cookbook "x", "1.0.0", { "onlyin1.0.0.rb" => "" } cookbook "x", "0.9.9", { "onlyin0.9.9.rb" => "hi" } end @@ -667,7 +656,6 @@ EOH end when_the_chef_server "is empty" do - when_the_repository "has an environment with the wrong name in the file" do before do file "environments/x.json", { "name" => "y" } @@ -679,7 +667,6 @@ EOH end when_the_repository "has an environment with no name in the file" do - before do file "environments/x.json", { "description" => "hi" } end @@ -716,7 +703,6 @@ EOM with_versioned_cookbooks do when_the_chef_server "has one of each thing" do - before do client "x", {} cookbook "x", "1.0.0" @@ -811,7 +797,6 @@ EOM end context "except the role file is textually different, but not ACTUALLY different" do - before do file "roles/x.json", < ""} + cookbook "x", "1.0.0", { "onlyin1.0.0.rb" => "" } cookbook "x", "0.9.9", { "onlyin0.9.9.rb" => "hi" } end it "knife upload /cookbooks uploads the local version" do @@ -1201,7 +1186,6 @@ EOM end when_the_chef_server "is empty" do - when_the_repository "has an environment with the wrong name in the file" do before do file "environments/x.json", { "name" => "y" } @@ -1248,7 +1232,6 @@ EOM end end # with versioned cookbooks - when_the_chef_server "has a user" do before do user "x", {} @@ -1280,7 +1263,6 @@ EOM group "blah", {} when_the_repository "has at least one of each thing" do - before do # TODO We have to upload acls for an existing group due to a lack of # dependency detection during upload. Fix that! @@ -1296,8 +1278,8 @@ EOM file "members.json", [ "bar" ] file "org.json", { "full_name" => "wootles" } file "nodes/x.json", {} - file "policies/x-1.0.0.json", { } - file "policies/blah-1.0.0.json", { } + file "policies/x-1.0.0.json", {} + file "policies/blah-1.0.0.json", {} file "policy_groups/x.json", { "policies" => { "x" => { "revision_id" => "1.0.0" }, "blah" => { "revision_id" => "1.0.0" } } } file "roles/x.json", {} end @@ -1397,9 +1379,9 @@ EOM environment "x", { "description" => "foo" } group "x", { "groups" => [ "admin" ] } node "x", { "run_list" => [ "blah" ] } - policy "x", "1.0.0", { } - policy "x", "1.0.1", { } - policy "y", "1.0.0", { } + policy "x", "1.0.0", {} + policy "x", "1.0.1", {} + policy "y", "1.0.0", {} policy_group "x", { "policies" => { "x" => { "revision_id" => "1.0.1" }, @@ -1443,7 +1425,7 @@ EOM when_the_repository "has an org.json that changes full_name" do before do - file "org.json", { "full_name" => "Something Else"} + file "org.json", { "full_name" => "Something Else" } end it "knife upload / emits a warning for bar and adds foo and foobar" do diff --git a/spec/integration/recipes/lwrp_inline_resources_spec.rb b/spec/integration/recipes/lwrp_inline_resources_spec.rb index dc7e19a3cb..69b1bb53f6 100644 --- a/spec/integration/recipes/lwrp_inline_resources_spec.rb +++ b/spec/integration/recipes/lwrp_inline_resources_spec.rb @@ -82,8 +82,8 @@ describe "LWRPs with inline resources" do action :b end }.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) + 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\"" end end @@ -91,7 +91,6 @@ describe "LWRPs with inline resources" do when_the_repository "has a cookbook with a nested LWRP" do before do directory "cookbooks/x" do - file "resources/do_nothing.rb", <<-EOM actions :create, :nothing default_action :create @@ -117,7 +116,6 @@ describe "LWRPs with inline resources" do x_my_machine "me" x_my_machine "you" EOM - end # directory 'cookbooks/x' end diff --git a/spec/integration/recipes/lwrp_spec.rb b/spec/integration/recipes/lwrp_spec.rb index 3bc008d4f8..79775ffaa4 100644 --- a/spec/integration/recipes/lwrp_spec.rb +++ b/spec/integration/recipes/lwrp_spec.rb @@ -21,7 +21,6 @@ describe "LWRPs" do when_the_repository "has a cookbook named l-w-r-p" do before do directory "cookbooks/l-w-r-p" do - file "resources/foo.rb", < ends[0] end - end end diff --git a/spec/scripts/ssl-serve.rb b/spec/scripts/ssl-serve.rb index 0a2376049b..284c58aa78 100644 --- a/spec/scripts/ssl-serve.rb +++ b/spec/scripts/ssl-serve.rb @@ -10,7 +10,6 @@ require "openssl" require "webrick" require "webrick/https" - $ssl = true CHEF_SPEC_DATA = File.expand_path("../../data", __FILE__) @@ -21,14 +20,12 @@ key = OpenSSL::PKey::RSA.new(key_text) server_opts = {} if $ssl -server_opts.merge!( { :SSLEnable => true, - :SSLVerifyClient => OpenSSL::SSL::VERIFY_NONE, - :SSLCertificate => cert, - :SSLPrivateKey => key }) + server_opts.merge!( { :SSLEnable => true, + :SSLVerifyClient => OpenSSL::SSL::VERIFY_NONE, + :SSLCertificate => cert, + :SSLPrivateKey => key }) end - - # 5 == debug, 3 == warning LOGGER = WEBrick::Log.new(STDOUT, 5) DEFAULT_OPTIONS = { @@ -48,5 +45,3 @@ server = WEBrick::HTTPServer.new(webrick_opts) trap "INT" do server.shutdown end server.start - - diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 7ada1fac9d..47432f5a77 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -27,7 +27,6 @@ end # Ruby 1.9 Compat $:.unshift File.expand_path("../..", __FILE__) - require "rubygems" require "rspec/mocks" @@ -50,9 +49,9 @@ require "chef" require "chef/knife" Dir["lib/chef/knife/**/*.rb"]. - map {|f| f.gsub("lib/", "") }. - map {|f| f.gsub(%r{\.rb$}, "") }. - each {|f| require f } + map { |f| f.gsub("lib/", "") }. + map { |f| f.gsub(%r{\.rb$}, "") }. + each { |f| require f } require "chef/resource_resolver" require "chef/provider_resolver" @@ -86,7 +85,7 @@ Dir["spec/support/**/*.rb"]. reject { |f| f =~ %r{^spec/support/platforms} }. reject { |f| f =~ %r{^spec/support/pedant} }. map { |f| f.gsub(%r{.rb$}, "") }. - map { |f| f.gsub(%r{spec/}, "")}. + map { |f| f.gsub(%r{spec/}, "") }. each { |f| require f } OHAI_SYSTEM = Ohai::System.new @@ -131,8 +130,8 @@ RSpec.configure do |config| config.filter_run_excluding :windows_only => true unless windows? config.filter_run_excluding :not_supported_on_mac_osx_106 => true if mac_osx_106? - config.filter_run_excluding :not_supported_on_mac_osx=> true if mac_osx? - config.filter_run_excluding :mac_osx_only=> true if !mac_osx? + config.filter_run_excluding :not_supported_on_mac_osx => true if mac_osx? + config.filter_run_excluding :mac_osx_only => true if !mac_osx? config.filter_run_excluding :not_supported_on_win2k3 => true if windows_win2k3? config.filter_run_excluding :not_supported_on_solaris => true if solaris? config.filter_run_excluding :not_supported_on_gce => true if gce? diff --git a/spec/stress/win32/file_spec.rb b/spec/stress/win32/file_spec.rb index f1c81eb9c6..ec9571c1bd 100644 --- a/spec/stress/win32/file_spec.rb +++ b/spec/stress/win32/file_spec.rb @@ -33,5 +33,4 @@ describe "Chef::ReservedNames::Win32::File", :windows_only do test = lambda { Chef::ReservedNames::Win32::File.symlink?(@path) } expect(test).not_to leak_handles(:warmup => 50, :iterations => 100) end - end diff --git a/spec/stress/win32/security_spec.rb b/spec/stress/win32/security_spec.rb index e9da56620e..c1d3c76b12 100644 --- a/spec/stress/win32/security_spec.rb +++ b/spec/stress/win32/security_spec.rb @@ -25,7 +25,6 @@ if windows? end describe "Chef::ReservedNames::Win32::Security", :windows_only do - def monkeyfoo File.join(CHEF_SPEC_DATA, "monkeyfoo").gsub("/", "\\") end @@ -65,5 +64,4 @@ describe "Chef::ReservedNames::Win32::Security", :windows_only do GC.start }.not_to leak_memory(:warmup => 50, :iterations => 100) end - end diff --git a/spec/support/chef_helpers.rb b/spec/support/chef_helpers.rb index a7c3b849cd..aa60737c86 100644 --- a/spec/support/chef_helpers.rb +++ b/spec/support/chef_helpers.rb @@ -25,7 +25,6 @@ Chef::Log.init(StringIO.new) Chef::Log.level(Chef::Config.log_level) Chef::Config.solo(false) - def sha256_checksum(path) OpenSSL::Digest::SHA256.hexdigest(File.read(path)) end diff --git a/spec/support/lib/chef/provider/snakeoil.rb b/spec/support/lib/chef/provider/snakeoil.rb index a42f889e74..d2a923124b 100644 --- a/spec/support/lib/chef/provider/snakeoil.rb +++ b/spec/support/lib/chef/provider/snakeoil.rb @@ -19,7 +19,6 @@ class Chef class Provider class SnakeOil < Chef::Provider - def load_current_resource true end diff --git a/spec/support/lib/chef/resource/cat.rb b/spec/support/lib/chef/resource/cat.rb index 44acddb653..c4246bb719 100644 --- a/spec/support/lib/chef/resource/cat.rb +++ b/spec/support/lib/chef/resource/cat.rb @@ -19,15 +19,14 @@ class Chef class Resource class Cat < Chef::Resource - attr_accessor :action - def initialize(name, run_context=nil) + def initialize(name, run_context = nil) super @action = "sell" end - def pretty_kitty(arg=nil) + def pretty_kitty(arg = nil) if arg == true or arg == false @pretty_kitty = arg end diff --git a/spec/support/lib/chef/resource/one_two_three_four.rb b/spec/support/lib/chef/resource/one_two_three_four.rb index efeeff0710..8e98e8b842 100644 --- a/spec/support/lib/chef/resource/one_two_three_four.rb +++ b/spec/support/lib/chef/resource/one_two_three_four.rb @@ -19,14 +19,13 @@ class Chef class Resource class OneTwoThreeFour < Chef::Resource - attr_reader :i_can_count def i_can_count(tf) @i_can_count = tf end - def something(arg=nil) + def something(arg = nil) if arg == true or arg == false @something = arg end diff --git a/spec/support/lib/chef/resource/openldap_includer.rb b/spec/support/lib/chef/resource/openldap_includer.rb index 7a284cfc61..5a7651b10d 100644 --- a/spec/support/lib/chef/resource/openldap_includer.rb +++ b/spec/support/lib/chef/resource/openldap_includer.rb @@ -16,7 +16,6 @@ # limitations under the License. # - class Chef class Resource class OpenldapIncluder < Chef::Resource::LWRPBase diff --git a/spec/support/lib/chef/resource/zen_follower.rb b/spec/support/lib/chef/resource/zen_follower.rb index 135aeb1513..836245a209 100644 --- a/spec/support/lib/chef/resource/zen_follower.rb +++ b/spec/support/lib/chef/resource/zen_follower.rb @@ -21,10 +21,9 @@ require "chef/json_compat" class Chef class Resource class ZenFollower < Chef::Resource - provides :follower, platform: "zen" - def master(arg=nil) + def master(arg = nil) if !arg.nil? @master = arg end diff --git a/spec/support/lib/chef/resource/zen_master.rb b/spec/support/lib/chef/resource/zen_master.rb index 530f2ea703..f5137c18ec 100644 --- a/spec/support/lib/chef/resource/zen_master.rb +++ b/spec/support/lib/chef/resource/zen_master.rb @@ -26,12 +26,11 @@ class Chef attr_reader :peace - def peace(tf) @peace = tf end - def something(arg=nil) + def something(arg = nil) if !arg.nil? @something = arg end diff --git a/spec/support/lib/library_load_order.rb b/spec/support/lib/library_load_order.rb index c47a2f2c74..6b4c54fe4f 100644 --- a/spec/support/lib/library_load_order.rb +++ b/spec/support/lib/library_load_order.rb @@ -18,5 +18,3 @@ module LibraryLoadOrder load_order << file end end - - diff --git a/spec/support/matchers/leak.rb b/spec/support/matchers/leak.rb index 0e31415940..09770590da 100644 --- a/spec/support/matchers/leak.rb +++ b/spec/support/matchers/leak.rb @@ -20,7 +20,7 @@ module Matchers module LeakBase include RSpec::Matchers - def initialize(opts={}, &block) + def initialize(opts = {}, &block) @warmup = opts[:warmup] || 5 @iterations = opts[:iterations] || 100 @variance = opts[:variance] || 5000 @@ -35,6 +35,7 @@ module Matchers end private + def match(measure, given_proc) profiler.start @@ -68,7 +69,6 @@ module Matchers end end end - end class LeakMemory @@ -90,6 +90,7 @@ module Matchers def leak_memory(opts, &block) Matchers::LeakMemory.new(opts, &block) end + def leak_handles(opts, &block) Matchers::LeakHandles.new(opts, &block) end diff --git a/spec/support/mock/constant.rb b/spec/support/mock/constant.rb index 98756d715f..a2abc1905e 100644 --- a/spec/support/mock/constant.rb +++ b/spec/support/mock/constant.rb @@ -9,7 +9,7 @@ def mock_constants(constants, &block) constants.each do |constant, val| source_object, const_name = parse_constant(constant) saved_constants[constant] = source_object.const_get(const_name) - with_warnings(nil) {source_object.const_set(const_name, val) } + with_warnings(nil) { source_object.const_set(const_name, val) } end begin diff --git a/spec/support/mock/platform.rb b/spec/support/mock/platform.rb index a8bbf13589..ef94678b64 100644 --- a/spec/support/mock/platform.rb +++ b/spec/support/mock/platform.rb @@ -16,10 +16,10 @@ def platform_mock(platform = :unix, &block) end if block_given? - mock_constants({"RUBY_PLATFORM" => (platform == :windows ? "i386-mingw32" : "x86_64-darwin11.2.0"), - "File::PATH_SEPARATOR" => (platform == :windows ? ";" : ":"), - "File::ALT_SEPARATOR" => (platform == :windows ? "\\" : nil) }) do -yield + mock_constants({ "RUBY_PLATFORM" => (platform == :windows ? "i386-mingw32" : "x86_64-darwin11.2.0"), + "File::PATH_SEPARATOR" => (platform == :windows ? ";" : ":"), + "File::ALT_SEPARATOR" => (platform == :windows ? "\\" : nil) }) do + yield end end end diff --git a/spec/support/platform_helpers.rb b/spec/support/platform_helpers.rb index a29cb61d00..b50c2a01f0 100644 --- a/spec/support/platform_helpers.rb +++ b/spec/support/platform_helpers.rb @@ -65,10 +65,10 @@ def windows_2008r2_or_later? host = wmi.first_of("Win32_OperatingSystem") version = host["version"] return false unless version - components = version.split(".").map do | component | + components = version.split(".").map do |component| component.to_i end - components.length >=2 && components[0] >= 6 && components[1] >= 1 + components.length >= 2 && components[0] >= 6 && components[1] >= 1 end def windows_powershell_dsc? @@ -114,7 +114,6 @@ def mac_osx? false end - # detects if the hardware is 64-bit (evaluates to true in "WOW64" mode in a 32-bit app on a 64-bit system) def windows64? windows? && ( ENV["PROCESSOR_ARCHITECTURE"] == "AMD64" || ENV["PROCESSOR_ARCHITEW6432"] == "AMD64" ) @@ -166,7 +165,7 @@ def selinux_enabled? # specs independent of product. selinuxenabled_path = which("selinuxenabled") if selinuxenabled_path - cmd = Mixlib::ShellOut.new(selinuxenabled_path, :returns => [0,1]) + cmd = Mixlib::ShellOut.new(selinuxenabled_path, :returns => [0, 1]) cmd_result = cmd.run_command case cmd_result.exitstatus when 1 @@ -213,7 +212,7 @@ class GCEDetector end def gce? - GCEDetector.can_metadata_connect?(Ohai::Mixin::GCEMetadata::GCE_METADATA_ADDR,80) + GCEDetector.can_metadata_connect?(Ohai::Mixin::GCEMetadata::GCE_METADATA_ADDR, 80) rescue SocketError false end diff --git a/spec/support/platforms/prof/gc.rb b/spec/support/platforms/prof/gc.rb index 81fb28dda7..74b25ff9de 100644 --- a/spec/support/platforms/prof/gc.rb +++ b/spec/support/platforms/prof/gc.rb @@ -20,7 +20,6 @@ module RSpec module Prof module GC class Profiler - # GC 1 invokes. # Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC time(ms) # 1 0.012 159240 212940 10647 0.00000000000001530000 @@ -46,9 +45,7 @@ module RSpec def handle_count 0 end - end end end end - diff --git a/spec/support/platforms/prof/win32.rb b/spec/support/platforms/prof/win32.rb index 61e9eec853..43cce47bcc 100644 --- a/spec/support/platforms/prof/win32.rb +++ b/spec/support/platforms/prof/win32.rb @@ -22,7 +22,6 @@ module RSpec module Prof module Win32 class Profiler - def start GC.start end @@ -39,8 +38,6 @@ module RSpec Chef::ReservedNames::Win32::Process.get_current_process.handle_count end end - end end end - diff --git a/spec/support/shared/context/client.rb b/spec/support/shared/context/client.rb index 3c88e36fbb..d8676ef168 100644 --- a/spec/support/shared/context/client.rb +++ b/spec/support/shared/context/client.rb @@ -98,7 +98,7 @@ shared_context "a client run" do # previous step. expect(Chef::ServerAPI).to receive(:new). with(Chef::Config[:chef_server_url], client_name: fqdn, - signing_key_filename: Chef::Config[:client_key]). + signing_key_filename: Chef::Config[:client_key]). exactly(:once). and_return(http_node_load) @@ -123,7 +123,7 @@ shared_context "a client run" do expect_any_instance_of(Chef::CookbookSynchronizer).to receive(:sync_cookbooks) expect(Chef::ServerAPI).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) expect(http_cookbook_sync).to receive(:post). - with("environments/_default/cookbook_versions", {:run_list => []}). + with("environments/_default/cookbook_versions", { :run_list => [] }). and_return({}) end @@ -183,7 +183,7 @@ shared_context "converge completed" do # --Client#save_updated_node expect(Chef::ServerAPI).to receive(:new).with(Chef::Config[:chef_server_url], client_name: fqdn, - signing_key_filename: Chef::Config[:client_key], validate_utf8: false).and_return(http_node_save) + signing_key_filename: Chef::Config[:client_key], validate_utf8: false).and_return(http_node_save) expect(http_node_save).to receive(:put).with("nodes/#{fqdn}", node.for_json).and_return(true) end end @@ -231,7 +231,7 @@ end shared_context "audit phase completed with failed controls" do let(:audit_runner) { instance_double("Chef::Audit::Runner", :failed? => true, - :num_failed => 1, :num_total => 3) } + :num_failed => 1, :num_total => 3) } let(:audit_error) do err = Chef::Exceptions::AuditsFailed.new(audit_runner.num_failed, audit_runner.num_total) diff --git a/spec/support/shared/examples/client.rb b/spec/support/shared/examples/client.rb index 5af63dc307..3c13cd767e 100644 --- a/spec/support/shared/examples/client.rb +++ b/spec/support/shared/examples/client.rb @@ -24,7 +24,7 @@ shared_examples "a completed run with audit failure" do end it "converges, runs audits, saves the node and raises the error in a wrapping error" do - expect{ client.run }.to raise_error(Chef::Exceptions::RunFailedWrappingError) do |error| + expect { client.run }.to raise_error(Chef::Exceptions::RunFailedWrappingError) do |error| expect(error.wrapped_errors.size).to eq(run_errors.size) run_errors.each do |run_error| expect(error.wrapped_errors).to include(run_error) @@ -42,7 +42,7 @@ shared_examples "a failed run" do include_context "run failed" it "skips node save and raises the error in a wrapping error" do - expect{ client.run }.to raise_error(Chef::Exceptions::RunFailedWrappingError) do |error| + expect { client.run }.to raise_error(Chef::Exceptions::RunFailedWrappingError) do |error| expect(error.wrapped_errors.size).to eq(run_errors.size) run_errors.each do |run_error| expect(error.wrapped_errors).to include(run_error) diff --git a/spec/support/shared/functional/diff_disabled.rb b/spec/support/shared/functional/diff_disabled.rb index 7ee9808a94..c40b1e6e49 100644 --- a/spec/support/shared/functional/diff_disabled.rb +++ b/spec/support/shared/functional/diff_disabled.rb @@ -1,5 +1,5 @@ -shared_context "diff disabled" do +shared_context "diff disabled" do before do Chef::Config[:diff_disabled] = true end diff --git a/spec/support/shared/functional/directory_resource.rb b/spec/support/shared/functional/directory_resource.rb index 88e716b498..00495a5e3e 100644 --- a/spec/support/shared/functional/directory_resource.rb +++ b/spec/support/shared/functional/directory_resource.rb @@ -17,10 +17,9 @@ # shared_examples_for "a directory resource" do - include_context "diff disabled" - let(:expect_updated?) {true} + let(:expect_updated?) { true } context "when the target directory does not exist" do before do @@ -144,7 +143,6 @@ shared_examples_for "a directory resource" do end end end - end shared_context Chef::Resource::Directory do diff --git a/spec/support/shared/functional/file_resource.rb b/spec/support/shared/functional/file_resource.rb index c7a9611786..193026537a 100644 --- a/spec/support/shared/functional/file_resource.rb +++ b/spec/support/shared/functional/file_resource.rb @@ -44,7 +44,6 @@ shared_context "deploying via destdir" do end end - shared_examples_for "a file with the wrong content" do before do # Assert starting state is as expected @@ -55,7 +54,6 @@ shared_examples_for "a file with the wrong content" do end describe "when diff is disabled" do - include_context "diff disabled" context "when running action :create" do @@ -103,7 +101,7 @@ shared_examples_for "a file with the wrong content" do end it "raises an exception" do - expect{ resource.run_action(:create) }.to raise_error(Chef::Exceptions::ChecksumMismatch) + expect { resource.run_action(:create) }.to raise_error(Chef::Exceptions::ChecksumMismatch) end end end @@ -140,7 +138,6 @@ shared_examples_for "a file with the wrong content" do expect(resource).to be_updated_by_last_action end end - end context "when diff is enabled" do @@ -243,18 +240,15 @@ end shared_examples_for "a file resource" do describe "when deploying with :move" do - include_context "deploying with move" describe "when deploying via tmpdir" do - include_context "deploying via tmpdir" it_behaves_like "a configured file resource" end describe "when deploying via destdir" do - include_context "deploying via destdir" it_behaves_like "a configured file resource" @@ -262,18 +256,15 @@ shared_examples_for "a file resource" do end describe "when deploying with :copy" do - include_context "deploying with copy" describe "when deploying via tmpdir" do - include_context "deploying via tmpdir" it_behaves_like "a configured file resource" end describe "when deploying via destdir" do - include_context "deploying via destdir" it_behaves_like "a configured file resource" @@ -281,7 +272,6 @@ shared_examples_for "a file resource" do end describe "when running under why run" do - before do Chef::Config[:why_run] = true Chef::Config[:ssl_verify_mode] = :verify_none @@ -303,22 +293,20 @@ shared_examples_for "a file resource" do expect(File).not_to exist(path) end end - end describe "when setting atomic_update" do it "booleans should work" do - expect {resource.atomic_update(true)}.not_to raise_error - expect {resource.atomic_update(false)}.not_to raise_error + expect { resource.atomic_update(true) }.not_to raise_error + expect { resource.atomic_update(false) }.not_to raise_error end it "anything else should raise an error" do - expect {resource.atomic_update(:copy)}.to raise_error(ArgumentError) - expect {resource.atomic_update(:move)}.to raise_error(ArgumentError) - expect {resource.atomic_update(958)}.to raise_error(ArgumentError) + expect { resource.atomic_update(:copy) }.to raise_error(ArgumentError) + expect { resource.atomic_update(:move) }.to raise_error(ArgumentError) + expect { resource.atomic_update(958) }.to raise_error(ArgumentError) end end - end shared_examples_for "file resource not pointing to a real file" do @@ -351,19 +339,18 @@ shared_examples_for "file resource not pointing to a real file" do describe "when force_unlink is set to false" do it ":create raises an error" do - expect {resource.run_action(:create) }.to raise_error(Chef::Exceptions::FileTypeMismatch) + expect { resource.run_action(:create) }.to raise_error(Chef::Exceptions::FileTypeMismatch) end end describe "when force_unlink is not set (default)" do it ":create raises an error" do - expect {resource.run_action(:create) }.to raise_error(Chef::Exceptions::FileTypeMismatch) + expect { resource.run_action(:create) }.to raise_error(Chef::Exceptions::FileTypeMismatch) end end end shared_examples_for "a configured file resource" do - include_context "diff disabled" before do @@ -405,7 +392,6 @@ shared_examples_for "a configured file resource" do File.join(CHEF_SPEC_DATA, "file-test-target") } - describe "when configured not to manage symlink's target" do before(:each) do # configure not to manage symlink source @@ -454,7 +440,6 @@ shared_examples_for "a configured file resource" do # (e.g., resolv.conf) has been converted to a symlink, we're okay with the # discrepancy. context "when configured to manage the symlink source", :unix_only do - before do resource.manage_symlink_source(true) end @@ -550,7 +535,6 @@ shared_examples_for "a configured file resource" do end context "when the symlink source is a real file" do - let(:wrong_content) { "this is the wrong content" } let(:link_path) { File.join(CHEF_SPEC_DATA, "points-to-real-file") } @@ -574,7 +558,6 @@ shared_examples_for "a configured file resource" do File.open(path, "wb") { |f| f.write(expected_content) } end - include_context "setup broken permissions" include_examples "a securable resource with existing target" @@ -583,7 +566,6 @@ shared_examples_for "a configured file resource" do resource.run_action(:create) expect(File).to be_symlink(link_path) end - end context "and the content is incorrect" do @@ -613,13 +595,10 @@ shared_examples_for "a configured file resource" do include_context "setup correct permissions" include_examples "a securable resource with existing target" - end - end context "when the symlink points to a symlink which points to a real file" do - let(:wrong_content) { "this is the wrong content" } let(:link_to_file_path) { File.join(CHEF_SPEC_DATA, "points-to-real-file") } let(:link_to_link_path) { File.join(CHEF_SPEC_DATA, "points-to-next-link") } @@ -652,7 +631,6 @@ shared_examples_for "a configured file resource" do expect(File).to be_symlink(link_to_link_path) expect(File).to be_symlink(link_to_file_path) end - end end end @@ -721,7 +699,7 @@ shared_examples_for "a configured file resource" do it_behaves_like "file resource not pointing to a real file" end - context "when the target file is a blockdev",:unix_only, :requires_root, :not_supported_on_solaris do + context "when the target file is a blockdev", :unix_only, :requires_root, :not_supported_on_solaris do include Chef::Mixin::ShellOut let(:path) do File.join(CHEF_SPEC_DATA, "testdev") @@ -739,7 +717,7 @@ shared_examples_for "a configured file resource" do it_behaves_like "file resource not pointing to a real file" end - context "when the target file is a chardev",:unix_only, :requires_root, :not_supported_on_solaris do + context "when the target file is a chardev", :unix_only, :requires_root, :not_supported_on_solaris do include Chef::Mixin::ShellOut let(:path) do File.join(CHEF_SPEC_DATA, "testdev") @@ -757,7 +735,7 @@ shared_examples_for "a configured file resource" do it_behaves_like "file resource not pointing to a real file" end - context "when the target file is a pipe",:unix_only do + context "when the target file is a pipe", :unix_only do include Chef::Mixin::ShellOut let(:path) do File.join(CHEF_SPEC_DATA, "testpipe") @@ -775,7 +753,7 @@ shared_examples_for "a configured file resource" do it_behaves_like "file resource not pointing to a real file" end - context "when the target file is a socket",:unix_only do + context "when the target file is a socket", :unix_only do require "socket" # It turns out that the path to a socket can have at most ~104 @@ -958,7 +936,6 @@ shared_examples_for "a configured file resource" do end describe "and the target file has the correct permissions" do - # When permissions and content are correct, chef should do nothing and # the resource should not be marked updated. let(:expect_updated?) { false } @@ -1015,10 +992,9 @@ shared_examples_for "a configured file resource" do end end end - end -shared_context Chef::Resource::File do +shared_context Chef::Resource::File do if windows? require "chef/win32/file" end diff --git a/spec/support/shared/functional/http.rb b/spec/support/shared/functional/http.rb index 2779730268..71b9578ca9 100644 --- a/spec/support/shared/functional/http.rb +++ b/spec/support/shared/functional/http.rb @@ -37,7 +37,7 @@ module ChefHTTPShared content end - def start_tiny_server(server_opts={}) + def start_tiny_server(server_opts = {}) nyan_uncompressed_size = File::Stat.new(nyan_uncompressed_filename).size nyan_compressed_size = File::Stat.new(nyan_compressed_filename).size @@ -162,18 +162,15 @@ module ChefHTTPShared # @api.get("/bad_request", 400, '{ "error": [ "Your request is just terrible." ] }') @api.post("/bad_request", 400, '{ "error": [ "Your request is just terrible." ] }') - end def stop_tiny_server @server.stop @server = @api = nil end - end shared_examples_for "downloading all the things" do - describe "when downloading a simple uncompressed file" do let(:source) { "http://localhost:9000/nyan_cat.png" } let(:expected_content) { binread(nyan_uncompressed_filename) } diff --git a/spec/support/shared/functional/securable_resource.rb b/spec/support/shared/functional/securable_resource.rb index 330183ebb1..d56facc388 100644 --- a/spec/support/shared/functional/securable_resource.rb +++ b/spec/support/shared/functional/securable_resource.rb @@ -150,7 +150,6 @@ shared_context "use Windows permissions", :windows_only do end shared_examples_for "a securable resource with existing target" do - include_context "diff disabled" context "on Unix", :unix_only do @@ -176,7 +175,6 @@ shared_examples_for "a securable resource with existing target" do it "is marked as updated only if changes are made" do expect(resource.updated_by_last_action?).to eq(expect_updated?) end - end describe "when setting the group", :requires_root do @@ -192,7 +190,6 @@ shared_examples_for "a securable resource with existing target" do it "is marked as updated only if changes are made" do expect(resource.updated_by_last_action?).to eq(expect_updated?) end - end describe "when setting the permissions from octal given as a String" do @@ -290,7 +287,6 @@ shared_examples_for "a securable resource with existing target" do end shared_examples_for "a securable resource without existing target" do - include_context "diff disabled" context "on Windows", :windows_only do @@ -364,7 +360,6 @@ shared_examples_for "a securable resource without existing target" do end describe "with rights and deny_rights attributes" do - it "correctly sets :read rights" do resource.rights(:read, "Guest") resource.run_action(:create) @@ -434,7 +429,6 @@ shared_examples_for "a securable resource without existing target" do allowed_acl(SID.Everyone, expected_read_perms) ) end - end context "with a mode attribute" do @@ -515,7 +509,7 @@ shared_examples_for "a securable resource without existing target" do resource.inherits(false) resource.run_action(:create) - descriptor.dacl.each do | ace | + descriptor.dacl.each do |ace| expect(ace.inherited?).to eq(false) end end @@ -542,6 +536,5 @@ shared_examples_for "a securable resource without existing target" do expect(resource_inherited_acls).to eq(parent_inherited_acls) end - end end diff --git a/spec/support/shared/functional/securable_resource_with_reporting.rb b/spec/support/shared/functional/securable_resource_with_reporting.rb index c9b5bae465..4d37efd9c2 100644 --- a/spec/support/shared/functional/securable_resource_with_reporting.rb +++ b/spec/support/shared/functional/securable_resource_with_reporting.rb @@ -21,9 +21,7 @@ ALL_EXPANDED_PERMISSIONS = ["generic read", "read attributes", "write attributes"] - shared_examples_for "a securable resource with reporting" do - include_context "diff disabled" let(:current_resource) do @@ -72,7 +70,6 @@ shared_examples_for "a securable resource with reporting" do end context "and owner is specified with a String (username) in new_resource", :requires_root => true do - # TODO/bug: duplicated from the "securable resource" tests if ohai[:platform] == "aix" @@ -89,11 +86,9 @@ shared_examples_for "a securable resource with reporting" do it "sets the owner on new_resource to the username (String) of the desired owner" do expect(resource.owner).to eq(expected_user_name) end - end context "and owner is specified with an Integer (uid) in new_resource", :requires_root => true do - # TODO: duplicated from "securable resource" if ohai[:platform] == "aix" let(:expected_user_name) { "guest" } @@ -115,7 +110,6 @@ shared_examples_for "a securable resource with reporting" do end context "and group is specified with a String (group name)", :requires_root => true do - let(:expected_group_name) { Etc.getgrent.name } before do @@ -126,7 +120,6 @@ shared_examples_for "a securable resource with reporting" do it "sets the group on new_resource to the group name (String) of the group" do expect(resource.group).to eq(expected_group_name) end - end context "and group is specified with an Integer (gid)", :requires_root => true do @@ -140,7 +133,6 @@ shared_examples_for "a securable resource with reporting" do it "sets the group on new_resource to the gid (Integer)" do expect(resource.group).to eq(expected_gid) end - end context "and mode is specified as a String" do @@ -190,7 +182,6 @@ shared_examples_for "a securable resource with reporting" do end context "and owner is specified with a String (username) in new_resource" do - let(:expected_user_name) { Etc.getpwuid(Process.uid).name } before do @@ -200,11 +191,9 @@ shared_examples_for "a securable resource with reporting" do it "sets the owner on new_resource to the username (String) of the desired owner" do expect(current_resource.owner).to eq(expected_user_name) end - end context "and owner is specified with an Integer (uid) in new_resource" do - let(:expected_uid) { Process.uid } before do @@ -224,7 +213,6 @@ shared_examples_for "a securable resource with reporting" do it "sets the group on new_resource to the group name (String) of the group" do expect(current_resource.group).to eq(@expected_group_name) end - end context "and group is specified with an Integer (gid)" do @@ -235,7 +223,6 @@ shared_examples_for "a securable resource with reporting" do it "sets the group on new_resource to the gid (Integer)" do expect(current_resource.group).to eq(@expected_gid) end - end context "and mode is specified as a String" do @@ -267,13 +254,10 @@ shared_examples_for "a securable resource with reporting" do end describe "reading file security metadata for reporting on windows", :windows_only do - context "when the target file doesn't exist" do - # Windows reporting data should look like this (+/- ish): # { "owner" => "bob", "checksum" => "ffff", "access control" => { "bob" => { "permissions" => ["perm1", "perm2", ...], "flags" => [] }}} - before do resource.action(:create) end @@ -293,15 +277,13 @@ shared_examples_for "a securable resource with reporting" do resource.run_action(:create) # TODO: most stable way to specify? expect(resource.owner).to eq(etc.getpwuid(process.uid).name) - expect(resource.state[:expanded_rights]).to eq({ "CURRENTUSER" => { "permissions" => ALL_EXPANDED_PERMISSIONS, "flags" => [] }}) + expect(resource.state[:expanded_rights]).to eq({ "CURRENTUSER" => { "permissions" => ALL_EXPANDED_PERMISSIONS, "flags" => [] } }) expect(resource.state[:expanded_deny_rights]).to eq({}) expect(resource.state[:inherits]).to be_truthy end end - - context "and owner is specified with a string (username) in new_resource" do - + context "and owner is specified with a string (username) in new_resource" do # TODO/bug: duplicated from the "securable resource" tests let(:expected_user_name) { "Guest" } @@ -313,11 +295,9 @@ shared_examples_for "a securable resource with reporting" do it "sets the owner on new_resource to the username (string) of the desired owner" do expect(resource.owner).to eq(expected_user_name) end - end context "and owner is specified with a fully qualified domain user" do - # TODO: duplicated from "securable resource" let(:expected_user_name) { 'domain\user' } @@ -331,7 +311,6 @@ shared_examples_for "a securable resource with reporting" do expect(resource.owner).to eq(expected_user_name) end end - end context "when the target file exists" do @@ -350,7 +329,6 @@ shared_examples_for "a securable resource with reporting" do end context "and owner is specified with a string (username) in new_resource" do - let(:expected_user_name) { etc.getpwuid(process.uid).name } before do @@ -360,11 +338,9 @@ shared_examples_for "a securable resource with reporting" do it "sets the owner on current_resource to the username (string) of the desired owner" do expect(current_resource.owner).to eq(expected_user_name) end - end context "and owner is specified as a fully qualified 'domain\\user' in new_resource" do - let(:expected_user_name) { 'domain\user' } before do @@ -391,8 +367,6 @@ shared_examples_for "a securable resource with reporting" do skip end end - - end end end diff --git a/spec/support/shared/functional/win32_service.rb b/spec/support/shared/functional/win32_service.rb index 5bd2d772cb..0f9072bdef 100644 --- a/spec/support/shared/functional/win32_service.rb +++ b/spec/support/shared/functional/win32_service.rb @@ -35,10 +35,8 @@ shared_context "using Win32::Service" do if File.exists?(test_service_file) File.delete(test_service_file) end - end - # Definition for the test-service let(:test_service) { diff --git a/spec/support/shared/functional/windows_script.rb b/spec/support/shared/functional/windows_script.rb index cad0d7e12d..86dc6e142a 100644 --- a/spec/support/shared/functional/windows_script.rb +++ b/spec/support/shared/functional/windows_script.rb @@ -27,7 +27,7 @@ shared_context Chef::Resource::WindowsScript do @ohai_reader.all_plugins(["platform", "kernel"]) new_node = Chef::Node.new - new_node.consume_external_attrs(@ohai_reader.data,{}) + new_node.consume_external_attrs(@ohai_reader.data, {}) events = Chef::EventDispatch::Dispatcher.new @@ -116,7 +116,7 @@ shared_context Chef::Resource::WindowsScript do let (:guard_architecture) { :i386 } it "raises an error" do resource.only_if resource_guard_command, :architecture => guard_architecture - expect{ resource.run_action(:run) }.to raise_error( + expect { resource.run_action(:run) }.to raise_error( Chef::Exceptions::Win32ArchitectureIncorrect, /cannot execute script with requested architecture 'i386' on Windows Nano Server/) end @@ -125,7 +125,6 @@ shared_context Chef::Resource::WindowsScript do end shared_examples_for "a Windows script running on Windows" do - describe "when the run action is invoked on Windows" do it "executes the script code" do resource.code("whoami > \"#{script_output_path}\"") @@ -198,5 +197,4 @@ shared_context Chef::Resource::WindowsScript do def get_process_architecture(suffix = "") get_windows_script_output(suffix).strip.downcase end - end diff --git a/spec/support/shared/integration/integration_helper.rb b/spec/support/shared/integration/integration_helper.rb index 5d4c01a44e..8840940e26 100644 --- a/spec/support/shared/integration/integration_helper.rb +++ b/spec/support/shared/integration/integration_helper.rb @@ -99,7 +99,7 @@ module IntegrationSupport File.expand_path(relative_path, (@parent_path || @repository_dir)) end - def cb_metadata(name, version, extra_text="") + def cb_metadata(name, version, extra_text = "") "name #{name.inspect}; version #{version.inspect}#{extra_text}" end @@ -128,14 +128,13 @@ module IntegrationSupport # TODO: "force" actually means "silence all exceptions". this # silences a weird permissions error on Windows that we should track # down, but for now there's no reason for it to blow up our CI. - FileUtils.remove_entry_secure(@repository_dir, force=Chef::Platform.windows?) + FileUtils.remove_entry_secure(@repository_dir, force = Chef::Platform.windows?) ensure @repository_dir = nil end end Dir.chdir(@old_cwd) if @old_cwd end - end # Versioned cookbooks @@ -150,5 +149,4 @@ module IntegrationSupport before(:each) { Chef::Config[:versioned_cookbooks] = false } after(:each) { Chef::Config.delete(:versioned_cookbooks) } end - end diff --git a/spec/support/shared/integration/knife_support.rb b/spec/support/shared/integration/knife_support.rb index fe9c6f78a7..25cacc1a28 100644 --- a/spec/support/shared/integration/knife_support.rb +++ b/spec/support/shared/integration/knife_support.rb @@ -103,7 +103,6 @@ module KnifeSupport private class KnifeResult - include ::RSpec::Matchers def initialize(stdout, stderr, exit_code) diff --git a/spec/support/shared/matchers/exit_with_code.rb b/spec/support/shared/matchers/exit_with_code.rb index cf1825f2ed..0804f66459 100644 --- a/spec/support/shared/matchers/exit_with_code.rb +++ b/spec/support/shared/matchers/exit_with_code.rb @@ -14,7 +14,7 @@ RSpec::Matchers.define :exit_with_code do |exp_code| failure_message do |block| "expected block to call exit(#{exp_code}) but exit" + - (actual.nil? ? " not called" : "(#{actual}) was called") + (actual.nil? ? " not called" : "(#{actual}) was called") end failure_message_when_negated do |block| @@ -28,5 +28,4 @@ RSpec::Matchers.define :exit_with_code do |exp_code| def supports_block_expectations? true end - end diff --git a/spec/support/shared/shared_examples.rb b/spec/support/shared/shared_examples.rb index 550fa2eb68..c7ee16d7c0 100644 --- a/spec/support/shared/shared_examples.rb +++ b/spec/support/shared/shared_examples.rb @@ -2,7 +2,6 @@ # Any object which defines a .to_json should import this test shared_examples "to_json equivalent to Chef::JSONCompat.to_json" do - let(:jsonable) { raise "You must define the subject when including this test" } @@ -10,5 +9,4 @@ shared_examples "to_json equivalent to Chef::JSONCompat.to_json" do it "should allow consumers to call #to_json or Chef::JSONCompat.to_json" do expect(jsonable.to_json).to eq(Chef::JSONCompat.to_json(jsonable)) end - end diff --git a/spec/support/shared/unit/api_error_inspector.rb b/spec/support/shared/unit/api_error_inspector.rb index 6e074d38a7..de32ad1c58 100644 --- a/spec/support/shared/unit/api_error_inspector.rb +++ b/spec/support/shared/unit/api_error_inspector.rb @@ -16,8 +16,6 @@ # limitations under the License. # - - # == API Error Inspector Examples # These tests are work in progress. They exercise the code enough to ensure it # runs without error, but don't make assertions about the output. This is @@ -26,7 +24,6 @@ # STDOUT and manually check the output. shared_examples_for "an api error inspector" do - before do @node_name = "test-node.example.com" @config = { @@ -39,7 +36,6 @@ shared_examples_for "an api error inspector" do @description = Chef::Formatters::ErrorDescription.new("Error registering the node:") @outputter = Chef::Formatters::IndentableOutputStream.new(StringIO.new, STDERR) #@outputter = Chef::Formatters::IndentableOutputStream.new(STDOUT, STDERR) - end describe "when explaining a network error" do @@ -52,7 +48,6 @@ shared_examples_for "an api error inspector" do it "prints a nice message" do @description.display(@outputter) end - end describe "when explaining a 'private key missing' error" do @@ -65,7 +60,6 @@ shared_examples_for "an api error inspector" do it "prints a nice message" do @description.display(@outputter) end - end describe "when explaining a 401 caused by clock skew" do @@ -81,7 +75,6 @@ shared_examples_for "an api error inspector" do it "prints a nice message" do @description.display(@outputter) end - end describe "when explaining a 401 (no clock skew)" do @@ -97,7 +90,6 @@ shared_examples_for "an api error inspector" do it "prints a nice message" do @description.display(@outputter) end - end describe "when explaining a 403" do @@ -113,7 +105,6 @@ shared_examples_for "an api error inspector" do it "prints a nice message" do @description.display(@outputter) end - end describe "when explaining a 400" do @@ -129,7 +120,6 @@ shared_examples_for "an api error inspector" do it "prints a nice message" do @description.display(@outputter) end - end describe "when explaining a 404" do @@ -188,5 +178,4 @@ shared_examples_for "an api error inspector" do @description.display(@outputter) end end - end diff --git a/spec/support/shared/unit/api_versioning.rb b/spec/support/shared/unit/api_versioning.rb index 195b65ff5b..923bd40a58 100644 --- a/spec/support/shared/unit/api_versioning.rb +++ b/spec/support/shared/unit/api_versioning.rb @@ -32,7 +32,7 @@ shared_examples_for "version handling" do end it "raises the original exception" do - expect{ object.send(method) }.to raise_error(exception_406) + expect { object.send(method) }.to raise_error(exception_406) end end # when the server does not support the min or max server API version that Chef::UserV1 supports end # version handling @@ -60,9 +60,8 @@ shared_examples_for "user and client reregister" do it "raises an error about only V0 being supported" do expect(object).to receive(:reregister_only_v0_supported_error_msg).with(max_version, min_version) - expect{ object.reregister }.to raise_error(Chef::Exceptions::OnlyApiVersion0SupportedForAction) + expect { object.reregister }.to raise_error(Chef::Exceptions::OnlyApiVersion0SupportedForAction) end - end context "when the exception is not versioning related" do before do @@ -70,7 +69,7 @@ shared_examples_for "user and client reregister" do end it "raises the original error" do - expect{ object.reregister }.to raise_error(generic_exception) + expect { object.reregister }.to raise_error(generic_exception) end end end diff --git a/spec/support/shared/unit/execute_resource.rb b/spec/support/shared/unit/execute_resource.rb index 27c60ef377..1ddf4d50b2 100644 --- a/spec/support/shared/unit/execute_resource.rb +++ b/spec/support/shared/unit/execute_resource.rb @@ -20,7 +20,6 @@ require "spec_helper" shared_examples_for "an execute resource" do - before(:each) do @resource = execute_resource end diff --git a/spec/support/shared/unit/knife_shared.rb b/spec/support/shared/unit/knife_shared.rb index 8f97cf60c0..0af05ffb80 100644 --- a/spec/support/shared/unit/knife_shared.rb +++ b/spec/support/shared/unit/knife_shared.rb @@ -16,7 +16,6 @@ # limitations under the License. # - shared_examples_for "mandatory field missing" do context "when field is nil" do before do diff --git a/spec/support/shared/unit/mock_shellout.rb b/spec/support/shared/unit/mock_shellout.rb index 05924e8a40..dac51be798 100644 --- a/spec/support/shared/unit/mock_shellout.rb +++ b/spec/support/shared/unit/mock_shellout.rb @@ -34,12 +34,15 @@ class MockShellout exitstatus: 0, }.merge(properties) end + def method_missing(name, *args) @properties[name.to_sym] end + def error? exitstatus != 0 end + def error! raise Mixlib::ShellOut::ShellCommandFailed, "Expected process to exit with 0, but received #{exitstatus}" if error? end diff --git a/spec/support/shared/unit/platform_introspector.rb b/spec/support/shared/unit/platform_introspector.rb index 30a2f61a70..e49667082f 100644 --- a/spec/support/shared/unit/platform_introspector.rb +++ b/spec/support/shared/unit/platform_introspector.rb @@ -17,7 +17,6 @@ # limitations under the License. # - shared_examples_for "a platform introspector" do before(:each) do @platform_hash = {} @@ -27,12 +26,12 @@ shared_examples_for "a platform introspector" do "1.2.3" => "#{x}-1.2.3", } end - @platform_hash["debian"] = {["5", "6"] => "debian-5/6", "default" => "debian"} + @platform_hash["debian"] = { ["5", "6"] => "debian-5/6", "default" => "debian" } @platform_hash["default"] = "default" # The following @platform_hash keys are used for testing version constraints - @platform_hash["exact_match"] = { "1.2.3" => "exact", ">= 1.0" => "not exact"} + @platform_hash["exact_match"] = { "1.2.3" => "exact", ">= 1.0" => "not exact" } @platform_hash["multiple_matches"] = { "~> 2.3.4" => "matched ~> 2.3.4", ">= 2.3" => "matched >=2.3" } - @platform_hash["invalid_cookbook_version"] = {">= 21" => "Matches a single number"} + @platform_hash["invalid_cookbook_version"] = { ">= 21" => "Matches a single number" } @platform_hash["successful_matches"] = { "< 3.0" => "matched < 3.0", ">= 3.0" => "matched >= 3.0" } @platform_family_hash = { @@ -93,7 +92,7 @@ shared_examples_for "a platform introspector" do it "raises RuntimeError" do node.automatic_attrs[:platform] = "multiple_matches" node.automatic_attrs[:platform_version] = "2.3.4" - expect {platform_introspector.value_for_platform(@platform_hash)}.to raise_error(RuntimeError) + expect { platform_introspector.value_for_platform(@platform_hash) }.to raise_error(RuntimeError) end it "should not require .0 to match >= 21.0" do @@ -123,7 +122,6 @@ shared_examples_for "a platform introspector" do end describe "when checking platform?" do - it "returns true if the node is a provided platform and platforms are provided as symbols" do node.automatic_attrs[:platform] = "ubuntu" expect(platform_introspector.platform?([:redhat, :ubuntu])).to eq(true) @@ -141,7 +139,6 @@ shared_examples_for "a platform introspector" do end describe "when checking platform_family?" do - it "returns true if the node is in a provided platform family and families are provided as symbols" do node.automatic_attrs[:platform_family] = "debian" expect(platform_introspector.platform_family?([:rhel, :debian])).to eq(true) @@ -160,7 +157,6 @@ shared_examples_for "a platform introspector" do it "returns false if the node is not of the provided platforms and platform_family is not set" do expect(platform_introspector.platform_family?(:splatlinux)).to eq(false) end - end # NOTE: this is a regression test for bug CHEF-1514 describe "when the value is an array" do @@ -171,7 +167,7 @@ shared_examples_for "a platform introspector" do "centos" => { "default" => [ :restart, :reload, :status ] }, "redhat" => { "default" => [ :restart, :reload, :status ] }, "fedora" => { "default" => [ :restart, :reload, :status ] }, - "default" => { "default" => [:restart, :reload ] }} + "default" => { "default" => [:restart, :reload ] } } end it "returns the correct default for a given platform" do @@ -186,6 +182,4 @@ shared_examples_for "a platform introspector" do expect(platform_introspector.value_for_platform(@platform_hash)).to eq([:restart, :reload]) end end - end - diff --git a/spec/support/shared/unit/provider/file.rb b/spec/support/shared/unit/provider/file.rb index 8ed67eb5a8..d1e5ad7cdf 100644 --- a/spec/support/shared/unit/provider/file.rb +++ b/spec/support/shared/unit/provider/file.rb @@ -110,24 +110,21 @@ end # Tempfile call `File.exist?()` internally which will cause test failures if # `File.exist?()` has been stubbed. class BasicTempfile < ::File - def self.make_tmp_path(basename) slug = "#{basename}-#{rand(1 << 128)}" File.join(Dir.tmpdir, slug) end def self.new(basename) - super(make_tmp_path(basename), File::RDWR|File::CREAT|File::EXCL, 0600) + super(make_tmp_path(basename), File::RDWR | File::CREAT | File::EXCL, 0600) end def unlink self.class.unlink(path) end - end shared_examples_for Chef::Provider::File do - let(:tempfile_path) do end @@ -159,7 +156,6 @@ shared_examples_for Chef::Provider::File do end context "when loading the current resource" do - context "when running load_current_resource" do # # the content objects need the current_resource to be loaded (esp remote_file), so calling @@ -325,7 +321,6 @@ shared_examples_for Chef::Provider::File do expect(provider.new_resource.mode).to eq("0321") end end - end context "examining file security metadata on Unix with a file that does not exist" do @@ -377,7 +372,6 @@ shared_examples_for Chef::Provider::File do end context "when loading the new_resource after the run" do - before do # fake that we're on unix even if we're on windows allow(ChefConfig).to receive(:windows?).and_return(false) @@ -419,12 +413,12 @@ shared_examples_for Chef::Provider::File do [:create, :create_if_missing, :touch].each do |action| context "action #{action}" do it "raises EnclosingDirectoryDoesNotExist" do - expect {provider.run_action(action)}.to raise_error(Chef::Exceptions::EnclosingDirectoryDoesNotExist) + expect { provider.run_action(action) }.to raise_error(Chef::Exceptions::EnclosingDirectoryDoesNotExist) end it "does not raise an exception in why-run mode" do Chef::Config[:why_run] = true - expect {provider.run_action(action)}.not_to raise_error + expect { provider.run_action(action) }.not_to raise_error Chef::Config[:why_run] = false end end @@ -435,19 +429,19 @@ shared_examples_for Chef::Provider::File do before { setup_unwritable_file } it "action delete raises InsufficientPermissions" do - expect {provider.run_action(:delete)}.to raise_error(Chef::Exceptions::InsufficientPermissions) + expect { provider.run_action(:delete) }.to raise_error(Chef::Exceptions::InsufficientPermissions) end it "action delete also raises InsufficientPermissions in why-run mode" do Chef::Config[:why_run] = true - expect {provider.run_action(:delete)}.to raise_error(Chef::Exceptions::InsufficientPermissions) + expect { provider.run_action(:delete) }.to raise_error(Chef::Exceptions::InsufficientPermissions) Chef::Config[:why_run] = false end end end context "action create" do - it "should create the file, update its contents and then set the acls on the file" do + it "should create the file, update its contents and then set the acls on the file" do setup_missing_file expect(provider).to receive(:do_create_file) expect(provider).to receive(:do_contents_changes) @@ -476,7 +470,7 @@ shared_examples_for Chef::Provider::File do allow(File).to receive(:directory?).with("C:\\Windows\\system32/cmd.exe").and_return(false) provider.new_resource.verify windows? ? "REM" : "true" provider.new_resource.verify windows? ? "cmd.exe /c exit 1" : "false" - expect{provider.send(:do_validate_content)}.to raise_error(Chef::Exceptions::ValidationFailed) + expect { provider.send(:do_validate_content) }.to raise_error(Chef::Exceptions::ValidationFailed) end end end @@ -520,14 +514,14 @@ shared_examples_for Chef::Provider::File do let(:diff_for_reporting) { "+++\n---\n+foo\n-bar\n" } before do allow(provider).to receive(:contents_changed?).and_return(true) - diff = double("Diff", :for_output => ["+++","---","+foo","-bar"], + diff = double("Diff", :for_output => ["+++", "---", "+foo", "-bar"], :for_reporting => diff_for_reporting ) allow(diff).to receive(:diff).with(resource_path, tempfile_path).and_return(true) expect(provider).to receive(:diff).at_least(:once).and_return(diff) expect(provider).to receive(:checksum).with(tempfile_path).and_return(tempfile_sha256) allow(provider).to receive(:managing_content?).and_return(true) allow(provider).to receive(:checksum).with(resource_path).and_return(tempfile_sha256) - expect(resource).not_to receive(:checksum).with(tempfile_sha256) # do not mutate the new resource + expect(resource).not_to receive(:checksum).with(tempfile_sha256) # do not mutate the new resource expect(provider.deployment_strategy).to receive(:deploy).with(tempfile_path, normalized_path) end context "when the file was created" do @@ -549,7 +543,7 @@ shared_examples_for Chef::Provider::File do end context "when the file was not created" do before do - allow(provider).to receive(:do_backup) # stub do_backup + allow(provider).to receive(:do_backup) # stub do_backup expect(provider).to receive(:needs_creating?).at_least(:once).and_return(false) end @@ -570,7 +564,7 @@ shared_examples_for Chef::Provider::File do end end - it "does nothing when the contents have not changed" do + it "does nothing when the contents have not changed" do allow(provider).to receive(:contents_changed?).and_return(false) expect(provider).not_to receive(:diff) provider.send(:do_contents_changes) @@ -580,20 +574,20 @@ shared_examples_for Chef::Provider::File do it "does nothing when there is no content to deploy (tempfile returned from contents is nil)" do expect(provider.send(:content)).to receive(:tempfile).at_least(:once).and_return(nil) expect(provider).not_to receive(:diff) - expect{ provider.send(:do_contents_changes) }.not_to raise_error + expect { provider.send(:do_contents_changes) }.not_to raise_error end it "raises an exception when the content object returns a tempfile with a nil path" do tempfile = double("Tempfile", :path => nil) expect(provider.send(:content)).to receive(:tempfile).at_least(:once).and_return(tempfile) - expect{ provider.send(:do_contents_changes) }.to raise_error + expect { provider.send(:do_contents_changes) }.to raise_error end it "raises an exception when the content object returns a tempfile that does not exist" do tempfile = double("Tempfile", :path => "/tmp/foo-bar-baz") expect(provider.send(:content)).to receive(:tempfile).at_least(:once).and_return(tempfile) expect(File).to receive(:exists?).with("/tmp/foo-bar-baz").and_return(false) - expect{ provider.send(:do_contents_changes) }.to raise_error + expect { provider.send(:do_contents_changes) }.to raise_error end end @@ -682,7 +676,6 @@ shared_examples_for Chef::Provider::File do end end end - end context "action delete" do @@ -767,9 +760,7 @@ shared_examples_for Chef::Provider::File do provider.run_action(:create_if_missing) end end - end - end shared_examples_for "a file provider with content field" do diff --git a/spec/support/shared/unit/provider/useradd_based_user_provider.rb b/spec/support/shared/unit/provider/useradd_based_user_provider.rb index ccc6e3fec6..c38f1d40cd 100644 --- a/spec/support/shared/unit/provider/useradd_based_user_provider.rb +++ b/spec/support/shared/unit/provider/useradd_based_user_provider.rb @@ -46,11 +46,10 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option @current_resource.manage_home false @current_resource.force false @current_resource.non_unique false - @current_resource.supports({:manage_home => false, :non_unique => false}) + @current_resource.supports({ :manage_home => false, :non_unique => false }) end describe "when setting option" do - supported_useradd_options.each do |attribute, option| it "should check for differences in #{attribute} between the new and current resources" do expect(@current_resource).to receive(attribute) @@ -64,8 +63,8 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option end it "should set the option for #{attribute} if the new resources #{attribute} is not nil, without homedir management" do - allow(@new_resource).to receive(:supports).and_return({:manage_home => false, - :non_unique => false}) + allow(@new_resource).to receive(:supports).and_return({ :manage_home => false, + :non_unique => false }) allow(@new_resource).to receive(attribute).and_return("hola") expect(provider.universal_options).to eql([option, "hola"]) end @@ -81,7 +80,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option it "should combine all the possible options" do combined_opts = [] - supported_useradd_options.sort{ |a,b| a[0] <=> b[0] }.each do |attribute, option| + supported_useradd_options.sort { |a, b| a[0] <=> b[0] }.each do |attribute, option| allow(@new_resource).to receive(attribute).and_return("hola") combined_opts << option << "hola" end @@ -103,8 +102,8 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option describe "when the resource has a different home directory and supports home directory management" do before do allow(@new_resource).to receive(:home).and_return("/wowaweea") - allow(@new_resource).to receive(:supports).and_return({:manage_home => true, - :non_unique => false}) + allow(@new_resource).to receive(:supports).and_return({ :manage_home => true, + :non_unique => false }) end it "should set -m -d /homedir" do @@ -128,8 +127,8 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option describe "when the resource supports non_unique ids" do before do - allow(@new_resource).to receive(:supports).and_return({:manage_home => false, - :non_unique => true}) + allow(@new_resource).to receive(:supports).and_return({ :manage_home => false, + :non_unique => true }) end it "should set -m -o" do @@ -161,7 +160,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option it "runs useradd with the computed command options" do command = ["useradd", - "-c", "Adam Jacob", + "-c", "Adam Jacob", "-g", "23" ] command.concat(["-p", "abracadabra"]) if supported_useradd_options.key?("password") command.concat([ "-s", "/usr/bin/zsh", @@ -174,7 +173,6 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option end describe "and home is not specified for new system user resource" do - before do provider.new_resource.system true # there is no public API to set attribute's value to nil @@ -193,9 +191,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option expect(provider).to receive(:shell_out!).with(*command).and_return(true) provider.create_user end - end - end describe "when managing a user" do @@ -239,7 +235,6 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option end describe "when removing a user" do - it "should run userdel with the new resources user name" do expect(provider).to receive(:shell_out!).with("userdel", @new_resource.username).and_return(true) provider.remove_user @@ -247,14 +242,14 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option it "should run userdel with the new resources user name and -r if manage_home is true" do @new_resource.supports({ :manage_home => true, - :non_unique => false}) + :non_unique => false }) expect(provider).to receive(:shell_out!).with("userdel", "-r", @new_resource.username).and_return(true) provider.remove_user end it "should run userdel with the new resources user name if non_unique is true" do @new_resource.supports({ :manage_home => false, - :non_unique => true}) + :non_unique => true }) expect(provider).to receive(:shell_out!).with("userdel", @new_resource.username).and_return(true) provider.remove_user end @@ -285,7 +280,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option it "should return false if status begins with P" do expect(provider).to receive(:shell_out!). - with("passwd", "-S", @new_resource.username, {:returns=>[0, 1]}). + with("passwd", "-S", @new_resource.username, { :returns => [0, 1] }). and_return(passwd_s_status) expect(provider.check_lock).to eql(false) end @@ -293,7 +288,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option it "should return false if status begins with N" do @stdout = "root N" expect(provider).to receive(:shell_out!). - with("passwd", "-S", @new_resource.username, {:returns=>[0, 1]}). + with("passwd", "-S", @new_resource.username, { :returns => [0, 1] }). and_return(passwd_s_status) expect(provider.check_lock).to eql(false) end @@ -301,7 +296,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option it "should return true if status begins with L" do @stdout = "root L" expect(provider).to receive(:shell_out!). - with("passwd", "-S", @new_resource.username, {:returns=>[0, 1]}). + with("passwd", "-S", @new_resource.username, { :returns => [0, 1] }). and_return(passwd_s_status) expect(provider.check_lock).to eql(true) end @@ -309,7 +304,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option it "should raise a Chef::Exceptions::User if passwd -S fails on anything other than redhat/centos" do @node.automatic_attrs[:platform] = "ubuntu" expect(provider).to receive(:shell_out!). - with("passwd", "-S", @new_resource.username, {:returns=>[0, 1]}). + with("passwd", "-S", @new_resource.username, { :returns => [0, 1] }). and_return(passwd_s_status) expect(passwd_s_status).to receive(:exitstatus).and_return(1) expect { provider.check_lock }.to raise_error(Chef::Exceptions::User) @@ -320,7 +315,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option @node.automatic_attrs[:platform] = os expect(passwd_s_status).to receive(:exitstatus).and_return(1) expect(provider).to receive(:shell_out!). - with("passwd", "-S", @new_resource.username, {:returns=>[0, 1]}). + with("passwd", "-S", @new_resource.username, { :returns => [0, 1] }). and_return(passwd_s_status) rpm_status = double("Mixlib::ShellOut command", :exitstatus => 0, :stdout => "passwd-0.73-1\n", :stderr => "") expect(provider).to receive(:shell_out!).with("rpm -q passwd").and_return(rpm_status) @@ -331,7 +326,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option @node.automatic_attrs[:platform] = os expect(passwd_s_status).to receive(:exitstatus).and_return(1) expect(provider).to receive(:shell_out!). - with("passwd", "-S", @new_resource.username, {:returns=>[0, 1]}). + with("passwd", "-S", @new_resource.username, { :returns => [0, 1] }). and_return(passwd_s_status) rpm_status = double("Mixlib::ShellOut command", :exitstatus => 0, :stdout => "passwd-0.73-2\n", :stderr => "") expect(provider).to receive(:shell_out!).with("rpm -q passwd").and_return(rpm_status) @@ -349,7 +344,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option before do passwd_status = double("Mixlib::ShellOut command", :exitstatus => 0, :stdout => "", :stderr => "passwd: user 'chef-test' does not exist\n") expect(provider).to receive(:shell_out!). - with("passwd", "-S", @new_resource.username, {:returns=>[0, 1]}). + with("passwd", "-S", @new_resource.username, { :returns => [0, 1] }). and_return(passwd_status) Chef::Config[:why_run] = true end @@ -431,4 +426,3 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option end end end - diff --git a/spec/support/shared/unit/resource/static_provider_resolution.rb b/spec/support/shared/unit/resource/static_provider_resolution.rb index 56ed49e00d..4ae5d4576f 100644 --- a/spec/support/shared/unit/resource/static_provider_resolution.rb +++ b/spec/support/shared/unit/resource/static_provider_resolution.rb @@ -16,8 +16,6 @@ # limitations under the License. # - - # # This is for typical "static" provider resolution which maps resources onto # providers based only on the node data. Its not really 'static' because it @@ -25,7 +23,7 @@ # a static mapping for the node (unlike the service resource which is # complicated). # -def static_provider_resolution(opts={}) +def static_provider_resolution(opts = {}) action = opts[:action] provider_class = opts[:provider] resource_class = opts[:resource] @@ -63,4 +61,3 @@ def static_provider_resolution(opts={}) end end end - diff --git a/spec/support/shared/unit/script_resource.rb b/spec/support/shared/unit/script_resource.rb index ba33d69a59..a3f0663f54 100644 --- a/spec/support/shared/unit/script_resource.rb +++ b/spec/support/shared/unit/script_resource.rb @@ -20,7 +20,6 @@ require "spec_helper" shared_examples_for "a script resource" do - it "should create a new Chef::Resource::Script" do expect(script_resource).to be_a_kind_of(Chef::Resource) expect(script_resource).to be_a_kind_of(Chef::Resource::Script) @@ -74,7 +73,7 @@ shared_examples_for "a script resource" do it "inherits exactly the :cwd, :environment, :group, :path, :user, and :umask attributes from a parent resource class" do inherited_difference = Chef::Resource::Script.guard_inherited_attributes - - [:cwd, :environment, :group, :path, :user, :umask ] + [:cwd, :environment, :group, :path, :user, :umask ] expect(inherited_difference).to eq([]) end diff --git a/spec/support/shared/unit/user_and_client_shared.rb b/spec/support/shared/unit/user_and_client_shared.rb index c8208c149b..47f00ceb81 100644 --- a/spec/support/shared/unit/user_and_client_shared.rb +++ b/spec/support/shared/unit/user_and_client_shared.rb @@ -17,9 +17,7 @@ # shared_examples_for "user or client create" do - context "when server API V1 is valid on the Chef Server receiving the request" do - it "creates a new object via the API" do expect(rest_v1).to receive(:post).with(url, payload).and_return({}) object.create @@ -27,12 +25,11 @@ shared_examples_for "user or client create" do it "creates a new object via the API with a public_key when it exists" do object.public_key "some_public_key" - expect(rest_v1).to receive(:post).with(url, payload.merge({:public_key => "some_public_key"})).and_return({}) + expect(rest_v1).to receive(:post).with(url, payload.merge({ :public_key => "some_public_key" })).and_return({}) object.create end context "raise error when create_key and public_key are both set" do - before do object.public_key "key" object.create_key true @@ -49,7 +46,7 @@ shared_examples_for "user or client create" do end it "creates a new object via the API with create_key" do - expect(rest_v1).to receive(:post).with(url, payload.merge({:create_key => true})).and_return({}) + expect(rest_v1).to receive(:post).with(url, payload.merge({ :create_key => true })).and_return({}) object.create end end @@ -86,11 +83,9 @@ shared_examples_for "user or client create" do end end end # when chef_key is returned by the server - end # when server API V1 is valid on the Chef Server receiving the request context "when server API V1 is not valid on the Chef Server receiving the request" do - context "when the server supports API V0" do before do allow(object).to receive(:server_client_api_version_intersection).and_return([0]) @@ -104,12 +99,9 @@ shared_examples_for "user or client create" do it "creates a new object via the API with a public_key when it exists" do object.public_key "some_public_key" - expect(rest_v0).to receive(:post).with(url, payload.merge({:public_key => "some_public_key"})).and_return({}) + expect(rest_v0).to receive(:post).with(url, payload.merge({ :public_key => "some_public_key" })).and_return({}) object.create end - end # when the server supports API V0 end # when server API V1 is not valid on the Chef Server receiving the request - end # user or client create - diff --git a/spec/support/shared/unit/windows_script_resource.rb b/spec/support/shared/unit/windows_script_resource.rb index 1dcbae76aa..cba7470f7e 100644 --- a/spec/support/shared/unit/windows_script_resource.rb +++ b/spec/support/shared/unit/windows_script_resource.rb @@ -31,7 +31,6 @@ shared_examples_for "a Windows script resource" do run_context = Chef::RunContext.new(node, nil, nil) @resource = resource_instance - end it "should be a kind of Chef::Resource::WindowsScript" do @@ -76,6 +75,4 @@ shared_examples_for "a Windows script resource" do end it_should_behave_like "a script resource" end - end - diff --git a/spec/tiny_server.rb b/spec/tiny_server.rb index 7a58328224..2e47f1ae2d 100644 --- a/spec/tiny_server.rb +++ b/spec/tiny_server.rb @@ -26,12 +26,10 @@ require "open-uri" require "chef/config" module TinyServer - class Server < Rack::Server - attr_writer :app - def self.setup(options=nil, &block) + def self.setup(options = nil, &block) tiny_app = new(options) app_code = Rack::Builder.new(&block).to_app tiny_app.app = app_code @@ -44,7 +42,6 @@ module TinyServer end class Manager - # 5 == debug, 3 == warning LOGGER = WEBrick::Log.new(STDOUT, 3) DEFAULT_OPTIONS = { @@ -56,7 +53,7 @@ module TinyServer :AccessLog => [] # Remove this option to enable the access log when debugging. } - def initialize(options=nil) + def initialize(options = nil) @options = options ? DEFAULT_OPTIONS.merge(options) : DEFAULT_OPTIONS @creator = caller.first end @@ -110,7 +107,6 @@ module TinyServer @server_thread.join @server_thread = nil end - end class API @@ -128,22 +124,22 @@ module TinyServer end def clear - @routes = {GET => [], PUT => [], POST => [], DELETE => []} + @routes = { GET => [], PUT => [], POST => [], DELETE => [] } end - def get(path, response_code, data=nil, headers=nil, &block) + def get(path, response_code, data = nil, headers = nil, &block) @routes[GET] << Route.new(path, Response.new(response_code, data, headers, &block)) end - def put(path, response_code, data=nil, headers=nil, &block) + def put(path, response_code, data = nil, headers = nil, &block) @routes[PUT] << Route.new(path, Response.new(response_code, data, headers, &block)) end - def post(path, response_code, data=nil, headers=nil, &block) + def post(path, response_code, data = nil, headers = nil, &block) @routes[POST] << Route.new(path, Response.new(response_code, data, headers, &block)) end - def delete(path, response_code, data=nil, headers=nil, &block) + def delete(path, response_code, data = nil, headers = nil, &block) @routes[DELETE] << Route.new(path, Response.new(response_code, data, headers, &block)) end @@ -151,11 +147,11 @@ module TinyServer if response = response_for_request(env) response.call else - debug_info = {:message => "no data matches the request for #{env['REQUEST_URI']}", - :available_routes => @routes, :request => env} + debug_info = { :message => "no data matches the request for #{env['REQUEST_URI']}", + :available_routes => @routes, :request => env } # Uncomment me for glorious debugging # pp :not_found => debug_info - [404, {"Content-Type" => "application/json"}, [ Chef::JSONCompat.to_json(debug_info) ]] + [404, { "Content-Type" => "application/json" }, [ Chef::JSONCompat.to_json(debug_info) ]] end end @@ -181,13 +177,12 @@ module TinyServer def to_s "#{@path_spec} => (#{@response})" end - end class Response - HEADERS = {"Content-Type" => "application/json"} + HEADERS = { "Content-Type" => "application/json" } - def initialize(response_code=200, data=nil, headers=nil, &block) + def initialize(response_code = 200, data = nil, headers = nil, &block) @response_code, @data = response_code, data @response_headers = headers ? HEADERS.merge(headers) : HEADERS @block = block_given? ? block : nil @@ -199,9 +194,7 @@ module TinyServer end def to_s - "#{@response_code} => #{(@data|| @block)}" + "#{@response_code} => #{(@data || @block)}" end - end - end diff --git a/spec/unit/api_client/registration_spec.rb b/spec/unit/api_client/registration_spec.rb index f41c5d8653..08dc6ed09f 100644 --- a/spec/unit/api_client/registration_spec.rb +++ b/spec/unit/api_client/registration_spec.rb @@ -22,7 +22,6 @@ require "tempfile" require "chef/api_client/registration" describe Chef::ApiClient::Registration do - let(:key_location) do make_tmpname("client-registration-key") end @@ -32,7 +31,7 @@ describe Chef::ApiClient::Registration do subject(:registration) { Chef::ApiClient::Registration.new(client_name, key_location) } let(:private_key_data) do - File.open(Chef::Config[:validation_key], "r") {|f| f.read.chomp } + File.open(Chef::Config[:validation_key], "r") { |f| f.read.chomp } end let(:http_mock) { double("Chef::ServerAPI mock") } @@ -67,7 +66,6 @@ describe Chef::ApiClient::Registration do let(:generated_private_key) { OpenSSL::PKey::RSA.new(generated_private_key_pem) } let(:generated_public_key) { generated_private_key.public_key } - let(:create_with_pkey_response) do { "uri" => "", @@ -78,12 +76,12 @@ describe Chef::ApiClient::Registration do end let(:update_with_pkey_response) do - {"name"=>client_name, - "admin"=>false, - "public_key"=> generated_public_key, - "validator"=>false, - "private_key"=>false, - "clientname"=>client_name} + { "name" => client_name, + "admin" => false, + "public_key" => generated_public_key, + "validator" => false, + "private_key" => false, + "clientname" => client_name } end before do @@ -147,7 +145,6 @@ describe Chef::ApiClient::Registration do end context "when local key generation is disabled" do - let(:expected_post_data) do { :name => client_name, :admin => false } end @@ -217,7 +214,7 @@ describe Chef::ApiClient::Registration do context "when the client key location is a symlink" do it "does not follow the symlink", :unix_only do - expected_flags = (File::CREAT|File::TRUNC|File::RDWR) + expected_flags = (File::CREAT | File::TRUNC | File::RDWR) if defined?(File::NOFOLLOW) expected_flags |= File::NOFOLLOW @@ -232,14 +229,13 @@ describe Chef::ApiClient::Registration do end it "follows the symlink", :unix_only do - expect(registration.file_flags).to eq(File::CREAT|File::TRUNC|File::RDWR) + expect(registration.file_flags).to eq(File::CREAT | File::TRUNC | File::RDWR) end end end end describe "when registering a client" do - before do allow(registration).to receive(:http_api).and_return(http_mock) end @@ -271,9 +267,7 @@ describe Chef::ApiClient::Registration do expect(http_mock).to receive(:post).exactly(6).times.and_raise(exception_500) - expect {registration.run}.to raise_error(Net::HTTPFatalError) + expect { registration.run }.to raise_error(Net::HTTPFatalError) end - end - end diff --git a/spec/unit/api_client_spec.rb b/spec/unit/api_client_spec.rb index 398181bfd0..c5feec3a4e 100644 --- a/spec/unit/api_client_spec.rb +++ b/spec/unit/api_client_spec.rb @@ -82,7 +82,6 @@ describe Chef::ApiClient do expect { @client.public_key Hash.new }.to raise_error(ArgumentError) end - it "has a private key attribute" do @client.private_key("super private") expect(@client.private_key).to eq("super private") @@ -215,13 +214,13 @@ describe Chef::ApiClient do before(:each) do client = { - "name" => "black", - "clientname" => "black", - "public_key" => "crowes", - "private_key" => "monkeypants", - "admin" => true, - "validator" => true, - "json_class" => "Chef::ApiClient", + "name" => "black", + "clientname" => "black", + "public_key" => "crowes", + "private_key" => "monkeypants", + "admin" => true, + "validator" => true, + "json_class" => "Chef::ApiClient", } @http_client = double("Chef::ServerAPI mock") allow(Chef::ServerAPI).to receive(:new).and_return(@http_client) @@ -252,7 +251,6 @@ describe Chef::ApiClient do it "includes the private key if present" do expect(@client.private_key).to eq("monkeypants") end - end describe "with correctly configured API credentials" do @@ -267,12 +265,10 @@ describe Chef::ApiClient do end let :private_key_data do - File.open(Chef::Config[:client_key], "r") {|f| f.read.chomp } + File.open(Chef::Config[:client_key], "r") { |f| f.read.chomp } end - end - describe "when requesting a new key" do before do @http_client = double("Chef::ServerAPI mock") @@ -299,7 +295,6 @@ describe Chef::ApiClient do expect(@http_client).to receive(:get).with("clients/lost-my-key").and_return(@api_client_without_key) end - context "and the client exists on a Chef 11-like server" do before do @api_client_with_key = Chef::ApiClient.new @@ -322,7 +317,7 @@ describe Chef::ApiClient do context "and the client exists on a Chef 10-like server" do before do - @api_client_with_key = {"name" => "lost-my-key", "private_key" => "the new private key"} + @api_client_with_key = { "name" => "lost-my-key", "private_key" => "the new private key" } expect(@http_client).to receive(:put). with("clients/lost-my-key", :name => "lost-my-key", :admin => false, :validator => false, :private_key => true). and_return(@api_client_with_key) @@ -338,7 +333,6 @@ describe Chef::ApiClient do expect(response.validator).to be_falsey end end - end end end diff --git a/spec/unit/api_client_v1_spec.rb b/spec/unit/api_client_v1_spec.rb index 6fb5ae40f2..920e522c6b 100644 --- a/spec/unit/api_client_v1_spec.rb +++ b/spec/unit/api_client_v1_spec.rb @@ -91,7 +91,6 @@ describe Chef::ApiClientV1 do expect { @client.public_key Hash.new }.to raise_error(ArgumentError) end - it "has a private key attribute" do @client.private_key("super private") expect(@client.private_key).to eq("super private") @@ -284,7 +283,6 @@ describe Chef::ApiClientV1 do it "includes the private key if present" do expect(@client.private_key).to eq("monkeypants") end - end describe "with correctly configured API credentials" do @@ -299,12 +297,10 @@ describe Chef::ApiClientV1 do end let :private_key_data do - File.open(Chef::Config[:client_key], "r") {|f| f.read.chomp } + File.open(Chef::Config[:client_key], "r") { |f| f.read.chomp } end - end - describe "when requesting a new key" do before do @http_client = double("Chef::ServerAPI mock") @@ -328,7 +324,7 @@ describe Chef::ApiClientV1 do describe "Versioned API Interactions" do let(:response_406) { OpenStruct.new(:code => "406") } let(:exception_406) { Net::HTTPServerException.new("406 Not Acceptable", response_406) } - let(:payload) { + let(:payload) { { :name => "some_name", :validator => true, @@ -346,7 +342,6 @@ describe Chef::ApiClientV1 do end describe "create" do - # from spec/support/shared/unit/user_and_client_shared.rb it_should_behave_like "user or client create" do let(:object) { @client } @@ -365,12 +360,10 @@ describe Chef::ApiClientV1 do let(:rest_v1) { @client.chef_rest_v1 } end end - end # create describe "update" do context "when a valid client is defined" do - shared_examples_for "client updating" do it "updates the client" do expect(rest). to receive(:put).with("clients/some_name", payload).and_return(payload) @@ -378,7 +371,6 @@ describe Chef::ApiClientV1 do end context "when only the name field exists" do - before do # needed since there is no way to set to nil via code @client.instance_variable_set(:@validator, nil) @@ -391,19 +383,16 @@ describe Chef::ApiClientV1 do end it "updates the client with only the name" do - expect(rest). to receive(:put).with("clients/some_name", {:name => "some_name"}).and_return({:name => "some_name"}) + expect(rest). to receive(:put).with("clients/some_name", { :name => "some_name" }).and_return({ :name => "some_name" }) @client.update end end - end context "when API V1 is supported by the server" do - it_should_behave_like "client updating" do let(:rest) { @client.chef_rest_v1 } end - end # when API V1 is supported by the server context "when API V1 is not supported by the server" do @@ -418,7 +407,6 @@ describe Chef::ApiClientV1 do end # when no version is supported context "when API V0 is supported" do - before do allow(@client.chef_rest_v1).to receive(:put).and_raise(exception_406) allow(@client).to receive(:server_client_api_version_intersection).and_return([0]) @@ -427,9 +415,7 @@ describe Chef::ApiClientV1 do it_should_behave_like "client updating" do let(:rest) { @client.chef_rest_v0 } end - end - end # when API V1 is not supported by the server end # when a valid client is defined end # update @@ -439,7 +425,7 @@ describe Chef::ApiClientV1 do describe "reregister" do context "when server API V0 is valid on the Chef Server receiving the request" do it "creates a new object via the API" do - expect(@client.chef_rest_v0).to receive(:put).with("clients/#{@client.name}", payload.merge({:private_key => true})).and_return({}) + expect(@client.chef_rest_v0).to receive(:put).with("clients/#{@client.name}", payload.merge({ :private_key => true })).and_return({}) @client.reregister end end # when server API V0 is valid on the Chef Server receiving the request @@ -452,6 +438,5 @@ describe Chef::ApiClientV1 do end end # when server API V0 is not supported by the Chef Server end # reregister - end end diff --git a/spec/unit/application/apply_spec.rb b/spec/unit/application/apply_spec.rb index 61d4150950..32d5cc1b43 100644 --- a/spec/unit/application/apply_spec.rb +++ b/spec/unit/application/apply_spec.rb @@ -18,7 +18,6 @@ require "spec_helper" describe Chef::Application::Apply do - before do @app = Chef::Application::Apply.new allow(@app).to receive(:configure_logging).and_return(true) @@ -89,10 +88,9 @@ describe Chef::Application::Apply do expect(Chef::Log).to receive(:debug).with(/^No recipe file provided/) expect { @app.run }.to raise_error(SystemExit) { |e| expect(e.status).to eq(1) } end - end describe "when the json_attribs configuration option is specified" do - let(:json_attribs) { {"a" => "b"} } + let(:json_attribs) { { "a" => "b" } } let(:config_fetcher) { double(Chef::ConfigFetcher, :fetch_json => json_attribs) } let(:json_source) { "https://foo.com/foo.json" } diff --git a/spec/unit/application/client_spec.rb b/spec/unit/application/client_spec.rb index dc3add6fd9..679425abbd 100644 --- a/spec/unit/application/client_spec.rb +++ b/spec/unit/application/client_spec.rb @@ -49,7 +49,6 @@ describe Chef::Application::Client, "reconfigure" do end context "when given a named_run_list" do - before do ARGV.replace( %w{ --named-run-list arglebargle-example } ) app.reconfigure @@ -58,7 +57,6 @@ describe Chef::Application::Client, "reconfigure" do it "sets named_run_list in Chef::Config" do expect(Chef::Config[:named_run_list]).to eq("arglebargle-example") end - end end @@ -141,22 +139,18 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config app.reconfigure expect(Chef::Config.interval).to be_nil end - end describe "when --no-listen is set" do - it "configures listen = false" do app.config[:listen] = false app.reconfigure expect(Chef::Config[:listen]).to eq(false) end - end describe "when the json_attribs configuration option is specified" do - - let(:json_attribs) { {"a" => "b"} } + let(:json_attribs) { { "a" => "b" } } let(:config_fetcher) { double(Chef::ConfigFetcher, :fetch_json => json_attribs) } let(:json_source) { "https://foo.com/foo.json" } @@ -243,7 +237,6 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config end describe "when both the pidfile and lockfile opts are set to the same value" do - before do Chef::Config[:pid_file] = "/path/to/file" Chef::Config[:lockfile] = "/path/to/file" @@ -255,7 +248,6 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config end end - describe Chef::Application::Client, "setup_application" do before do @app = Chef::Application::Client.new @@ -387,7 +379,6 @@ describe Chef::Application::Client, "run_application", :unix_only do # Chef::Log.level = :debug allow(@app).to receive(:run_chef_client) do - run_count += 1 if run_count > 3 exit 0 diff --git a/spec/unit/application/knife_spec.rb b/spec/unit/application/knife_spec.rb index ba02e44481..36ae23e608 100644 --- a/spec/unit/application/knife_spec.rb +++ b/spec/unit/application/knife_spec.rb @@ -182,7 +182,7 @@ describe Chef::Application::Knife do end it "should load the environment from the config file" do - config_file = File.join(CHEF_SPEC_DATA,"environment-config.rb") + config_file = File.join(CHEF_SPEC_DATA, "environment-config.rb") with_argv(*%W{noop knife command -c #{config_file}}) do expect(@knife).to receive(:exit).with(0) @knife.run @@ -199,7 +199,7 @@ describe Chef::Application::Knife do end it "should override the config file environment with the CLI environment" do - config_file = File.join(CHEF_SPEC_DATA,"environment-config.rb") + config_file = File.join(CHEF_SPEC_DATA, "environment-config.rb") with_argv(*%W{noop knife command -c #{config_file} -E override}) do expect(@knife).to receive(:exit).with(0) @knife.run @@ -208,7 +208,7 @@ describe Chef::Application::Knife do end it "should override the config file environment with the CLI environment regardless of order" do - config_file = File.join(CHEF_SPEC_DATA,"environment-config.rb") + config_file = File.join(CHEF_SPEC_DATA, "environment-config.rb") with_argv(*%W{noop knife command -E override -c #{config_file}}) do expect(@knife).to receive(:exit).with(0) @knife.run @@ -225,5 +225,4 @@ describe Chef::Application::Knife do end end end - end diff --git a/spec/unit/application/solo_spec.rb b/spec/unit/application/solo_spec.rb index 0f95e9d0d6..22c61fcbe9 100644 --- a/spec/unit/application/solo_spec.rb +++ b/spec/unit/application/solo_spec.rb @@ -18,7 +18,6 @@ require "spec_helper" describe Chef::Application::Solo do - let(:app) { Chef::Application::Solo.new } before do @@ -87,7 +86,7 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config end describe "when the json_attribs configuration option is specified" do - let(:json_attribs) { {"a" => "b"} } + let(:json_attribs) { { "a" => "b" } } let(:config_fetcher) { double(Chef::ConfigFetcher, :fetch_json => json_attribs) } let(:json_source) { "https://foo.com/foo.json" } @@ -107,7 +106,7 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config let(:tarfile) { StringIO.new("remote_tarball_content") } let(:target_file) { StringIO.new } let(:shellout) { double(run_command: nil, error!: nil, stdout: "") } - + before do Chef::Config[:cookbook_path] = "#{Dir.tmpdir}/chef-solo/cookbooks" Chef::Config[:recipe_url] = "http://junglist.gen.nz/recipes.tgz" @@ -137,14 +136,14 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config end it "should untar the target file to the parent of the cookbook path" do - expect(Mixlib::ShellOut).to receive(:new).with("tar zxvf #{Dir.tmpdir}/chef-solo/recipes.tgz -C #{Dir.tmpdir}/chef-solo") + expect(Mixlib::ShellOut).to receive(:new).with("tar zxvf #{Dir.tmpdir}/chef-solo/recipes.tgz -C #{Dir.tmpdir}/chef-solo") app.reconfigure end end end describe "when the json_attribs and recipe_url configuration options are both specified" do - let(:json_attribs) { {"a" => "b"} } + let(:json_attribs) { { "a" => "b" } } let(:config_fetcher) { double(Chef::ConfigFetcher, :fetch_json => json_attribs) } let(:json_source) { "https://foo.com/foo.json" } @@ -182,5 +181,4 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config app.setup_application end end - end diff --git a/spec/unit/application_spec.rb b/spec/unit/application_spec.rb index 1b91aafe8d..d55403482b 100644 --- a/spec/unit/application_spec.rb +++ b/spec/unit/application_spec.rb @@ -35,7 +35,6 @@ describe Chef::Application do end context "when there are no configuration errors" do - before do expect(Chef::Log).to_not receive(:fatal) expect(Chef::Application).to_not receive(:fatal!) @@ -250,9 +249,7 @@ describe Chef::Application do end end - context "with an invalid log location" do - it "logs a fatal error and exits" do Chef::Config[:log_location] = "/tmp/non-existing-dir/logfile" expect(Chef::Log).to receive(:fatal).at_least(:once) @@ -261,7 +258,6 @@ describe Chef::Application do end end - describe "class method: fatal!" do before do allow(STDERR).to receive(:puts).with("FATAL: blah").and_return(true) @@ -287,7 +283,6 @@ describe Chef::Application do Chef::Application.fatal! "blah" end end - end describe "setup_application" do @@ -347,7 +342,6 @@ describe Chef::Application do end end end - end describe "configuration errors" do diff --git a/spec/unit/audit/audit_event_proxy_spec.rb b/spec/unit/audit/audit_event_proxy_spec.rb index 39fa057cba..4365f1a70f 100644 --- a/spec/unit/audit/audit_event_proxy_spec.rb +++ b/spec/unit/audit/audit_event_proxy_spec.rb @@ -22,7 +22,6 @@ require "spec_helper" require "chef/audit/audit_event_proxy" describe Chef::Audit::AuditEventProxy do - let(:stdout) { StringIO.new } let(:events) { double("Chef::Events") } let(:audit_event_proxy) { Chef::Audit::AuditEventProxy.new(stdout) } @@ -32,14 +31,12 @@ describe Chef::Audit::AuditEventProxy do end describe "#example_group_started" do - let(:description) { "poots" } let(:group) { double("ExampleGroup", :parent_groups => parents, - :description => description) } + :description => description) } let(:notification) { double("Notification", :group => group) } context "when notified from a top-level example group" do - let(:parents) { [double("ExampleGroup")] } it "notifies control_group_started event" do @@ -52,7 +49,6 @@ describe Chef::Audit::AuditEventProxy do end context "when notified from an inner-level example group" do - let(:parents) { [double("ExampleGroup"), double("OuterExampleGroup")] } it "does nothing" do @@ -63,7 +59,6 @@ describe Chef::Audit::AuditEventProxy do end describe "#stop" do - let(:examples) { [] } let(:notification) { double("Notification", :examples => examples) } let(:exception) { nil } @@ -81,7 +76,6 @@ describe Chef::Audit::AuditEventProxy do end context "when an example succeeded" do - let(:examples) { [example] } let(:excpetion) { nil } @@ -99,7 +93,6 @@ describe Chef::Audit::AuditEventProxy do end context "when an example failed" do - let(:examples) { [example] } let(:exception) { double("ExpectationNotMet") } @@ -117,12 +110,11 @@ describe Chef::Audit::AuditEventProxy do end describe "#build_control_from" do - let(:examples) { [example] } let(:example) { double("Example", :metadata => metadata, - :description => example_description, - :full_description => full_description, :exception => nil) } + :description => example_description, + :full_description => full_description, :exception => nil) } let(:metadata) { { @@ -160,7 +152,6 @@ describe Chef::Audit::AuditEventProxy do } shared_examples "built control" do - before do if described_class allow(described_class).to receive(:instance_variable_get). @@ -307,5 +298,4 @@ describe Chef::Audit::AuditEventProxy do end end end - end diff --git a/spec/unit/audit/audit_reporter_spec.rb b/spec/unit/audit/audit_reporter_spec.rb index 28f2f2db45..7910cf57a3 100644 --- a/spec/unit/audit/audit_reporter_spec.rb +++ b/spec/unit/audit/audit_reporter_spec.rb @@ -21,7 +21,6 @@ require "spec_helper" describe Chef::Audit::AuditReporter do - let(:rest) { double("rest") } let(:reporter) { described_class.new(rest) } let(:node) { double("node", :name => "sofreshsoclean") } @@ -29,10 +28,9 @@ describe Chef::Audit::AuditReporter do let(:start_time) { Time.new(2014, 12, 3, 9, 31, 05, "-08:00") } let(:end_time) { Time.new(2014, 12, 3, 9, 36, 14, "-08:00") } let(:run_status) { instance_double(Chef::RunStatus, :node => node, :run_id => run_id, - :start_time => start_time, :end_time => end_time) } + :start_time => start_time, :end_time => end_time) } describe "#audit_phase_start" do - it "notifies audit phase start to debug log" do expect(Chef::Log).to receive(:debug).with(/Audit Reporter starting/) reporter.audit_phase_start(run_status) @@ -50,7 +48,6 @@ describe Chef::Audit::AuditReporter do end describe "#run_completed" do - let(:audit_data) { Chef::Audit::AuditData.new(node.name, run_id) } let(:run_data) { audit_data.to_hash } @@ -84,14 +81,13 @@ describe Chef::Audit::AuditReporter do end context "when audit phase failed" do - let(:audit_error) { double("AuditError", :class => "Chef::Exceptions::AuditError", - :message => "Audit phase failed with error message: derpderpderp", - :backtrace => ["/path/recipe.rb:57", "/path/library.rb:106"]) } + :message => "Audit phase failed with error message: derpderpderp", + :backtrace => ["/path/recipe.rb:57", "/path/library.rb:106"]) } - before do - reporter.instance_variable_set(:@audit_phase_error, audit_error) - end + before do + reporter.instance_variable_set(:@audit_phase_error, audit_error) + end it "reports an error" do reporter.run_completed(node) @@ -103,11 +99,9 @@ Chef::Exceptions::AuditError: Audit phase failed with error message: derpderpder /path/library.rb:106 EOM end - end context "when unable to post to server" do - let(:error) do e = StandardError.new e.set_backtrace(caller) @@ -120,7 +114,6 @@ EOM end context "the error is an http error" do - let(:response) { double("response", :code => code) } before do @@ -131,7 +124,6 @@ EOM end context "when the code is 404" do - let(:code) { "404" } it "logs that the server doesn't support audit reporting" do @@ -141,7 +133,6 @@ EOM end shared_examples "non-404 error code" do - it "saves the error report" do expect(Chef::FileCache).to receive(:store). with("failed-audit-data.json", an_instance_of(String), 0640). @@ -152,7 +143,6 @@ EOM expect(Chef::Log).to receive(:error).with(/Failed to post audit report to server/) reporter.run_completed(node) end - end context "when the code is not 404" do @@ -166,21 +156,17 @@ EOM let(:code) { nil } end end - end context "the error is not an http error" do - it "logs the error" do expect(error).to receive(:respond_to?).with(:response).and_return(false) expect(Chef::Log).to receive(:error).with(/Failed to post audit report to server/) reporter.run_completed(node) end - end context "when reporting url fatals are enabled" do - before do allow(Chef::Config).to receive(:[]). with(:enable_reporting_url_fatals). @@ -191,15 +177,13 @@ EOM expect(error).to receive(:respond_to?).with(:response).and_return(false) allow(Chef::Log).to receive(:error).and_return(true) expect(Chef::Log).to receive(:error).with(/Reporting fatals enabled. Aborting run./) - expect{ reporter.run_completed(node) }.to raise_error(error) + expect { reporter.run_completed(node) }.to raise_error(error) end - end end end context "when auditing is not enabled" do - before do allow(Chef::Log).to receive(:debug) end @@ -209,11 +193,9 @@ EOM expect(Chef::Log).to receive(:debug).with("Audit Reports are disabled. Skipping sending reports.") reporter.run_completed(node) end - end context "when the run fails before audits" do - before do allow(Chef::Log).to receive(:debug) end @@ -224,22 +206,20 @@ EOM expect(Chef::Log).to receive(:debug).with("Run failed before audit mode was initialized, not sending audit report to server") reporter.run_completed(node) end - end end describe "#run_failed" do - let(:audit_data) { Chef::Audit::AuditData.new(node.name, run_id) } let(:run_data) { audit_data.to_hash } let(:audit_error) { double("AuditError", :class => "Chef::Exceptions::AuditError", - :message => "Audit phase failed with error message: derpderpderp", - :backtrace => ["/path/recipe.rb:57", "/path/library.rb:106"]) } + :message => "Audit phase failed with error message: derpderpderp", + :backtrace => ["/path/recipe.rb:57", "/path/library.rb:106"]) } let(:run_error) { double("RunError", :class => "Chef::Exceptions::RunError", - :message => "This error shouldn't be reported.", - :backtrace => ["fix it", "fix it", "fix it"]) } + :message => "This error shouldn't be reported.", + :backtrace => ["fix it", "fix it", "fix it"]) } before do allow(reporter).to receive(:auditing_enabled?).and_return(true) @@ -275,7 +255,6 @@ EOM end shared_context "audit data" do - let(:control_group_foo) { instance_double(Chef::Audit::ControlGroupData, :metadata => double("foo metadata")) } let(:control_group_bar) { instance_double(Chef::Audit::ControlGroupData, @@ -366,7 +345,7 @@ EOM context "when a control group with the same name has been seen" do it "raises an exception" do expect(ordered_control_groups).to receive(:has_key?).with(name).and_return(true) - expect{ reporter.control_group_started(name) }.to raise_error(Chef::Exceptions::AuditControlGroupDuplicate) + expect { reporter.control_group_started(name) }.to raise_error(Chef::Exceptions::AuditControlGroupDuplicate) end end end @@ -399,7 +378,6 @@ EOM describe "#auditing_enabled?" do shared_examples "enabled?" do |true_or_false| - it "returns #{true_or_false}" do expect(Chef::Config).to receive(:[]). with(:audit_mode). @@ -426,5 +404,4 @@ EOM end end end - end diff --git a/spec/unit/audit/control_group_data_spec.rb b/spec/unit/audit/control_group_data_spec.rb index a18e33a40a..8e6f62b8fc 100644 --- a/spec/unit/audit/control_group_data_spec.rb +++ b/spec/unit/audit/control_group_data_spec.rb @@ -22,7 +22,6 @@ require "spec_helper" require "securerandom" describe Chef::Audit::AuditData do - let(:node_name) { "noodles" } let(:run_id) { SecureRandom.uuid } let(:audit_data) { described_class.new(node_name, run_id) } @@ -36,11 +35,9 @@ describe Chef::Audit::AuditData do audit_data.add_control_group(control_group_1) expect(audit_data.control_groups).to include(control_group_1) end - end context "when adding additional control groups" do - before do audit_data.add_control_group(control_group_1) end @@ -58,7 +55,6 @@ describe Chef::Audit::AuditData do end describe "#to_hash" do - let(:audit_data_hash) { audit_data.to_hash } it "returns a hash" do @@ -71,9 +67,8 @@ describe Chef::Audit::AuditData do end describe ":control_groups" do - - let(:control_hash_1) { {:name => "control group 1"} } - let(:control_hash_2) { {:name => "control group 2"} } + let(:control_hash_1) { { :name => "control group 1" } } + let(:control_hash_2) { { :name => "control group 2" } } let(:control_groups) { audit_data_hash[:control_groups] } @@ -84,7 +79,6 @@ describe Chef::Audit::AuditData do end context "with one control group added" do - before do allow(audit_data).to receive(:control_groups).and_return([control_group_1]) end @@ -97,7 +91,6 @@ describe Chef::Audit::AuditData do end context "with multiple control groups added" do - before do allow(audit_data).to receive(:control_groups).and_return([control_group_1, control_group_2]) end @@ -115,7 +108,6 @@ describe Chef::Audit::AuditData do end describe Chef::Audit::ControlData do - let(:name) { "ramen" } let(:resource_type) { double("Service") } let(:resource_name) { "mysql" } @@ -123,12 +115,10 @@ describe Chef::Audit::ControlData do let(:line_number) { 27 } let(:control_data) { described_class.new(name: name, - resource_type: resource_type, resource_name: resource_name, - context: context, line_number: line_number) } - + resource_type: resource_type, resource_name: resource_name, + context: context, line_number: line_number) } describe "#to_hash" do - let(:control_data_hash) { control_data.to_hash } it "returns a hash" do @@ -141,15 +131,12 @@ describe Chef::Audit::ControlData do end context "when context is nil" do - it "sets :context to an empty array" do expect(control_data_hash[:context]).to eq [] end - end context "when context is non-nil" do - let(:context) { ["outer"] } it "sets :context to its value" do @@ -160,12 +147,10 @@ describe Chef::Audit::ControlData do end describe Chef::Audit::ControlGroupData do - let(:name) { "balloon" } let(:control_group_data) { described_class.new(name) } shared_context "control data" do - let(:name) { "" } let(:resource_type) { nil } let(:resource_name) { nil } @@ -181,21 +166,20 @@ describe Chef::Audit::ControlGroupData do :line_number => line_number, } } - end shared_context "control" do include_context "control data" let(:control) { Chef::Audit::ControlData.new(name: name, - resource_type: resource_type, resource_name: resource_name, - context: context, line_number: line_number) } + resource_type: resource_type, resource_name: resource_name, + context: context, line_number: line_number) } before do allow(Chef::Audit::ControlData).to receive(:new). with(name: name, resource_type: resource_type, - resource_name: resource_name, context: context, - line_number: line_number). + resource_name: resource_name, context: context, + line_number: line_number). and_return(control) end end @@ -284,7 +268,6 @@ describe Chef::Audit::ControlGroupData do end context "when details are not provided" do - let(:details) { nil } it "does not save details to the control" do @@ -296,7 +279,6 @@ describe Chef::Audit::ControlGroupData do end context "when details are provided" do - let(:details) { "yep that didn't work" } it "saves details to the control" do @@ -342,7 +324,6 @@ describe Chef::Audit::ControlGroupData do context "when one audit fails" do shared_examples "mixed audit results" do include_examples "multiple audits", "failure" do - let(:audit_results) { [] } let(:num_success) { audit_results.count("success") } let(:num_failure) { 1 } @@ -385,7 +366,6 @@ describe Chef::Audit::ControlGroupData do end describe "#to_hash" do - let(:control_group_data_hash) { control_group_data.to_hash } it "returns a hash" do @@ -399,7 +379,6 @@ describe Chef::Audit::ControlGroupData do end describe ":controls" do - let(:control_group_controls) { control_group_data_hash[:controls] } context "with no controls added" do @@ -428,14 +407,12 @@ describe Chef::Audit::ControlGroupData do control_group_data.to_hash expect(control_hash).to have_key(:sequence_number) end - end context "with multiple controls added" do - - let(:control_hash_1) { {:line_number => 27} } - let(:control_hash_2) { {:line_number => 13} } - let(:control_hash_3) { {:line_number => 35} } + let(:control_hash_1) { { :line_number => 27 } } + let(:control_hash_2) { { :line_number => 13 } } + let(:control_hash_3) { { :line_number => 35 } } let(:control_1) { double("control 1", :line_number => control_hash_1[:line_number], @@ -474,5 +451,4 @@ describe Chef::Audit::ControlGroupData do end end end - end diff --git a/spec/unit/audit/logger_spec.rb b/spec/unit/audit/logger_spec.rb index 51a32d906e..fccb55ee8e 100644 --- a/spec/unit/audit/logger_spec.rb +++ b/spec/unit/audit/logger_spec.rb @@ -18,7 +18,6 @@ require "spec_helper" describe Chef::Audit::Logger do - before(:each) do Chef::Audit::Logger.instance_variable_set(:@buffer, nil) end @@ -38,5 +37,4 @@ describe Chef::Audit::Logger do it "calling it before @buffer is set returns an empty string" do expect(Chef::Audit::Logger.read_buffer).to eq("") end - end diff --git a/spec/unit/audit/runner_spec.rb b/spec/unit/audit/runner_spec.rb index 70fff6faf3..86bde7a502 100644 --- a/spec/unit/audit/runner_spec.rb +++ b/spec/unit/audit/runner_spec.rb @@ -24,7 +24,6 @@ require "chef/audit/rspec_formatter" require "rspec/support/spec/in_sub_process" require "rspec/support/spec/stderr_splitter" - describe Chef::Audit::Runner do include RSpec::Support::InSubProcess @@ -52,7 +51,6 @@ describe Chef::Audit::Runner do end context "during #run" do - describe "#setup" do let(:log_location) { File.join(Dir.tmpdir, "audit_log") } let(:color) { false } @@ -100,8 +98,8 @@ describe Chef::Audit::Runner do end context "audits exist" do - let(:audits) { {"audit_name" => group} } - let(:group) {Struct.new(:args, :block).new(["group_name"], nil)} + let(:audits) { { "audit_name" => group } } + let(:group) { Struct.new(:args, :block).new(["group_name"], nil) } it "sends the audits to the world" do runner.send(:register_control_groups) @@ -141,5 +139,4 @@ describe Chef::Audit::Runner do expect(runner.num_total).to eq(0) end end - end diff --git a/spec/unit/chef_fs/config_spec.rb b/spec/unit/chef_fs/config_spec.rb index c126d05c93..a0ed5146ca 100644 --- a/spec/unit/chef_fs/config_spec.rb +++ b/spec/unit/chef_fs/config_spec.rb @@ -57,21 +57,20 @@ describe Chef::ChefFS::Config do end describe "local FS configuration" do - let(:chef_config) do Mash.new({ - client_path: "/base_path/clients", - cookbook_path: "/base_path/cookbooks", - data_bag_path: "/base_path/data_bags", - environment_path: "/base_path/environments", - node_path: "/base_path/nodes", - role_path: "/base_path/roles", - user_path: "/base_path/users", - policy_path: "/base_path/policies", - },) + client_path: "/base_path/clients", + cookbook_path: "/base_path/cookbooks", + data_bag_path: "/base_path/data_bags", + environment_path: "/base_path/environments", + node_path: "/base_path/nodes", + role_path: "/base_path/roles", + user_path: "/base_path/users", + policy_path: "/base_path/policies", + },) end - let(:chef_fs_config) { Chef::ChefFS::Config.new(chef_config, Dir.pwd) } + let(:chef_fs_config) { Chef::ChefFS::Config.new(chef_config, Dir.pwd) } subject(:local_fs) { chef_fs_config.local_fs } diff --git a/spec/unit/chef_fs/data_handler/group_handler_spec.rb b/spec/unit/chef_fs/data_handler/group_handler_spec.rb index a1baabc14f..849bc84f92 100644 --- a/spec/unit/chef_fs/data_handler/group_handler_spec.rb +++ b/spec/unit/chef_fs/data_handler/group_handler_spec.rb @@ -45,8 +45,8 @@ describe Chef::ChefFS::DataHandler::GroupDataHandler do let(:normalized) do { "actors" => { "users" => %w{fizz buzz}, - "clients"=> %w{honey sting}, - "groups"=> [], + "clients" => %w{honey sting}, + "groups" => [], }, "groupname" => "workers", "name" => "worker_bees", diff --git a/spec/unit/chef_fs/diff_spec.rb b/spec/unit/chef_fs/diff_spec.rb index e0e507ce89..04f237718b 100644 --- a/spec/unit/chef_fs/diff_spec.rb +++ b/spec/unit/chef_fs/diff_spec.rb @@ -34,57 +34,57 @@ describe "diff", :uses_diff => true do context "with two filesystems with all types of difference" do let(:a) { memory_fs("a", { - :both_dirs => { - :sub_both_dirs => { :subsub => nil }, - :sub_both_files => nil, - :sub_both_files_different => "a\n", - :sub_both_dirs_empty => {}, - :sub_dirs_empty_in_a_filled_in_b => {}, - :sub_dirs_empty_in_b_filled_in_a => { :subsub => nil }, - :sub_a_only_dir => { :subsub => nil }, - :sub_a_only_file => nil, - :sub_dir_in_a_file_in_b => {}, - :sub_file_in_a_dir_in_b => nil, - }, - :both_files => nil, - :both_files_different => "a\n", - :both_dirs_empty => {}, - :dirs_empty_in_a_filled_in_b => {}, - :dirs_empty_in_b_filled_in_a => { :subsub => nil }, - :dirs_in_a_cannot_be_in_b => {}, - :file_in_a_cannot_be_in_b => nil, - :a_only_dir => { :subsub => nil }, - :a_only_file => nil, - :dir_in_a_file_in_b => {}, - :file_in_a_dir_in_b => nil, - }, /cannot_be_in_a/) + :both_dirs => { + :sub_both_dirs => { :subsub => nil }, + :sub_both_files => nil, + :sub_both_files_different => "a\n", + :sub_both_dirs_empty => {}, + :sub_dirs_empty_in_a_filled_in_b => {}, + :sub_dirs_empty_in_b_filled_in_a => { :subsub => nil }, + :sub_a_only_dir => { :subsub => nil }, + :sub_a_only_file => nil, + :sub_dir_in_a_file_in_b => {}, + :sub_file_in_a_dir_in_b => nil, + }, + :both_files => nil, + :both_files_different => "a\n", + :both_dirs_empty => {}, + :dirs_empty_in_a_filled_in_b => {}, + :dirs_empty_in_b_filled_in_a => { :subsub => nil }, + :dirs_in_a_cannot_be_in_b => {}, + :file_in_a_cannot_be_in_b => nil, + :a_only_dir => { :subsub => nil }, + :a_only_file => nil, + :dir_in_a_file_in_b => {}, + :file_in_a_dir_in_b => nil, + }, /cannot_be_in_a/) } let(:b) { memory_fs("b", { - :both_dirs => { - :sub_both_dirs => { :subsub => nil }, - :sub_both_files => nil, - :sub_both_files_different => "b\n", - :sub_both_dirs_empty => {}, - :sub_dirs_empty_in_a_filled_in_b => { :subsub => nil }, - :sub_dirs_empty_in_b_filled_in_a => {}, - :sub_b_only_dir => { :subsub => nil }, - :sub_b_only_file => nil, - :sub_dir_in_a_file_in_b => nil, - :sub_file_in_a_dir_in_b => {}, - }, - :both_files => nil, - :both_files_different => "b\n", - :both_dirs_empty => {}, - :dirs_empty_in_a_filled_in_b => { :subsub => nil }, - :dirs_empty_in_b_filled_in_a => {}, - :dirs_in_b_cannot_be_in_a => {}, - :file_in_b_cannot_be_in_a => nil, - :b_only_dir => { :subsub => nil }, - :b_only_file => nil, - :dir_in_a_file_in_b => nil, - :file_in_a_dir_in_b => {}, - }, /cannot_be_in_b/) + :both_dirs => { + :sub_both_dirs => { :subsub => nil }, + :sub_both_files => nil, + :sub_both_files_different => "b\n", + :sub_both_dirs_empty => {}, + :sub_dirs_empty_in_a_filled_in_b => { :subsub => nil }, + :sub_dirs_empty_in_b_filled_in_a => {}, + :sub_b_only_dir => { :subsub => nil }, + :sub_b_only_file => nil, + :sub_dir_in_a_file_in_b => nil, + :sub_file_in_a_dir_in_b => {}, + }, + :both_files => nil, + :both_files_different => "b\n", + :both_dirs_empty => {}, + :dirs_empty_in_a_filled_in_b => { :subsub => nil }, + :dirs_empty_in_b_filled_in_a => {}, + :dirs_in_b_cannot_be_in_a => {}, + :file_in_b_cannot_be_in_a => nil, + :b_only_dir => { :subsub => nil }, + :b_only_file => nil, + :dir_in_a_file_in_b => nil, + :file_in_a_dir_in_b => {}, + }, /cannot_be_in_b/) } it "Chef::ChefFS::CommandLine.diff_print(/)" do results = [] @@ -98,63 +98,63 @@ describe "diff", :uses_diff => true do CONTEXT_LINE_NUMBERS -a +b -','diff --knife a/both_dirs/sub_dirs_empty_in_a_filled_in_b/subsub b/both_dirs/sub_dirs_empty_in_a_filled_in_b/subsub +', 'diff --knife a/both_dirs/sub_dirs_empty_in_a_filled_in_b/subsub b/both_dirs/sub_dirs_empty_in_a_filled_in_b/subsub new file --- /dev/null DATE +++ b/both_dirs/sub_dirs_empty_in_a_filled_in_b/subsub DATE CONTEXT_LINE_NUMBERS +subsub -','diff --knife a/both_dirs/sub_dirs_empty_in_b_filled_in_a/subsub b/both_dirs/sub_dirs_empty_in_b_filled_in_a/subsub +', 'diff --knife a/both_dirs/sub_dirs_empty_in_b_filled_in_a/subsub b/both_dirs/sub_dirs_empty_in_b_filled_in_a/subsub deleted file --- a/both_dirs/sub_dirs_empty_in_b_filled_in_a/subsub DATE +++ /dev/null DATE CONTEXT_LINE_NUMBERS -subsub -',"Only in a/both_dirs: sub_a_only_dir -",'diff --knife a/both_dirs/sub_a_only_file b/both_dirs/sub_a_only_file +', "Only in a/both_dirs: sub_a_only_dir +", 'diff --knife a/both_dirs/sub_a_only_file b/both_dirs/sub_a_only_file deleted file --- a/both_dirs/sub_a_only_file DATE +++ /dev/null DATE CONTEXT_LINE_NUMBERS -sub_a_only_file -',"File a/both_dirs/sub_dir_in_a_file_in_b is a directory while file b/both_dirs/sub_dir_in_a_file_in_b is a regular file -","File a/both_dirs/sub_file_in_a_dir_in_b is a regular file while file b/both_dirs/sub_file_in_a_dir_in_b is a directory -","Only in b/both_dirs: sub_b_only_dir -",'diff --knife a/both_dirs/sub_b_only_file b/both_dirs/sub_b_only_file +', "File a/both_dirs/sub_dir_in_a_file_in_b is a directory while file b/both_dirs/sub_dir_in_a_file_in_b is a regular file +", "File a/both_dirs/sub_file_in_a_dir_in_b is a regular file while file b/both_dirs/sub_file_in_a_dir_in_b is a directory +", "Only in b/both_dirs: sub_b_only_dir +", 'diff --knife a/both_dirs/sub_b_only_file b/both_dirs/sub_b_only_file new file --- /dev/null DATE +++ b/both_dirs/sub_b_only_file DATE CONTEXT_LINE_NUMBERS +sub_b_only_file -','diff --knife a/both_files_different b/both_files_different +', 'diff --knife a/both_files_different b/both_files_different --- a/both_files_different DATE +++ b/both_files_different DATE CONTEXT_LINE_NUMBERS -a +b -','diff --knife a/dirs_empty_in_a_filled_in_b/subsub b/dirs_empty_in_a_filled_in_b/subsub +', 'diff --knife a/dirs_empty_in_a_filled_in_b/subsub b/dirs_empty_in_a_filled_in_b/subsub new file --- /dev/null DATE +++ b/dirs_empty_in_a_filled_in_b/subsub DATE CONTEXT_LINE_NUMBERS +subsub -','diff --knife a/dirs_empty_in_b_filled_in_a/subsub b/dirs_empty_in_b_filled_in_a/subsub +', 'diff --knife a/dirs_empty_in_b_filled_in_a/subsub b/dirs_empty_in_b_filled_in_a/subsub deleted file --- a/dirs_empty_in_b_filled_in_a/subsub DATE +++ /dev/null DATE CONTEXT_LINE_NUMBERS -subsub -',"Only in a: a_only_dir -",'diff --knife a/a_only_file b/a_only_file +', "Only in a: a_only_dir +", 'diff --knife a/a_only_file b/a_only_file deleted file --- a/a_only_file DATE +++ /dev/null DATE CONTEXT_LINE_NUMBERS -a_only_file -',"File a/dir_in_a_file_in_b is a directory while file b/dir_in_a_file_in_b is a regular file -","File a/file_in_a_dir_in_b is a regular file while file b/file_in_a_dir_in_b is a directory -","Only in b: b_only_dir -",'diff --knife a/b_only_file b/b_only_file +', "File a/dir_in_a_file_in_b is a directory while file b/dir_in_a_file_in_b is a regular file +", "File a/file_in_a_dir_in_b is a regular file while file b/file_in_a_dir_in_b is a directory +", "Only in b: b_only_dir +", 'diff --knife a/b_only_file b/b_only_file new file --- /dev/null DATE +++ b/b_only_file DATE @@ -174,29 +174,29 @@ CONTEXT_LINE_NUMBERS CONTEXT_LINE_NUMBERS -a +b -','diff --knife a/both_dirs/sub_dirs_empty_in_a_filled_in_b/subsub b/both_dirs/sub_dirs_empty_in_a_filled_in_b/subsub +', 'diff --knife a/both_dirs/sub_dirs_empty_in_a_filled_in_b/subsub b/both_dirs/sub_dirs_empty_in_a_filled_in_b/subsub new file --- /dev/null DATE +++ b/both_dirs/sub_dirs_empty_in_a_filled_in_b/subsub DATE CONTEXT_LINE_NUMBERS +subsub -','diff --knife a/both_dirs/sub_dirs_empty_in_b_filled_in_a/subsub b/both_dirs/sub_dirs_empty_in_b_filled_in_a/subsub +', 'diff --knife a/both_dirs/sub_dirs_empty_in_b_filled_in_a/subsub b/both_dirs/sub_dirs_empty_in_b_filled_in_a/subsub deleted file --- a/both_dirs/sub_dirs_empty_in_b_filled_in_a/subsub DATE +++ /dev/null DATE CONTEXT_LINE_NUMBERS -subsub -',"Only in a/both_dirs: sub_a_only_dir -",'diff --knife a/both_dirs/sub_a_only_file b/both_dirs/sub_a_only_file +', "Only in a/both_dirs: sub_a_only_dir +", 'diff --knife a/both_dirs/sub_a_only_file b/both_dirs/sub_a_only_file deleted file --- a/both_dirs/sub_a_only_file DATE +++ /dev/null DATE CONTEXT_LINE_NUMBERS -sub_a_only_file -',"File a/both_dirs/sub_dir_in_a_file_in_b is a directory while file b/both_dirs/sub_dir_in_a_file_in_b is a regular file -","File a/both_dirs/sub_file_in_a_dir_in_b is a regular file while file b/both_dirs/sub_file_in_a_dir_in_b is a directory -","Only in b/both_dirs: sub_b_only_dir -",'diff --knife a/both_dirs/sub_b_only_file b/both_dirs/sub_b_only_file +', "File a/both_dirs/sub_dir_in_a_file_in_b is a directory while file b/both_dirs/sub_dir_in_a_file_in_b is a regular file +", "File a/both_dirs/sub_file_in_a_dir_in_b is a regular file while file b/both_dirs/sub_file_in_a_dir_in_b is a directory +", "Only in b/both_dirs: sub_b_only_dir +", 'diff --knife a/both_dirs/sub_b_only_file b/both_dirs/sub_b_only_file new file --- /dev/null DATE +++ b/both_dirs/sub_b_only_file DATE @@ -211,26 +211,26 @@ CONTEXT_LINE_NUMBERS end expect(results).to match_array([ "Common subdirectories: b/both_dirs -",'diff --knife a/both_files_different b/both_files_different +", 'diff --knife a/both_files_different b/both_files_different --- a/both_files_different DATE +++ b/both_files_different DATE CONTEXT_LINE_NUMBERS -a +b -',"Common subdirectories: b/both_dirs_empty -","Common subdirectories: b/dirs_empty_in_b_filled_in_a -","Common subdirectories: b/dirs_empty_in_a_filled_in_b -","Only in a: a_only_dir -",'diff --knife a/a_only_file b/a_only_file +', "Common subdirectories: b/both_dirs_empty +", "Common subdirectories: b/dirs_empty_in_b_filled_in_a +", "Common subdirectories: b/dirs_empty_in_a_filled_in_b +", "Only in a: a_only_dir +", 'diff --knife a/a_only_file b/a_only_file deleted file --- a/a_only_file DATE +++ /dev/null DATE CONTEXT_LINE_NUMBERS -a_only_file -',"File a/dir_in_a_file_in_b is a directory while file b/dir_in_a_file_in_b is a regular file -","File a/file_in_a_dir_in_b is a regular file while file b/file_in_a_dir_in_b is a directory -","Only in b: b_only_dir -",'diff --knife a/b_only_file b/b_only_file +', "File a/dir_in_a_file_in_b is a directory while file b/dir_in_a_file_in_b is a regular file +", "File a/file_in_a_dir_in_b is a regular file while file b/file_in_a_dir_in_b is a directory +", "Only in b: b_only_dir +", 'diff --knife a/b_only_file b/b_only_file new file --- /dev/null DATE +++ b/b_only_file DATE @@ -245,26 +245,26 @@ CONTEXT_LINE_NUMBERS end expect(results).to match_array([ "Common subdirectories: b/both_dirs -",'diff --knife a/both_files_different b/both_files_different +", 'diff --knife a/both_files_different b/both_files_different --- a/both_files_different DATE +++ b/both_files_different DATE CONTEXT_LINE_NUMBERS -a +b -',"Common subdirectories: b/both_dirs_empty -","Common subdirectories: b/dirs_empty_in_b_filled_in_a -","Common subdirectories: b/dirs_empty_in_a_filled_in_b -","Only in a: a_only_dir -",'diff --knife a/a_only_file b/a_only_file +', "Common subdirectories: b/both_dirs_empty +", "Common subdirectories: b/dirs_empty_in_b_filled_in_a +", "Common subdirectories: b/dirs_empty_in_a_filled_in_b +", "Only in a: a_only_dir +", 'diff --knife a/a_only_file b/a_only_file deleted file --- a/a_only_file DATE +++ /dev/null DATE CONTEXT_LINE_NUMBERS -a_only_file -',"File a/dir_in_a_file_in_b is a directory while file b/dir_in_a_file_in_b is a regular file -","File a/file_in_a_dir_in_b is a regular file while file b/file_in_a_dir_in_b is a directory -","Only in b: b_only_dir -",'diff --knife a/b_only_file b/b_only_file +', "File a/dir_in_a_file_in_b is a directory while file b/dir_in_a_file_in_b is a regular file +", "File a/file_in_a_dir_in_b is a regular file while file b/file_in_a_dir_in_b is a directory +", "Only in b: b_only_dir +", 'diff --knife a/b_only_file b/b_only_file new file --- /dev/null DATE +++ b/b_only_file DATE diff --git a/spec/unit/chef_fs/file_pattern_spec.rb b/spec/unit/chef_fs/file_pattern_spec.rb index a919c50114..c4d076ef90 100644 --- a/spec/unit/chef_fs/file_pattern_spec.rb +++ b/spec/unit/chef_fs/file_pattern_spec.rb @@ -478,7 +478,6 @@ describe Chef::ChefFS::FilePattern do end end - # match? # - single element matches (empty, fixed, ?, *, characters, escapes) # - nested matches diff --git a/spec/unit/chef_fs/file_system_spec.rb b/spec/unit/chef_fs/file_system_spec.rb index 9f07197832..f599c89eeb 100644 --- a/spec/unit/chef_fs/file_system_spec.rb +++ b/spec/unit/chef_fs/file_system_spec.rb @@ -57,18 +57,18 @@ describe Chef::ChefFS::FileSystem do context "with a populated filesystem" do let(:fs) { memory_fs("", { - :a => { - :aa => { - :c => "", - :zz => "", - }, - :ab => { - :c => "" - }, - }, - :x => "", - :y => {}, - },) + :a => { + :aa => { + :c => "", + :zz => "", + }, + :ab => { + :c => "" + }, + }, + :x => "", + :y => {}, + },) } context "list" do it "/**" do diff --git a/spec/unit/chef_fs/parallelizer.rb b/spec/unit/chef_fs/parallelizer.rb index 8f6f9e71fc..da18117bbd 100644 --- a/spec/unit/chef_fs/parallelizer.rb +++ b/spec/unit/chef_fs/parallelizer.rb @@ -25,7 +25,7 @@ describe Chef::ChefFS::Parallelizer do it "parallel_do creates unordered output as soon as it is available" do outputs = [] - parallelizer.parallel_do([0.5,0.3,0.1]) do |val| + parallelizer.parallel_do([0.5, 0.3, 0.1]) do |val| sleep val outputs << val end @@ -50,18 +50,18 @@ describe Chef::ChefFS::Parallelizer do 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) do |val| sleep val val end expect(enum.map do |value| - expect(elapsed_time).to be < value+0.1 + expect(elapsed_time).to be < value + 0.1 value end).to eq([ 0.1, 0.3, 0.5 ]) end it "An exception in input is passed through but does NOT stop processing" do - input = TestEnumerable.new(0.5,0.3,0.1) do + input = TestEnumerable.new(0.5, 0.3, 0.1) do raise "hi" end enum = parallelize(input, :ordered => false) { |x| sleep(x); x } @@ -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) do |x| if x == "x" sleep 0.1 raise "hi" @@ -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) do |x| if x == "x" sleep(0.1) raise "hi" @@ -122,7 +122,7 @@ describe Chef::ChefFS::Parallelizer do 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]) do |val| sleep val val end.enum_for(:each_with_index) @@ -133,7 +133,7 @@ describe Chef::ChefFS::Parallelizer do end it "Exceptions in input are raised in the correct sequence but do NOT stop processing" do - input = TestEnumerable.new(0.5,0.3,0.1) do + input = TestEnumerable.new(0.5, 0.3, 0.1) do raise "hi" end results = [] @@ -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]) do |x| if x == "x" sleep(0.1) raise "hi" @@ -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) do |x| if x == "x" sleep(0.1) raise "hi" @@ -188,7 +188,7 @@ describe Chef::ChefFS::Parallelizer do end enum = parallelize(input) { |x| x } expect(enum.map do |value| - expect(elapsed_time).to be < (value+1)*0.1 + expect(elapsed_time).to be < (value + 1) * 0.1 value end).to eq([ 1, 2, 3 ]) end @@ -233,7 +233,7 @@ describe Chef::ChefFS::Parallelizer do it "parallelize with :main_thread_processing = false waits for the job to finish" do expect(parallelizer.parallelize([1], :main_thread_processing => false) do |x| sleep(0.1) - x+1 + x + 1 end.to_a).to eq([ 2 ]) expect(elapsed_time).to be > 0.3 end @@ -267,7 +267,7 @@ describe Chef::ChefFS::Parallelizer do context "enumerable methods should run efficiently" do it ".count does not process anything" do outputs_processed = 0 - input_mapper = TestEnumerable.new(1,2,3,4,5,6) + input_mapper = TestEnumerable.new(1, 2, 3, 4, 5, 6) enum = parallelizer.parallelize(input_mapper) do |x| outputs_processed += 1 sleep(0.05) # Just enough to yield and get other inputs in the queue @@ -280,7 +280,7 @@ 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) + input_mapper = TestEnumerable.new(1, 1, 1, 1, 2, 2, 2, 3, 3, 4) enum = parallelizer.parallelize(input_mapper) do |x| outputs_processed += 1 x @@ -293,40 +293,40 @@ 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) + input_mapper = TestEnumerable.new(1, 2, 3, 4, 5, 6) enum = parallelizer.parallelize(input_mapper) do |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(enum.first(2)).to eq([1, 2]) expect(outputs_processed).to eq(3) expect(input_mapper.num_processed).to eq(3) end 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) + input_mapper = TestEnumerable.new(1, 2, 3, 4, 5, 6) enum = parallelizer.parallelize(input_mapper) do |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(enum.take(2)).to eq([1, 2]) expect(outputs_processed).to eq(2) expect(input_mapper.num_processed).to eq(2) end 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) + input_mapper = TestEnumerable.new(1, 2, 3, 4, 5, 6) enum = parallelizer.parallelize(input_mapper) do |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(enum.drop(2)).to eq([3, 4, 5, 6]) expect(outputs_processed).to eq(4) expect(input_mapper.num_processed).to eq(6) end @@ -334,33 +334,33 @@ describe Chef::ChefFS::Parallelizer do if Enumerable.method_defined?(:lazy) 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) + input_mapper = TestEnumerable.new(1, 2, 3, 4, 5, 6) enum = parallelizer.parallelize(input_mapper) do |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(enum.lazy.take(2).to_a).to eq([1, 2]) expect(outputs_processed).to eq(2) expect(input_mapper.num_processed).to eq(2) end 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) + input_mapper = TestEnumerable.new(1, 2, 3, 4, 5, 6) enum = parallelizer.parallelize(input_mapper) do |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(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) end it "lazy enumerable is actually lazy" do outputs_processed = 0 - input_mapper = TestEnumerable.new(1,2,3,4,5,6) + input_mapper = TestEnumerable.new(1, 2, 3, 4, 5, 6) enum = parallelizer.parallelize(input_mapper) do |x| outputs_processed += 1 sleep(0.05) # Just enough to yield and get other inputs in the queue @@ -378,32 +378,32 @@ describe Chef::ChefFS::Parallelizer do context "running enumerable multiple times should function correctly" 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) + input_mapper = TestEnumerable.new(1, 2, 3) enum = parallelizer.parallelize(input_mapper) do |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(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) expect(input_mapper.num_processed).to eq(6) end 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) + input_mapper = TestEnumerable.new(1, 2, 3) enum = parallelizer.parallelize(input_mapper) do |x| outputs_processed += 1 x end expect(enum.first).to eq(1) - expect(enum.map { |x| x }).to eq([1,2,3]) + expect(enum.map { |x| x }).to eq([1, 2, 3]) expect(outputs_processed).to be >= 4 expect(input_mapper.num_processed).to be >= 4 end it "two simultaneous enumerations throws an exception" do - enum = parallelizer.parallelize([1,2,3]) { |x| x } + enum = parallelizer.parallelize([1, 2, 3]) { |x| x } a = enum.enum_for(:each) a.next expect do @@ -421,7 +421,7 @@ describe Chef::ChefFS::Parallelizer do context "And main_thread_processing on" do it "succeeds in running" do - expect(parallelizer.parallelize([0.5]) { |x| x*2 }.to_a).to eq([1]) + expect(parallelizer.parallelize([0.5]) { |x| x * 2 }.to_a).to eq([1]) end end end @@ -432,16 +432,16 @@ describe Chef::ChefFS::Parallelizer do end it "does not have contention issues with large numbers of inputs" do - expect(parallelizer.parallelize(1.upto(500)) { |x| x+1 }.to_a).to eq(2.upto(501).to_a) + expect(parallelizer.parallelize(1.upto(500)) { |x| x + 1 }.to_a).to eq(2.upto(501).to_a) end it "does not have contention issues with large numbers of inputs with ordering off" do - expect(parallelizer.parallelize(1.upto(500), :ordered => false) { |x| x+1 }.to_a.sort).to eq(2.upto(501).to_a) + expect(parallelizer.parallelize(1.upto(500), :ordered => false) { |x| x + 1 }.to_a.sort).to eq(2.upto(501).to_a) end it "does not have contention issues with large numbers of jobs and inputs with ordering off" do parallelizers = 0.upto(99).map do - parallelizer.parallelize(1.upto(500)) { |x| x+1 } + parallelizer.parallelize(1.upto(500)) { |x| x + 1 } end outputs = [] threads = 0.upto(99).map do |i| diff --git a/spec/unit/chef_fs/path_util_spec.rb b/spec/unit/chef_fs/path_util_spec.rb index 823f7c393c..93205a1815 100644 --- a/spec/unit/chef_fs/path_util_spec.rb +++ b/spec/unit/chef_fs/path_util_spec.rb @@ -69,7 +69,7 @@ describe Chef::ChefFS::PathUtils do end it "handles paths with .. and ." do - expect(Chef::ChefFS::PathUtils.realest_path(good_path+"/../.")).to eq(File.expand_path(parent_path)) + expect(Chef::ChefFS::PathUtils.realest_path(good_path + "/../.")).to eq(File.expand_path(parent_path)) end it "handles paths with *" do diff --git a/spec/unit/client_spec.rb b/spec/unit/client_spec.rb index 7431f804b9..e86818ffd6 100644 --- a/spec/unit/client_spec.rb +++ b/spec/unit/client_spec.rb @@ -89,9 +89,7 @@ describe Chef::Client do expect(Chef::Config[:force_logger]).to be_truthy expect(client.formatters_for_run).to eq([[:null]]) end - end - end context "and STDOUT is not a TTY" do @@ -112,7 +110,6 @@ describe Chef::Client do end end end - end context "when a formatter is configured" do @@ -151,7 +148,6 @@ describe Chef::Client do expect(min_formatter.output.err.path).to eq(@tmpout.path) end end - end end @@ -181,7 +177,7 @@ describe Chef::Client do describe "calling run" do include_examples "a successful client run" do - let(:client_opts) { {:override_runlist => "recipe[override_recipe]"} } + let(:client_opts) { { :override_runlist => "recipe[override_recipe]" } } def stub_for_sync_cookbooks # --Client#setup_run_context @@ -190,7 +186,7 @@ describe Chef::Client do expect_any_instance_of(Chef::CookbookSynchronizer).to receive(:sync_cookbooks) expect(Chef::ServerAPI).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) expect(http_cookbook_sync).to receive(:post). - with("environments/_default/cookbook_versions", {:run_list => ["override_recipe"]}). + with("environments/_default/cookbook_versions", { :run_list => ["override_recipe"] }). and_return({}) end @@ -215,7 +211,7 @@ describe Chef::Client do include_examples "a successful client run" do let(:new_runlist) { "recipe[new_run_list_recipe]" } - let(:client_opts) { {:runlist => new_runlist} } + let(:client_opts) { { :runlist => new_runlist } } def stub_for_sync_cookbooks # --Client#setup_run_context @@ -224,7 +220,7 @@ describe Chef::Client do expect_any_instance_of(Chef::CookbookSynchronizer).to receive(:sync_cookbooks) expect(Chef::ServerAPI).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) expect(http_cookbook_sync).to receive(:post). - with("environments/_default/cookbook_versions", {:run_list => ["new_run_list_recipe"]}). + with("environments/_default/cookbook_versions", { :run_list => ["new_run_list_recipe"] }). and_return({}) end @@ -388,7 +384,7 @@ describe Chef::Client do expect(node.chef_environment).to eq("_default") Chef::Config[:environment] = "A" - test_env = {"name" => "A"} + test_env = { "name" => "A" } mock_chef_rest = double("Chef::ServerAPI") expect(mock_chef_rest).to receive(:get).with("environments/A").and_return(test_env) @@ -508,7 +504,6 @@ describe Chef::Client do expect { client.node_name }.to raise_error(Chef::Exceptions::CannotDetermineNodeName) end end - end describe "always attempt to run handlers" do diff --git a/spec/unit/config_fetcher_spec.rb b/spec/unit/config_fetcher_spec.rb index 84aad38876..73f1ec8674 100644 --- a/spec/unit/config_fetcher_spec.rb +++ b/spec/unit/config_fetcher_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" require "chef/config_fetcher" describe Chef::ConfigFetcher do - let(:valid_json) { Chef::JSONCompat.to_json({:a=>"b"}) } + let(:valid_json) { Chef::JSONCompat.to_json({ :a => "b" }) } let(:invalid_json) { %q[{"syntax-error": "missing quote}] } let(:http) { double("Chef::HTTP::Simple") } @@ -27,34 +27,27 @@ describe Chef::ConfigFetcher do end context "with a relative path" do - let(:config_location) { "client.rb" } it "gives the expanded path to the config file" do expected = File.join(Dir.pwd, config_location) expect(fetcher.expanded_path).to eq(expected) end - end context "and consuming JSON" do - let(:config_location) { "/etc/chef/first-boot.json" } - it "returns the parsed JSON" do expect(::File).to receive(:read). with(config_location). and_return(valid_json) - expect(fetcher.fetch_json).to eq({"a" => "b"}) + expect(fetcher.fetch_json).to eq({ "a" => "b" }) end context "and the JSON is invalid" do - it "reports the JSON error" do - - expect(::File).to receive(:read). with(config_location). and_return(invalid_json) @@ -65,11 +58,9 @@ describe Chef::ConfigFetcher do end end end - end context "with an HTTP URL config location" do - let(:config_location) { "https://example.com/client.rb" } let(:config_content) { "# The client.rb content" } @@ -78,7 +69,6 @@ describe Chef::ConfigFetcher do end describe "reading the file" do - before do expect(Chef::HTTP::Simple).to receive(:new). with(config_location). @@ -86,8 +76,8 @@ describe Chef::ConfigFetcher do end it "reads the file over HTTP" do - expect(http).to receive(:get). - with("").and_return(config_content) + expect(http).to receive(:get). + with("").and_return(config_content) expect(fetcher.read_config).to eq(config_content) end @@ -97,7 +87,7 @@ describe Chef::ConfigFetcher do it "fetches the file and parses it" do expect(http).to receive(:get). with("").and_return(valid_json) - expect(fetcher.fetch_json).to eq({"a" => "b"}) + expect(fetcher.fetch_json).to eq({ "a" => "b" }) end context "and the JSON is invalid" do @@ -112,17 +102,13 @@ describe Chef::ConfigFetcher do end end end - end context "with a nil config file argument" do - let(:config_location) { nil } it "returns the config location unchanged for #expanded_path" do expect(fetcher.expanded_path).to eq(nil) end end - - end diff --git a/spec/unit/config_spec.rb b/spec/unit/config_spec.rb index 68cb589251..e6a7676f7a 100644 --- a/spec/unit/config_spec.rb +++ b/spec/unit/config_spec.rb @@ -4,7 +4,6 @@ require "spec_helper" require "chef/config" RSpec.describe Chef::Config do - shared_examples_for "deprecated by ohai but not deprecated" do it "does not emit a deprecation warning when set" do expect(Chef::Log).to_not receive(:warn). @@ -27,5 +26,4 @@ RSpec.describe Chef::Config do let(:value) { "path/to/log" } end end - end diff --git a/spec/unit/cookbook/cookbook_version_loader_spec.rb b/spec/unit/cookbook/cookbook_version_loader_spec.rb index 10495d180a..6e791447bc 100644 --- a/spec/unit/cookbook/cookbook_version_loader_spec.rb +++ b/spec/unit/cookbook/cookbook_version_loader_spec.rb @@ -24,7 +24,6 @@ describe Chef::Cookbook::CookbookVersionLoader do end describe "loading a cookbook" do - let(:chefignore) { nil } let(:cookbook_path) { File.join(CHEF_SPEC_DATA, "cookbooks/openldap") } @@ -79,7 +78,6 @@ describe Chef::Cookbook::CookbookVersionLoader do end context "when a cookbook has ignored files" do - let(:chefignore) { Chef::Cookbook::Chefignore.new(File.join(CHEF_SPEC_DATA, "cookbooks")) } let(:cookbook_path) { File.join(CHEF_SPEC_DATA, "kitchen/openldap") } @@ -89,11 +87,9 @@ describe Chef::Cookbook::CookbookVersionLoader do expect(loaded_cookbook.recipe_filenames).to include(full_path("recipes/woot.rb")) expect(loaded_cookbook.recipe_filenames).to_not include(full_path("recipes/ignoreme.rb")) end - end context "when the given path is not actually a cookbook" do - let(:cookbook_path) { File.join(CHEF_SPEC_DATA, "cookbooks/NOTHING_HERE_FOLKS") } it "raises an error when loading with #load!" do @@ -103,21 +99,17 @@ describe Chef::Cookbook::CookbookVersionLoader do it "skips the cookbook when called with #load" do expect { cookbook_loader.load }.to_not raise_error end - end context "when a cookbook has a metadata name different than directory basename" do - let(:cookbook_path) { File.join(CHEF_SPEC_DATA, "cookbooks/name-mismatch-versionnumber") } it "prefers the metadata name to the directory basename" do expect(loaded_cookbook.name).to eq(:"name-mismatch") end - end context "when a cookbook has a metadata file with a ruby error [CHEF-2923]" do - let(:cookbook_path) { File.join(CHEF_SPEC_DATA, "invalid-metadata-chef-repo/invalid-metadata") } it "raises an error when loading with #load!" do @@ -141,11 +133,9 @@ describe Chef::Cookbook::CookbookVersionLoader do expect(cookbook_loader.metadata_error).to be_a(StandardError) expect(cookbook_loader.metadata_error.message).to eq("THIS METADATA HAS A BUG") end - end context "when a cookbook has a metadata file with invalid metadata" do - let(:cookbook_path) { File.join(CHEF_SPEC_DATA, "incomplete-metadata-chef-repo/incomplete-metadata") } let(:error_message) do @@ -178,10 +168,6 @@ describe Chef::Cookbook::CookbookVersionLoader do # metadata syntax error that is the actual cause. expect(cookbook_loader.cookbook_name).to eq(:"incomplete-metadata") end - end - end - end - diff --git a/spec/unit/cookbook/file_vendor_spec.rb b/spec/unit/cookbook/file_vendor_spec.rb index ea6f8d010d..97b7f70766 100644 --- a/spec/unit/cookbook/file_vendor_spec.rb +++ b/spec/unit/cookbook/file_vendor_spec.rb @@ -18,11 +18,9 @@ require "spec_helper" describe Chef::Cookbook::FileVendor do - let(:file_vendor_class) { Class.new(described_class) } context "when configured to fetch files over http" do - let(:http) { double("Chef::ServerAPI") } before do @@ -38,9 +36,8 @@ describe Chef::Cookbook::FileVendor do end context "with a manifest from a cookbook version" do - # A manifest is a Hash of the format defined by Chef::CookbookVersion#manifest - let(:manifest) { {:cookbook_name => "bob", :name => "bob-1.2.3"} } + let(:manifest) { { :cookbook_name => "bob", :name => "bob-1.2.3" } } it "creates a RemoteFileVendor for a given manifest" do file_vendor = file_vendor_class.create_from_manifest(manifest) @@ -48,13 +45,11 @@ describe Chef::Cookbook::FileVendor do expect(file_vendor.rest).to eq(http) expect(file_vendor.cookbook_name).to eq("bob") end - end context "with a manifest from a cookbook artifact" do - # A manifest is a Hash of the format defined by Chef::CookbookVersion#manifest - let(:manifest) { {:name => "bob"} } + let(:manifest) { { :name => "bob" } } it "creates a RemoteFileVendor for a given manifest" do file_vendor = file_vendor_class.create_from_manifest(manifest) @@ -62,16 +57,14 @@ describe Chef::Cookbook::FileVendor do expect(file_vendor.rest).to eq(http) expect(file_vendor.cookbook_name).to eq("bob") end - end end context "when configured to load files from disk" do - let(:cookbook_path) { %w{/var/chef/cookbooks /var/chef/other_cookbooks} } # A manifest is a Hash of the format defined by Chef::CookbookVersion#manifest - let(:manifest) { {:cookbook_name => "bob"} } + let(:manifest) { { :cookbook_name => "bob" } } before do file_vendor_class.fetch_from_disk(cookbook_path) @@ -91,8 +84,5 @@ describe Chef::Cookbook::FileVendor do expect(file_vendor.cookbook_name).to eq("bob") expect(file_vendor.repo_paths).to eq(cookbook_path) end - end - end - diff --git a/spec/unit/cookbook/metadata_spec.rb b/spec/unit/cookbook/metadata_spec.rb index 351792175f..4e95163db7 100644 --- a/spec/unit/cookbook/metadata_spec.rb +++ b/spec/unit/cookbook/metadata_spec.rb @@ -21,7 +21,6 @@ require "spec_helper" require "chef/cookbook/metadata" describe Chef::Cookbook::Metadata do - let(:metadata) { Chef::Cookbook::Metadata.new } describe "when comparing for equality" do @@ -76,11 +75,9 @@ describe Chef::Cookbook::Metadata do expect(metadata).not_to eq(duck_type) end end - end describe "when first created" do - it "has no name" do expect(metadata.name).to eq(nil) end @@ -155,9 +152,7 @@ describe Chef::Cookbook::Metadata do end describe "validation" do - context "when no required fields are set" do - it "is not valid" do expect(metadata).not_to be_valid end @@ -166,7 +161,6 @@ describe Chef::Cookbook::Metadata do expected_errors = ["The `name' attribute is required in cookbook metadata"] expect(metadata.errors).to eq(expected_errors) end - end context "when all required fields are set" do @@ -181,9 +175,7 @@ describe Chef::Cookbook::Metadata do it "has no validation errors" do expect(metadata.errors).to be_empty end - end - end describe "adding a supported platform" do @@ -205,7 +197,7 @@ describe Chef::Cookbook::Metadata do :issues_url => "http://example.com/issues", :privacy => true, } - params.sort { |a,b| a.to_s <=> b.to_s }.each do |field, field_value| + params.sort { |a, b| a.to_s <=> b.to_s }.each do |field, field_value| describe field do it "should be set-able via #{field}" do expect(metadata.send(field, field_value)).to eql(field_value) @@ -230,7 +222,6 @@ describe Chef::Cookbook::Metadata do end describe "describing dependencies" do - dep_types = { :depends => [ :dependencies, "foo::bar", "> 0.2" ], :recommends => [ :recommendations, "foo::bar", ">= 0.2" ], @@ -239,7 +230,7 @@ describe Chef::Cookbook::Metadata do :provides => [ :providing, "foo::bar", "<= 0.2" ], :replaces => [ :replacing, "foo::bar", "= 0.2.1" ], } - dep_types.sort { |a,b| a.to_s <=> b.to_s }.each do |dep, dep_args| + dep_types.sort { |a, b| a.to_s <=> b.to_s }.each do |dep, dep_args| check_with = dep_args.shift describe dep do it "should be set-able via #{dep}" do @@ -260,7 +251,7 @@ describe Chef::Cookbook::Metadata do :provides => [ :providing, "foo::bar", "<=0.2", "<= 0.2" ], :replaces => [ :replacing, "foo::bar", "=0.2.1", "= 0.2.1" ], } - dep_types.sort { |a,b| a.to_s <=> b.to_s }.each do |dep, dep_args| + dep_types.sort { |a, b| a.to_s <=> b.to_s }.each do |dep, dep_args| check_with = dep_args.shift normalized_version = dep_args.pop describe dep do @@ -274,7 +265,6 @@ describe Chef::Cookbook::Metadata do end end - describe "in the obsoleted format" do dep_types = { :depends => [ "foo::bar", "> 0.2", "< 1.0" ], @@ -287,12 +277,11 @@ describe Chef::Cookbook::Metadata do dep_types.each do |dep, dep_args| it "for #{dep} raises an informative error instead of vomiting on your shoes" do - expect {metadata.send(dep, *dep_args)}.to raise_error(Chef::Exceptions::ObsoleteDependencySyntax) + expect { metadata.send(dep, *dep_args) }.to raise_error(Chef::Exceptions::ObsoleteDependencySyntax) end end end - describe "with obsolete operators" do dep_types = { :depends => [ "foo::bar", ">> 0.2"], @@ -305,7 +294,7 @@ describe Chef::Cookbook::Metadata do dep_types.each do |dep, dep_args| it "for #{dep} raises an informative error instead of vomiting on your shoes" do - expect {metadata.send(dep, *dep_args)}.to raise_error(Chef::Exceptions::InvalidVersionConstraint) + expect { metadata.send(dep, *dep_args) }.to raise_error(Chef::Exceptions::InvalidVersionConstraint) end end end @@ -345,11 +334,11 @@ describe Chef::Cookbook::Metadata do end it "should work with multiple simple constraints" do - expect_chef_version_works(["~> 12.5.1"],["~> 11.18.10"]) + expect_chef_version_works(["~> 12.5.1"], ["~> 11.18.10"]) end it "should work with multiple complex constraints" do - expect_chef_version_works([">= 11.14.2", "< 11.18.10"],[">= 12.2.1", "< 12.5.1"]) + expect_chef_version_works([">= 11.14.2", "< 11.18.10"], [">= 12.2.1", "< 12.5.1"]) end it "should fail validation on a simple pessimistic constraint" do @@ -368,12 +357,12 @@ describe Chef::Cookbook::Metadata do end it "should fail validation when all ranges fail" do - expect_chef_version_works([">= 999.0", "< 999.9"],[">= 0.0.1", "< 0.0.9"]) + expect_chef_version_works([">= 999.0", "< 999.9"], [">= 0.0.1", "< 0.0.9"]) expect { metadata.validate_chef_version! }.to raise_error(Chef::Exceptions::CookbookChefVersionMismatch) end it "should pass validation when one constraint passes" do - expect_chef_version_works([">= 999.0", "< 999.9"],["= #{Chef::VERSION}"]) + expect_chef_version_works([">= 999.0", "< 999.9"], ["= #{Chef::VERSION}"]) expect { metadata.validate_chef_version! }.not_to raise_error end end @@ -397,11 +386,11 @@ describe Chef::Cookbook::Metadata do end it "should work with multiple simple constraints" do - expect_ohai_version_works(["~> 12.5.1"],["~> 11.18.10"]) + expect_ohai_version_works(["~> 12.5.1"], ["~> 11.18.10"]) end it "should work with multiple complex constraints" do - expect_ohai_version_works([">= 11.14.2", "< 11.18.10"],[">= 12.2.1", "< 12.5.1"]) + expect_ohai_version_works([">= 11.14.2", "< 11.18.10"], [">= 12.2.1", "< 12.5.1"]) end it "should fail validation on a simple pessimistic constraint" do @@ -420,12 +409,12 @@ describe Chef::Cookbook::Metadata do end it "should fail validation when all ranges fail" do - expect_ohai_version_works([">= 999.0", "< 999.9"],[">= 0.0.1", "< 0.0.9"]) + expect_ohai_version_works([">= 999.0", "< 999.9"], [">= 0.0.1", "< 0.0.9"]) expect { metadata.validate_ohai_version! }.to raise_error(Chef::Exceptions::CookbookOhaiVersionMismatch) end it "should pass validation when one constraint passes" do - expect_ohai_version_works([">= 999.0", "< 999.9"],["= #{Ohai::VERSION}"]) + expect_ohai_version_works([">= 999.0", "< 999.9"], ["= #{Ohai::VERSION}"]) expect { metadata.validate_ohai_version! }.not_to raise_error end end @@ -540,22 +529,22 @@ describe Chef::Cookbook::Metadata do expect(metadata.attributes["db/mysql/databases"][:choice]).to eq([]) end - it "should let calculated be true or false" do - expect { - metadata.attribute("db/mysql/databases", :calculated => true) - }.not_to raise_error - expect { - metadata.attribute("db/mysql/databases", :calculated => false) - }.not_to raise_error - expect { - metadata.attribute("db/mysql/databases", :calculated => Hash.new) - }.to raise_error(ArgumentError) - end + it "should let calculated be true or false" do + expect { + metadata.attribute("db/mysql/databases", :calculated => true) + }.not_to raise_error + expect { + metadata.attribute("db/mysql/databases", :calculated => false) + }.not_to raise_error + expect { + metadata.attribute("db/mysql/databases", :calculated => Hash.new) + }.to raise_error(ArgumentError) + end - it "should set calculated to false by default" do - metadata.attribute("db/mysql/databases", {}) - expect(metadata.attributes["db/mysql/databases"][:calculated]).to eq(false) - end + it "should set calculated to false by default" do + metadata.attribute("db/mysql/databases", {}) + expect(metadata.attributes["db/mysql/databases"][:calculated]).to eq(false) + end it "accepts String for the attribute type" do expect { @@ -578,11 +567,11 @@ describe Chef::Cookbook::Metadata do }.not_to raise_error end - it "should let type be hash (backwards compatibility only)" do + it "should let type be hash (backwards compatibility only)" do expect { metadata.attribute("db/mysql/databases", :type => "hash") }.not_to raise_error - end + end it "should let required be required, recommended or optional" do expect { @@ -766,7 +755,6 @@ describe Chef::Cookbook::Metadata do expect(metadata.providing.has_key?("test_cookbook")).to eq(true) expect(metadata.providing.has_key?("test_cookbook::enlighten")).to eq(true) end - end describe "json" do @@ -800,7 +788,6 @@ describe Chef::Cookbook::Metadata do end describe "serialize" do - let(:deserialized_metadata) { Chef::JSONCompat.from_json(Chef::JSONCompat.to_json(metadata)) } it "should serialize to a json hash" do @@ -844,10 +831,8 @@ describe Chef::Cookbook::Metadata do end describe "deserialize" do - let(:deserialized_metadata) { Chef::Cookbook::Metadata.from_json(Chef::JSONCompat.to_json(metadata)) } - it "should deserialize to a Chef::Cookbook::Metadata object" do expect(deserialized_metadata).to be_a_kind_of(Chef::Cookbook::Metadata) end @@ -922,6 +907,5 @@ describe Chef::Cookbook::Metadata do end end end - end end diff --git a/spec/unit/cookbook/synchronizer_spec.rb b/spec/unit/cookbook/synchronizer_spec.rb index d8f7f7d293..566a3467a4 100644 --- a/spec/unit/cookbook/synchronizer_spec.rb +++ b/spec/unit/cookbook/synchronizer_spec.rb @@ -4,7 +4,6 @@ require "chef/cookbook_version" describe Chef::CookbookCacheCleaner do describe "when cleaning up unused cookbook components" do - let(:cleaner) do cleaner = Chef::CookbookCacheCleaner.instance cleaner.reset! @@ -93,7 +92,7 @@ describe Chef::CookbookSynchronizer do let(:cookbook_a_manifest) do segments = [ :resources, :providers, :recipes, :definitions, :libraries, :attributes, :files, :templates, :root_files ] - cookbook_a_manifest = segments.inject({}) {|h, segment| h[segment.to_s] = []; h} + cookbook_a_manifest = segments.inject({}) { |h, segment| h[segment.to_s] = []; h } cookbook_a_manifest["recipes"] = [ cookbook_a_default_recipe ] cookbook_a_manifest["attributes"] = [ cookbook_a_default_attrs ] cookbook_a_manifest["templates"] = [ cookbook_a_template ] @@ -157,7 +156,7 @@ describe Chef::CookbookSynchronizer do let(:file_cache) { double("Chef::FileCache with files from unused cookbooks") } let(:cookbook_manifest) do - {"valid1"=> {}, "valid2" => {}} + { "valid1" => {}, "valid2" => {} } end it "removes unneeded cookbooks" do @@ -175,7 +174,7 @@ describe Chef::CookbookSynchronizer do let(:file_cache) { double("Chef::FileCache with files from unused cookbooks") } let(:cookbook_manifest) do - {"valid1"=> {}, "valid2" => {}} + { "valid1" => {}, "valid2" => {} } end it "removes only deleted files" do diff --git a/spec/unit/cookbook/syntax_check_spec.rb b/spec/unit/cookbook/syntax_check_spec.rb index 02762535ce..0cf4382f56 100644 --- a/spec/unit/cookbook/syntax_check_spec.rb +++ b/spec/unit/cookbook/syntax_check_spec.rb @@ -38,7 +38,7 @@ describe Chef::Cookbook::SyntaxCheck do recipes/default.rb recipes/gigantor.rb recipes/one.rb - recipes/return.rb }.map{ |f| File.join(cookbook_path, f) } + recipes/return.rb }.map { |f| File.join(cookbook_path, f) } end before do @@ -48,7 +48,7 @@ describe Chef::Cookbook::SyntaxCheck do @attr_files = %w{default.rb smokey.rb}.map { |f| File.join(cookbook_path, "attributes", f) } @libr_files = %w{openldap.rb openldap/version.rb}.map { |f| File.join(cookbook_path, "libraries", f) } - @defn_files = %w{client.rb server.rb}.map { |f| File.join(cookbook_path, "definitions", f)} + @defn_files = %w{client.rb server.rb}.map { |f| File.join(cookbook_path, "definitions", f) } @recipes = %w{default.rb gigantor.rb one.rb return.rb}.map { |f| File.join(cookbook_path, "recipes", f) } @ruby_files = @attr_files + @libr_files + @defn_files + @recipes + [File.join(cookbook_path, "metadata.rb")] basenames = %w{ helpers_via_partial_test.erb @@ -62,7 +62,7 @@ describe Chef::Cookbook::SyntaxCheck do some_windows_line_endings.erb all_windows_line_endings.erb no_windows_line_endings.erb } - @template_files = basenames.map { |f| File.join(cookbook_path, "templates", "default", f)} + @template_files = basenames.map { |f| File.join(cookbook_path, "templates", "default", f) } end after do @@ -104,7 +104,6 @@ describe Chef::Cookbook::SyntaxCheck do it "lists the erb templates in the cookbook" do expect(syntax_check.template_files.sort).to eq(@template_files.sort) end - end describe "when validating cookbooks" do @@ -171,9 +170,8 @@ describe Chef::Cookbook::SyntaxCheck do it "does not remove the invalid template from the list of untested templates" do expect(syntax_check.untested_template_files).to include(File.join(cookbook_path, "templates", "default", "borken.erb")) - expect {syntax_check.validate_templates}.not_to change(syntax_check, :untested_template_files) + expect { syntax_check.validate_templates }.not_to change(syntax_check, :untested_template_files) end - end describe "and an ignored file has a syntax error" do @@ -192,9 +190,7 @@ describe Chef::Cookbook::SyntaxCheck do expect(syntax_check.validate_ruby_files).to be_truthy expect(syntax_check.untested_ruby_files).to be_empty end - end - end describe "and the files have been syntax checked previously" do diff --git a/spec/unit/cookbook_loader_spec.rb b/spec/unit/cookbook_loader_spec.rb index df2777ff43..d18ca8a131 100644 --- a/spec/unit/cookbook_loader_spec.rb +++ b/spec/unit/cookbook_loader_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::CookbookLoader do before do - allow(ChefConfig).to receive(:windows?) {false} + allow(ChefConfig).to receive(:windows?) { false } end let(:repo_paths) do [ @@ -48,7 +48,6 @@ describe Chef::CookbookLoader do cookbook_loader.load_cookbooks end - context "after loading all cookbooks" do before(:each) do cookbook_loader.load_cookbooks @@ -168,13 +167,10 @@ describe Chef::CookbookLoader do expect(cookbook_loader.metadata[:openldap].name.to_s).to eq("openldap") expect(cookbook_loader.metadata[:openldap]).to be_a_kind_of(Chef::Cookbook::Metadata) end - end # referencing cookbook files - end # loading all cookbooks context "loading all cookbooks when one has invalid metadata" do - let(:repo_paths) do [ File.join(CHEF_SPEC_DATA, "kitchen"), @@ -186,11 +182,9 @@ describe Chef::CookbookLoader do it "does not squelch the exception" do expect { cookbook_loader.load_cookbooks }.to raise_error("THIS METADATA HAS A BUG") end - end describe "loading only one cookbook" do - let(:openldap_cookbook) { cookbook_loader["openldap"] } let(:cookbook_as_hash) { Chef::CookbookManifest.new(openldap_cookbook).to_hash } @@ -240,7 +234,6 @@ describe Chef::CookbookLoader do end context "when an unrelated cookbook has invalid metadata" do - let(:repo_paths) do [ File.join(CHEF_SPEC_DATA, "kitchen"), @@ -256,7 +249,6 @@ describe Chef::CookbookLoader do it "surfaces the exception if the cookbook is loaded later" do expect { cookbook_loader["invalid-metadata"] }.to raise_error("THIS METADATA HAS A BUG") end - end describe "loading all cookbooks after loading only one cookbook" do @@ -276,7 +268,6 @@ describe Chef::CookbookLoader do end # loading only one cookbook describe "loading a single cookbook with a different name than basename" do - before(:each) do cookbook_loader.load_cookbook("name-mismatch") end @@ -286,6 +277,5 @@ describe Chef::CookbookLoader do expect(cookbook_version).to be_a_kind_of(Chef::CookbookVersion) expect(cookbook_version.name).to eq(:"name-mismatch") end - end end diff --git a/spec/unit/cookbook_manifest_spec.rb b/spec/unit/cookbook_manifest_spec.rb index d2a1a83e37..a301fe3ca1 100644 --- a/spec/unit/cookbook_manifest_spec.rb +++ b/spec/unit/cookbook_manifest_spec.rb @@ -21,7 +21,6 @@ require "chef/digester" require "pathname" describe Chef::CookbookManifest do - let(:version) { "1.2.3" } let(:identifier) { "9e10455ce2b4a4e29424b7064b1d67a1a25c9d3b" } @@ -46,17 +45,14 @@ describe Chef::CookbookManifest do subject(:cookbook_manifest) { Chef::CookbookManifest.new(cookbook_version, policy_mode: policy_mode) } context "when policy mode is not specified" do - subject(:cookbook_manifest) { Chef::CookbookManifest.new(cookbook_version) } it "defaults to policies disabled" do expect(cookbook_manifest.policy_mode?).to be(false) end - end describe "collecting cookbook data from the cookbook version object" do - it "delegates `name' to cookbook_version" do expect(cookbook_manifest.name).to eq("tatft") end @@ -85,11 +81,9 @@ describe Chef::CookbookManifest do expect(cookbook_version).to receive(:segment_filenames).with(:recipes).and_return([]) expect(cookbook_manifest.segment_filenames(:recipes)).to eq([]) end - end context "when given an empty cookbook" do - let(:expected_hash) do { "chef_type" => "cookbook_version", @@ -101,26 +95,24 @@ describe Chef::CookbookManifest do "frozen?" => false, - "recipes" =>[], - "definitions" =>[], - "libraries" =>[], - "attributes" =>[], - "files" =>[], - "templates" =>[], - "resources" =>[], - "providers" =>[], - "root_files" =>[], + "recipes" => [], + "definitions" => [], + "libraries" => [], + "attributes" => [], + "files" => [], + "templates" => [], + "resources" => [], + "providers" => [], + "root_files" => [], } end it "converts the CookbookVersion to a ruby Hash representation" do expect(cookbook_manifest.to_hash).to eq(expected_hash) end - end context "when given a cookbook with files" do - let(:cookbook_root) { File.join(CHEF_SPEC_DATA, "cb_version_cookbooks", "tatft") } let(:attribute_filenames) { Dir[File.join(cookbook_root, "attributes", "**", "*.rb")] } @@ -138,7 +130,6 @@ describe Chef::CookbookManifest do def map_to_file_specs(paths) paths.map do |path| - relative_path = Pathname.new(path).relative_path_from(Pathname.new(cookbook_root)).to_s { @@ -194,13 +185,10 @@ describe Chef::CookbookManifest do expect(cookbook_manifest_hash[key]).to eq(expected_hash[key]) end end - end describe "providing upstream URLs for save" do - context "and policy mode is disabled" do - it "gives the save URL" do expect(cookbook_manifest.save_url).to eq("cookbooks/tatft/1.2.3") end @@ -208,11 +196,9 @@ describe Chef::CookbookManifest do it "gives the force save URL" do expect(cookbook_manifest.force_save_url).to eq("cookbooks/tatft/1.2.3?force=true") end - end context "and policy mode is enabled" do - let(:policy_mode) { true } let(:cookbook_manifest_hash) { cookbook_manifest.to_hash } @@ -236,9 +222,6 @@ describe Chef::CookbookManifest do it "gives the force save URL" do expect(cookbook_manifest.force_save_url).to eq("cookbook_artifacts/tatft/9e10455ce2b4a4e29424b7064b1d67a1a25c9d3b?force=true") end - end end - end - diff --git a/spec/unit/cookbook_site_streaming_uploader_spec.rb b/spec/unit/cookbook_site_streaming_uploader_spec.rb index a2511fcdf1..b111b2948b 100644 --- a/spec/unit/cookbook_site_streaming_uploader_spec.rb +++ b/spec/unit/cookbook_site_streaming_uploader_spec.rb @@ -31,13 +31,10 @@ class FakeTempfile def path "#{@basename}.ZZZ" end - end describe Chef::CookbookSiteStreamingUploader do - describe "create_build_dir" do - before(:each) do @cookbook_repo = File.expand_path(File.join(CHEF_SPEC_DATA, "cookbooks")) @loader = Chef::CookbookLoader.new(@cookbook_repo) @@ -54,11 +51,9 @@ describe Chef::CookbookSiteStreamingUploader do expect(FileUtils).to receive(:cp).exactly(files_count).times Chef::CookbookSiteStreamingUploader.create_build_dir(cookbook) end - end # create_build_dir describe "make_request" do - before(:each) do @uri = "http://cookbooks.dummy.com/api/v1/cookbooks" @secret_filename = File.join(CHEF_SPEC_DATA, "ssl/private_key.pem") @@ -102,25 +97,24 @@ describe Chef::CookbookSiteStreamingUploader do it "should be able to receive files to attach as argument" do Chef::CookbookSiteStreamingUploader.make_request(:put, @uri, "bill", @secret_filename, { - :myfile => File.new(File.join(CHEF_SPEC_DATA, "config.rb")), # a dummy file - }) + :myfile => File.new(File.join(CHEF_SPEC_DATA, "config.rb")), # a dummy file + }) end it "should be able to receive strings to attach as argument" do Chef::CookbookSiteStreamingUploader.make_request(:put, @uri, "bill", @secret_filename, { - :mystring => "Lorem ipsum" - }) + :mystring => "Lorem ipsum" + }) end it "should be able to receive strings and files as argument at the same time" do Chef::CookbookSiteStreamingUploader.make_request(:put, @uri, "bill", @secret_filename, { - :myfile1 => File.new(File.join(CHEF_SPEC_DATA, "config.rb")), - :mystring1 => "Lorem ipsum", - :myfile2 => File.new(File.join(CHEF_SPEC_DATA, "config.rb")), - :mystring2 => "Dummy text", - }) + :myfile1 => File.new(File.join(CHEF_SPEC_DATA, "config.rb")), + :mystring1 => "Lorem ipsum", + :myfile2 => File.new(File.join(CHEF_SPEC_DATA, "config.rb")), + :mystring2 => "Dummy text", + }) end - end # make_request describe "StreamPart" do @@ -142,7 +136,6 @@ describe Chef::CookbookSiteStreamingUploader do @file.rewind expect(@stream_part.read(0, 4)).to eql(content) end - end # StreamPart describe "StringPart" do @@ -162,7 +155,6 @@ describe Chef::CookbookSiteStreamingUploader do it "should read with offset and how_much" do expect(@string_part.read(2, 4)).to eql(@str[2, 4]) end - end # StringPart describe "MultipartStream" do @@ -193,7 +185,5 @@ describe Chef::CookbookSiteStreamingUploader do @multipart_stream.read(10, dst_buf) expect(dst_buf).to eql("#{@string1}#{@string2}"[0, 10]) end - end # MultipartStream - end diff --git a/spec/unit/cookbook_spec.rb b/spec/unit/cookbook_spec.rb index f931b43eaa..62c7bb4107 100644 --- a/spec/unit/cookbook_spec.rb +++ b/spec/unit/cookbook_spec.rb @@ -62,5 +62,4 @@ describe Chef::CookbookVersion do it "should raise an ArgumentException if you try to load a bad recipe name" do expect { @cookbook.load_recipe("doesnt_exist", @node) }.to raise_error(ArgumentError) end - end diff --git a/spec/unit/cookbook_uploader_spec.rb b/spec/unit/cookbook_uploader_spec.rb index 943fbf828d..59ba1c91b7 100644 --- a/spec/unit/cookbook_uploader_spec.rb +++ b/spec/unit/cookbook_uploader_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::CookbookUploader do - let(:http_client) { double("Chef::ServerAPI") } let(:cookbook_loader) do @@ -71,14 +70,13 @@ describe Chef::CookbookUploader do end describe "uploading cookbooks" do - def url_for(cksum) "https://storage.example.com/#{cksum}" end let(:sandbox_response) do sandbox_checksums = cksums_not_on_remote.inject({}) do |cksum_map, cksum| - cksum_map[cksum] = { "needs_upload" => true, "url" => url_for(cksum)} + cksum_map[cksum] = { "needs_upload" => true, "url" => url_for(cksum) } cksum_map end { "checksums" => sandbox_checksums, "uri" => sandbox_commit_uri } @@ -86,7 +84,7 @@ describe Chef::CookbookUploader do def expect_sandbox_create expect(http_client).to receive(:post). - with("sandboxes", {:checksums => checksums_set}). + with("sandboxes", { :checksums => checksums_set }). and_return(sandbox_response) end @@ -102,7 +100,6 @@ describe Chef::CookbookUploader do expect(http_client).to receive(:put). with(url_for(md5), IO.binread(file_path), upload_headers) - end end @@ -111,20 +108,17 @@ describe Chef::CookbookUploader do end def expect_sandbox_commit - expect(http_client).to receive(:put).with(sandbox_commit_uri, {:is_completed => true}) + expect(http_client).to receive(:put).with(sandbox_commit_uri, { :is_completed => true }) end def expect_cookbook_create cookbooks_to_upload.each do |cookbook| - expect(http_client).to receive(:put). with(expected_save_url(cookbook), cookbook) - end end context "when no files exist on the server" do - let(:cksums_not_on_remote) do checksums_of_cookbook_files.keys end @@ -137,11 +131,9 @@ describe Chef::CookbookUploader do uploader.upload_cookbooks end - end context "when some files exist on the server" do - let(:cksums_not_on_remote) do checksums_of_cookbook_files.keys[0, 1] end @@ -154,11 +146,9 @@ describe Chef::CookbookUploader do uploader.upload_cookbooks end - end context "when all files already exist on the server" do - let(:cksums_not_on_remote) { [] } it "uploads all files in a sandbox transaction, then creates cookbooks on the server" do @@ -169,11 +159,9 @@ describe Chef::CookbookUploader do uploader.upload_cookbooks end - end context "when policy_mode is specified" do - let(:cksums_not_on_remote) do checksums_of_cookbook_files.keys end @@ -192,9 +180,6 @@ describe Chef::CookbookUploader do uploader.upload_cookbooks end - - end end - end diff --git a/spec/unit/cookbook_version_file_specificity_spec.rb b/spec/unit/cookbook_version_file_specificity_spec.rb index d3fac7256f..9236170a5a 100644 --- a/spec/unit/cookbook_version_file_specificity_spec.rb +++ b/spec/unit/cookbook_version_file_specificity_spec.rb @@ -199,10 +199,8 @@ describe Chef::CookbookVersion, "file specificity" do }, ] } - end - it "should return a manifest record based on priority preference: host" do node = Chef::Node.new node.automatic_attrs[:platform] = "ubuntu" @@ -303,7 +301,6 @@ describe Chef::CookbookVersion, "file specificity" do end describe "when fetching the contents of a directory by file specificity" do - it "should return a directory of manifest records based on priority preference: host" do node = Chef::Node.new node.automatic_attrs[:platform] = "ubuntu" @@ -314,7 +311,7 @@ describe Chef::CookbookVersion, "file specificity" do expect(manifest_records).not_to be_nil expect(manifest_records.size).to eq(2) - checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } + checksums = manifest_records.map { |manifest_record| manifest_record[:checksum] } expect(checksums.sort).to eq(["csum-host-1", "csum-host-2"]) end @@ -328,7 +325,7 @@ describe Chef::CookbookVersion, "file specificity" do expect(manifest_records).not_to be_nil expect(manifest_records.size).to eq(2) - checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } + checksums = manifest_records.map { |manifest_record| manifest_record[:checksum] } expect(checksums.sort).to eq(["csum-platver-full-1", "csum-platver-full-2"]) end @@ -342,7 +339,7 @@ describe Chef::CookbookVersion, "file specificity" do expect(manifest_records).not_to be_nil expect(manifest_records.size).to eq(2) - checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } + checksums = manifest_records.map { |manifest_record| manifest_record[:checksum] } expect(checksums.sort).to eq(["csum-platver-partial-1", "csum-platver-partial-2"]) end @@ -356,7 +353,7 @@ describe Chef::CookbookVersion, "file specificity" do expect(manifest_records).not_to be_nil expect(manifest_records.size).to eq(2) - checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } + checksums = manifest_records.map { |manifest_record| manifest_record[:checksum] } expect(checksums.sort).to eq(["csum-plat-1", "csum-plat-2"]) end @@ -370,7 +367,7 @@ describe Chef::CookbookVersion, "file specificity" do expect(manifest_records).not_to be_nil expect(manifest_records.size).to eq(2) - checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } + checksums = manifest_records.map { |manifest_record| manifest_record[:checksum] } expect(checksums.sort).to eq(["csum-default-1", "csum-default-2"]) end @@ -384,7 +381,7 @@ describe Chef::CookbookVersion, "file specificity" do expect(manifest_records).not_to be_nil expect(manifest_records.size).to eq(2) - checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } + checksums = manifest_records.map { |manifest_record| manifest_record[:checksum] } expect(checksums.sort).to eq(["csum2-platver-full-1", "csum2-platver-full-2"]) end @@ -398,7 +395,7 @@ describe Chef::CookbookVersion, "file specificity" do expect(manifest_records).not_to be_nil expect(manifest_records.size).to eq(2) - checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } + checksums = manifest_records.map { |manifest_record| manifest_record[:checksum] } expect(checksums.sort).to eq(["csum2-platver-partial-1", "csum2-platver-partial-2"]) end @@ -412,7 +409,7 @@ describe Chef::CookbookVersion, "file specificity" do expect(manifest_records).not_to be_nil expect(manifest_records.size).to eq(2) - checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } + checksums = manifest_records.map { |manifest_record| manifest_record[:checksum] } expect(checksums.sort).to eq(["csum3-platver-full-1", "csum3-platver-full-2"]) end @@ -426,7 +423,7 @@ describe Chef::CookbookVersion, "file specificity" do expect(manifest_records).not_to be_nil expect(manifest_records.size).to eq(2) - checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } + checksums = manifest_records.map { |manifest_record| manifest_record[:checksum] } expect(checksums.sort).to eq(["csum4-platver-full-1", "csum4-platver-full-2"]) end end diff --git a/spec/unit/cookbook_version_spec.rb b/spec/unit/cookbook_version_spec.rb index cabfc228ea..687c78f303 100644 --- a/spec/unit/cookbook_version_spec.rb +++ b/spec/unit/cookbook_version_spec.rb @@ -71,7 +71,6 @@ describe Chef::CookbookVersion do it "has empty metadata" do expect(@cookbook_version.metadata).to eq(Chef::Cookbook::Metadata.new) end - end describe "with a cookbook directory named tatft" do @@ -151,7 +150,6 @@ describe Chef::CookbookVersion do end end end - end describe "with a cookbook directory named cookbook2 that has unscoped files" do @@ -230,12 +228,9 @@ describe Chef::CookbookVersion do it "should not see a non-existent file using an array lookup" do expect(@cookbook_version).not_to have_cookbook_file_for_node(@node, ["missing.txt"]) end - end - describe "<=>" do - it "should sort based on the version number" do examples = [ # smaller, larger @@ -270,13 +265,12 @@ describe Chef::CookbookVersion do expect(a).to eq(b) end - it "should not allow you to sort cookbooks with different names" do apt = Chef::CookbookVersion.new "apt", "/tmp/blah" apt.version = "1.0" god = Chef::CookbookVersion.new "god", "/tmp/blah" god.version = "2.0" - expect {apt <=> god}.to raise_error(Chef::Exceptions::CookbookVersionNameMismatch) + expect { apt <=> god }.to raise_error(Chef::Exceptions::CookbookVersionNameMismatch) end end @@ -296,25 +290,21 @@ describe Chef::CookbookVersion do "1 2 3", "1-2-3", "1_2_3", "1.2_3", "1.2-3"] the_error = Chef::Exceptions::InvalidCookbookVersion bad_versions.each do |v| - expect {@cbv.version = v}.to raise_error(the_error) + expect { @cbv.version = v }.to raise_error(the_error) end end - end describe "when deprecation warnings are errors" do - subject(:cbv) { Chef::CookbookVersion.new("version validation", "/tmp/blah") } it "errors on #status and #status=" do expect { cbv.status = :wat }.to raise_error(Chef::Exceptions::DeprecatedFeatureError) expect { cbv.status }.to raise_error(Chef::Exceptions::DeprecatedFeatureError) end - end describe "deprecated features" do - subject(:cbv) { Chef::CookbookVersion.new("tatft", "/tmp/blah").tap { |c| c.version = "1.2.3" } } before do @@ -335,10 +325,8 @@ describe Chef::CookbookVersion do expect(cbv.status).to eq(:ready) end - include_examples "to_json equivalent to Chef::JSONCompat.to_json" do let(:jsonable) { Chef::CookbookVersion.new("tatft", "/tmp/blah") } end - end end diff --git a/spec/unit/daemon_spec.rb b/spec/unit/daemon_spec.rb index e31ce7d151..d69826fb85 100644 --- a/spec/unit/daemon_spec.rb +++ b/spec/unit/daemon_spec.rb @@ -33,9 +33,7 @@ describe Chef::Daemon do end describe ".pid_file" do - describe "when the pid_file option has been set" do - before do Chef::Config[:pid_file] = "/var/run/chef/chef-client.pid" end @@ -46,7 +44,6 @@ describe Chef::Daemon do end describe "without the pid_file option set" do - before do Chef::Daemon.name = "chef-client" end @@ -54,12 +51,10 @@ describe Chef::Daemon do it "should return a valued based on @name" do expect(Chef::Daemon.pid_file).to eql("/tmp/chef-client.pid") end - end end describe ".pid_from_file" do - before do Chef::Config[:pid_file] = "/var/run/chef/chef-client.pid" end @@ -71,7 +66,6 @@ describe Chef::Daemon do end describe ".change_privilege" do - before do allow(Chef::Application).to receive(:fatal!).and_return(true) Chef::Config[:user] = "aj" @@ -84,7 +78,6 @@ describe Chef::Daemon do end describe "when the user and group options are supplied" do - before do Chef::Config[:group] = "staff" end @@ -114,7 +107,6 @@ describe Chef::Daemon do end describe "._change_privilege" do - before do allow(Process).to receive(:euid).and_return(0) allow(Process).to receive(:egid).and_return(0) @@ -169,6 +161,5 @@ describe Chef::Daemon do Chef::Daemon._change_privilege("aj") end end - end end diff --git a/spec/unit/data_bag_item_spec.rb b/spec/unit/data_bag_item_spec.rb index 22ed95267a..84eb04d9da 100644 --- a/spec/unit/data_bag_item_spec.rb +++ b/spec/unit/data_bag_item_spec.rb @@ -176,7 +176,6 @@ describe Chef::DataBagItem do let(:deserial) { Chef::DataBagItem.from_hash(Chef::JSONCompat.parse(Chef::JSONCompat.to_json(data_bag_item))) } - it "should deserialize to a Chef::DataBagItem object" do expect(deserial).to be_a_kind_of(Chef::DataBagItem) end @@ -205,7 +204,7 @@ describe Chef::DataBagItem do end it "inspects as data_bag_item[BAG, ID, RAW_DATA]" do - raw_data = {"id" => "heart_of_darkness", "author" => "Conrad"} + raw_data = { "id" => "heart_of_darkness", "author" => "Conrad" } data_bag_item.raw_data = raw_data data_bag_item.data_bag("books") @@ -219,7 +218,7 @@ describe Chef::DataBagItem do let(:data_bag_item) { data_bag_item = Chef::DataBagItem.new data_bag_item["id"] = "heart of darkness" - data_bag_item.raw_data = {"id" => "heart_of_darkness", "author" => "Conrad"} + data_bag_item.raw_data = { "id" => "heart_of_darkness", "author" => "Conrad" } data_bag_item.data_bag("books") data_bag_item } @@ -255,7 +254,6 @@ describe Chef::DataBagItem do data_bag_item.save end end - end describe "destroy" do @@ -278,7 +276,7 @@ describe Chef::DataBagItem do describe "when loading" do before do - data_bag_item.raw_data = {"id" => "charlie", "shell" => "zsh", "ssh_keys" => %w{key1 key2}} + data_bag_item.raw_data = { "id" => "charlie", "shell" => "zsh", "ssh_keys" => %w{key1 key2} } data_bag_item.data_bag("users") end @@ -314,7 +312,7 @@ describe Chef::DataBagItem do end it "converts the raw data to a data bag item" do - expect(Chef::DataBag).to receive(:load).with("users").and_return({"charlie" => data_bag_item.to_hash}) + expect(Chef::DataBag).to receive(:load).with("users").and_return({ "charlie" => data_bag_item.to_hash }) item = Chef::DataBagItem.load("users", "charlie") expect(item).to be_a_kind_of(Chef::DataBagItem) expect(item).to eq(data_bag_item) diff --git a/spec/unit/data_bag_spec.rb b/spec/unit/data_bag_spec.rb index c2bcff4378..05c55cba96 100644 --- a/spec/unit/data_bag_spec.rb +++ b/spec/unit/data_bag_spec.rb @@ -77,7 +77,6 @@ describe Chef::DataBag do let(:jsonable) { @data_bag } end end - end describe "when saving" do @@ -110,7 +109,6 @@ describe Chef::DataBag do @data_bag.save end end - end describe "when loading" do describe "from an API call" do @@ -127,9 +125,9 @@ describe Chef::DataBag do it "should return the data bag" do allow(Chef::ServerAPI).to receive(:new).and_return(@http_client) - expect(@http_client).to receive(:get).with("data/foo").and_return({"bar" => "https://myserver.example.com/data/foo/bar"}) + expect(@http_client).to receive(:get).with("data/foo").and_return({ "bar" => "https://myserver.example.com/data/foo/bar" }) data_bag = Chef::DataBag.load("foo") - expect(data_bag).to eq({"bar" => "https://myserver.example.com/data/foo/bar"}) + expect(data_bag).to eq({ "bar" => "https://myserver.example.com/data/foo/bar" }) end end @@ -180,7 +178,7 @@ describe Chef::DataBag do expect(IO).to receive(:read).with(File.join(@paths.first, "foo/bar.json")).and_return('{"id": "bar", "name": "Bob Bar" }') expect(IO).to receive(:read).with(File.join(@paths.first, "foo/baz.json")).and_return('{"id": "baz", "name": "John Baz" }') data_bag = Chef::DataBag.load("foo") - expect(data_bag).to eq({ "bar" => { "id" => "bar", "name" => "Bob Bar" }, "baz" => { "id" => "baz", "name" => "John Baz" }}) + expect(data_bag).to eq({ "bar" => { "id" => "bar", "name" => "Bob Bar" }, "baz" => { "id" => "baz", "name" => "John Baz" } }) end it "should raise if data bag has items with similar names but different content" do @@ -208,7 +206,7 @@ describe Chef::DataBag do expect(IO).to receive(:read).with(File.join(path, "foo/baz.json")).and_return(item_with_same_content) end data_bag = Chef::DataBag.load("foo") - test_data_bag = { "bar" => { "id" => "bar", "name" => "Bob Bar"} } + test_data_bag = { "bar" => { "id" => "bar", "name" => "Bob Bar" } } expect(data_bag).to eq(test_data_bag) end @@ -222,7 +220,7 @@ describe Chef::DataBag do expect(IO).to receive(:read).with(File.join(path, "foo/baz.json")).and_return(test_uniq_item) end data_bag = Chef::DataBag.load("foo") - test_data_bag = { "bar" => { "id" => "bar", "name" => "Bob Bar"} } + test_data_bag = { "bar" => { "id" => "bar", "name" => "Bob Bar" } } @paths.each_with_index do |path, index| test_data_bag["baz_#{index}"] = { "id" => "baz_#{index}", "name" => "John Baz", "path" => path } end @@ -245,7 +243,6 @@ describe Chef::DataBag do Chef::DataBag.load("foo") }.to raise_error Chef::Exceptions::InvalidDataBagPath, "Data bag path '/var/chef/data_bags' is invalid" end - end describe "data bag with string path" do @@ -256,5 +253,4 @@ describe Chef::DataBag do it_should_behave_like "data bag in solo mode", ["/var/chef/data_bags", "/var/chef/data_bags_2"] end end - end diff --git a/spec/unit/deprecation_spec.rb b/spec/unit/deprecation_spec.rb index af8e34850b..2462d912c9 100644 --- a/spec/unit/deprecation_spec.rb +++ b/spec/unit/deprecation_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "chef/deprecation/warnings" describe Chef::Deprecation do - # Support code for Chef::Deprecation def self.class_from_string(str) @@ -146,5 +145,4 @@ describe Chef::Deprecation do end end end - end diff --git a/spec/unit/digester_spec.rb b/spec/unit/digester_spec.rb index 9fa0f9235b..a255bce677 100644 --- a/spec/unit/digester_spec.rb +++ b/spec/unit/digester_spec.rb @@ -26,7 +26,6 @@ describe Chef::Digester do end describe "when computing checksums of cookbook files and templates" do - it "proxies the class method checksum_for_file to the instance" do expect(@cache).to receive(:checksum_for_file).with("a_file_or_a_fail") Chef::Digester.checksum_for_file("a_file_or_a_fail") @@ -43,8 +42,5 @@ describe Chef::Digester do expected_md5 = "0e157ac1e2dd73191b76067fb6b4bceb" expect(@cache.generate_md5_checksum(io)).to eq(expected_md5) end - end - end - diff --git a/spec/unit/dsl/audit_spec.rb b/spec/unit/dsl/audit_spec.rb index df8dbc95c0..d7a55c89cb 100644 --- a/spec/unit/dsl/audit_spec.rb +++ b/spec/unit/dsl/audit_spec.rb @@ -17,15 +17,15 @@ describe Chef::DSL::Audit do let(:cookbook_collection) { {} } it "raises an error when a block of audits is not provided" do - expect{ auditor.control_group "name" }.to raise_error(Chef::Exceptions::NoAuditsProvided) + expect { auditor.control_group "name" }.to raise_error(Chef::Exceptions::NoAuditsProvided) end it "raises an error when no audit name is given" do - expect{ auditor.control_group do end }.to raise_error(Chef::Exceptions::AuditNameMissing) + expect { auditor.control_group do end }.to raise_error(Chef::Exceptions::AuditNameMissing) end context "audits already populated" do - let(:audits) { {"unique" => {} } } + let(:audits) { { "unique" => {} } } it "raises an error if the audit name is a duplicate" do expect { auditor.control_group "unique" do end }.to raise_error(Chef::Exceptions::AuditControlGroupDuplicate) @@ -39,5 +39,4 @@ describe Chef::DSL::Audit do expect { auditor.control_group "unique" do end }.to raise_error(NoMethodError, /undefined method `cookbook_name'/) end end - end diff --git a/spec/unit/dsl/data_query_spec.rb b/spec/unit/dsl/data_query_spec.rb index 36f9aa13b1..22b4c07b80 100644 --- a/spec/unit/dsl/data_query_spec.rb +++ b/spec/unit/dsl/data_query_spec.rb @@ -35,23 +35,23 @@ describe Chef::DSL::DataQuery do describe "::data_bag" do it "lists the items in a data bag" do allow(Chef::DataBag).to receive(:load) - .with("bag_name") - .and_return("item_1" => "http://url_for/item_1", "item_2" => "http://url_for/item_2") + .with("bag_name") + .and_return("item_1" => "http://url_for/item_1", "item_2" => "http://url_for/item_2") expect( language.data_bag("bag_name").sort ).to eql %w{item_1 item_2} end end shared_examples_for "a data bag item" do it "validates the name of the data bag you're trying to load an item from" do - expect{ language.send(method_name, " %%^& ", "item_name") }.to raise_error(Chef::Exceptions::InvalidDataBagName) + expect { language.send(method_name, " %%^& ", "item_name") }.to raise_error(Chef::Exceptions::InvalidDataBagName) end it "validates the id of the data bag item you're trying to load" do - expect{ language.send(method_name, "bag_name", " 987 (*&()") }.to raise_error(Chef::Exceptions::InvalidDataBagItemID) + expect { language.send(method_name, "bag_name", " 987 (*&()") }.to raise_error(Chef::Exceptions::InvalidDataBagItemID) end it "validates that the id of the data bag item is not nil" do - expect{ language.send(method_name, "bag_name", nil) }.to raise_error(Chef::Exceptions::InvalidDataBagItemID) + expect { language.send(method_name, "bag_name", nil) }.to raise_error(Chef::Exceptions::InvalidDataBagItemID) end end @@ -100,7 +100,6 @@ describe Chef::DSL::DataQuery do expect( Chef::Log ).to receive(:debug).with(/Data bag item looks encrypted/) expect(language.data_bag_item(bag_name, item_name)).to eq(enc_data_bag) end - end end end diff --git a/spec/unit/dsl/platform_introspection_spec.rb b/spec/unit/dsl/platform_introspection_spec.rb index 24f63d126b..86239b8f81 100644 --- a/spec/unit/dsl/platform_introspection_spec.rb +++ b/spec/unit/dsl/platform_introspection_spec.rb @@ -28,20 +28,18 @@ class LanguageTester end describe "PlatformIntrospection implementors" do - let(:node) { Chef::Node.new } let(:platform_introspector) { LanguageTester.new(node) } it_behaves_like "a platform introspector" - end describe Chef::DSL::PlatformIntrospection::PlatformDependentValue do before do platform_hash = { - :openbsd => {:default => "free, functional, secure"}, - [:redhat, :centos, :fedora, :scientific] => {:default => '"stable"'}, - :ubuntu => {"10.04" => "using upstart more", :default => "using init more"}, + :openbsd => { :default => "free, functional, secure" }, + [:redhat, :centos, :fedora, :scientific] => { :default => '"stable"' }, + :ubuntu => { "10.04" => "using upstart more", :default => "using init more" }, :default => "bork da bork", } @platform_specific_value = Chef::DSL::PlatformIntrospection::PlatformDependentValue.new(platform_hash) @@ -60,12 +58,12 @@ describe Chef::DSL::PlatformIntrospection::PlatformDependentValue do end it "returns a value for a specific platform version" do - node = {:platform => "ubuntu", :platform_version => "10.04"} + node = { :platform => "ubuntu", :platform_version => "10.04" } expect(@platform_specific_value.value_for_node(node)).to eq("using upstart more") end it "returns a platform-default value if the platform version doesn't match an explicit one" do - node = {:platform => "ubuntu", :platform_version => "9.10" } + node = { :platform => "ubuntu", :platform_version => "9.10" } expect(@platform_specific_value.value_for_node(node)).to eq("using init more") end @@ -77,10 +75,9 @@ describe Chef::DSL::PlatformIntrospection::PlatformDependentValue do end it "raises an argument error if the platform hash is not correctly structured" do - bad_hash = {:ubuntu => :foo} # should be :ubuntu => {:default => 'foo'} - expect {Chef::DSL::PlatformIntrospection::PlatformDependentValue.new(bad_hash)}.to raise_error(ArgumentError) + bad_hash = { :ubuntu => :foo } # should be :ubuntu => {:default => 'foo'} + expect { Chef::DSL::PlatformIntrospection::PlatformDependentValue.new(bad_hash) }.to raise_error(ArgumentError) end - end describe Chef::DSL::PlatformIntrospection::PlatformFamilyDependentValue do before do @@ -101,7 +98,6 @@ describe Chef::DSL::PlatformIntrospection::PlatformFamilyDependentValue do expect(@platform_family_value.value_for_node(:platform_family => :os2)).to eq("default value") end - it "returns a value for the platform family when it was set as a string but fetched as a symbol" do expect(@platform_family_value.value_for_node(:platform_family => :debian)).to eq("debian value") end @@ -126,5 +122,4 @@ describe Chef::DSL::PlatformIntrospection::PlatformFamilyDependentValue do platform_specific_value = Chef::DSL::PlatformIntrospection::PlatformFamilyDependentValue.new({}) expect(platform_specific_value.value_for_node(:platform_family => "foo")).to be_nil end - end diff --git a/spec/unit/dsl/reboot_pending_spec.rb b/spec/unit/dsl/reboot_pending_spec.rb index 42891195bf..33e96e0e7a 100644 --- a/spec/unit/dsl/reboot_pending_spec.rb +++ b/spec/unit/dsl/reboot_pending_spec.rb @@ -34,22 +34,22 @@ describe Chef::DSL::RebootPending do allow(recipe).to receive(:registry_key_exists?).and_return(false) allow(recipe).to receive(:registry_value_exists?).and_return(false) end - + it 'should return true if "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations" exists' do allow(recipe).to receive(:registry_value_exists?).with('HKLM\SYSTEM\CurrentControlSet\Control\Session Manager', { :name => "PendingFileRenameOperations" }).and_return(true) expect(recipe.reboot_pending?).to be_truthy end - + it 'should return true if "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" exists' do allow(recipe).to receive(:registry_key_exists?).with('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired').and_return(true) expect(recipe.reboot_pending?).to be_truthy end - + it 'should return true if key "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootRequired" exists' do allow(recipe).to receive(:registry_key_exists?).with('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending').and_return(true) expect(recipe.reboot_pending?).to be_truthy end - + context "version is server 2003" do before do allow(Chef::Platform).to receive(:windows_server_2003?).and_return(true) @@ -58,34 +58,33 @@ describe Chef::DSL::RebootPending do it 'should return true if value "HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile" contains specific data on 2k3' do allow(recipe).to receive(:registry_key_exists?).with('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile').and_return(true) allow(recipe).to receive(:registry_get_values).with('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile').and_return( - [{:name => "Flags", :type => :dword, :data => 3}]) + [{ :name => "Flags", :type => :dword, :data => 3 }]) expect(recipe.reboot_pending?).to be_truthy end end end - + context "platform is ubuntu" do before do allow(recipe).to receive(:platform?).with("ubuntu").and_return(true) end - + it "should return true if /var/run/reboot-required exists" do allow(File).to receive(:exists?).with("/var/run/reboot-required").and_return(true) expect(recipe.reboot_pending?).to be_truthy end - + it "should return false if /var/run/reboot-required does not exist" do allow(File).to receive(:exists?).with("/var/run/reboot-required").and_return(false) expect(recipe.reboot_pending?).to be_falsey end end - end # describe in isolation describe "in a recipe" do it "responds to reboot_pending?" do # Chef::Recipe.new(cookbook_name, recipe_name, run_context(node, cookbook_collection, events)) - recipe = Chef::Recipe.new(nil,nil,Chef::RunContext.new(Chef::Node.new, {}, nil)) + recipe = Chef::Recipe.new(nil, nil, Chef::RunContext.new(Chef::Node.new, {}, nil)) expect(recipe).to respond_to(:reboot_pending?) end end # describe in a recipe diff --git a/spec/unit/dsl/recipe_spec.rb b/spec/unit/dsl/recipe_spec.rb index 534e430817..f0a8302f0d 100644 --- a/spec/unit/dsl/recipe_spec.rb +++ b/spec/unit/dsl/recipe_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" require "chef/dsl/recipe" - RecipeDSLExampleClass = Struct.new(:cookbook_name, :recipe_name) class RecipeDSLExampleClass include Chef::DSL::Recipe @@ -33,12 +32,10 @@ end # TODO: most of DSL::Recipe's implementation is tested in Chef::Recipe's tests, # move those to here. describe Chef::DSL::Recipe do - let(:cookbook_name) { "example_cb" } let(:recipe_name) { "example_recipe" } shared_examples_for "A Recipe DSL Implementation" do - it "responds to cookbook_name" do expect(recipe.cookbook_name).to eq(cookbook_name) end @@ -61,22 +58,16 @@ describe Chef::DSL::Recipe do end context "when included in a class that defines the required interface directly" do - let(:recipe) { RecipeDSLExampleClass.new(cookbook_name, recipe_name) } include_examples "A Recipe DSL Implementation" - end # This is the situation that occurs when the Recipe DSL gets mixed in to a # resource, for example. context "when included in a class that defines the required interface in a superclass" do - let(:recipe) { RecipeDSLExampleSubclass.new(cookbook_name, recipe_name) } include_examples "A Recipe DSL Implementation" - end - end - diff --git a/spec/unit/dsl/regsitry_helper_spec.rb b/spec/unit/dsl/regsitry_helper_spec.rb index 9b527ec36c..cda986b7d1 100644 --- a/spec/unit/dsl/regsitry_helper_spec.rb +++ b/spec/unit/dsl/regsitry_helper_spec.rb @@ -20,11 +20,10 @@ require "chef/dsl/registry_helper" require "spec_helper" describe Chef::Resource::RegistryKey do - before (:all) do events = Chef::EventDispatch::Dispatcher.new node = Chef::Node.new - node.consume_external_attrs(OHAI_SYSTEM.data,{}) + node.consume_external_attrs(OHAI_SYSTEM.data, {}) run_context = Chef::RunContext.new(node, {}, events) @resource = Chef::Resource::new("foo", run_context) end @@ -50,4 +49,3 @@ describe Chef::Resource::RegistryKey do end end end - diff --git a/spec/unit/dsl/resources_spec.rb b/spec/unit/dsl/resources_spec.rb index 3952483efc..53cd6fcdb1 100644 --- a/spec/unit/dsl/resources_spec.rb +++ b/spec/unit/dsl/resources_spec.rb @@ -44,7 +44,7 @@ describe Chef::DSL::Resources do end end end - it { is_expected.to eq [[:test_resource, "test_name"]]} + it { is_expected.to eq [[:test_resource, "test_name"]] } end context "with no resource added" do @@ -77,9 +77,9 @@ describe Chef::DSL::Resources do before do Chef::DSL::Resources.add_resource_dsl(:test_resource) test_class.new.instance_eval do - test_resource { } + test_resource {} end end - it { is_expected.to eq [[:test_resource, nil]]} + it { is_expected.to eq [[:test_resource, nil]] } end end diff --git a/spec/unit/encrypted_data_bag_item/check_encrypted_spec.rb b/spec/unit/encrypted_data_bag_item/check_encrypted_spec.rb index f435137061..611d40eed0 100644 --- a/spec/unit/encrypted_data_bag_item/check_encrypted_spec.rb +++ b/spec/unit/encrypted_data_bag_item/check_encrypted_spec.rb @@ -24,7 +24,6 @@ class CheckEncryptedTester end describe Chef::EncryptedDataBagItem::CheckEncrypted do - let(:tester) { CheckEncryptedTester.new } it "detects the item is not encrypted when the data is empty" do @@ -32,20 +31,19 @@ describe Chef::EncryptedDataBagItem::CheckEncrypted do end it "detects the item is not encrypted when the data only contains an id" do - expect(tester.encrypted?({id: "foo"})).to eq(false) + expect(tester.encrypted?({ id: "foo" })).to eq(false) end context "when the item is encrypted" do - let(:default_secret) { "abc123SECRET" } let(:item_name) { "item_name" } let(:raw_data) {{ - "id" => item_name, - "greeting" => "hello", - "nested" => { - "a1" => [1, 2, 3], - "a2" => { "b1" => true }, - }, + "id" => item_name, + "greeting" => "hello", + "nested" => { + "a1" => [1, 2, 3], + "a2" => { "b1" => true }, + }, }} let(:version) { 1 } @@ -89,7 +87,5 @@ describe Chef::EncryptedDataBagItem::CheckEncrypted do let(:encryptor) { Chef::EncryptedDataBagItem::Encryptor::Version3Encryptor } end end - end - end diff --git a/spec/unit/encrypted_data_bag_item_spec.rb b/spec/unit/encrypted_data_bag_item_spec.rb index 15e4057ec3..badb72c161 100644 --- a/spec/unit/encrypted_data_bag_item_spec.rb +++ b/spec/unit/encrypted_data_bag_item_spec.rb @@ -32,10 +32,9 @@ module Version0Encryptor end end -describe Chef::EncryptedDataBagItem::Encryptor do - +describe Chef::EncryptedDataBagItem::Encryptor do subject(:encryptor) { described_class.new(plaintext_data, key) } - let(:plaintext_data) { {"foo" => "bar"} } + let(:plaintext_data) { { "foo" => "bar" } } let(:key) { "passwd" } it "encrypts to format version 1 by default" do @@ -58,7 +57,6 @@ describe Chef::EncryptedDataBagItem::Encryptor do it "serializes the value in a de-serializable way" do expect(Chef::JSONCompat.from_json(encryptor.serialized_data)["json_wrapper"]).to eq 5 end - end describe "wrapping secret values in an envelope" do @@ -72,7 +70,6 @@ describe Chef::EncryptedDataBagItem::Encryptor do end describe "when using version 2 format" do - before do Chef::Config[:data_bag_encrypt_version] = 2 end @@ -98,7 +95,6 @@ describe Chef::EncryptedDataBagItem::Encryptor do end context "on supported platforms", :aes_256_gcm_only, :ruby_20_only do - it "creates a version 3 encryptor" do expect(encryptor).to be_a_instance_of(Chef::EncryptedDataBagItem::Encryptor::Version3Encryptor) end @@ -118,7 +114,6 @@ describe Chef::EncryptedDataBagItem::Encryptor do it "throws an error if auth tag is read before encrypting the data" do expect { encryptor.auth_tag }.to raise_error(Chef::EncryptedDataBagItem::EncryptionFailure) end - end # context on supported platforms context "on unsupported platforms" do @@ -133,26 +128,20 @@ describe Chef::EncryptedDataBagItem::Encryptor do end context "on platforms with old OpenSSL", :openssl_lt_101 do - it "throws an error warning about the OpenSSL version" do expect { encryptor }.to raise_error(Chef::EncryptedDataBagItem::EncryptedDataBagRequirementsFailure, /requires an OpenSSL/) end - end # context on platforms with old OpenSSL - end # context on unsupported platforms - end # when using version 3 format - end describe Chef::EncryptedDataBagItem::Decryptor do - subject(:decryptor) { described_class.for(encrypted_value, decryption_key) } - let(:plaintext_data) { {"foo" => "bar"} } + let(:plaintext_data) { { "foo" => "bar" } } let(:encryption_key) { "passwd" } let(:decryption_key) { encryption_key } - let(:json_wrapped_data) { Chef::JSONCompat.to_json({"json_wrapper" => plaintext_data}) } + let(:json_wrapped_data) { Chef::JSONCompat.to_json({ "json_wrapper" => plaintext_data }) } shared_examples "decryption examples" do it "decrypts the encrypted value" do @@ -165,9 +154,7 @@ describe Chef::EncryptedDataBagItem::Decryptor do end context "when decrypting a version 3 (JSON+aes-256-gcm+random iv+auth tag) encrypted value" do - context "on supported platforms", :aes_256_gcm_only, :ruby_20_only do - let(:encrypted_value) do Chef::EncryptedDataBagItem::Encryptor::Version3Encryptor.new(plaintext_data, encryption_key).for_encrypted_item end @@ -185,7 +172,6 @@ describe Chef::EncryptedDataBagItem::Decryptor do encrypted_value.delete("auth_tag") expect { decryptor.for_decrypted_item }.to raise_error(Chef::EncryptedDataBagItem::DecryptionFailure) end - end # context on supported platforms context "on unsupported platforms" do @@ -199,15 +185,11 @@ describe Chef::EncryptedDataBagItem::Decryptor do end context "on platforms with old OpenSSL", :openssl_lt_101 do - it "throws an error warning about the OpenSSL version" do expect { decryptor }.to raise_error(Chef::EncryptedDataBagItem::EncryptedDataBagRequirementsFailure, /requires an OpenSSL/) end - end # context on unsupported platforms - end # context on platforms with old OpenSSL - end # context when decrypting a version 3 context "when decrypting a version 2 (JSON+aes-256-cbc+hmac-sha256+random iv) encrypted value" do @@ -232,11 +214,9 @@ describe Chef::EncryptedDataBagItem::Decryptor do encrypted_value.delete("hmac") expect { decryptor.for_decrypted_item }.to raise_error(Chef::EncryptedDataBagItem::DecryptionFailure) end - end context "when decrypting a version 1 (JSON+aes-256-cbc+random iv) encrypted value" do - let(:encrypted_value) do Chef::EncryptedDataBagItem::Encryptor.new(plaintext_data, encryption_key).for_encrypted_item end @@ -285,12 +265,10 @@ describe Chef::EncryptedDataBagItem::Decryptor do it "raises an error attempting to decrypt" do expect { decryptor }.to raise_error(Chef::EncryptedDataBagItem::UnacceptableEncryptedDataBagItemFormat) end - end - end - context "when decrypting a version 0 (YAML+aes-256-cbc+no iv) encrypted value", :not_supported_under_fips do + context "when decrypting a version 0 (YAML+aes-256-cbc+no iv) encrypted value", :not_supported_under_fips do let(:encrypted_value) do Version0Encryptor.encrypt_value(plaintext_data, encryption_key) end @@ -311,9 +289,7 @@ describe Chef::EncryptedDataBagItem::Decryptor do it "raises an error attempting to decrypt" do expect { decryptor }.to raise_error(Chef::EncryptedDataBagItem::UnacceptableEncryptedDataBagItemFormat) end - end - end end @@ -321,15 +297,14 @@ describe Chef::EncryptedDataBagItem do subject { described_class } let(:encrypted_data_bag_item) { subject.new(encoded_data, secret) } let(:plaintext_data) {{ - "id" => "item_name", - "greeting" => "hello", - "nested" => { "a1" => [1, 2, 3], "a2" => { "b1" => true }}, + "id" => "item_name", + "greeting" => "hello", + "nested" => { "a1" => [1, 2, 3], "a2" => { "b1" => true } }, }} let(:secret) { "abc123SECRET" } let(:encoded_data) { subject.encrypt_data_bag_item(plaintext_data, secret) } describe "encrypting" do - it "doesn't encrypt the 'id' key" do expect(encoded_data["id"]).to eq "item_name" end @@ -353,11 +328,9 @@ describe Chef::EncryptedDataBagItem do expect(encoded_data["nested"]["encrypted_data"]).to eq(encryptor.for_encrypted_item["encrypted_data"]) end - end describe "decrypting" do - it "doesn't try to decrypt 'id'" do expect(encrypted_data_bag_item["id"]).to eq(plaintext_data["id"]) end diff --git a/spec/unit/environment_spec.rb b/spec/unit/environment_spec.rb index ef8abc3f15..358f3ff2de 100644 --- a/spec/unit/environment_spec.rb +++ b/spec/unit/environment_spec.rb @@ -167,7 +167,7 @@ describe Chef::Environment do before(:each) do @environment.name("spec") @environment.description("Where we run the spec tests") - @environment.cookbook_versions({:apt => "= 1.2.3"}) + @environment.cookbook_versions({ :apt => "= 1.2.3" }) @hash = @environment.to_hash end @@ -190,7 +190,7 @@ describe Chef::Environment do before(:each) do @environment.name("spec") @environment.description("Where we run the spec tests") - @environment.cookbook_versions({:apt => "= 1.2.3"}) + @environment.cookbook_versions({ :apt => "= 1.2.3" }) @json = @environment.to_json end @@ -302,7 +302,6 @@ describe Chef::Environment do "Environment cookbook version constraints not allowed in chef-solo" end end - end describe "when updating from a parameter hash" do @@ -329,13 +328,13 @@ describe Chef::Environment do # NOTE: I'm only choosing this (admittedly weird) structure for the hash b/c the better more obvious # one, i.e, {:cookbook_version_constraints => {COOKBOOK_NAME => CONSTRAINT}} is difficult to implement # the way merb does params - params = {:name=>"superbowl", :cookbook_version => {"0" => "apache2 ~> 1.0.0", "1" => "nginx < 2.0.0"}} + params = { :name => "superbowl", :cookbook_version => { "0" => "apache2 ~> 1.0.0", "1" => "nginx < 2.0.0" } } @environment.update_from_params(params) - expect(@environment.cookbook_versions).to eq({"apache2" => "~> 1.0.0", "nginx" => "< 2.0.0"}) + expect(@environment.cookbook_versions).to eq({ "apache2" => "~> 1.0.0", "nginx" => "< 2.0.0" }) end it "validates the cookbook constraints" do - params = {:cookbook_version => {"0" => "apache2 >>> 1.0.0"}} + params = { :cookbook_version => { "0" => "apache2 >>> 1.0.0" } } expect(@environment.update_from_params(params)).to be_falsey err_msg = @environment.invalid_fields[:cookbook_version]["0"] expect(err_msg).to eq("apache2 >>> 1.0.0 is not a valid cookbook constraint") @@ -353,14 +352,13 @@ describe Chef::Environment do it "updates default attributes from a JSON string in params[:attributes]" do @environment.update_from_params(:name => "fuuu", :default_attributes => %q|{"fuuu":"RAGE"}|) - expect(@environment.default_attributes).to eq({"fuuu" => "RAGE"}) + expect(@environment.default_attributes).to eq({ "fuuu" => "RAGE" }) end it "updates override attributes from a JSON string in params[:attributes]" do @environment.update_from_params(:name => "fuuu", :override_attributes => %q|{"foo":"override"}|) - expect(@environment.override_attributes).to eq({"foo" => "override"}) + expect(@environment.override_attributes).to eq({ "foo" => "override" }) end - end describe "api model" do @@ -405,7 +403,7 @@ 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")).exactly(2).times.and_return(true) expect(File).to receive(:readable?).with(File.join(Chef::Config[:environment_path], "foo.rb")).and_return(true) - role_dsl="name \"foo\"\ndescription \"desc\"\n" + role_dsl = "name \"foo\"\ndescription \"desc\"\n" expect(IO).to receive(:read).with(File.join(Chef::Config[:environment_path], "foo.rb")).and_return(role_dsl) Chef::Environment.load("foo") end @@ -438,7 +436,7 @@ 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")).exactly(2).times.and_return(true) expect(File).to receive(:readable?).with(File.join(Chef::Config[:environment_path], "foo.rb")).and_return(true) - role_dsl="name \"foo\"\ndescription \"desc\"\n" + role_dsl = "name \"foo\"\ndescription \"desc\"\n" expect(IO).to receive(:read).with(File.join(Chef::Config[:environment_path], "foo.rb")).and_return(role_dsl) environment = Chef::Environment.load("foo") @@ -466,5 +464,4 @@ describe Chef::Environment do end end end - end diff --git a/spec/unit/event_dispatch/dispatcher_spec.rb b/spec/unit/event_dispatch/dispatcher_spec.rb index 814377a776..7992dd85ae 100644 --- a/spec/unit/event_dispatch/dispatcher_spec.rb +++ b/spec/unit/event_dispatch/dispatcher_spec.rb @@ -21,7 +21,6 @@ require "spec_helper" require "chef/event_dispatch/dispatcher" describe Chef::EventDispatch::Dispatcher do - subject(:dispatcher) { Chef::EventDispatch::Dispatcher.new } let(:event_sink) { instance_double("Chef::EventDispatch::Base") } @@ -31,7 +30,6 @@ describe Chef::EventDispatch::Dispatcher do end context "when an event sink is registered" do - before do dispatcher.register(event_sink) end @@ -75,7 +73,6 @@ describe Chef::EventDispatch::Dispatcher do end end - context "when two event sinks have different arguments for an event" do let(:event_sink_1) do Class.new(Chef::EventDispatch::Base) do diff --git a/spec/unit/event_dispatch/dsl_spec.rb b/spec/unit/event_dispatch/dsl_spec.rb index d18234c08a..979b067fb6 100644 --- a/spec/unit/event_dispatch/dsl_spec.rb +++ b/spec/unit/event_dispatch/dsl_spec.rb @@ -32,7 +32,7 @@ describe Chef::EventDispatch::DSL do Chef.set_run_context(run_context) end - subject{ described_class.new("test") } + subject { described_class.new("test") } it "set handler name" do subject.on(:run_started) {} @@ -46,7 +46,7 @@ describe Chef::EventDispatch::DSL do end it "register user hooks against valid event type" do - subject.on(:run_failed) {"testhook"} + subject.on(:run_failed) { "testhook" } 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 {} resource.run_action(:run) expect(calls).to eq([: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 {} resource.run_action(:run) expect(events.subscribers.first.instance_variable_get(:@ivar)).to eq([1, 2]) end diff --git a/spec/unit/exceptions_spec.rb b/spec/unit/exceptions_spec.rb index c834f7dbe1..d5b1164e7e 100644 --- a/spec/unit/exceptions_spec.rb +++ b/spec/unit/exceptions_spec.rb @@ -72,7 +72,7 @@ describe Chef::Exceptions do exception_to_super_class.each do |exception, expected_super_class| it "should have an exception class of #{exception} which inherits from #{expected_super_class}" do - expect{ raise exception }.to raise_error(expected_super_class) + expect { raise exception }.to raise_error(expected_super_class) end if exception.methods.include?(:to_json) @@ -95,7 +95,7 @@ describe Chef::Exceptions do end context "initialized with nothing" do - let(:e) { Chef::Exceptions::RunFailedWrappingError.new } + let(:e) { Chef::Exceptions::RunFailedWrappingError.new } let(:num_errors) { 0 } let(:backtrace) { [] } @@ -103,7 +103,7 @@ describe Chef::Exceptions do end context "initialized with nil" do - let(:e) { Chef::Exceptions::RunFailedWrappingError.new(nil, nil) } + let(:e) { Chef::Exceptions::RunFailedWrappingError.new(nil, nil) } let(:num_errors) { 0 } let(:backtrace) { [] } @@ -111,7 +111,7 @@ describe Chef::Exceptions do end context "initialized with 1 error and nil" do - let(:e) { Chef::Exceptions::RunFailedWrappingError.new(RuntimeError.new("foo"), nil) } + let(:e) { Chef::Exceptions::RunFailedWrappingError.new(RuntimeError.new("foo"), nil) } let(:num_errors) { 1 } let(:backtrace) { ["1) RuntimeError - foo"] } @@ -119,12 +119,11 @@ describe Chef::Exceptions do end context "initialized with 2 errors" do - let(:e) { Chef::Exceptions::RunFailedWrappingError.new(RuntimeError.new("foo"), RuntimeError.new("bar")) } + let(:e) { Chef::Exceptions::RunFailedWrappingError.new(RuntimeError.new("foo"), RuntimeError.new("bar")) } let(:num_errors) { 2 } let(:backtrace) { ["1) RuntimeError - foo", "", "2) RuntimeError - bar"] } include_examples "RunFailedWrappingError expectations" end - end end diff --git a/spec/unit/file_cache_spec.rb b/spec/unit/file_cache_spec.rb index 8486b4517f..e63a8b0dba 100644 --- a/spec/unit/file_cache_spec.rb +++ b/spec/unit/file_cache_spec.rb @@ -36,10 +36,9 @@ describe Chef::FileCache do end it "creates the cached file at the correct relative path" do - expect(File).to receive(:open).with(File.join(@file_cache_path, "whiz", "bang"), "w",416).and_yield(@io) + expect(File).to receive(:open).with(File.join(@file_cache_path, "whiz", "bang"), "w", 416).and_yield(@io) Chef::FileCache.store("whiz/bang", "borkborkbork") end - end describe "when storing a file" do @@ -51,7 +50,6 @@ describe Chef::FileCache do Chef::FileCache.store("whiz/bang", "borkborkbork") expect(@io.string).to eq("borkborkbork") end - end describe "when loading cached files" do @@ -76,7 +74,6 @@ describe Chef::FileCache do Chef::FileCache.delete("whiz/bang") expect(File).not_to exist(File.join(@file_cache_path, "whiz", "bang")) end - end describe "when listing files in the cache" do @@ -94,7 +91,6 @@ describe Chef::FileCache do it "searches for cached files by globbing" do expect(Chef::FileCache.find("snappy/**/*")).to eq(%w{snappy/patter}) end - end describe "when checking for the existence of a file" do diff --git a/spec/unit/file_content_management/deploy/cp_spec.rb b/spec/unit/file_content_management/deploy/cp_spec.rb index 48df5ca4de..95b56774f5 100644 --- a/spec/unit/file_content_management/deploy/cp_spec.rb +++ b/spec/unit/file_content_management/deploy/cp_spec.rb @@ -19,12 +19,10 @@ require "spec_helper" describe Chef::FileContentManagement::Deploy::Cp do - let(:content_deployer) { described_class.new } let(:target_file_path) { "/etc/my_app.conf" } describe "creating the file" do - it "touches the file to create it" do expect(FileUtils).to receive(:touch).with(target_file_path) content_deployer.create(target_file_path) @@ -32,15 +30,11 @@ describe Chef::FileContentManagement::Deploy::Cp do end describe "updating the file" do - let(:staging_file_path) { "/tmp/random-dir/staging-file.tmp" } it "copies the staging file's content" do expect(FileUtils).to receive(:cp).with(staging_file_path, target_file_path) content_deployer.deploy(staging_file_path, target_file_path) end - end end - - diff --git a/spec/unit/file_content_management/deploy/mv_unix_spec.rb b/spec/unit/file_content_management/deploy/mv_unix_spec.rb index 8c96042a15..f1eb247975 100644 --- a/spec/unit/file_content_management/deploy/mv_unix_spec.rb +++ b/spec/unit/file_content_management/deploy/mv_unix_spec.rb @@ -19,12 +19,10 @@ require "spec_helper" describe Chef::FileContentManagement::Deploy::MvUnix do - let(:content_deployer) { described_class.new } let(:target_file_path) { "/etc/my_app.conf" } describe "creating the file" do - it "touches the file to create it" do expect(FileUtils).to receive(:touch).with(target_file_path) content_deployer.create(target_file_path) @@ -32,7 +30,6 @@ describe Chef::FileContentManagement::Deploy::MvUnix do end describe "updating the file" do - let(:staging_file_path) { "/tmp/random-dir/staging-file.tmp" } let(:target_file_mode) { 0644 } @@ -54,7 +51,6 @@ describe Chef::FileContentManagement::Deploy::MvUnix do # * The owner and group of the target file match the owner and group of the # staging file. context "when the user has permissions to set file ownership" do - # For the purposes of this test, the uid/gid can be anything. These # values are just chosen because (assuming chef-client's euid == 1001 and # egid == 1001), the `chown` call is allowed by the OS. See the @@ -70,11 +66,9 @@ describe Chef::FileContentManagement::Deploy::MvUnix do it "fixes up permissions and moves the file into place" do content_deployer.deploy(staging_file_path, target_file_path) end - end context "when the user does not have permissions to set file ownership" do - # The test code does not care what these values are. These values are # chosen because they're representitive of the case that chef-client is # running as non-root and is managing a file that got ownership set to @@ -96,8 +90,5 @@ describe Chef::FileContentManagement::Deploy::MvUnix do content_deployer.deploy(staging_file_path, target_file_path) end end - end end - - diff --git a/spec/unit/file_content_management/deploy/mv_windows_spec.rb b/spec/unit/file_content_management/deploy/mv_windows_spec.rb index 8f54226a9d..97ae332974 100644 --- a/spec/unit/file_content_management/deploy/mv_windows_spec.rb +++ b/spec/unit/file_content_management/deploy/mv_windows_spec.rb @@ -34,12 +34,10 @@ end require "chef/file_content_management/deploy/mv_windows" describe Chef::FileContentManagement::Deploy::MvWindows do - let(:content_deployer) { described_class.new } let(:target_file_path) { "/etc/my_app.conf" } describe "creating the file" do - it "touches the file to create it" do expect(FileUtils).to receive(:touch).with(target_file_path) content_deployer.create(target_file_path) @@ -47,7 +45,6 @@ describe Chef::FileContentManagement::Deploy::MvWindows do end describe "updating the file" do - let(:staging_file_path) { "/tmp/random-dir/staging-file.tmp" } let(:target_file_security_object) do @@ -63,7 +60,6 @@ describe Chef::FileContentManagement::Deploy::MvWindows do to receive(:new). with(target_file_path). and_return(target_file_security_object, updated_target_security_object) - end context "when run without adminstrator privileges" do @@ -72,13 +68,11 @@ describe Chef::FileContentManagement::Deploy::MvWindows do end it "errors out with a WindowsNotAdmin error" do - expect { content_deployer.deploy(staging_file_path, target_file_path)}.to raise_error(Chef::Exceptions::WindowsNotAdmin) + expect { content_deployer.deploy(staging_file_path, target_file_path) }.to raise_error(Chef::Exceptions::WindowsNotAdmin) end - end context "when run with administrator privileges" do - let(:original_target_file_owner) { double("original target file owner") } let(:original_target_file_group) { double("original target file group") } @@ -92,7 +86,6 @@ describe Chef::FileContentManagement::Deploy::MvWindows do double "security descriptor for target file" end - before do allow(target_file_security_object).to receive(:security_descriptor).and_return(target_file_security_descriptor) @@ -103,7 +96,6 @@ describe Chef::FileContentManagement::Deploy::MvWindows do end context "and the target file has no dacl or sacl" do - before do allow(target_file_security_descriptor).to receive(:dacl_present?).and_return(false) allow(target_file_security_descriptor).to receive(:sacl_present?).and_return(false) @@ -112,11 +104,9 @@ describe Chef::FileContentManagement::Deploy::MvWindows do it "fixes up permissions and moves the file into place" do content_deployer.deploy(staging_file_path, target_file_path) end - end context "and the target file has null dacl and sacl" do - before do allow(target_file_security_descriptor).to receive(:dacl_present?).and_return(true) allow(target_file_security_descriptor).to receive(:dacl).and_return(nil) @@ -130,11 +120,9 @@ describe Chef::FileContentManagement::Deploy::MvWindows do expect(updated_target_security_object).to receive(:set_sacl).with(nil, false) end - it "fixes up permissions and moves the file into place" do content_deployer.deploy(staging_file_path, target_file_path) end - end context "and the target has an empty dacl and sacl" do @@ -154,7 +142,6 @@ describe Chef::FileContentManagement::Deploy::MvWindows do with([]). and_return(empty_dacl) - allow(target_file_security_descriptor).to receive(:sacl_present?).and_return(true) allow(target_file_security_descriptor).to receive(:sacl_inherits?).and_return(false) @@ -164,12 +151,10 @@ describe Chef::FileContentManagement::Deploy::MvWindows do with([]). and_return(empty_sacl) - expect(updated_target_security_object).to receive(:set_dacl).with(empty_dacl, false) expect(updated_target_security_object).to receive(:set_sacl).with(empty_sacl, false) end - it "fixes up permissions and moves the file into place" do content_deployer.deploy(staging_file_path, target_file_path) end @@ -228,12 +213,7 @@ describe Chef::FileContentManagement::Deploy::MvWindows do content_deployer.deploy(staging_file_path, target_file_path) end end - end - end - end end - - diff --git a/spec/unit/formatters/doc_spec.rb b/spec/unit/formatters/doc_spec.rb index 34121ab589..ebc0e77a2f 100644 --- a/spec/unit/formatters/doc_spec.rb +++ b/spec/unit/formatters/doc_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Formatters::Base do - let(:out) { StringIO.new } let(:err) { StringIO.new } @@ -28,15 +27,15 @@ describe Chef::Formatters::Base do it "prints a policyfile's name and revision ID" do minimal_policyfile = { - "revision_id"=> "613f803bdd035d574df7fa6da525b38df45a74ca82b38b79655efed8a189e073", - "name"=> "jenkins", - "run_list"=> [ + "revision_id" => "613f803bdd035d574df7fa6da525b38df45a74ca82b38b79655efed8a189e073", + "name" => "jenkins", + "run_list" => [ "recipe[apt::default]", "recipe[java::default]", "recipe[jenkins::master]", "recipe[policyfile_demo::default]", ], - "cookbook_locks"=> { }, + "cookbook_locks" => {}, } formatter.policyfile_loaded(minimal_policyfile) diff --git a/spec/unit/formatters/error_inspectors/api_error_formatting_spec.rb b/spec/unit/formatters/error_inspectors/api_error_formatting_spec.rb index e1c1419eca..8c1ddb5019 100644 --- a/spec/unit/formatters/error_inspectors/api_error_formatting_spec.rb +++ b/spec/unit/formatters/error_inspectors/api_error_formatting_spec.rb @@ -27,7 +27,6 @@ describe Chef::Formatters::APIErrorFormatting do allow(response).to receive(:body) end - context "when describe_406_error is called" do context "when response['x-ops-server-api-version'] exists" do let(:min_version) { "2" } @@ -47,23 +46,22 @@ describe Chef::Formatters::APIErrorFormatting do end it "prints an error about client and server API version incompatibility with a min API version" do - expect(error_description).to receive(:section).with("Incompatible server API version:",/a min API version of #{min_version}/) + expect(error_description).to receive(:section).with("Incompatible server API version:", /a min API version of #{min_version}/) class_instance.describe_406_error(error_description, response) end it "prints an error about client and server API version incompatibility with a max API version" do - expect(error_description).to receive(:section).with("Incompatible server API version:",/a max API version of #{max_version}/) + expect(error_description).to receive(:section).with("Incompatible server API version:", /a max API version of #{max_version}/) class_instance.describe_406_error(error_description, response) end it "prints an error describing the request API version" do - expect(error_description).to receive(:section).with("Incompatible server API version:",/a request with an API version of #{request_version}/) + expect(error_description).to receive(:section).with("Incompatible server API version:", /a request with an API version of #{request_version}/) class_instance.describe_406_error(error_description, response) end end context "when response.body['error'] != 'invalid-x-ops-server-api-version'" do - before do allow(response).to receive(:[]).with("x-ops-server-api-version").and_return(nil) end diff --git a/spec/unit/formatters/error_inspectors/compile_error_inspector_spec.rb b/spec/unit/formatters/error_inspectors/compile_error_inspector_spec.rb index 9abf27ced2..67abf91fd5 100644 --- a/spec/unit/formatters/error_inspectors/compile_error_inspector_spec.rb +++ b/spec/unit/formatters/error_inspectors/compile_error_inspector_spec.rb @@ -18,7 +18,7 @@ require "spec_helper" -BAD_RECIPE=<<-E +BAD_RECIPE = <<-E # # Cookbook Name:: syntax-err # Recipe:: default @@ -37,7 +37,6 @@ end E describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do - let(:node_name) { "test-node.example.com" } let(:description) { Chef::Formatters::ErrorDescription.new("Error Evaluating File:") } @@ -56,9 +55,7 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do subject(:inspector) { described_class.new(path_to_failed_file, exception) } describe "finding the code responsible for the error" do - context "when the stacktrace includes cookbook files" do - let(:trace) do [ "/home/someuser/dev-laptop/cookbooks/syntax-err/recipes/default.rb:14:in `from_file'", @@ -91,7 +88,7 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do describe "when explaining an error in the compile phase" do before do - recipe_lines = BAD_RECIPE.split("\n").map {|l| l << "\n" } + recipe_lines = BAD_RECIPE.split("\n").map { |l| l << "\n" } expect(IO).to receive(:readlines).with(path_to_failed_file).and_return(recipe_lines) inspector.add_explanation(description) end @@ -137,7 +134,6 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do end context "when the error does not contain any lines from cookbooks" do - let(:trace) do [ "/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-10.14.0/lib/chef/run_context.rb:144:in `rescue in block in load_libraries'", @@ -171,12 +167,10 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do it "reports the error was not located within cookbooks" do expect(inspector.found_error_in_cookbooks?).to be(false) end - end end describe "when explaining an error on windows" do - let(:trace_with_upcase_drive) do [ "C:/opscode/chef/var/cache/cookbooks/foo/recipes/default.rb:14 in `from_file'", @@ -209,13 +203,12 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do before do allow(Chef::Config).to receive(:cookbook_path).and_return([ "C:/opscode/chef/var/cache/cookbooks" ]) - recipe_lines = BAD_RECIPE.split("\n").map {|l| l << "\n" } + recipe_lines = BAD_RECIPE.split("\n").map { |l| l << "\n" } expect(IO).to receive(:readlines).at_least(1).times.with(full_path_to_failed_file).and_return(recipe_lines) inspector.add_explanation(description) end context "when the drive letter in the path is uppercase" do - let(:full_path_to_failed_file) { "C:/opscode/chef#{path_to_failed_file}" } it "reports the error was not located within cookbooks" do @@ -236,7 +229,6 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do end context "when the drive letter in the path is lowercase" do - let(:trace) do trace_with_upcase_drive.map { |line| line.gsub(/^C:/, "c:") } end @@ -259,7 +251,5 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do description.display(outputter) end end - end - end diff --git a/spec/unit/formatters/error_inspectors/cookbook_resolve_error_inspector_spec.rb b/spec/unit/formatters/error_inspectors/cookbook_resolve_error_inspector_spec.rb index 700d7fa7ed..d96cfc1ede 100644 --- a/spec/unit/formatters/error_inspectors/cookbook_resolve_error_inspector_spec.rb +++ b/spec/unit/formatters/error_inspectors/cookbook_resolve_error_inspector_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do - before do @expanded_run_list = Chef::RunList.new("recipe[annoyances]", "recipe[apache2]", "recipe[users]", "recipe[chef::client]") @@ -31,7 +30,6 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do describe "when explaining a 403 error" do before do - @response_body = %q({"error": [{"message": "gtfo"}]) @response = Net::HTTPForbidden.new("1.1", "403", "(response) forbidden") allow(@response).to receive(:body).and_return(@response_body) @@ -44,7 +42,6 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do it "prints a nice message" do expect { @description.display(@outputter) }.not_to raise_error end - end describe "when explaining a PreconditionFailed (412) error with current error message style" do @@ -52,7 +49,6 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do # which must be re-parsed to get the actual data. before do - @response_body = "{\"error\":[\"{\\\"non_existent_cookbooks\\\":[\\\"apache2\\\"],\\\"cookbooks_with_no_versions\\\":[\\\"users\\\"],\\\"message\\\":\\\"Run list contains invalid items: no such cookbook nope.\\\"}\"]}" @response = Net::HTTPPreconditionFailed.new("1.1", "412", "(response) unauthorized") allow(@response).to receive(:body).and_return(@response_body) @@ -70,7 +66,6 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do expect(observed_output).to include("users") expect(observed_output).not_to include("Run list contains invalid items: no such cookbook nope.") end - end describe "when explaining a PreconditionFailed (412) error with current error message style without cookbook details" do @@ -80,7 +75,6 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do # details. But we should still print a pretty error message. before do - @response_body = "{\"error\":[{\"non_existent_cookbooks\":[],\"cookbooks_with_no_versions\":[],\"message\":\"unable to solve dependencies in alotted time.\"}]}" @response = Net::HTTPPreconditionFailed.new("1.1", "412", "(response) unauthorized") allow(@response).to receive(:body).and_return(@response_body) @@ -95,7 +89,6 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do @outputter_output.rewind expect(@outputter_output.read).to include("unable to solve dependencies in alotted time.") end - end describe "when explaining a PreconditionFailed (412) error with single encoded JSON" do @@ -103,7 +96,6 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do # which must be re-parsed to get the actual data. before do - @response_body = "{\"error\":[{\"non_existent_cookbooks\":[\"apache2\"],\"cookbooks_with_no_versions\":[\"users\"],\"message\":\"Run list contains invalid items: no such cookbook nope.\"}]}" @response = Net::HTTPPreconditionFailed.new("1.1", "412", "(response) unauthorized") allow(@response).to receive(:body).and_return(@response_body) @@ -121,9 +113,5 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do expect(observed_output).to include("users") expect(observed_output).not_to include("Run list contains invalid items: no such cookbook nope.") end - end end - - - diff --git a/spec/unit/formatters/error_inspectors/cookbook_sync_error_inspector_spec.rb b/spec/unit/formatters/error_inspectors/cookbook_sync_error_inspector_spec.rb index 02846af24a..059fcfc481 100644 --- a/spec/unit/formatters/error_inspectors/cookbook_sync_error_inspector_spec.rb +++ b/spec/unit/formatters/error_inspectors/cookbook_sync_error_inspector_spec.rb @@ -38,6 +38,5 @@ describe Chef::Formatters::ErrorInspectors::CookbookSyncErrorInspector do it "prints a nice message" do @description.display(@outputter) end - end end diff --git a/spec/unit/formatters/error_inspectors/node_load_error_inspector_spec.rb b/spec/unit/formatters/error_inspectors/node_load_error_inspector_spec.rb index 52432e8fc2..93aac417fa 100644 --- a/spec/unit/formatters/error_inspectors/node_load_error_inspector_spec.rb +++ b/spec/unit/formatters/error_inspectors/node_load_error_inspector_spec.rb @@ -21,7 +21,6 @@ require "spec_helper" # spec_helper loads the shared examples already. #require 'support/shared/unit/api_error_inspector_spec' - describe Chef::Formatters::ErrorInspectors::NodeLoadErrorInspector do it_behaves_like "an api error inspector" end diff --git a/spec/unit/formatters/error_inspectors/registration_error_inspector_spec.rb b/spec/unit/formatters/error_inspectors/registration_error_inspector_spec.rb index ed525a2228..cea93888eb 100644 --- a/spec/unit/formatters/error_inspectors/registration_error_inspector_spec.rb +++ b/spec/unit/formatters/error_inspectors/registration_error_inspector_spec.rb @@ -21,7 +21,6 @@ require "spec_helper" # spec_helper loads the shared examples already. #require 'support/shared/unit/api_error_inspector_spec' - describe Chef::Formatters::ErrorInspectors::RegistrationErrorInspector do it_behaves_like "an api error inspector" 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 57fc4d38e2..dc86f2f08f 100644 --- a/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb +++ b/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb @@ -48,7 +48,6 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do describe "when explaining an error converging a resource" do before do @resource = package("non-existing-package") do - only_if do true end @@ -95,7 +94,7 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do @error = begin @context.render_template_from_string("foo\nbar\nbaz\n<%= this_is_not_defined %>\nquin\nqunx\ndunno") - rescue Chef::Mixin::Template::TemplateError => e + rescue Chef::Mixin::Template::TemplateError => e e end @@ -107,8 +106,6 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do @description.display(@outputter) expect(@stdout.string).to include(@error.source_listing) end - - end describe "recipe_snippet" do @@ -186,8 +183,5 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do @description.display(@outputter) end end - end - - end diff --git a/spec/unit/formatters/error_inspectors/run_list_expansion_error_inspector_spec.rb b/spec/unit/formatters/error_inspectors/run_list_expansion_error_inspector_spec.rb index bfa9a30099..dbf33b3bad 100644 --- a/spec/unit/formatters/error_inspectors/run_list_expansion_error_inspector_spec.rb +++ b/spec/unit/formatters/error_inspectors/run_list_expansion_error_inspector_spec.rb @@ -31,7 +31,6 @@ describe Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector do end describe "when explaining a missing role error" do - before do @run_list_expansion = Chef::RunList::RunListExpansion.new("_default", @node.run_list) @run_list_expansion.missing_roles_with_including_role << [ "role[missing-role]", "role[base]" ] @@ -39,7 +38,6 @@ describe Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector do @exception = Chef::Exceptions::MissingRole.new(@run_list_expansion) - @inspector = Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector.new(@node, @exception) @inspector.add_explanation(@description) end @@ -47,12 +45,10 @@ describe Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector do it "prints a pretty message" do @description.display(@outputter) end - end describe "when explaining an HTTP 403 error" do before do - @response_body = "forbidden" @response = Net::HTTPForbidden.new("1.1", "403", "(response) forbidden") allow(@response).to receive(:body).and_return(@response_body) @@ -66,7 +62,6 @@ describe Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector do it "prints a pretty message" do @description.display(@outputter) end - end describe "when explaining an HTTP 401 error" do @@ -78,8 +73,8 @@ describe Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector do @inspector = Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector.new(@node, @exception) allow(@inspector).to receive(:config).and_return(:node_name => "unit-test.example.com", - :client_key => "/etc/chef/client.pem", - :chef_server_url => "http://chef.example.com") + :client_key => "/etc/chef/client.pem", + :chef_server_url => "http://chef.example.com") @inspector.add_explanation(@description) end @@ -88,6 +83,4 @@ describe Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector do @description.display(@outputter) end end - end - diff --git a/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb b/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb index 315e457cb2..c155be55f2 100644 --- a/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb +++ b/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb @@ -69,7 +69,6 @@ describe Chef::GuardInterpreter::ResourceGuardInterpreter do it "fails when parent_resource is nil" do expect { Chef::GuardInterpreter::ResourceGuardInterpreter.new(nil, "echo hi", nil) }.to raise_error(ArgumentError, /Node for guard resource parent must not be nil/) end - end describe "#evaluate" do @@ -118,7 +117,7 @@ describe Chef::GuardInterpreter::ResourceGuardInterpreter do end it "merges to :code" do - expect(command_opts).to receive(:merge).with({:code => "exit 0"}).and_call_original + expect(command_opts).to receive(:merge).with({ :code => "exit 0" }).and_call_original expect(guard_interpreter.evaluate).to eq(true) end end @@ -131,7 +130,7 @@ describe Chef::GuardInterpreter::ResourceGuardInterpreter do end it "merges to :code" do - expect(command_opts).to receive(:merge).with({:command => "exit 0"}).and_call_original + expect(command_opts).to receive(:merge).with({ :command => "exit 0" }).and_call_original expect(guard_interpreter.evaluate).to eq(true) end end @@ -145,11 +144,10 @@ describe Chef::GuardInterpreter::ResourceGuardInterpreter do end it "merges to :command" do - expect(command_opts).to receive(:merge).with({:command => "exit 0"}).and_call_original + expect(command_opts).to receive(:merge).with({ :command => "exit 0" }).and_call_original expect(guard_interpreter.evaluate).to eq(true) end end - end end end diff --git a/spec/unit/guard_interpreter_spec.rb b/spec/unit/guard_interpreter_spec.rb index aaa9a9ebf1..1bfc831177 100644 --- a/spec/unit/guard_interpreter_spec.rb +++ b/spec/unit/guard_interpreter_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::GuardInterpreter do describe "#for_resource" do - let (:resource) { Chef::Resource.new("foo")} + let (:resource) { Chef::Resource.new("foo") } it "returns a DefaultGuardInterpreter if the resource has guard_interpreter set to :default" do resource.guard_interpreter :default diff --git a/spec/unit/handler/json_file_spec.rb b/spec/unit/handler/json_file_spec.rb index fd3438e65e..d8f56b21a9 100644 --- a/spec/unit/handler/json_file_spec.rb +++ b/spec/unit/handler/json_file_spec.rb @@ -49,7 +49,6 @@ describe Chef::Handler::JsonFile do allow(File).to receive(:open).and_yield(@file_mock) end - it "saves run status data to a file as JSON" do expect(@handler).to receive(:build_report_dir) @handler.run_report_unsafe(@run_status) @@ -59,6 +58,5 @@ describe Chef::Handler::JsonFile do expect(reported_data["end_time"]).to eq((@expected_time + 5).to_s) expect(reported_data["elapsed_time"]).to eq(5) end - end end diff --git a/spec/unit/handler_spec.rb b/spec/unit/handler_spec.rb index f0c78d9bc1..5e06dfbffd 100644 --- a/spec/unit/handler_spec.rb +++ b/spec/unit/handler_spec.rb @@ -100,7 +100,7 @@ describe Chef::Handler do $report_ran = true raise Exception, "I died the deth" end - expect {@handler.run_report_safely(@run_status)}.not_to raise_error + expect { @handler.run_report_safely(@run_status) }.not_to raise_error expect($report_ran).to be_truthy end it "does not fail if the report handler does not raise an exception" do @@ -108,7 +108,7 @@ describe Chef::Handler do def @handler.report $report_ran = true end - expect {@handler.run_report_safely(@run_status)}.not_to raise_error + expect { @handler.run_report_safely(@run_status) }.not_to raise_error expect($report_ran).to be_truthy end end @@ -211,5 +211,4 @@ describe Chef::Handler do expect(@handler.data).to eq(@run_status.to_hash) end end - end diff --git a/spec/unit/http/authenticator_spec.rb b/spec/unit/http/authenticator_spec.rb index 3650e99a02..9856604150 100644 --- a/spec/unit/http/authenticator_spec.rb +++ b/spec/unit/http/authenticator_spec.rb @@ -35,15 +35,15 @@ describe Chef::HTTP::Authenticator do it "merges the default version of X-Ops-Server-API-Version into the headers" do # headers returned expect(class_instance.handle_request(method, url, headers, data)[2]). - to include({"X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION}) + to include({ "X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION }) end context "when api_version is set to something other than the default" do - let(:class_instance) { Chef::HTTP::Authenticator.new({:api_version => "-10"}) } + let(:class_instance) { Chef::HTTP::Authenticator.new({ :api_version => "-10" }) } it "merges the requested version of X-Ops-Server-API-Version into the headers" do expect(class_instance.handle_request(method, url, headers, data)[2]). - to include({"X-Ops-Server-API-Version" => "-10"}) + to include({ "X-Ops-Server-API-Version" => "-10" }) end end end @@ -59,7 +59,6 @@ describe Chef::HTTP::Authenticator do expect(class_instance).to_not receive(:authentication_headers) class_instance.handle_request(method, url, headers, data) end - end context "when sign_requests?" do @@ -72,7 +71,7 @@ describe Chef::HTTP::Authenticator do it "calls authentication_headers with the proper input" do expect(class_instance).to receive(:authentication_headers).with( method, url, data, - {"X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION}).and_return({}) + { "X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION }).and_return({}) class_instance.handle_request(method, url, headers, data) end end diff --git a/spec/unit/http/basic_client_spec.rb b/spec/unit/http/basic_client_spec.rb index 4abdb52620..d1d9362fce 100644 --- a/spec/unit/http/basic_client_spec.rb +++ b/spec/unit/http/basic_client_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" require "chef/http/basic_client" describe "HTTP Connection" do - let(:uri) { URI("https://example.com:4443") } subject(:basic_client) { Chef::HTTP::BasicClient.new(uri) } @@ -58,14 +57,12 @@ describe "HTTP Connection" do context "when the config setting is normalized (does not contain the scheme)" do include_examples "a proxy uri" do - let(:proxy_prefix) { "" } before do Chef::Config["#{uri.scheme}_proxy"] = proxy Chef::Config[:no_proxy] = nil end - end end @@ -77,14 +74,11 @@ describe "HTTP Connection" do Chef::Config["#{uri.scheme}_proxy"] = proxy Chef::Config[:no_proxy] = nil end - end end context "when the proxy is set by the environment" do - include_examples "a proxy uri" do - let(:env) do { "https_proxy" => "https://proxy.mycorp.com:8080", @@ -107,7 +101,6 @@ describe "HTTP Connection" do expect(basic_client.http_proxy_pass(proxy_uri)).to eq("opensesame") end end - end context "when an empty proxy is set by the environment" do diff --git a/spec/unit/http/http_request_spec.rb b/spec/unit/http/http_request_spec.rb index 29562de021..27e84b1ba1 100644 --- a/spec/unit/http/http_request_spec.rb +++ b/spec/unit/http/http_request_spec.rb @@ -19,9 +19,7 @@ require "spec_helper" describe Chef::HTTP::HTTPRequest do - context "with HTTP url scheme" do - it "should not include port 80 in Host header" do request = Chef::HTTP::HTTPRequest.new(:GET, URI("http://dummy.com"), "") @@ -51,11 +49,9 @@ describe Chef::HTTP::HTTPRequest do expect(request.headers["Host"]).to eql("yourhost.com:8888") end - end context "with HTTPS url scheme" do - it "should not include port 443 in Host header" do request = Chef::HTTP::HTTPRequest.new(:GET, URI("https://dummy.com"), "") @@ -79,7 +75,6 @@ describe Chef::HTTP::HTTPRequest do expect(request.headers["Host"]).to eql("dummy.com") end - end it "should pass on explicit Host header unchanged" do @@ -87,5 +82,4 @@ describe Chef::HTTP::HTTPRequest do expect(request.headers["Host"]).to eql("myhost.com:80") end - end diff --git a/spec/unit/http/json_input_spec.rb b/spec/unit/http/json_input_spec.rb index e26e030737..3f547c0b48 100644 --- a/spec/unit/http/json_input_spec.rb +++ b/spec/unit/http/json_input_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "chef/http/json_input" describe Chef::HTTP::JSONInput do - let(:json_encoder) { described_class.new() } let(:url) { URI.parse("http://example.com") } @@ -54,7 +53,6 @@ describe Chef::HTTP::JSONInput do end context "when handling a request with no body" do - let(:http_method) { :get } let(:data) { nil } @@ -64,13 +62,11 @@ describe Chef::HTTP::JSONInput do end context "when the request should be serialized" do - let(:http_method) { :put } - let(:data) { {foo: "bar"} } + let(:data) { { foo: "bar" } } let(:expected_data) { %q[{"foo":"bar"}] } context "and the request has a ruby object as the body and no explicit content-type" do - it "serializes the body to json" do # Headers Hash get mutated, so we start by asserting it's empty: expect(headers).to be_empty @@ -84,7 +80,6 @@ describe Chef::HTTP::JSONInput do end context "ant the request has an explicit content type of json" do - it "serializes the body to json when content-type is all lowercase" do headers["content-type"] = "application/json" @@ -95,13 +90,10 @@ describe Chef::HTTP::JSONInput do expect(headers).to have_key("Content-Type") expect(headers["Content-Type"]).to eq("application/json") end - end - end context "when handling a request with an explicit content type other than json" do - let(:http_method) { :put } let(:data) { "some arbitrary bytes" } @@ -111,7 +103,7 @@ describe Chef::HTTP::JSONInput do expect(handle_request).to eq([http_method, url, headers, data]) # not normalized - expect(headers).to eq({"content-type" => "application/x-binary"}) + expect(headers).to eq({ "content-type" => "application/x-binary" }) end it "does not serialize the body to json when content type is given in capitalized form" do @@ -120,9 +112,7 @@ describe Chef::HTTP::JSONInput do expect(handle_request).to eq([http_method, url, headers, data]) # not normalized - expect(headers).to eq({"Content-Type" => "application/x-binary"}) + expect(headers).to eq({ "Content-Type" => "application/x-binary" }) end - end - end diff --git a/spec/unit/http/socketless_chef_zero_client_spec.rb b/spec/unit/http/socketless_chef_zero_client_spec.rb index 4b45582ec4..9094baa656 100644 --- a/spec/unit/http/socketless_chef_zero_client_spec.rb +++ b/spec/unit/http/socketless_chef_zero_client_spec.rb @@ -19,7 +19,6 @@ require "chef/http/socketless_chef_zero_client" describe Chef::HTTP::SocketlessChefZeroClient do - let(:relative_url) { "" } let(:uri_str) { "chefzero://localhost:1/#{relative_url}" } let(:uri) { URI(uri_str) } @@ -35,7 +34,6 @@ describe Chef::HTTP::SocketlessChefZeroClient do end describe "converting requests to rack format" do - let(:expected_rack_req) do { "SCRIPT_NAME" => "", @@ -50,7 +48,6 @@ describe Chef::HTTP::SocketlessChefZeroClient do end context "when the request has no body" do - let(:method) { :GET } let(:relative_url) { "clients" } let(:headers) { { "Accept" => "application/json" } } @@ -67,11 +64,9 @@ describe Chef::HTTP::SocketlessChefZeroClient do expect(rack_req[key]).to eq(value) end end - end context "when the request has a body" do - let(:method) { :PUT } let(:relative_url) { "clients/foo" } let(:headers) { { "Accept" => "application/json" } } @@ -88,17 +83,13 @@ describe Chef::HTTP::SocketlessChefZeroClient do expect(rack_req[key]).to eq(value) end end - end - end describe "converting responses to Net::HTTP objects" do - let(:net_http_response) { zero_client.to_net_http(code, headers, body) } context "when the request was successful (2XX)" do - let(:code) { 200 } let(:headers) { { "Content-Type" => "Application/JSON" } } let(:body) { [ "bunch o' JSON" ] } @@ -110,13 +101,11 @@ describe Chef::HTTP::SocketlessChefZeroClient do end it "does not fail when calling read_body with a block" do - expect(net_http_response.read_body {|chunk| chunk }).to eq("bunch o' JSON") + expect(net_http_response.read_body { |chunk| chunk }).to eq("bunch o' JSON") end - end context "when the requested object doesn't exist (404)" do - let(:code) { 404 } let(:headers) { { "Content-Type" => "Application/JSON" } } let(:body) { [ "nope" ] } @@ -125,11 +114,9 @@ describe Chef::HTTP::SocketlessChefZeroClient do expect(net_http_response).to be_a_kind_of(Net::HTTPNotFound) end end - end describe "request-response round trip" do - let(:method) { :GET } let(:relative_url) { "clients" } let(:headers) { { "Accept" => "application/json" } } @@ -149,7 +136,6 @@ describe Chef::HTTP::SocketlessChefZeroClient do } end - let(:response_code) { 200 } let(:response_headers) { { "Content-Type" => "Application/JSON" } } let(:response_body) { [ "bunch o' JSON" ] } @@ -168,7 +154,5 @@ describe Chef::HTTP::SocketlessChefZeroClient do expect(net_http_response.code).to eq("200") expect(net_http_response.body).to eq("bunch o' JSON") end - end - end diff --git a/spec/unit/http/ssl_policies_spec.rb b/spec/unit/http/ssl_policies_spec.rb index 7dbe06ee8e..f37b17bf14 100644 --- a/spec/unit/http/ssl_policies_spec.rb +++ b/spec/unit/http/ssl_policies_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "chef/http/ssl_policies" describe "HTTP SSL Policy" do - before do Chef::Config[:ssl_client_cert] = nil Chef::Config[:ssl_client_key] = nil @@ -36,7 +35,6 @@ describe "HTTP SSL Policy" do end describe Chef::HTTP::DefaultSSLPolicy do - let(:ssl_policy) { Chef::HTTP::DefaultSSLPolicy.new(unconfigured_http_client) } describe "when configured with :ssl_verify_mode set to :verify peer" do @@ -54,7 +52,7 @@ describe "HTTP SSL Policy" do it "raises a ConfigurationError if :ssl_ca_path is set to a path that doesn't exist" do Chef::Config[:ssl_ca_path] = "/dev/null/nothing_here" - expect {http_client}.to raise_error(Chef::Exceptions::ConfigurationError) + expect { http_client }.to raise_error(Chef::Exceptions::ConfigurationError) end it "should set the CA path if that is set in the configuration" do @@ -64,7 +62,7 @@ describe "HTTP SSL Policy" do it "raises a ConfigurationError if :ssl_ca_file is set to a file that does not exist" do Chef::Config[:ssl_ca_file] = "/dev/null/nothing_here" - expect {http_client}.to raise_error(Chef::Exceptions::ConfigurationError) + expect { http_client }.to raise_error(Chef::Exceptions::ConfigurationError) end it "should set the CA file if that is set in the configuration" do @@ -85,24 +83,24 @@ describe "HTTP SSL Policy" do end describe "when configured with a client certificate" do - before {@url = URI.parse("https://chef.example.com:4443/")} + before { @url = URI.parse("https://chef.example.com:4443/") } it "raises ConfigurationError if the certificate file doesn't exist" do Chef::Config[:ssl_client_cert] = "/dev/null/nothing_here" Chef::Config[:ssl_client_key] = CHEF_SPEC_DATA + "/ssl/chef-rspec.key" - expect {http_client}.to raise_error(Chef::Exceptions::ConfigurationError) + expect { http_client }.to raise_error(Chef::Exceptions::ConfigurationError) end it "raises ConfigurationError if the certificate file doesn't exist" do Chef::Config[:ssl_client_cert] = CHEF_SPEC_DATA + "/ssl/chef-rspec.cert" Chef::Config[:ssl_client_key] = "/dev/null/nothing_here" - expect {http_client}.to raise_error(Chef::Exceptions::ConfigurationError) + expect { http_client }.to raise_error(Chef::Exceptions::ConfigurationError) end it "raises a ConfigurationError if one of :ssl_client_cert and :ssl_client_key is set but not both" do Chef::Config[:ssl_client_cert] = "/dev/null/nothing_here" Chef::Config[:ssl_client_key] = nil - expect {http_client}.to raise_error(Chef::Exceptions::ConfigurationError) + expect { http_client }.to raise_error(Chef::Exceptions::ConfigurationError) end it "configures the HTTP client's cert and private key" do @@ -152,7 +150,6 @@ describe "HTTP SSL Policy" do end describe Chef::HTTP::APISSLPolicy do - let(:ssl_policy) { Chef::HTTP::APISSLPolicy.new(unconfigured_http_client) } context "when verify_api_cert is set" do @@ -164,7 +161,5 @@ describe "HTTP SSL Policy" do expect(http_client.verify_mode).to eq(OpenSSL::SSL::VERIFY_PEER) end end - end end - diff --git a/spec/unit/http/validate_content_length_spec.rb b/spec/unit/http/validate_content_length_spec.rb index 00f69c7e6f..3b959f29f4 100644 --- a/spec/unit/http/validate_content_length_spec.rb +++ b/spec/unit/http/validate_content_length_spec.rb @@ -29,7 +29,7 @@ describe Chef::HTTP::ValidateContentLength do let(:headers) { {} } let(:data) { false } - let(:request) { } + let(:request) {} let(:return_value) { "200" } # Test Variables @@ -105,7 +105,7 @@ describe Chef::HTTP::ValidateContentLength do end describe "without Content-Length header" do - let(:response_headers) { { } } + let(:response_headers) { {} } [ "direct", "streaming" ].each do |req_type| describe "when running #{req_type} request" do @@ -180,7 +180,7 @@ describe Chef::HTTP::ValidateContentLength do end it "should reset internal counter" do - expect(middleware.instance_variable_get(:@content_length_counter)).to be_nil + expect(middleware.instance_variable_get(:@content_length_counter)).to be_nil end it "should validate correctly second time" do @@ -188,5 +188,4 @@ describe Chef::HTTP::ValidateContentLength do expect(debug_output).to include("Content-Length validated correctly.") end end - end diff --git a/spec/unit/http_spec.rb b/spec/unit/http_spec.rb index 12c3bfcaef..87e68dc0e5 100644 --- a/spec/unit/http_spec.rb +++ b/spec/unit/http_spec.rb @@ -27,9 +27,7 @@ class Chef::HTTP end describe Chef::HTTP do - context "when given a chefzero:// URL" do - let(:uri) { URI("chefzero://localhost:1") } subject(:http) { Chef::HTTP.new(uri) } @@ -38,11 +36,9 @@ describe Chef::HTTP do expect(http.http_client).to be_a_kind_of(Chef::HTTP::SocketlessChefZeroClient) expect(http.http_client.url).to eq(uri) end - end describe "create_url" do - it "should return a correctly formatted url 1/3 CHEF-5261" do http = Chef::HTTP.new("http://www.getchef.com") expect(http.create_url("api/endpoint")).to eql(URI.parse("http://www.getchef.com/api/endpoint")) @@ -64,11 +60,9 @@ describe Chef::HTTP do expect { http.create_url("HTTP://www1.chef.io/") }.not_to raise_error expect(http.create_url("HTTP://www2.chef.io/")).to eql(URI.parse("http://www2.chef.io/")) end - end # create_url describe "head" do - it 'should return nil for a "200 Success" response (CHEF-4762)' do resp = Net::HTTPOK.new("1.1", 200, "OK") expect(resp).to receive(:read_body).and_return(nil) @@ -86,11 +80,9 @@ describe Chef::HTTP do expect(http.head("http://www.getchef.com/")).to eql(false) end - end # head describe "retrying connection errors" do - let(:uri) { "https://chef.example/organizations/default/" } subject(:http) { Chef::HTTP.new(uri) } @@ -109,7 +101,6 @@ describe Chef::HTTP do end shared_examples_for "retriable_request_errors" do - before do expect(low_level_client).to receive(:request).exactly(5).times.and_raise(exception) expect(http).to receive(:sleep).exactly(5).times.and_return(1) @@ -119,11 +110,9 @@ describe Chef::HTTP do it "retries the request 5 times" do http.get("/") end - end shared_examples_for "errors_that_are_not_retried" do - before do expect(low_level_client).to receive(:request).exactly(1).times.and_raise(exception) expect(http).to_not receive(:sleep) @@ -136,59 +125,45 @@ describe Chef::HTTP do end context "when ECONNRESET is raised" do - let(:exception) { Errno::ECONNRESET.new("example error") } include_examples "retriable_request_errors" - end context "when SocketError is raised" do - let(:exception) { SocketError.new("example error") } include_examples "retriable_request_errors" - end context "when ETIMEDOUT is raised" do - let(:exception) { Errno::ETIMEDOUT.new("example error") } include_examples "retriable_request_errors" - end context "when ECONNREFUSED is raised" do - let(:exception) { Errno::ECONNREFUSED.new("example error") } include_examples "retriable_request_errors" - end context "when Timeout::Error is raised" do - let(:exception) { Timeout::Error.new("example error") } include_examples "retriable_request_errors" - end context "when OpenSSL::SSL::SSLError is raised" do - let(:exception) { OpenSSL::SSL::SSLError.new("example error") } include_examples "retriable_request_errors" - end context "when OpenSSL::SSL::SSLError is raised for certificate validation failure" do - let(:exception) { OpenSSL::SSL::SSLError.new("ssl_connect returned=1 errno=0 state=sslv3 read server certificate b: certificate verify failed") } include_examples "errors_that_are_not_retried" - end end end diff --git a/spec/unit/json_compat_spec.rb b/spec/unit/json_compat_spec.rb index c31ab05f45..4da29fe4ec 100644 --- a/spec/unit/json_compat_spec.rb +++ b/spec/unit/json_compat_spec.rb @@ -58,14 +58,14 @@ describe Chef::JSONCompat do let(:json) { '{"json_class": "Chef::Sandbox", "arbitrary": "data"}' } it "returns a Hash, because Chef::Sandbox is a dummy class" do - expect(Chef::JSONCompat.from_json(json)).to eq({"json_class" => "Chef::Sandbox", "arbitrary" => "data"}) + expect(Chef::JSONCompat.from_json(json)).to eq({ "json_class" => "Chef::Sandbox", "arbitrary" => "data" }) end end describe "when pretty printing an object that defines #to_json" do class Foo def to_json(*a) - Chef::JSONCompat.to_json({"foo" => 1234, "bar" => {"baz" => 5678}}, *a) + Chef::JSONCompat.to_json({ "foo" => 1234, "bar" => { "baz" => 5678 } }, *a) end end diff --git a/spec/unit/key_spec.rb b/spec/unit/key_spec.rb index 5912016577..b24a463e0d 100644 --- a/spec/unit/key_spec.rb +++ b/spec/unit/key_spec.rb @@ -24,7 +24,7 @@ describe Chef::Key do # whether user or client irrelevent to these tests let(:key) { Chef::Key.new("original_actor", "user") } let(:public_key_string) do - < "key_name", "public_key" => public_key_string, "private_key" => "some_private_key", - "expiration_date" => "infinity"} + "expiration_date" => "infinity" } Chef::Key.from_json(o.to_json) end let(:key_with_create_key_field) do @@ -324,7 +322,7 @@ EOS "name" => "key_name", "public_key" => public_key_string, "private_key" => "some_private_key", - "expiration_date" => "infinity"} + "expiration_date" => "infinity" } Chef::Key.from_json(o.to_json) end let(:key_with_create_key_field) do @@ -336,7 +334,6 @@ EOS end end # when deserializing from JSON - describe "API Interactions" do let(:rest) do Chef::Config[:chef_server_root] = "http://www.example.com" @@ -358,8 +355,8 @@ EOS describe "list" do context "when listing keys for a user" do - let(:response) { [{"uri" => "http://www.example.com/users/keys/foobar", "name"=>"foobar", "expired"=>false}] } - let(:inflated_response) { {"foobar" => user_key} } + let(:response) { [{ "uri" => "http://www.example.com/users/keys/foobar", "name" => "foobar", "expired" => false }] } + let(:inflated_response) { { "foobar" => user_key } } it "lists all keys" do expect(rest).to receive(:get).with("users/#{user_key.actor}/keys").and_return(response) @@ -371,12 +368,11 @@ EOS expect(rest).to receive(:get).with("users/#{user_key.actor}/keys").and_return(response) expect(Chef::Key.list_by_user("foobar", true)).to eq(inflated_response) end - end context "when listing keys for a client" do - let(:response) { [{"uri" => "http://www.example.com/users/keys/foobar", "name"=>"foobar", "expired"=>false}] } - let(:inflated_response) { {"foobar" => client_key} } + let(:response) { [{ "uri" => "http://www.example.com/users/keys/foobar", "name" => "foobar", "expired" => false }] } + let(:inflated_response) { { "foobar" => client_key } } it "lists all keys" do expect(rest).to receive(:get).with("clients/#{client_key.actor}/keys").and_return(response) @@ -388,11 +384,9 @@ EOS expect(rest).to receive(:get).with("clients/#{user_key.actor}/keys").and_return(response) expect(Chef::Key.list_by_client("foobar", true)).to eq(inflated_response) end - end end - describe "create" do shared_examples_for "create key" do context "when a field is missing" do @@ -409,9 +403,9 @@ EOS it "creates a new key via the API with the fingerprint as the name" do expect(rest).to receive(:post).with(url, - {"name" => "12:3e:33:73:0b:f4:ec:72:dc:f0:4c:51:62:27:08:76:96:24:f4:4a", - "public_key" => key.public_key, - "expiration_date" => key.expiration_date}).and_return({}) + { "name" => "12:3e:33:73:0b:f4:ec:72:dc:f0:4c:51:62:27:08:76:96:24:f4:4a", + "public_key" => key.public_key, + "expiration_date" => key.expiration_date }).and_return({}) key.create end end @@ -427,15 +421,14 @@ EOS context "when create_key is false" do it "creates a new key via the API" do expect(rest).to receive(:post).with(url, - {"name" => key.name, - "public_key" => key.public_key, - "expiration_date" => key.expiration_date}).and_return({}) + { "name" => key.name, + "public_key" => key.public_key, + "expiration_date" => key.expiration_date }).and_return({}) key.create end end context "when create_key is true and public_key is nil" do - before do key.delete_public_key key.create_key true @@ -459,11 +452,11 @@ EOS context "when the server returns the private_key via key.create" do before do - allow(rest).to receive(:post).with(url, $expected_input).and_return({"private_key" => "this_private_key"}) + allow(rest).to receive(:post).with(url, $expected_input).and_return({ "private_key" => "this_private_key" }) end it "key.create returns the original key plus the private_key" do - expect(key.create.to_hash).to eq($expected_output.merge({"private_key" => "this_private_key"})) + expect(key.create.to_hash).to eq($expected_output.merge({ "private_key" => "this_private_key" })) end end end @@ -533,10 +526,9 @@ EOS key.name "key_name" key.create_key true allow(rest).to receive(:put).with(url, key.to_hash).and_return({ - "key" => "key_name", - "public_key" => public_key_string, - },) - + "key" => "key_name", + "public_key" => public_key_string, + },) end it "returns a key with public_key populated" do @@ -566,13 +558,12 @@ EOS let(:key) { client_key } end end - end #update describe "load" do shared_examples_for "load" do it "should load a named key from the API" do - expect(rest).to receive(:get).with(url).and_return({"user" => "foobar", "name" => "test_key_name", "public_key" => public_key_string, "expiration_date" => "infinity"}) + expect(rest).to receive(:get).with(url).and_return({ "user" => "foobar", "name" => "test_key_name", "public_key" => public_key_string, "expiration_date" => "infinity" }) key = Chef::Key.send(load_method, "foobar", "test_key_name") expect(key.actor).to eq("foobar") expect(key.name).to eq("test_key_name") @@ -594,7 +585,6 @@ EOS let(:url) { "clients/foobar/keys/test_key_name" } end end - end #load describe "destroy" do diff --git a/spec/unit/knife/bootstrap/chef_vault_handler_spec.rb b/spec/unit/knife/bootstrap/chef_vault_handler_spec.rb index ffc851e2b5..148d5ae2cd 100644 --- a/spec/unit/knife/bootstrap/chef_vault_handler_spec.rb +++ b/spec/unit/knife/bootstrap/chef_vault_handler_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Knife::Bootstrap::ChefVaultHandler do - let(:stdout) { StringIO.new } let(:stderr) { StringIO.new } let(:stdin) { StringIO.new } @@ -114,7 +113,6 @@ describe Chef::Knife::Bootstrap::ChefVaultHandler do end context "from knife_config[:bootstrap_vault_file]" do - def setup_file_contents(json) stringio = StringIO.new(json) knife_config[:bootstrap_vault_file] = "/foo/bar/baz" diff --git a/spec/unit/knife/bootstrap/client_builder_spec.rb b/spec/unit/knife/bootstrap/client_builder_spec.rb index c509c70872..79ff9d51e5 100644 --- a/spec/unit/knife/bootstrap/client_builder_spec.rb +++ b/spec/unit/knife/bootstrap/client_builder_spec.rb @@ -18,9 +18,7 @@ require "spec_helper" - describe Chef::Knife::Bootstrap::ClientBuilder do - let(:stdout) { StringIO.new } let(:stderr) { StringIO.new } let(:stdin) { StringIO.new } @@ -122,7 +120,6 @@ describe Chef::Knife::Bootstrap::ClientBuilder do client_builder.run expect(client_builder.client).to eq(client) end - end context "#client_path" do @@ -131,7 +128,7 @@ describe Chef::Knife::Bootstrap::ClientBuilder do end end - context "#create_node!" do + context "#create_node!" do before do # mock out the rest of #run expect(client_builder).to receive(:sanity_check) @@ -181,8 +178,8 @@ describe Chef::Knife::Bootstrap::ClientBuilder do end it "builds a node with first_boot_attributes if they're given" do - knife_config[:first_boot_attributes] = {:baz => :quux} - expect(node).to receive(:normal_attrs=).with({:baz=>:quux}) + knife_config[:first_boot_attributes] = { :baz => :quux } + expect(node).to receive(:normal_attrs=).with({ :baz => :quux }) expect(node).to receive(:run_list).with([]) client_builder.run end diff --git a/spec/unit/knife/bootstrap_spec.rb b/spec/unit/knife/bootstrap_spec.rb index e6a78df8ba..226fb271f2 100644 --- a/spec/unit/knife/bootstrap_spec.rb +++ b/spec/unit/knife/bootstrap_spec.rb @@ -51,7 +51,7 @@ describe Chef::Knife::Bootstrap do context "with --bootstrap-vault-item" do let(:bootstrap_cli_options) { [ "--bootstrap-vault-item", "vault1:item1", "--bootstrap-vault-item", "vault1:item2", "--bootstrap-vault-item", "vault2:item1" ] } it "sets the knife config cli option correctly" do - expect(knife.config[:bootstrap_vault_item]).to eq({"vault1"=>["item1", "item2"], "vault2"=>["item1"]}) + expect(knife.config[:bootstrap_vault_item]).to eq({ "vault1" => ["item1", "item2"], "vault2" => ["item1"] }) end end @@ -102,7 +102,7 @@ describe Chef::Knife::Bootstrap do context "when :bootstrap_template config is set to a template name" do let(:bootstrap_template) { "example" } - let(:builtin_template_path) { File.expand_path(File.join(File.dirname(__FILE__), "../../../lib/chef/knife/bootstrap/templates", "example.erb"))} + let(:builtin_template_path) { File.expand_path(File.join(File.dirname(__FILE__), "../../../lib/chef/knife/bootstrap/templates", "example.erb")) } let(:chef_config_dir_template_path) { "/knife/chef/config/bootstrap/example.erb" } @@ -209,7 +209,7 @@ describe Chef::Knife::Bootstrap do ["-d", "--distro", "-t", "--bootstrap-template", "--template-file"].each do |t| context "when #{t} option is given in the command line" do it "sets the knife :bootstrap_template config" do - knife.parse_options([t,"blahblah"]) + knife.parse_options([t, "blahblah"]) knife.merge_configs expect(knife.bootstrap_template).to eq("blahblah") end @@ -224,7 +224,7 @@ describe Chef::Knife::Bootstrap do end it "should have role[base] in the run_list" do - knife.parse_options(["-r","role[base]"]) + knife.parse_options(["-r", "role[base]"]) knife.merge_configs expect(knife.render_template).to eq('{"run_list":["role[base]"]}') end @@ -238,7 +238,7 @@ describe Chef::Knife::Bootstrap do context "with bootstrap_attribute options" do let(:jsonfile) { file = Tempfile.new (["node", ".json"]) - File.open(file.path, "w") {|f| f.puts '{"foo":{"bar":"baz"}}' } + File.open(file.path, "w") { |f| f.puts '{"foo":{"bar":"baz"}}' } file } @@ -264,7 +264,7 @@ describe Chef::Knife::Bootstrap do knife.parse_options(["-j", '{"foo":{"bar":"baz"}}']) knife.parse_options(["--json-attribute-file", jsonfile.path]) knife.merge_configs - expect{ knife.run }.to raise_error(Chef::Exceptions::BootstrapCommandInputError) + expect { knife.run }.to raise_error(Chef::Exceptions::BootstrapCommandInputError) jsonfile.close end end @@ -297,7 +297,7 @@ describe Chef::Knife::Bootstrap do k end - let(:options){ ["--bootstrap-no-proxy", setting, "-s", "foo"] } + let(:options) { ["--bootstrap-no-proxy", setting, "-s", "foo"] } let(:template_file) { File.expand_path(File.join(CHEF_SPEC_DATA, "bootstrap", "no_proxy.erb")) } let(:rendered_template) do knife.render_template @@ -339,7 +339,7 @@ describe Chef::Knife::Bootstrap do let(:options) { ["--node-ssl-verify-mode", "all"] } it "raises error" do - expect{ rendered_template }.to raise_error + expect { rendered_template }.to raise_error end end @@ -381,7 +381,6 @@ describe Chef::Knife::Bootstrap do expect(knife).to receive(:read_secret).and_return(secret) expect(rendered_template).to match(%r{encrypted_data_bag_secret\s*"/etc/chef/encrypted_data_bag_secret"}) end - end describe "when transferring trusted certificates" do @@ -459,42 +458,34 @@ describe Chef::Knife::Bootstrap do end describe "handling policyfile options" do - context "when only policy_name is given" do - let(:bootstrap_cli_options) { %w{ --policy-name my-app-server } } it "returns an error stating that policy_name and policy_group must be given together" do expect { knife.validate_options! }.to raise_error(SystemExit) expect(stderr.string).to include("ERROR: --policy-name and --policy-group must be specified together") end - end context "when only policy_group is given" do - let(:bootstrap_cli_options) { %w{ --policy-group staging } } it "returns an error stating that policy_name and policy_group must be given together" do expect { knife.validate_options! }.to raise_error(SystemExit) expect(stderr.string).to include("ERROR: --policy-name and --policy-group must be specified together") end - end context "when both policy_name and policy_group are given, but run list is also given" do - let(:bootstrap_cli_options) { %w{ --policy-name my-app --policy-group staging --run-list cookbook } } it "returns an error stating that policyfile and run_list are exclusive" do expect { knife.validate_options! }.to raise_error(SystemExit) expect(stderr.string).to include("ERROR: Policyfile options and --run-list are exclusive") end - end context "when policy_name and policy_group are given with no conflicting options" do - let(:bootstrap_cli_options) { %w{ --policy-name my-app --policy-group staging } } it "passes options validation" do @@ -505,14 +496,12 @@ describe Chef::Knife::Bootstrap do expect(knife.bootstrap_context.first_boot).to have_key(:policy_name) expect(knife.bootstrap_context.first_boot).to have_key(:policy_group) end - end # https://github.com/chef/chef/issues/4131 # Arguably a bug in the plugin: it shouldn't be setting this to nil, but it # worked before, so make it work now. context "when a plugin sets the run list option to nil" do - before do knife.config[:run_list] = nil end @@ -520,9 +509,7 @@ describe Chef::Knife::Bootstrap do it "passes options validation" do expect { knife.validate_options! }.to_not raise_error end - end - end describe "when configuring the underlying knife ssh command" do @@ -633,7 +620,7 @@ describe Chef::Knife::Bootstrap do describe "when falling back to password auth when host key auth fails" do let(:knife_ssh_with_password_auth) do knife.name_args = ["foo.example.com"] - knife.config[:ssh_user] = "rooty" + knife.config[:ssh_user] = "rooty" knife.config[:ssh_identity_file] = "~/.ssh/me.rsa" allow(knife).to receive(:render_template).and_return("") k = knife.knife_ssh @@ -662,7 +649,7 @@ describe Chef::Knife::Bootstrap do let(:knife_ssh) do knife.name_args = ["foo.example.com"] knife.config[:chef_node_name] = "foo.example.com" - knife.config[:ssh_user] = "rooty" + knife.config[:ssh_user] = "rooty" knife.config[:ssh_identity_file] = "~/.ssh/me.rsa" allow(knife).to receive(:render_template).and_return("") knife_ssh = knife.knife_ssh @@ -677,7 +664,6 @@ describe Chef::Knife::Bootstrap do allow(File).to receive(:exist?).with(File.expand_path(Chef::Config[:validation_key])).and_return(true) end - it "configures the underlying ssh command and then runs it" do expect(knife_ssh).to receive(:run) knife.run @@ -769,6 +755,5 @@ describe Chef::Knife::Bootstrap do end describe "specifying ssl verification" do - end end diff --git a/spec/unit/knife/client_bulk_delete_spec.rb b/spec/unit/knife/client_bulk_delete_spec.rb index 42110d8180..096fba632a 100644 --- a/spec/unit/knife/client_bulk_delete_spec.rb +++ b/spec/unit/knife/client_bulk_delete_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::Knife::ClientBulkDelete do let(:stdout_io) { StringIO.new } - let(:stdout) {stdout_io.string} + let(:stdout) { stdout_io.string } let(:stderr_io) { StringIO.new } let(:stderr) { stderr_io.string } @@ -69,7 +69,7 @@ describe Chef::Knife::ClientBulkDelete do clients } - let(:client_names) { nonvalidator_client_names + validator_client_names} + let(:client_names) { nonvalidator_client_names + validator_client_names } let(:clients) { nonvalidator_clients.merge(validator_clients) } @@ -128,7 +128,7 @@ describe Chef::Knife::ClientBulkDelete do end describe "with --delete-validators" do - let(:option_args) { {:delete_validators => true} } + let(:option_args) { { :delete_validators => true } } it "should mention that validator clients will be deleted" do knife.run diff --git a/spec/unit/knife/client_create_spec.rb b/spec/unit/knife/client_create_spec.rb index 7c3d837c97..bd9d4a1d63 100644 --- a/spec/unit/knife/client_create_spec.rb +++ b/spec/unit/knife/client_create_spec.rb @@ -24,7 +24,6 @@ describe Chef::Knife::ClientCreate do let(:stderr) { StringIO.new } let(:stdout) { StringIO.new } - let(:default_client_hash) do { "name" => "adam", @@ -53,7 +52,7 @@ describe Chef::Knife::ClientCreate do end before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" end describe "run" do diff --git a/spec/unit/knife/client_delete_spec.rb b/spec/unit/knife/client_delete_spec.rb index eee665a7b4..f1af3c3d4e 100644 --- a/spec/unit/knife/client_delete_spec.rb +++ b/spec/unit/knife/client_delete_spec.rb @@ -69,7 +69,7 @@ describe Chef::Knife::ClientDelete do it "should not delete validator client if --delete-validators is not set" do @client.validator(true) expect(@knife.ui).to receive(:fatal) - expect { @knife.run}.to raise_error(SystemExit) + expect { @knife.run }.to raise_error(SystemExit) end it "should delete validator client if --delete-validators is set" do diff --git a/spec/unit/knife/client_reregister_spec.rb b/spec/unit/knife/client_reregister_spec.rb index 6776cafa0a..f549dc181f 100644 --- a/spec/unit/knife/client_reregister_spec.rb +++ b/spec/unit/knife/client_reregister_spec.rb @@ -58,5 +58,4 @@ describe Chef::Knife::ClientReregister do expect(filehandle.string).to eq("foo_key") end end - end diff --git a/spec/unit/knife/client_show_spec.rb b/spec/unit/knife/client_show_spec.rb index 9dfb0666de..47b4b6ccb0 100644 --- a/spec/unit/knife/client_show_spec.rb +++ b/spec/unit/knife/client_show_spec.rb @@ -36,7 +36,7 @@ describe Chef::Knife::ClientShow do @knife.config[:format] = "json" @stdout = StringIO.new allow(@knife.ui).to receive(:stdout).and_return(@stdout) - fake_client_contents = {"foo"=>"bar", "baz"=>"qux"} + fake_client_contents = { "foo" => "bar", "baz" => "qux" } expect(Chef::ApiClientV1).to receive(:load).with("adam").and_return(fake_client_contents) @knife.run expect(@stdout.string).to eql("{\n \"foo\": \"bar\",\n \"baz\": \"qux\"\n}\n") diff --git a/spec/unit/knife/configure_client_spec.rb b/spec/unit/knife/configure_client_spec.rb index 54fed02ca3..e2886f63f4 100644 --- a/spec/unit/knife/configure_client_spec.rb +++ b/spec/unit/knife/configure_client_spec.rb @@ -44,9 +44,9 @@ describe Chef::Knife::ConfigureClient do @client_file = StringIO.new @validation_file = StringIO.new expect(File).to receive(:open).with("/home/bob/.chef/client.rb", "w"). - and_yield(@client_file) + and_yield(@client_file) expect(File).to receive(:open).with("/home/bob/.chef/validation.pem", "w"). - and_yield(@validation_file) + and_yield(@validation_file) expect(IO).to receive(:read).and_return("foo_bar_baz") end @@ -79,6 +79,4 @@ describe Chef::Knife::ConfigureClient do end end end - end - diff --git a/spec/unit/knife/configure_spec.rb b/spec/unit/knife/configure_spec.rb index 6c1d98c2f5..e96115c056 100644 --- a/spec/unit/knife/configure_spec.rb +++ b/spec/unit/knife/configure_spec.rb @@ -4,7 +4,7 @@ describe Chef::Knife::Configure do before do Chef::Log.logger = Logger.new(StringIO.new) - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::Configure.new @rest_client = double("null rest client", :post => { :result => :true }) allow(@knife).to receive(:rest).and_return(@rest_client) @@ -22,7 +22,6 @@ describe Chef::Knife::Configure do allow(Ohai::System).to receive(:new).and_return(ohai) end - let(:fqdn) { "foo.example.org" } let(:ohai) do @@ -41,7 +40,6 @@ describe Chef::Knife::Configure do let(:default_server_url) { "https://#{fqdn}:443" } - it "asks the user for the URL of the chef server" do @knife.ask_user_for_config expect(@out.string).to match(Regexp.escape("Please enter the chef server URL: [#{default_server_url}]")) @@ -220,7 +218,7 @@ describe Chef::Knife::Configure do expect(File).to receive(:expand_path).with("/home/you/.chef/a-new-user.pem").and_return("/home/you/.chef/a-new-user.pem") expect(File).to receive(:expand_path).with(default_validator_key).and_return(default_validator_key) expect(File).to receive(:expand_path).with(default_admin_key).and_return(default_admin_key) - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" user_command = Chef::Knife::UserCreate.new expect(user_command).to receive(:run) diff --git a/spec/unit/knife/cookbook_bulk_delete_spec.rb b/spec/unit/knife/cookbook_bulk_delete_spec.rb index 72299f4920..09e4764b8f 100644 --- a/spec/unit/knife/cookbook_bulk_delete_spec.rb +++ b/spec/unit/knife/cookbook_bulk_delete_spec.rb @@ -22,9 +22,9 @@ describe Chef::Knife::CookbookBulkDelete do before(:each) do Chef::Log.logger = Logger.new(StringIO.new) - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::CookbookBulkDelete.new - @knife.config = {:print_after => nil} + @knife.config = { :print_after => nil } @knife.name_args = ["."] @stdout = StringIO.new @stderr = StringIO.new @@ -41,18 +41,15 @@ describe Chef::Knife::CookbookBulkDelete do allow(@rest).to receive(:delete).and_return(true) allow(@knife).to receive(:rest).and_return(@rest) allow(Chef::CookbookVersion).to receive(:list).and_return(@cookbooks) - end - - describe "when there are several cookbooks on the server" do before do - @cheezburger = {"cheezburger" => {"url" => "file:///dev/null", "versions" => [{"url" => "file:///dev/null-cheez", "version" => "1.0.0"}]}} + @cheezburger = { "cheezburger" => { "url" => "file:///dev/null", "versions" => [{ "url" => "file:///dev/null-cheez", "version" => "1.0.0" }] } } allow(@rest).to receive(:get).with("cookbooks/cheezburger").and_return(@cheezburger) - @pizza = {"pizza" => {"url" => "file:///dev/null", "versions" => [{"url" => "file:///dev/null-pizza", "version" => "2.0.0"}]}} + @pizza = { "pizza" => { "url" => "file:///dev/null", "versions" => [{ "url" => "file:///dev/null-pizza", "version" => "2.0.0" }] } } allow(@rest).to receive(:get).with("cookbooks/pizza").and_return(@pizza) - @lasagna = {"lasagna" => {"url" => "file:///dev/null", "versions" => [{"url" => "file:///dev/null-lasagna", "version" => "3.0.0"}]}} + @lasagna = { "lasagna" => { "url" => "file:///dev/null", "versions" => [{ "url" => "file:///dev/null-lasagna", "version" => "3.0.0" }] } } allow(@rest).to receive(:get).with("cookbooks/lasagna").and_return(@lasagna) end @@ -68,7 +65,7 @@ describe Chef::Knife::CookbookBulkDelete do end it "should delete each cookbook" do - {"cheezburger" => "1.0.0", "pizza" => "2.0.0", "lasagna" => "3.0.0"}.each do |cookbook_name, version| + { "cheezburger" => "1.0.0", "pizza" => "2.0.0", "lasagna" => "3.0.0" }.each do |cookbook_name, version| expect(@rest).to receive(:delete).with("cookbooks/#{cookbook_name}/#{version}") end @knife.run @@ -85,5 +82,4 @@ describe Chef::Knife::CookbookBulkDelete do @knife.name_args = [] expect { @knife.run }.to raise_error(SystemExit) end - end diff --git a/spec/unit/knife/cookbook_create_spec.rb b/spec/unit/knife/cookbook_create_spec.rb index 1989516c1b..e1958cb3fc 100644 --- a/spec/unit/knife/cookbook_create_spec.rb +++ b/spec/unit/knife/cookbook_create_spec.rb @@ -21,7 +21,7 @@ require "tmpdir" describe Chef::Knife::CookbookCreate do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::CookbookCreate.new @knife.config = {} @knife.name_args = ["foobar"] @@ -30,11 +30,10 @@ describe Chef::Knife::CookbookCreate do end describe "run" do - # Fixes CHEF-2579 it "should expand the path of the cookbook directory" do expect(File).to receive(:expand_path).with("~/tmp/monkeypants") - @knife.config = {:cookbook_path => "~/tmp/monkeypants"} + @knife.config = { :cookbook_path => "~/tmp/monkeypants" } allow(@knife).to receive(:create_cookbook) allow(@knife).to receive(:create_readme) allow(@knife).to receive(:create_changelog) @@ -44,7 +43,7 @@ describe Chef::Knife::CookbookCreate do it "should create a new cookbook with default values to copyright name, email, readme format and license if those are not supplied" do @dir = Dir.tmpdir - @knife.config = {:cookbook_path => @dir} + @knife.config = { :cookbook_path => @dir } expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "YOUR_COMPANY_NAME", "none") expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) @@ -58,7 +57,7 @@ describe Chef::Knife::CookbookCreate do :cookbook_path => @dir, :cookbook_copyright => "Opscode, Inc", } - @knife.name_args=["foobar"] + @knife.name_args = ["foobar"] expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "none") expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) @@ -73,7 +72,7 @@ describe Chef::Knife::CookbookCreate do :cookbook_copyright => "Opscode, Inc", :cookbook_email => "nuo@opscode.com", } - @knife.name_args=["foobar"] + @knife.name_args = ["foobar"] expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "none") expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) @@ -89,7 +88,7 @@ describe Chef::Knife::CookbookCreate do :cookbook_email => "nuo@opscode.com", :cookbook_license => "apachev2", } - @knife.name_args=["foobar"] + @knife.name_args = ["foobar"] expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "apachev2") expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) @@ -105,7 +104,7 @@ describe Chef::Knife::CookbookCreate do :cookbook_email => "nuo@opscode.com", :cookbook_license => false, } - @knife.name_args=["foobar"] + @knife.name_args = ["foobar"] expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "none") expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) @@ -121,7 +120,7 @@ describe Chef::Knife::CookbookCreate do :cookbook_email => "nuo@opscode.com", :cookbook_license => "false", } - @knife.name_args=["foobar"] + @knife.name_args = ["foobar"] expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "none") expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) @@ -137,7 +136,7 @@ describe Chef::Knife::CookbookCreate do :cookbook_email => "nuo@opscode.com", :cookbook_license => "gplv2", } - @knife.name_args=["foobar"] + @knife.name_args = ["foobar"] expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "gplv2") expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) @@ -153,7 +152,7 @@ describe Chef::Knife::CookbookCreate do :cookbook_email => "nuo@opscode.com", :cookbook_license => "gplv3", } - @knife.name_args=["foobar"] + @knife.name_args = ["foobar"] expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "gplv3") expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) @@ -169,7 +168,7 @@ describe Chef::Knife::CookbookCreate do :cookbook_email => "nuo@opscode.com", :cookbook_license => "mit", } - @knife.name_args=["foobar"] + @knife.name_args = ["foobar"] expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) @@ -186,7 +185,7 @@ describe Chef::Knife::CookbookCreate do :cookbook_license => "mit", :readme_format => "rdoc", } - @knife.name_args=["foobar"] + @knife.name_args = ["foobar"] expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "rdoc") expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) @@ -203,7 +202,7 @@ describe Chef::Knife::CookbookCreate do :cookbook_license => "mit", :readme_format => "mkd", } - @knife.name_args=["foobar"] + @knife.name_args = ["foobar"] expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "mkd") expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) @@ -220,7 +219,7 @@ describe Chef::Knife::CookbookCreate do :cookbook_license => "mit", :readme_format => "txt", } - @knife.name_args=["foobar"] + @knife.name_args = ["foobar"] expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "txt") expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) @@ -237,7 +236,7 @@ describe Chef::Knife::CookbookCreate do :cookbook_license => "mit", :readme_format => "foo", } - @knife.name_args=["foobar"] + @knife.name_args = ["foobar"] expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "foo") expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) @@ -252,9 +251,8 @@ describe Chef::Knife::CookbookCreate do it "should throw an argument error" do @dir = Dir.tmpdir - expect{@knife.run}.to raise_error(ArgumentError) + expect { @knife.run }.to raise_error(ArgumentError) end end - end end diff --git a/spec/unit/knife/cookbook_delete_spec.rb b/spec/unit/knife/cookbook_delete_spec.rb index f27bfeaa80..f51a92f126 100644 --- a/spec/unit/knife/cookbook_delete_spec.rb +++ b/spec/unit/knife/cookbook_delete_spec.rb @@ -63,7 +63,7 @@ describe Chef::Knife::CookbookDelete do it "should prompt to purge the files" do @knife.config[:purge] = true expect(@knife).to receive(:confirm). - with(/.+Are you sure you want to purge files.+/) + with(/.+Are you sure you want to purge files.+/) expect(@knife).to receive(:delete_without_explicit_version) @knife.run end @@ -127,9 +127,9 @@ describe Chef::Knife::CookbookDelete do before(:each) do @rest_mock = double("rest") expect(@knife).to receive(:rest).and_return(@rest_mock) - @cookbook_data = { "foobar" => { "versions" => [{"version" => "1.0.0"}, - {"version" => "1.1.0"}, - {"version" => "2.0.0"} ]} + @cookbook_data = { "foobar" => { "versions" => [{ "version" => "1.0.0" }, + { "version" => "1.1.0" }, + { "version" => "2.0.0" } ] } } end @@ -235,5 +235,4 @@ describe Chef::Knife::CookbookDelete do end end end - end diff --git a/spec/unit/knife/cookbook_download_spec.rb b/spec/unit/knife/cookbook_download_spec.rb index c515693a53..07405e44b4 100644 --- a/spec/unit/knife/cookbook_download_spec.rb +++ b/spec/unit/knife/cookbook_download_spec.rb @@ -49,20 +49,20 @@ describe Chef::Knife::CookbookDownload do @manifest_data = { :recipes => [ - {"path" => "recipes/foo.rb", - "url" => "http://example.org/files/foo.rb"}, - {"path" => "recipes/bar.rb", - "url" => "http://example.org/files/bar.rb"}, + { "path" => "recipes/foo.rb", + "url" => "http://example.org/files/foo.rb" }, + { "path" => "recipes/bar.rb", + "url" => "http://example.org/files/bar.rb" }, ], :templates => [ - {"path" => "templates/default/foo.erb", - "url" => "http://example.org/files/foo.erb"}, - {"path" => "templates/default/bar.erb", - "url" => "http://example.org/files/bar.erb"}, + { "path" => "templates/default/foo.erb", + "url" => "http://example.org/files/foo.erb" }, + { "path" => "templates/default/bar.erb", + "url" => "http://example.org/files/bar.erb" }, ], :attributes => [ - {"path" => "attributes/default.rb", - "url" => "http://example.org/files/default.rb"}, + { "path" => "attributes/default.rb", + "url" => "http://example.org/files/default.rb" }, ], } @@ -102,17 +102,17 @@ describe Chef::Knife::CookbookDownload do before(:each) do @files.map { |f| File.dirname(f) }.flatten.uniq.each do |dir| expect(FileUtils).to receive(:mkdir_p).with("/var/tmp/chef/foobar-1.0.0/#{dir}"). - at_least(:once) + at_least(:once) end @files_mocks.each_pair do |file, mock| expect(@rest_mock).to receive(:streaming_request).with("http://example.org/files/#{file}"). - and_return(mock) + and_return(mock) end @files.each do |f| expect(FileUtils).to receive(:mv). - with("/var/tmp/#{File.basename(f)}", "/var/tmp/chef/foobar-1.0.0/#{f}") + with("/var/tmp/#{File.basename(f)}", "/var/tmp/chef/foobar-1.0.0/#{f}") end end @@ -135,14 +135,11 @@ describe Chef::Knife::CookbookDownload do end end end - end end - end describe "determine_version" do - it "should return nil if there are no versions" do expect(@knife).to receive(:available_versions).and_return(nil) expect(@knife.determine_version).to eq(nil) @@ -165,7 +162,7 @@ describe Chef::Knife::CookbookDownload do it "should return and set the version to the latest version" do @knife.config[:latest] = true expect(@knife).to receive(:available_versions).at_least(:once). - and_return(["1.0.0", "1.1.0", "2.0.0"]) + and_return(["1.0.0", "1.1.0", "2.0.0"]) @knife.determine_version expect(@knife.version.to_s).to eq("2.0.0") end @@ -179,15 +176,15 @@ describe Chef::Knife::CookbookDownload do it "should return nil if there are no versions" do expect(Chef::CookbookVersion).to receive(:available_versions). - with("foobar"). - and_return(nil) + with("foobar"). + and_return(nil) expect(@knife.available_versions).to eq(nil) end it "should return the available versions" do expect(Chef::CookbookVersion).to receive(:available_versions). - with("foobar"). - and_return(["1.1.0", "2.0.0", "1.0.0"]) + with("foobar"). + and_return(["1.1.0", "2.0.0", "1.0.0"]) expect(@knife.available_versions).to eq([Chef::Version.new("1.0.0"), Chef::Version.new("1.1.0"), Chef::Version.new("2.0.0")]) @@ -195,9 +192,9 @@ describe Chef::Knife::CookbookDownload do it "should avoid multiple API calls to the server" do expect(Chef::CookbookVersion).to receive(:available_versions). - once. - with("foobar"). - and_return(["1.1.0", "2.0.0", "1.0.0"]) + once. + with("foobar"). + and_return(["1.1.0", "2.0.0", "1.0.0"]) @knife.available_versions @knife.available_versions end @@ -233,5 +230,4 @@ describe Chef::Knife::CookbookDownload do expect { @knife.ask_which_version }.to raise_error(SystemExit) end end - end diff --git a/spec/unit/knife/cookbook_list_spec.rb b/spec/unit/knife/cookbook_list_spec.rb index cc45970ead..4c0c734f1e 100644 --- a/spec/unit/knife/cookbook_list_spec.rb +++ b/spec/unit/knife/cookbook_list_spec.rb @@ -27,9 +27,9 @@ describe Chef::Knife::CookbookList do @base_url = "https://server.example.com/cookbooks" @cookbook_data = {} @cookbook_names.each do |item| - @cookbook_data[item] = {"url" => "#{@base_url}/#{item}", - "versions" => [{"version" => "1.0.1", - "url" => "#{@base_url}/#{item}/1.0.1"}]} + @cookbook_data[item] = { "url" => "#{@base_url}/#{item}", + "versions" => [{ "version" => "1.0.1", + "url" => "#{@base_url}/#{item}/1.0.1" }] } end @stdout = StringIO.new allow(@knife.ui).to receive(:stdout).and_return(@stdout) @@ -38,7 +38,7 @@ describe Chef::Knife::CookbookList do describe "run" do it "should display the latest version of the cookbooks" do expect(@rest_mock).to receive(:get).with("/cookbooks?num_versions=1"). - and_return(@cookbook_data) + and_return(@cookbook_data) @knife.run @cookbook_names.each do |item| expect(@stdout.string).to match /#{item}\s+1\.0\.1/ @@ -48,8 +48,8 @@ describe Chef::Knife::CookbookList do it "should query cookbooks for the configured environment" do @knife.config[:environment] = "production" expect(@rest_mock).to receive(:get). - with("/environments/production/cookbooks?num_versions=1"). - and_return(@cookbook_data) + with("/environments/production/cookbooks?num_versions=1"). + and_return(@cookbook_data) @knife.run end @@ -68,21 +68,20 @@ describe Chef::Knife::CookbookList do describe "with -a or --all" do before do @cookbook_names.each do |item| - @cookbook_data[item]["versions"] << {"version" => "1.0.0", - "url" => "#{@base_url}/#{item}/1.0.0"} + @cookbook_data[item]["versions"] << { "version" => "1.0.0", + "url" => "#{@base_url}/#{item}/1.0.0" } end end it "should display all versions of the cookbooks" do @knife.config[:all_versions] = true expect(@rest_mock).to receive(:get).with("/cookbooks?num_versions=all"). - and_return(@cookbook_data) + and_return(@cookbook_data) @knife.run @cookbook_names.each do |item| expect(@stdout.string).to match /#{item}\s+1\.0\.1\s+1\.0\.0/ end end end - end end diff --git a/spec/unit/knife/cookbook_metadata_from_file_spec.rb b/spec/unit/knife/cookbook_metadata_from_file_spec.rb index f09a4fc53c..81ac2dc2c6 100644 --- a/spec/unit/knife/cookbook_metadata_from_file_spec.rb +++ b/spec/unit/knife/cookbook_metadata_from_file_spec.rb @@ -22,7 +22,7 @@ require "spec_helper" describe Chef::Knife::CookbookMetadataFromFile do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @src = File.expand_path(File.join(CHEF_SPEC_DATA, "metadata", "quick_start", "metadata.rb")) @tgt = File.expand_path(File.join(CHEF_SPEC_DATA, "metadata", "quick_start", "metadata.json")) @knife = Chef::Knife::CookbookMetadataFromFile.new @@ -60,6 +60,5 @@ describe Chef::Knife::CookbookMetadataFromFile do expect(Chef::JSONCompat).to receive(:to_json_pretty).with(@md) @knife.run end - end end diff --git a/spec/unit/knife/cookbook_metadata_spec.rb b/spec/unit/knife/cookbook_metadata_spec.rb index 2f6480a06b..da169e2b93 100644 --- a/spec/unit/knife/cookbook_metadata_spec.rb +++ b/spec/unit/knife/cookbook_metadata_spec.rb @@ -78,26 +78,25 @@ describe Chef::Knife::CookbookMetadata do end end end - end describe "generate_metadata" do before(:each) do @knife.config[:cookbook_path] = @cookbook_dir allow(File).to receive(:expand_path).with("#{@cookbook_dir}/foobar/metadata.rb"). - and_return("#{@cookbook_dir}/foobar/metadata.rb") + and_return("#{@cookbook_dir}/foobar/metadata.rb") end it "should generate the metadata from metadata.rb if it exists" do expect(File).to receive(:exists?).with("#{@cookbook_dir}/foobar/metadata.rb"). - and_return(true) + and_return(true) expect(@knife).to receive(:generate_metadata_from_file).with("foobar", "#{@cookbook_dir}/foobar/metadata.rb") @knife.run end it "should validate the metadata json if metadata.rb does not exist" do expect(File).to receive(:exists?).with("#{@cookbook_dir}/foobar/metadata.rb"). - and_return(false) + and_return(false) expect(@knife).to receive(:validate_metadata_json).with(@cookbook_dir, "foobar") @knife.run end @@ -114,10 +113,10 @@ describe Chef::Knife::CookbookMetadata do expect(@metadata_mock).to receive(:name).with("foobar") expect(@metadata_mock).to receive(:from_file).with("#{@cookbook_dir}/foobar/metadata.rb") expect(File).to receive(:open).with("#{@cookbook_dir}/foobar/metadata.json", "w"). - and_yield(@json_file_mock) + and_yield(@json_file_mock) expect(@json_file_mock).to receive(:write).with(@json_data) expect(Chef::JSONCompat).to receive(:to_json_pretty).with(@metadata_mock). - and_return(@json_data) + and_return(@json_data) @knife.generate_metadata_from_file("foobar", "#{@cookbook_dir}/foobar/metadata.rb") expect(@stderr.string).to match /generating metadata for foobar from #{@cookbook_dir}\/foobar\/metadata\.rb/im end @@ -141,16 +140,16 @@ describe Chef::Knife::CookbookMetadata do describe "validate_metadata_json" do it "should validate the metadata json" do expect(File).to receive(:exist?).with("#{@cookbook_dir}/foobar/metadata.json"). - and_return(true) + and_return(true) expect(IO).to receive(:read).with("#{@cookbook_dir}/foobar/metadata.json"). - and_return(@json_data) + and_return(@json_data) expect(Chef::Cookbook::Metadata).to receive(:validate_json).with(@json_data) @knife.validate_metadata_json(@cookbook_dir, "foobar") end it "should not try to validate the metadata json if the file does not exist" do expect(File).to receive(:exist?).with("#{@cookbook_dir}/foobar/metadata.json"). - and_return(false) + and_return(false) expect(IO).not_to receive(:read) expect(Chef::Cookbook::Metadata).not_to receive(:validate_json) @knife.validate_metadata_json(@cookbook_dir, "foobar") @@ -161,9 +160,9 @@ describe Chef::Knife::CookbookMetadata do }.each_pair do |klass, description| it "should print an error and exit when an #{description} syntax exception is encountered" do expect(File).to receive(:exist?).with("#{@cookbook_dir}/foobar/metadata.json"). - and_return(true) + and_return(true) expect(IO).to receive(:read).with("#{@cookbook_dir}/foobar/metadata.json"). - and_return(@json_data) + and_return(@json_data) exception = klass.new("#{description} blah") allow(Chef::Cookbook::Metadata).to receive(:validate_json).and_raise(exception) expect { @@ -175,5 +174,4 @@ describe Chef::Knife::CookbookMetadata do end end end - end diff --git a/spec/unit/knife/cookbook_show_spec.rb b/spec/unit/knife/cookbook_show_spec.rb index ee9fb1c081..e0ab8a124a 100644 --- a/spec/unit/knife/cookbook_show_spec.rb +++ b/spec/unit/knife/cookbook_show_spec.rb @@ -21,9 +21,9 @@ require "spec_helper" describe Chef::Knife::CookbookShow do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::CookbookShow.new - @knife.config = { } + @knife.config = {} @knife.name_args = [ "cookbook_name" ] @rest = double(Chef::ServerAPI) allow(@knife).to receive(:rest).and_return(@rest) @@ -72,7 +72,7 @@ describe Chef::Knife::CookbookShow do describe "with 2 arguments: name and version" do before(:each) do @knife.name_args << "0.1.0" - @response = { "0.1.0" => { "recipes" => {"default.rb" => ""} } } + @response = { "0.1.0" => { "recipes" => { "default.rb" => "" } } } end it "should show the specific part of a cookbook" do @@ -97,7 +97,7 @@ describe Chef::Knife::CookbookShow do ] } @cookbook_response.manifest = @manifest - @response = {"name"=>"default.rb", "url"=>"http://example.org/files/default.rb", "checksum"=>"1234", "path"=>"recipes/default.rb"} + @response = { "name" => "default.rb", "url" => "http://example.org/files/default.rb", "checksum" => "1234", "path" => "recipes/default.rb" } end it "should print the json of the part" do @@ -216,8 +216,6 @@ describe Chef::Knife::CookbookShow do @knife.run end end - end end end - diff --git a/spec/unit/knife/cookbook_site_download_spec.rb b/spec/unit/knife/cookbook_site_download_spec.rb index 530ac576e0..1c680c2f8c 100644 --- a/spec/unit/knife/cookbook_site_download_spec.rb +++ b/spec/unit/knife/cookbook_site_download_spec.rb @@ -19,7 +19,6 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") describe Chef::Knife::CookbookSiteDownload do - describe "run" do before do @knife = Chef::Knife::CookbookSiteDownload.new @@ -36,8 +35,8 @@ describe Chef::Knife::CookbookSiteDownload do allow(@knife.ui).to receive(:stderr).and_return(@stderr) allow(@knife).to receive(:noauth_rest).and_return(@noauth_rest) expect(@noauth_rest).to receive(:get). - with("#{@cookbook_api_url}/apache2"). - and_return(@current_data) + with("#{@cookbook_api_url}/apache2"). + and_return(@current_data) end context "when the cookbook is deprecated and not forced" do @@ -47,9 +46,9 @@ describe Chef::Knife::CookbookSiteDownload do it "should warn with info about the replacement" do expect(@knife.ui).to receive(:warn). - with(/.+deprecated.+replaced by other_apache2.+/i) + with(/.+deprecated.+replaced by other_apache2.+/i) expect(@knife.ui).to receive(:warn). - with(/use --force.+download.+/i) + with(/use --force.+download.+/i) @knife.run end end @@ -58,7 +57,7 @@ describe Chef::Knife::CookbookSiteDownload do before do @cookbook_data = { "version" => @version, "file" => "http://example.com/apache2_#{@version_us}.tgz" } - @temp_file = double( :path => "/tmp/apache2_#{@version_us}.tgz" ) + @temp_file = double( :path => "/tmp/apache2_#{@version_us}.tgz" ) @file = File.join(Dir.pwd, "apache2-#{@version}.tar.gz") expect(@noauth_rest).to receive(:sign_on_redirect=).with(false) @@ -67,11 +66,11 @@ describe Chef::Knife::CookbookSiteDownload do context "downloading the latest version" do before do expect(@noauth_rest).to receive(:get). - with(@current_data["latest_version"]). - and_return(@cookbook_data) + with(@current_data["latest_version"]). + and_return(@cookbook_data) expect(@noauth_rest).to receive(:get). - with(@cookbook_data["file"], true). - and_return(@temp_file) + with(@cookbook_data["file"], true). + and_return(@temp_file) end context "and it is deprecated and with --force" do @@ -82,13 +81,12 @@ describe Chef::Knife::CookbookSiteDownload do it "should download the latest version" do expect(@knife.ui).to receive(:warn). - with(/.+deprecated.+replaced by other_apache2.+/i) + with(/.+deprecated.+replaced by other_apache2.+/i) expect(FileUtils).to receive(:cp).with(@temp_file.path, @file) @knife.run expect(@stderr.string).to match /downloading apache2.+version.+#{Regexp.escape(@version)}/i expect(@stderr.string).to match /cookbook save.+#{Regexp.escape(@file)}/i end - end it "should download the latest version" do @@ -132,20 +130,17 @@ describe Chef::Knife::CookbookSiteDownload do it "should download the desired version" do expect(@noauth_rest).to receive(:get). - with("#{@cookbook_api_url}/apache2/versions/#{@version_us}"). - and_return(@cookbook_data) + with("#{@cookbook_api_url}/apache2/versions/#{@version_us}"). + and_return(@cookbook_data) expect(@noauth_rest).to receive(:get). - with(@cookbook_data["file"], true). - and_return(@temp_file) + with(@cookbook_data["file"], true). + and_return(@temp_file) expect(FileUtils).to receive(:cp).with(@temp_file.path, @file) @knife.run expect(@stderr.string).to match /downloading apache2.+version.+#{Regexp.escape(@version)}/i expect(@stderr.string).to match /cookbook save.+#{Regexp.escape(@file)}/i end end - end - end - end diff --git a/spec/unit/knife/cookbook_site_install_spec.rb b/spec/unit/knife/cookbook_site_install_spec.rb index b0b1e8aec2..166ba0cb08 100644 --- a/spec/unit/knife/cookbook_site_install_spec.rb +++ b/spec/unit/knife/cookbook_site_install_spec.rb @@ -192,6 +192,5 @@ describe Chef::Knife::CookbookSiteInstall do expect(error.install_path).to eq(install_path) } end - end end diff --git a/spec/unit/knife/cookbook_site_share_spec.rb b/spec/unit/knife/cookbook_site_share_spec.rb index 051a3ed168..c8777312cb 100644 --- a/spec/unit/knife/cookbook_site_share_spec.rb +++ b/spec/unit/knife/cookbook_site_share_spec.rb @@ -22,7 +22,6 @@ require "chef/cookbook_uploader" require "chef/cookbook_site_streaming_uploader" describe Chef::Knife::CookbookSiteShare do - before(:each) do @knife = Chef::Knife::CookbookSiteShare.new # Merge default settings in. @@ -50,7 +49,6 @@ describe Chef::Knife::CookbookSiteShare do end describe "run" do - before(:each) do allow(@knife).to receive(:do_upload).and_return(true) @category_response = { @@ -145,8 +143,8 @@ describe Chef::Knife::CookbookSiteShare do it "should list files in the tarball" do allow(@knife).to receive(:tar_cmd).and_return("footar") - expect(@knife).to receive(:shell_out!).with("footar -czf #{@cookbook.name}.tgz #{@cookbook.name}", {:cwd => "/var/tmp/dummy"}) - expect(@knife).to receive(:shell_out!).with("footar -tzf #{@cookbook.name}.tgz", {:cwd => "/var/tmp/dummy"}) + expect(@knife).to receive(:shell_out!).with("footar -czf #{@cookbook.name}.tgz #{@cookbook.name}", { :cwd => "/var/tmp/dummy" }) + expect(@knife).to receive(:shell_out!).with("footar -tzf #{@cookbook.name}.tgz", { :cwd => "/var/tmp/dummy" }) @knife.run end @@ -159,7 +157,6 @@ describe Chef::Knife::CookbookSiteShare do end describe "do_upload" do - before(:each) do @upload_response = double("Net::HTTPResponse") allow(Chef::CookbookSiteStreamingUploader).to receive(:post).and_return(@upload_response) @@ -172,7 +169,7 @@ describe Chef::Knife::CookbookSiteShare do end it 'should post the cookbook to "https://supermarket.chef.io"' do - response_text = Chef::JSONCompat.to_json({:uri => "https://supermarket.chef.io/cookbooks/cookbook_name"}) + response_text = Chef::JSONCompat.to_json({ :uri => "https://supermarket.chef.io/cookbooks/cookbook_name" }) allow(@upload_response).to receive(:body).and_return(response_text) allow(@upload_response).to receive(:code).and_return(201) expect(Chef::CookbookSiteStreamingUploader).to receive(:post).with(/supermarket\.chef\.io/, anything(), anything(), anything()) @@ -180,7 +177,7 @@ describe Chef::Knife::CookbookSiteShare do end it "should alert the user when a version already exists" do - response_text = Chef::JSONCompat.to_json({:error_messages => ["Version already exists"]}) + response_text = Chef::JSONCompat.to_json({ :error_messages => ["Version already exists"] }) allow(@upload_response).to receive(:body).and_return(response_text) allow(@upload_response).to receive(:code).and_return(409) expect { @knife.run }.to raise_error(SystemExit) @@ -188,7 +185,7 @@ describe Chef::Knife::CookbookSiteShare do end it "should pass any errors on to the user" do - response_text = Chef::JSONCompat.to_json({:error_messages => ["You're holding it wrong"]}) + response_text = Chef::JSONCompat.to_json({ :error_messages => ["You're holding it wrong"] }) allow(@upload_response).to receive(:body).and_return(response_text) allow(@upload_response).to receive(:code).and_return(403) expect { @knife.run }.to raise_error(SystemExit) @@ -196,14 +193,12 @@ describe Chef::Knife::CookbookSiteShare do end it "should print the body if no errors are exposed on failure" do - response_text = Chef::JSONCompat.to_json({:system_error => "Your call was dropped", :reason => "There's a map for that"}) + response_text = Chef::JSONCompat.to_json({ :system_error => "Your call was dropped", :reason => "There's a map for that" }) allow(@upload_response).to receive(:body).and_return(response_text) allow(@upload_response).to receive(:code).and_return(500) expect(@knife.ui).to receive(:error).with(/#{Regexp.escape(response_text)}/)#.ordered expect(@knife.ui).to receive(:error).with(/Unknown error/)#.ordered expect { @knife.run }.to raise_error(SystemExit) end - end - end diff --git a/spec/unit/knife/cookbook_site_unshare_spec.rb b/spec/unit/knife/cookbook_site_unshare_spec.rb index 8e4358226d..ae83c1b703 100644 --- a/spec/unit/knife/cookbook_site_unshare_spec.rb +++ b/spec/unit/knife/cookbook_site_unshare_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Knife::CookbookSiteUnshare do - before(:each) do @knife = Chef::Knife::CookbookSiteUnshare.new @knife.name_args = ["cookbook_name"] @@ -34,7 +33,6 @@ describe Chef::Knife::CookbookSiteUnshare do end describe "run" do - describe "with no cookbook argument" do it "should print the usage and exit" do @knife.name_args = [] @@ -71,7 +69,5 @@ describe Chef::Knife::CookbookSiteUnshare do expect(@knife.ui).to receive(:info) @knife.run end - end - end diff --git a/spec/unit/knife/cookbook_test_spec.rb b/spec/unit/knife/cookbook_test_spec.rb index 841ebe5f6f..3eedae875b 100644 --- a/spec/unit/knife/cookbook_test_spec.rb +++ b/spec/unit/knife/cookbook_test_spec.rb @@ -23,9 +23,9 @@ Chef::Knife::CookbookTest.load_deps describe Chef::Knife::CookbookTest do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::CookbookTest.new - @knife.config[:cookbook_path] = File.join(CHEF_SPEC_DATA,"cookbooks") + @knife.config[:cookbook_path] = File.join(CHEF_SPEC_DATA, "cookbooks") allow(@knife.cookbook_loader).to receive(:cookbook_exists?).and_return(true) @cookbooks = [] %w{tats central_market jimmy_johns pho}.each do |cookbook_name| @@ -79,6 +79,5 @@ describe Chef::Knife::CookbookTest do @knife.run end end - end end diff --git a/spec/unit/knife/cookbook_upload_spec.rb b/spec/unit/knife/cookbook_upload_spec.rb index 1445f8c086..68b32906f2 100644 --- a/spec/unit/knife/cookbook_upload_spec.rb +++ b/spec/unit/knife/cookbook_upload_spec.rb @@ -26,7 +26,7 @@ describe Chef::Knife::CookbookUpload do let(:cookbook) { Chef::CookbookVersion.new("test_cookbook", "/tmp/blah.txt") } let(:cookbooks_by_name) do - {cookbook.name => cookbook} + { cookbook.name => cookbook } end let(:cookbook_loader) do @@ -62,8 +62,8 @@ describe Chef::Knife::CookbookUpload do allow(cookbook_loader).to receive(:each).and_yield("test_cookbook", test_cookbook) allow(cookbook_loader).to receive(:cookbook_names).and_return(["test_cookbook"]) expect(Chef::CookbookUploader).to receive(:new). - with( kind_of(Array), { :force => nil, :concurrency => 3}). - and_return(double("Chef::CookbookUploader", :upload_cookbooks=> true)) + with( kind_of(Array), { :force => nil, :concurrency => 3 }). + and_return(double("Chef::CookbookUploader", :upload_cookbooks => true)) knife.run end end @@ -103,16 +103,15 @@ describe Chef::Knife::CookbookUpload do end context "when uploading a cookbook that uses deprecated overlays" do - before do allow(cookbook_loader).to receive(:merged_cookbooks).and_return(["test_cookbook"]) allow(cookbook_loader).to receive(:merged_cookbook_paths). - and_return({"test_cookbook" => %w{/path/one/test_cookbook /path/two/test_cookbook}}) + and_return({ "test_cookbook" => %w{/path/one/test_cookbook /path/two/test_cookbook} }) end it "emits a warning" do knife.run - expected_message=<<-E + expected_message = <<-E WARNING: The cookbooks: test_cookbook exist in multiple places in your cookbook_path. A composite version of these cookbooks has been compiled for uploading. @@ -196,9 +195,9 @@ E before(:each) do cookbook.metadata.depends("dependency") - allow(cookbook_loader).to receive(:[]) do |ckbk| + allow(cookbook_loader).to receive(:[]) do |ckbk| { "test_cookbook" => cookbook, - "dependency" => cookbook_dependency}[ckbk] + "dependency" => cookbook_dependency }[ckbk] end allow(knife).to receive(:cookbook_names).and_return(["cookbook_dependency", "test_cookbook"]) @stdout, @stderr, @stdin = StringIO.new, StringIO.new, StringIO.new @@ -209,11 +208,11 @@ E expect(cookbook_loader).to receive(:[]).once.with("test_cookbook") expect(cookbook_loader).not_to receive(:load_cookbooks) expect(cookbook_uploader).not_to receive(:upload_cookbooks) - expect {knife.run}.to raise_error(SystemExit) + expect { knife.run }.to raise_error(SystemExit) end it "should output a message for a single missing dependency" do - expect {knife.run}.to raise_error(SystemExit) + expect { knife.run }.to raise_error(SystemExit) expect(@stderr.string).to include("Cookbook test_cookbook depends on cookbooks which are not currently") expect(@stderr.string).to include("being uploaded and cannot be found on the server.") expect(@stderr.string).to include("The missing cookbook(s) are: 'dependency' version '>= 0.0.0'") @@ -222,13 +221,13 @@ E it "should output a message for a multiple missing dependencies which are concatenated" do cookbook_dependency2 = Chef::CookbookVersion.new("dependency2") cookbook.metadata.depends("dependency2") - allow(cookbook_loader).to receive(:[]) do |ckbk| + allow(cookbook_loader).to receive(:[]) do |ckbk| { "test_cookbook" => cookbook, "dependency" => cookbook_dependency, - "dependency2" => cookbook_dependency2}[ckbk] + "dependency2" => cookbook_dependency2 }[ckbk] end allow(knife).to receive(:cookbook_names).and_return(["dependency", "dependency2", "test_cookbook"]) - expect {knife.run}.to raise_error(SystemExit) + expect { knife.run }.to raise_error(SystemExit) expect(@stderr.string).to include("Cookbook test_cookbook depends on cookbooks which are not currently") expect(@stderr.string).to include("being uploaded and cannot be found on the server.") expect(@stderr.string).to include("The missing cookbook(s) are:") diff --git a/spec/unit/knife/core/bootstrap_context_spec.rb b/spec/unit/knife/core/bootstrap_context_spec.rb index 16c0867610..e3bce0cb65 100644 --- a/spec/unit/knife/core/bootstrap_context_spec.rb +++ b/spec/unit/knife/core/bootstrap_context_spec.rb @@ -26,7 +26,7 @@ describe Chef::Knife::Core::BootstrapContext do Chef::Config[:fips] = false end - let(:config) { {:foo => :bar, :color => true} } + let(:config) { { :foo => :bar, :color => true } } let(:run_list) { Chef::RunList.new("recipe[tmux]", "role[base]") } let(:chef_config) do { @@ -41,7 +41,7 @@ describe Chef::Knife::Core::BootstrapContext do subject(:bootstrap_context) { described_class.new(config, run_list, chef_config, secret) } it "initializes with Chef 11 parameters" do - expect{described_class.new(config, run_list, chef_config)}.not_to raise_error + expect { described_class.new(config, run_list, chef_config) }.not_to raise_error end it "runs chef with the first-boot.json with no environment specified" do @@ -49,14 +49,14 @@ describe Chef::Knife::Core::BootstrapContext do end describe "when in verbosity mode" do - let(:config) { {:verbosity => 2, :color => true} } + let(:config) { { :verbosity => 2, :color => true } } it "adds '-l debug' when verbosity is >= 2" do expect(bootstrap_context.start_chef).to eq "chef-client -j /etc/chef/first-boot.json -l debug" end end describe "when no color value has been set in config" do - let(:config) { {:color => false } } + let(:config) { { :color => false } } it "adds '--no-color' when color is false" do expect(bootstrap_context.start_chef).to eq "chef-client -j /etc/chef/first-boot.json --no-color" end @@ -67,7 +67,7 @@ describe Chef::Knife::Core::BootstrapContext do end it "generates the config file data" do - expected=<<-EXPECTED + expected = <<-EXPECTED log_location STDOUT chef_server_url "http://chef.example.com:4444" validation_client_name "chef-validator-testing" @@ -81,14 +81,14 @@ EXPECTED end describe "alternate chef-client path" do - let(:chef_config){ {:chef_client_path => "/usr/local/bin/chef-client"} } + let(:chef_config) { { :chef_client_path => "/usr/local/bin/chef-client" } } it "runs chef-client from another path when specified" do expect(bootstrap_context.start_chef).to eq "/usr/local/bin/chef-client -j /etc/chef/first-boot.json" end end describe "validation key path that contains a ~" do - let(:chef_config){ {:validation_key => "~/my.key"} } + let(:chef_config) { { :validation_key => "~/my.key" } } it "reads the validation key when it contains a ~" do expect(File).to receive(:exist?).with(File.expand_path("my.key", ENV["HOME"])).and_return(true) expect(IO).to receive(:read).with(File.expand_path("my.key", ENV["HOME"])) @@ -97,47 +97,45 @@ EXPECTED end describe "when an explicit node name is given" do - let(:config){ {:chef_node_name => "foobar.example.com" }} + let(:config) { { :chef_node_name => "foobar.example.com" } } it "sets the node name in the client.rb" do expect(bootstrap_context.config_content).to match(/node_name "foobar\.example\.com"/) end end describe "when bootstrapping into a specific environment" do - let(:config){ {:environment => "prodtastic", :color => true} } + let(:config) { { :environment => "prodtastic", :color => true } } it "starts chef in the configured environment" do expect(bootstrap_context.start_chef).to eq("chef-client -j /etc/chef/first-boot.json -E prodtastic") end end describe "when tags are given" do - let(:config) { {:tags => [ "unicorn" ] } } + let(:config) { { :tags => [ "unicorn" ] } } it "adds the attributes to first_boot" do - expect(Chef::JSONCompat.to_json(bootstrap_context.first_boot)).to eq(Chef::JSONCompat.to_json({:run_list => run_list, :tags => ["unicorn"]})) + expect(Chef::JSONCompat.to_json(bootstrap_context.first_boot)).to eq(Chef::JSONCompat.to_json({ :run_list => run_list, :tags => ["unicorn"] })) end end describe "when JSON attributes are given" do - let(:config) { {:first_boot_attributes => {:baz => :quux}} } + let(:config) { { :first_boot_attributes => { :baz => :quux } } } it "adds the attributes to first_boot" do - expect(Chef::JSONCompat.to_json(bootstrap_context.first_boot)).to eq(Chef::JSONCompat.to_json({:baz => :quux, :run_list => run_list})) + expect(Chef::JSONCompat.to_json(bootstrap_context.first_boot)).to eq(Chef::JSONCompat.to_json({ :baz => :quux, :run_list => run_list })) end end describe "when JSON attributes are NOT given" do it "sets first_boot equal to run_list" do - expect(Chef::JSONCompat.to_json(bootstrap_context.first_boot)).to eq(Chef::JSONCompat.to_json({:run_list => run_list})) + expect(Chef::JSONCompat.to_json(bootstrap_context.first_boot)).to eq(Chef::JSONCompat.to_json({ :run_list => run_list })) end end describe "when policy_name and policy_group are present in config" do - let(:config) { { policy_name: "my_app_server", policy_group: "staging" } } it "includes them in the first_boot data and excludes run_list" do expect(Chef::JSONCompat.to_json(bootstrap_context.first_boot)).to eq(Chef::JSONCompat.to_json(config)) end - end describe "when an encrypted_data_bag_secret is provided" do @@ -160,7 +158,7 @@ EXPECTED describe "when a bootstrap_version is specified" do let(:chef_config) do { - :knife => {:bootstrap_version => "11.12.4" } + :knife => { :bootstrap_version => "11.12.4" } } end @@ -172,7 +170,7 @@ EXPECTED describe "when a pre-release bootstrap_version is specified" do let(:chef_config) do { - :knife => {:bootstrap_version => "11.12.4.rc.0" } + :knife => { :bootstrap_version => "11.12.4.rc.0" } } end @@ -196,7 +194,7 @@ EXPECTED describe "when configured in config" do let(:chef_config) do { - :knife => {:ssl_verify_mode => :verify_peer} + :knife => { :ssl_verify_mode => :verify_peer } } end @@ -205,7 +203,7 @@ EXPECTED end describe "when configured via CLI" do - let(:config) {{:node_ssl_verify_mode => "none"}} + let(:config) { { :node_ssl_verify_mode => "none" } } it "uses CLI value" do expect(bootstrap_context.config_content).to include("ssl_verify_mode :verify_none") @@ -222,7 +220,7 @@ EXPECTED describe "when configured in config" do let(:chef_config) do { - :knife => {:verify_api_cert => :false} + :knife => { :verify_api_cert => :false } } end @@ -231,7 +229,7 @@ EXPECTED end describe "when configured via CLI" do - let(:config) {{:node_verify_api_cert => true}} + let(:config) { { :node_verify_api_cert => true } } it "uses CLI value" do expect(bootstrap_context.config_content).to include("verify_api_cert true") @@ -246,12 +244,11 @@ EXPECTED end describe "when configured via cli" do - let(:config) {{:prerelease => true}} + let(:config) { { :prerelease => true } } it "uses CLI value" do expect(bootstrap_context.latest_current_chef_version_string).to eq("-p") end end end - end diff --git a/spec/unit/knife/core/cookbook_scm_repo_spec.rb b/spec/unit/knife/core/cookbook_scm_repo_spec.rb index d1f5aeef85..20340359a0 100644 --- a/spec/unit/knife/core/cookbook_scm_repo_spec.rb +++ b/spec/unit/knife/core/cookbook_scm_repo_spec.rb @@ -49,7 +49,7 @@ BRANCHES describe "when sanity checking the repo" do it "exits when the directory does not exist" do expect(::File).to receive(:directory?).with(@repo_path).and_return(false) - expect {@cookbook_repo.sanity_check}.to raise_error(SystemExit) + expect { @cookbook_repo.sanity_check }.to raise_error(SystemExit) end describe "and the repo dir exists" do @@ -59,7 +59,7 @@ BRANCHES it "exits when there is no git repo" do allow(::File).to receive(:directory?).with(/.*\.git/).and_return(false) - expect {@cookbook_repo.sanity_check}.to raise_error(SystemExit) + expect { @cookbook_repo.sanity_check }.to raise_error(SystemExit) end describe "and the repo is a git repo" do @@ -68,9 +68,9 @@ BRANCHES end it "exits when the default branch doesn't exist" do - @nobranches = Mixlib::ShellOut.new.tap {|s|s.stdout.replace "\n"} + @nobranches = Mixlib::ShellOut.new.tap { |s| s.stdout.replace "\n" } expect(@cookbook_repo).to receive(:shell_out!).with("git branch --no-color", :cwd => @repo_path).and_return(@nobranches) - expect {@cookbook_repo.sanity_check}.to raise_error(SystemExit) + expect { @cookbook_repo.sanity_check }.to raise_error(SystemExit) end describe "and the default branch exists" do @@ -86,19 +86,18 @@ BRANCHES M chef/lib/chef/knife/cookbook_site_vendor.rb DIRTY expect(@cookbook_repo).to receive(:shell_out!).with("git status --porcelain", :cwd => @repo_path).and_return(@dirty_status) - expect {@cookbook_repo.sanity_check}.to raise_error(SystemExit) + expect { @cookbook_repo.sanity_check }.to raise_error(SystemExit) end describe "and the repo is clean" do before do - @clean_status = Mixlib::ShellOut.new.tap {|s| s.stdout.replace("\n")} + @clean_status = Mixlib::ShellOut.new.tap { |s| s.stdout.replace("\n") } allow(@cookbook_repo).to receive(:shell_out!).with("git status --porcelain", :cwd => @repo_path).and_return(@clean_status) end it "passes the sanity check" do @cookbook_repo.sanity_check end - end end end diff --git a/spec/unit/knife/core/custom_manifest_loader_spec.rb b/spec/unit/knife/core/custom_manifest_loader_spec.rb index 3668fca6ad..9ebaa65b35 100644 --- a/spec/unit/knife/core/custom_manifest_loader_spec.rb +++ b/spec/unit/knife/core/custom_manifest_loader_spec.rb @@ -21,13 +21,13 @@ describe Chef::Knife::SubcommandLoader::CustomManifestLoader do let(:ec2_server_create_plugin) { "/usr/lib/ruby/gems/knife-ec2-0.5.12/lib/chef/knife/ec2_server_create.rb" } let(:manifest_content) do { "plugins" => { - "knife-ec2" => { - "paths" => [ - ec2_server_create_plugin - ] - } + "knife-ec2" => { + "paths" => [ + ec2_server_create_plugin + ] } } + } end let(:loader) do Chef::Knife::SubcommandLoader::CustomManifestLoader.new(File.join(CHEF_SPEC_DATA, "knife-site-subcommands"), diff --git a/spec/unit/knife/core/gem_glob_loader_spec.rb b/spec/unit/knife/core/gem_glob_loader_spec.rb index 9fd880a810..ea484c2380 100644 --- a/spec/unit/knife/core/gem_glob_loader_spec.rb +++ b/spec/unit/knife/core/gem_glob_loader_spec.rb @@ -18,14 +18,14 @@ require "spec_helper" describe Chef::Knife::SubcommandLoader::GemGlobLoader do - let(:loader) { Chef::Knife::SubcommandLoader::GemGlobLoader.new(File.join(CHEF_SPEC_DATA, "knife-site-subcommands")) } - let(:home) { File.join(CHEF_SPEC_DATA, "knife-home") } - let(:plugin_dir) { File.join(home, ".chef", "plugins", "knife") } + let(:loader) { Chef::Knife::SubcommandLoader::GemGlobLoader.new(File.join(CHEF_SPEC_DATA, "knife-site-subcommands")) } + let(:home) { File.join(CHEF_SPEC_DATA, "knife-home") } + let(:plugin_dir) { File.join(home, ".chef", "plugins", "knife") } - before do - allow(ChefConfig).to receive(:windows?) { false } - Chef::Util::PathHelper.class_variable_set(:@@home_dir, home) - end + before do + allow(ChefConfig).to receive(:windows?) { false } + Chef::Util::PathHelper.class_variable_set(:@@home_dir, home) + end after do Chef::Util::PathHelper.class_variable_set(:@@home_dir, nil) @@ -40,7 +40,7 @@ describe Chef::Knife::SubcommandLoader::GemGlobLoader do it "finds files installed via rubygems" do expect(loader.find_subcommands_via_rubygems).to include("chef/knife/node_create") - loader.find_subcommands_via_rubygems.each {|rel_path, abs_path| expect(abs_path).to match(%r{chef/knife/.+})} + loader.find_subcommands_via_rubygems.each { |rel_path, abs_path| expect(abs_path).to match(%r{chef/knife/.+}) } end it "finds files from latest version of installed gems" do @@ -65,7 +65,7 @@ describe Chef::Knife::SubcommandLoader::GemGlobLoader do it "finds files using a dirglob when rubygems is not available" do expect(loader.find_subcommands_via_dirglob).to include("chef/knife/node_create") - loader.find_subcommands_via_dirglob.each {|rel_path, abs_path| expect(abs_path).to match(%r{chef/knife/.+})} + loader.find_subcommands_via_dirglob.each { |rel_path, abs_path| expect(abs_path).to match(%r{chef/knife/.+}) } end it "finds user-specific subcommands in the user's ~/.chef directory" do @@ -87,7 +87,6 @@ describe Chef::Knife::SubcommandLoader::GemGlobLoader do # error. We also want to ensure that we only load builtin commands from the # "primary" chef install. context "when a different version of chef is also installed as a gem" do - let(:all_found_commands) do [ "/opt/chefdk/embedded/apps/chef/lib/chef/knife/bootstrap.rb", @@ -165,7 +164,6 @@ describe Chef::Knife::SubcommandLoader::GemGlobLoader do it "ignores commands from the non-matching gem install" do expect(loader.find_subcommands_via_rubygems.values).to eq(expected_valid_commands) end - end describe "finding 3rd party plugins" do @@ -178,7 +176,6 @@ describe Chef::Knife::SubcommandLoader::GemGlobLoader do allow(ENV).to receive(:[]).with("HOME").and_return(env_home) end - it "searches rubygems for plugins" do if Gem::Specification.respond_to?(:latest_specs) expect(Gem::Specification).to receive(:latest_specs).and_call_original diff --git a/spec/unit/knife/core/hashed_command_loader_spec.rb b/spec/unit/knife/core/hashed_command_loader_spec.rb index ca9aeec60c..d9f5e5761c 100644 --- a/spec/unit/knife/core/hashed_command_loader_spec.rb +++ b/spec/unit/knife/core/hashed_command_loader_spec.rb @@ -47,11 +47,11 @@ describe Chef::Knife::SubcommandLoader::HashedCommandLoader do describe "#list_commands" do it "lists all commands by category when no argument is given" do - expect(loader.list_commands).to eq({"cool" => ["cool_a"], "cooler" => ["cooler_b"]}) + expect(loader.list_commands).to eq({ "cool" => ["cool_a"], "cooler" => ["cooler_b"] }) end it "lists only commands in the given category when a category is given" do - expect(loader.list_commands("cool")).to eq({"cool" => ["cool_a"]}) + expect(loader.list_commands("cool")).to eq({ "cool" => ["cool_a"] }) end end diff --git a/spec/unit/knife/core/node_editor_spec.rb b/spec/unit/knife/core/node_editor_spec.rb index e64faebf6b..32ce402e19 100644 --- a/spec/unit/knife/core/node_editor_spec.rb +++ b/spec/unit/knife/core/node_editor_spec.rb @@ -43,7 +43,7 @@ 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 + "policy_name, policy_group, and run_list properties" do expected = node_data.select do |key,| %w{ name chef_environment normal policy_name policy_group run_list }.include?(key) @@ -74,7 +74,7 @@ describe Chef::Knife::NodeEditor do expect(ui).to have_received(:warn) .with "Changing the name of a node results in a new node being " + - "created, test_node will not be modified or removed." + "created, test_node will not be modified or removed." expect(ui).to have_received(:confirm) .with("Proceed with creation of new node") @@ -189,7 +189,7 @@ describe Chef::Knife::NodeEditor do end it 'returns an array of property names that doesn\'t include ' + - "the non-editable properties" do + "the non-editable properties" do expect(subject.updated?).to eql %w{ normal policy_name policy_group run_list } end end diff --git a/spec/unit/knife/core/object_loader_spec.rb b/spec/unit/knife/core/object_loader_spec.rb index 9cabf2ba63..19356b7d2c 100644 --- a/spec/unit/knife/core/object_loader_spec.rb +++ b/spec/unit/knife/core/object_loader_spec.rb @@ -43,7 +43,6 @@ describe Chef::Knife::Core::ObjectLoader do "roles" => Chef::Role, "environments" => Chef::Environment, }.each do |repo_location, chef_class| - describe "when the file is a #{chef_class}" do before do @loader = Chef::Knife::Core::ObjectLoader.new(chef_class, @knife.ui) @@ -77,5 +76,4 @@ describe Chef::Knife::Core::ObjectLoader do end end end - end diff --git a/spec/unit/knife/core/ui_spec.rb b/spec/unit/knife/core/ui_spec.rb index 13fd304a2e..642f7b9f79 100644 --- a/spec/unit/knife/core/ui_spec.rb +++ b/spec/unit/knife/core/ui_spec.rb @@ -46,7 +46,7 @@ describe Chef::Knife::UI do context "when editing is disabled" do before do @ui.config[:disable_editing] = true - stub_const("Tempfile", double) # Tempfiles should never be invoked + stub_const("Tempfile", double) # Tempfiles should never be invoked end context "when parse_output is false" do it "returns pretty json string" do @@ -59,7 +59,6 @@ describe Chef::Knife::UI do expect(subject).to eql(ruby_for_json) end end - end context "when editing is enabled" do @@ -97,7 +96,7 @@ describe Chef::Knife::UI do expect(IO).not_to receive(:read) end it "throws an exception" do - expect{ subject }.to raise_error(RuntimeError) + expect { subject }.to raise_error(RuntimeError) end end context "when running the editor fails with false" do @@ -106,7 +105,7 @@ describe Chef::Knife::UI do expect(IO).not_to receive(:read) end it "throws an exception" do - expect{ subject }.to raise_error(RuntimeError) + expect { subject }.to raise_error(RuntimeError) end end end @@ -166,20 +165,20 @@ describe Chef::Knife::UI do it "should throw Errno::EIO exceptions" do allow(@out).to receive(:puts).and_raise(Errno::EIO) allow(@err).to receive(:puts).and_raise(Errno::EIO) - expect {@ui.send(method, "hi")}.to raise_error(Errno::EIO) + expect { @ui.send(method, "hi") }.to raise_error(Errno::EIO) end it "should ignore Errno::EPIPE exceptions (CHEF-3516)" do allow(@out).to receive(:puts).and_raise(Errno::EPIPE) allow(@err).to receive(:puts).and_raise(Errno::EPIPE) - expect {@ui.send(method, "hi")}.to raise_error(SystemExit) + expect { @ui.send(method, "hi") }.to raise_error(SystemExit) end it "should throw Errno::EPIPE exceptions with -VV (CHEF-3516)" do @config[:verbosity] = 2 allow(@out).to receive(:puts).and_raise(Errno::EPIPE) allow(@err).to receive(:puts).and_raise(Errno::EPIPE) - expect {@ui.send(method, "hi")}.to raise_error(Errno::EPIPE) + expect { @ui.send(method, "hi") }.to raise_error(Errno::EPIPE) end end @@ -192,7 +191,7 @@ describe Chef::Knife::UI do end it "formats hashes appropriately" do - @ui.output({"hi" => "a", "lo" => "b" }) + @ui.output({ "hi" => "a", "lo" => "b" }) expect(@out.string).to eq < { }, "b" => "c" }) + @ui.output({ "a" => {}, "b" => "c" }) expect(@out.string).to eq < "go", "hi" => "ho", "id" => "sample-data-bag-item" } @ui.config[:attribute] = ["gi", "hi"] - expect(@ui.format_for_display(input)).to eq({ "sample-data-bag-item" => { "gi" => "go", "hi"=> "ho" } }) + expect(@ui.format_for_display(input)).to eq({ "sample-data-bag-item" => { "gi" => "go", "hi" => "ho" } }) end it "should handle attributes named the same as methods" do @@ -364,7 +363,7 @@ EOM end it "should handle nested attributes named the same as methods" do - input = { "keys" => {"keys" => "values"}, "hi" => "ho", "id" => "sample-data-bag-item" } + input = { "keys" => { "keys" => "values" }, "hi" => "ho", "id" => "sample-data-bag-item" } @ui.config[:attribute] = "keys.keys" expect(@ui.format_for_display(input)).to eq({ "sample-data-bag-item" => { "keys.keys" => "values" } }) end @@ -373,11 +372,11 @@ EOM allow_any_instance_of(Chef::Node).to receive(:name).and_return("chef.localdomain") input = Chef::Node.new @ui.config[:attribute] = "name" - expect(@ui.format_for_display(input)).to eq( {"chef.localdomain"=>{"name"=>"chef.localdomain"} }) + expect(@ui.format_for_display(input)).to eq( { "chef.localdomain" => { "name" => "chef.localdomain" } }) end it "returns nil when given an attribute path that isn't a name or attribute" do - input = { "keys" => {"keys" => "values"}, "hi" => "ho", "id" => "sample-data-bag-item" } + input = { "keys" => { "keys" => "values" }, "hi" => "ho", "id" => "sample-data-bag-item" } non_existing_path = "nope.nada.nothingtoseehere" @ui.config[:attribute] = non_existing_path expect(@ui.format_for_display(input)).to eq({ "sample-data-bag-item" => { non_existing_path => nil } }) @@ -420,10 +419,10 @@ EOM describe "with --with-uri" do it "should return the URIs" do response = { - "cookbook_name"=>{ + "cookbook_name" => { "1.0.0" => "http://url/cookbooks/1.0.0", "2.0.0" => "http://url/cookbooks/2.0.0", - "3.0.0" => "http://url/cookbooks/3.0.0"} + "3.0.0" => "http://url/cookbooks/3.0.0" } } @ui.config[:with_uri] = true expect(@ui.format_cookbook_list_for_display(@item)).to eq(response) @@ -460,8 +459,8 @@ EOM end describe "confirm" do - let(:stdout) {StringIO.new} - let(:output) {stdout.string} + let(:stdout) { StringIO.new } + let(:output) { stdout.string } let(:question) { "monkeys rule" } let(:answer) { "y" } @@ -587,5 +586,4 @@ EOM expect(out.string).to eq("your chef server URL? [http://localhost:4000] ") end end - end diff --git a/spec/unit/knife/data_bag_create_spec.rb b/spec/unit/knife/data_bag_create_spec.rb index 9356974735..a313143128 100644 --- a/spec/unit/knife/data_bag_create_spec.rb +++ b/spec/unit/knife/data_bag_create_spec.rb @@ -36,7 +36,7 @@ describe Chef::Knife::DataBagCreate do let(:secret) { "abc123SECRET" } - let(:raw_hash) {{ "login_name" => "alphaomega", "id" => item_name }} + let(:raw_hash) { { "login_name" => "alphaomega", "id" => item_name } } let(:config) { {} } @@ -49,7 +49,7 @@ describe Chef::Knife::DataBagCreate do it "tries to create a data bag with an invalid name when given one argument" do knife.name_args = ["invalid&char"] expect(Chef::DataBag).to receive(:validate_name!).with(knife.name_args[0]).and_raise(Chef::Exceptions::InvalidDataBagName) - expect {knife.run}.to exit_with_code(1) + expect { knife.run }.to exit_with_code(1) end context "when given one argument" do @@ -58,7 +58,7 @@ describe Chef::Knife::DataBagCreate do end it "creates a data bag" do - expect(rest).to receive(:post).with("data", {"name" => bag_name}) + expect(rest).to receive(:post).with("data", { "name" => bag_name }) expect(knife.ui).to receive(:info).with("Created data_bag[#{bag_name}]") knife.run @@ -75,7 +75,7 @@ describe Chef::Knife::DataBagCreate do it "creates a data bag item" do expect(knife).to receive(:create_object).and_yield(raw_hash) expect(knife).to receive(:encryption_secret_provided?).and_return(false) - expect(rest).to receive(:post).with("data", {"name" => bag_name}).ordered + expect(rest).to receive(:post).with("data", { "name" => bag_name }).ordered expect(rest).to receive(:post).with("data/#{bag_name}", item).ordered knife.run @@ -99,11 +99,10 @@ describe Chef::Knife::DataBagCreate do .to receive(:encrypt_data_bag_item) .with(raw_hash, secret) .and_return(encoded_data) - expect(rest).to receive(:post).with("data", {"name" => bag_name}).ordered + expect(rest).to receive(:post).with("data", { "name" => bag_name }).ordered expect(rest).to receive(:post).with("data/#{bag_name}", item).ordered knife.run end end - end diff --git a/spec/unit/knife/data_bag_edit_spec.rb b/spec/unit/knife/data_bag_edit_spec.rb index 42558c5cbd..b1dc60f67d 100644 --- a/spec/unit/knife/data_bag_edit_spec.rb +++ b/spec/unit/knife/data_bag_edit_spec.rb @@ -33,9 +33,9 @@ describe Chef::Knife::DataBagEdit do k end - let(:raw_hash) { {"login_name" => "alphaomega", "id" => "item_name"} } - let(:db) { Chef::DataBagItem.from_hash(raw_hash)} - let(:raw_edited_hash) { {"login_name" => "rho", "id" => "item_name", "new_key" => "new_value"} } + let(:raw_hash) { { "login_name" => "alphaomega", "id" => "item_name" } } + let(:db) { Chef::DataBagItem.from_hash(raw_hash) } + let(:raw_edited_hash) { { "login_name" => "rho", "id" => "item_name", "new_key" => "new_value" } } let(:rest) { double("Chef::ServerAPI") } let(:stdout) { StringIO.new } @@ -65,7 +65,7 @@ describe Chef::Knife::DataBagEdit do it "requires data bag and item arguments" do knife.name_args = [] expect(stdout).to receive(:puts).twice.with(anything) - expect {knife.run}.to exit_with_code(1) + expect { knife.run }.to exit_with_code(1) expect(stdout.string).to eq("") end @@ -74,7 +74,7 @@ describe Chef::Knife::DataBagEdit do end context "when config[:print_after] is set" do - let(:config) { {:print_after => true} } + let(:config) { { :print_after => true } } before do expect(knife.ui).to receive(:output).with(raw_edited_hash) end @@ -121,7 +121,6 @@ describe Chef::Knife::DataBagEdit do expect(knife).to receive(:encryption_secret_provided_ignore_encrypt_flag?).and_return(false) expect(knife.ui).to receive(:fatal).with("You cannot edit an encrypted data bag without providing the secret.") - expect {knife.run}.to exit_with_code(1) + expect { knife.run }.to exit_with_code(1) end - end diff --git a/spec/unit/knife/data_bag_from_file_spec.rb b/spec/unit/knife/data_bag_from_file_spec.rb index 4a31c480c0..6eb870436d 100644 --- a/spec/unit/knife/data_bag_from_file_spec.rb +++ b/spec/unit/knife/data_bag_from_file_spec.rb @@ -73,9 +73,9 @@ describe Chef::Knife::DataBagFromFile do let(:data_bags_path) { "data_bags" } let(:plain_data) { { - "id" => "item_name", - "greeting" => "hello", - "nested" => { "a1" => [1, 2, 3], "a2" => { "b1" => true }}, + "id" => "item_name", + "greeting" => "hello", + "nested" => { "a1" => [1, 2, 3], "a2" => { "b1" => true } }, } } let(:enc_data) { Chef::EncryptedDataBagItem.encrypt_data_bag_item(plain_data, secret) } @@ -117,7 +117,6 @@ describe Chef::Knife::DataBagFromFile do end describe "loading all data bags" do - it "loads all data bags when -a or --all options is provided" do knife.name_args = [] config[:all] = true @@ -141,7 +140,6 @@ describe Chef::Knife::DataBagFromFile do knife.run end - end describe "encrypted data bag items" do @@ -158,15 +156,13 @@ describe Chef::Knife::DataBagFromFile do knife.run end - end describe "command line parsing" do it "prints help if given no arguments" do knife.name_args = [bag_name] - expect {knife.run}.to exit_with_code(1) + expect { knife.run }.to exit_with_code(1) expect(stdout.string).to start_with("knife data bag from file BAG FILE|FOLDER [FILE|FOLDER..] (options)") end end - end diff --git a/spec/unit/knife/data_bag_secret_options_spec.rb b/spec/unit/knife/data_bag_secret_options_spec.rb index 2f4d8c8a88..b9f80d3cbb 100644 --- a/spec/unit/knife/data_bag_secret_options_spec.rb +++ b/spec/unit/knife/data_bag_secret_options_spec.rb @@ -48,7 +48,6 @@ describe Chef::Knife::DataBagSecretOptions do end describe "#validate_secrets" do - it "throws an error when provided with both --secret and --secret-file on the CL" do Chef::Config[:knife][:cl_secret_file] = secret_file.path Chef::Config[:knife][:cl_secret] = secret @@ -66,11 +65,9 @@ describe Chef::Knife::DataBagSecretOptions do example_db.validate_secrets end - end describe "#read_secret" do - it "returns the secret first" do Chef::Config[:knife][:cl_secret] = secret expect(example_db).to receive(:config).and_return({ :secret => secret }) @@ -95,11 +92,9 @@ describe Chef::Knife::DataBagSecretOptions do expect(Chef::EncryptedDataBagItem).to receive(:load_secret).with(secret_file.path).and_return("secret file contents") expect(example_db.read_secret).to eq("secret file contents") end - end describe "#encryption_secret_provided?" do - it "returns true if the secret is passed on the CL" do Chef::Config[:knife][:cl_secret] = secret expect(example_db.encryption_secret_provided?).to eq(true) @@ -159,7 +154,5 @@ describe Chef::Knife::DataBagSecretOptions do it "returns false if --encrypt is not provided and need_encrypt_flag is false" do expect(example_db.encryption_secret_provided_ignore_encrypt_flag?).to eq(false) end - end - end diff --git a/spec/unit/knife/data_bag_show_spec.rb b/spec/unit/knife/data_bag_show_spec.rb index 489949a0e9..3442f9a45c 100644 --- a/spec/unit/knife/data_bag_show_spec.rb +++ b/spec/unit/knife/data_bag_show_spec.rb @@ -25,7 +25,6 @@ require "chef/json_compat" require "tempfile" describe Chef::Knife::DataBagShow do - before do Chef::Config[:node_name] = "webmonkey.example.com" knife.name_args = [bag_name, item_name] @@ -45,10 +44,10 @@ describe Chef::Knife::DataBagShow do let(:bag_name) { "sudoing_admins" } let(:item_name) { "ME" } - let(:data_bag_contents) { { "id" => "id", "baz"=>"http://localhost:4000/data/bag_o_data/baz", - "qux"=>"http://localhost:4000/data/bag_o_data/qux"} } - let(:enc_hash) {Chef::EncryptedDataBagItem.encrypt_data_bag_item(data_bag_contents, secret)} - let(:data_bag) {Chef::DataBagItem.from_hash(data_bag_contents)} + let(:data_bag_contents) { { "id" => "id", "baz" => "http://localhost:4000/data/bag_o_data/baz", + "qux" => "http://localhost:4000/data/bag_o_data/qux" } } + let(:enc_hash) { Chef::EncryptedDataBagItem.encrypt_data_bag_item(data_bag_contents, secret) } + let(:data_bag) { Chef::DataBagItem.from_hash(data_bag_contents) } let(:data_bag_with_encoded_hash) { Chef::DataBagItem.from_hash(enc_hash) } let(:enc_data_bag) { Chef::EncryptedDataBagItem.new(enc_hash, secret) } @@ -56,7 +55,7 @@ describe Chef::Knife::DataBagShow do # # let(:raw_hash) {{ "login_name" => "alphaomega", "id" => item_name }} # - let(:config) { {format: "json"} } + let(:config) { { format: "json" } } context "Data bag to show is encrypted" do before do @@ -116,8 +115,7 @@ qux: http://localhost:4000/data/bag_o_data/qux} it "raises an error when no @name_args are provided" do knife.name_args = [] - expect {knife.run}.to exit_with_code(1) + expect { knife.run }.to exit_with_code(1) expect(stdout.string).to start_with("knife data bag show BAG [ITEM] (options)") end - end diff --git a/spec/unit/knife/environment_compare_spec.rb b/spec/unit/knife/environment_compare_spec.rb index 5d4a71d3a4..5df8e55b8e 100644 --- a/spec/unit/knife/environment_compare_spec.rb +++ b/spec/unit/knife/environment_compare_spec.rb @@ -21,7 +21,7 @@ require "spec_helper" describe Chef::Knife::EnvironmentCompare do before(:each) do @knife = Chef::Knife::EnvironmentCompare.new - + @environments = { "cita" => "http://localhost:4000/environments/cita", "citm" => "http://localhost:4000/environments/citm", @@ -33,10 +33,10 @@ describe Chef::Knife::EnvironmentCompare do "cita" => { "foo" => "= 1.0.1", "bar" => "= 0.0.4" }, "citm" => { "foo" => "= 1.0.1", "bar" => "= 0.0.2" }, } - + allow(@knife).to receive(:constraint_list).and_return(@constraints) - @cookbooks = { "foo"=>"= 1.0.1", "bar"=>"= 0.0.1" } + @cookbooks = { "foo" => "= 1.0.1", "bar" => "= 0.0.1" } allow(@knife).to receive(:cookbook_list).and_return(@cookbooks) @@ -46,10 +46,10 @@ describe Chef::Knife::EnvironmentCompare do @base_url = "https://server.example.com/cookbooks" @cookbook_data = {} @cookbook_names.each do |item| - @cookbook_data[item] = {"url" => "#{@base_url}/#{item}", - "versions" => [{"version" => "1.0.1", - "url" => "#{@base_url}/#{item}/1.0.1"}]} - end + @cookbook_data[item] = { "url" => "#{@base_url}/#{item}", + "versions" => [{ "version" => "1.0.1", + "url" => "#{@base_url}/#{item}/1.0.1" }] } + end allow(@rest_double).to receive(:get).with("/cookbooks?num_versions=1").and_return(@cookbook_data) @@ -65,7 +65,7 @@ describe Chef::Knife::EnvironmentCompare do expect(@stdout.string).to match /#{item}/ and expect(@stdout.string.lines.count).to be 4 end end - + it "should display 4 number of lines" do @knife.config[:format] = "summary" @knife.run @@ -90,7 +90,7 @@ describe Chef::Knife::EnvironmentCompare do expect(@stdout.string.lines.count).to be 3 end end - + describe "with -a or --all" do it "should display all cookbooks" do @knife.config[:format] = "summary" @@ -108,5 +108,4 @@ describe Chef::Knife::EnvironmentCompare do expect(@stdout.string.lines.count).to be 8 end end - end diff --git a/spec/unit/knife/environment_from_file_spec.rb b/spec/unit/knife/environment_from_file_spec.rb index afabc0051f..4505da3637 100644 --- a/spec/unit/knife/environment_from_file_spec.rb +++ b/spec/unit/knife/environment_from_file_spec.rb @@ -32,7 +32,7 @@ describe Chef::Knife::EnvironmentFromFile do @environment = Chef::Environment.new @environment.name("spec") @environment.description("runs the unit tests") - @environment.cookbook_versions({"apt" => "= 1.2.3"}) + @environment.cookbook_versions({ "apt" => "= 1.2.3" }) allow(@environment).to receive(:save).and_return true allow(@knife.loader).to receive(:load_from).and_return @environment end @@ -61,7 +61,7 @@ describe Chef::Knife::EnvironmentFromFile do allow(File).to receive(:expand_path).with("./environments/").and_return("/tmp/environments") allow(Dir).to receive(:glob).with("/tmp/environments/*.{json,rb}").and_return(["spec.rb", "apple.rb"]) @knife.name_args = [] - allow(@knife).to receive(:config).and_return({:all => true}) + allow(@knife).to receive(:config).and_return({ :all => true }) expect(@environment).to receive(:save).twice @knife.run end diff --git a/spec/unit/knife/environment_list_spec.rb b/spec/unit/knife/environment_list_spec.rb index 2ee11e91dc..636b32273e 100644 --- a/spec/unit/knife/environment_list_spec.rb +++ b/spec/unit/knife/environment_list_spec.rb @@ -39,7 +39,7 @@ describe Chef::Knife::EnvironmentList do end it "should print the environment names in a sorted list" do - names = @environments.keys.sort { |a,b| a <=> b } + names = @environments.keys.sort { |a, b| a <=> b } expect(@knife).to receive(:output).with(names) @knife.run end diff --git a/spec/unit/knife/index_rebuild_spec.rb b/spec/unit/knife/index_rebuild_spec.rb index 1e9803c4b7..baaa0a53ca 100644 --- a/spec/unit/knife/index_rebuild_spec.rb +++ b/spec/unit/knife/index_rebuild_spec.rb @@ -19,9 +19,8 @@ require "spec_helper" describe Chef::Knife::IndexRebuild do - - let(:knife){Chef::Knife::IndexRebuild.new} - let(:rest_client){double(Chef::ServerAPI)} + let(:knife) { Chef::Knife::IndexRebuild.new } + let(:rest_client) { double(Chef::ServerAPI) } let(:stub_rest!) do expect(knife).to receive(:rest).and_return(rest_client) @@ -49,14 +48,14 @@ describe Chef::Knife::IndexRebuild do end context "against a Chef 11 server" do - let(:api_header_value){"flavor=osc;version=11.0.0;erchef=1.2.3"} + let(:api_header_value) { "flavor=osc;version=11.0.0;erchef=1.2.3" } it "retrieves API information" do - expect(knife.grab_api_info).to eq({"flavor" => "osc", "version" => "11.0.0", "erchef" => "1.2.3"}) + expect(knife.grab_api_info).to eq({ "flavor" => "osc", "version" => "11.0.0", "erchef" => "1.2.3" }) end end # Chef 11 context "against a Chef 10 server" do - let(:api_header_value){nil} + let(:api_header_value) { nil } it "finds no API information" do expect(knife.grab_api_info).to eq({}) end @@ -66,11 +65,11 @@ describe Chef::Knife::IndexRebuild do context "#unsupported_version?" do context "with Chef 11 API metadata" do it "is unsupported" do - expect(knife.unsupported_version?({"version" => "11.0.0", "flavor" => "osc", "erchef" => "1.2.3"})).to be_truthy + expect(knife.unsupported_version?({ "version" => "11.0.0", "flavor" => "osc", "erchef" => "1.2.3" })).to be_truthy end it "only truly relies on the version being non-nil" do - expect(knife.unsupported_version?({"version" => "1", "flavor" => "osc", "erchef" => "1.2.3"})).to be_truthy + expect(knife.unsupported_version?({ "version" => "1", "flavor" => "osc", "erchef" => "1.2.3" })).to be_truthy end end @@ -83,7 +82,6 @@ describe Chef::Knife::IndexRebuild do end # unsupported_version? context "Simulating a 'knife index rebuild' run" do - before :each do expect(knife).to receive(:grab_api_info).and_return(api_info) server_specific_stubs! @@ -91,7 +89,7 @@ describe Chef::Knife::IndexRebuild do context "against a Chef 11 server" do let(:api_info) do - {"flavor" => "osc", + { "flavor" => "osc", "version" => "11.0.0", "erchef" => "1.2.3", } @@ -107,7 +105,7 @@ describe Chef::Knife::IndexRebuild do end context "against a Chef 10 server" do - let(:api_info){ {} } + let(:api_info) { {} } let(:server_specific_stubs!) do stub_rest! expect(rest_client).to receive(:post).with("/search/reindex", {}).and_return("representative output") @@ -121,8 +119,4 @@ describe Chef::Knife::IndexRebuild do end end end - end - - - diff --git a/spec/unit/knife/key_create_spec.rb b/spec/unit/knife/key_create_spec.rb index 1b9e551df7..1647b14dc2 100644 --- a/spec/unit/knife/key_create_spec.rb +++ b/spec/unit/knife/key_create_spec.rb @@ -95,7 +95,7 @@ Tfuc9dUYsFjptWYrV6pfEQ+bgo1OGBXORBFcFL+2D7u9JYquKrMgosznHoEkQNLo context "when public_key and key_name weren't passed" do it "raises a Chef::Exceptions::KeyCommandInputError with the proper error message" do - expect{ key_create_object.run }.to raise_error(Chef::Exceptions::KeyCommandInputError, key_create_object.public_key_or_key_name_error_msg) + expect { key_create_object.run }.to raise_error(Chef::Exceptions::KeyCommandInputError, key_create_object.public_key_or_key_name_error_msg) end end @@ -221,4 +221,3 @@ Tfuc9dUYsFjptWYrV6pfEQ+bgo1OGBXORBFcFL+2D7u9JYquKrMgosznHoEkQNLo end end end - diff --git a/spec/unit/knife/key_delete_spec.rb b/spec/unit/knife/key_delete_spec.rb index 0f09ec9c3d..c20f9341b0 100644 --- a/spec/unit/knife/key_delete_spec.rb +++ b/spec/unit/knife/key_delete_spec.rb @@ -45,8 +45,8 @@ describe "key delete commands that inherit knife" do context "when the service object is called" do it "creates a new instance of Chef::Knife::KeyDelete with the correct args" do expect(Chef::Knife::KeyDelete).to receive(:new). - with("charmander-key", "charmander", command.actor_field_name, command.ui). - and_return(service_object) + with("charmander-key", "charmander", command.actor_field_name, command.ui). + and_return(service_object) command.service_object end end # when the service object is called @@ -116,8 +116,6 @@ describe Chef::Knife::KeyDelete do key_delete_object.run end end # when the command is run - - end # key delete run command context "when actor_field_name is 'user'" do @@ -132,4 +130,3 @@ describe Chef::Knife::KeyDelete do end end end - diff --git a/spec/unit/knife/key_edit_spec.rb b/spec/unit/knife/key_edit_spec.rb index 3a9689d4d1..d294f3a25f 100644 --- a/spec/unit/knife/key_edit_spec.rb +++ b/spec/unit/knife/key_edit_spec.rb @@ -45,8 +45,8 @@ describe "key edit commands that inherit knife" do context "when the service object is called" do it "creates a new instance of Chef::Knife::KeyEdit with the correct args" do expect(Chef::Knife::KeyEdit).to receive(:new). - with("charmander-key", "charmander", command.actor_field_name, command.ui, command.config). - and_return(service_object) + with("charmander-key", "charmander", command.actor_field_name, command.ui, command.config). + and_return(service_object) command.service_object end end # when the service object is called @@ -114,7 +114,6 @@ Tfuc9dUYsFjptWYrV6pfEQ+bgo1OGBXORBFcFL+2D7u9JYquKrMgosznHoEkQNLo allow(key_edit_object).to receive(:display_info) end - context "when public_key and create_key are passed" do before do key_edit_object.config[:public_key] = "public_key_path" @@ -122,7 +121,7 @@ Tfuc9dUYsFjptWYrV6pfEQ+bgo1OGBXORBFcFL+2D7u9JYquKrMgosznHoEkQNLo end it "raises a Chef::Exceptions::KeyCommandInputError with the proper error message" do - expect{ key_edit_object.run }.to raise_error(Chef::Exceptions::KeyCommandInputError, key_edit_object.public_key_and_create_key_error_msg) + expect { key_edit_object.run }.to raise_error(Chef::Exceptions::KeyCommandInputError, key_edit_object.public_key_and_create_key_error_msg) end end @@ -246,11 +245,7 @@ Tfuc9dUYsFjptWYrV6pfEQ+bgo1OGBXORBFcFL+2D7u9JYquKrMgosznHoEkQNLo end end end # when the server returns a private key - end # when the command is run - - - end # key edit run command context "when actor_field_name is 'user'" do diff --git a/spec/unit/knife/key_list_spec.rb b/spec/unit/knife/key_list_spec.rb index 989deac76e..af8a53f5a8 100644 --- a/spec/unit/knife/key_list_spec.rb +++ b/spec/unit/knife/key_list_spec.rb @@ -98,7 +98,7 @@ describe Chef::Knife::KeyList do end it "raises a Chef::Exceptions::KeyCommandInputError with the proper error message" do - expect{ key_list_object.run }.to raise_error(Chef::Exceptions::KeyCommandInputError, key_list_object.expired_and_non_expired_msg) + expect { key_list_object.run }.to raise_error(Chef::Exceptions::KeyCommandInputError, key_list_object.expired_and_non_expired_msg) end end @@ -183,9 +183,7 @@ describe Chef::Knife::KeyList do key_list_object.run end end # when with_details is true - end # when the command is run - end # key list run command context "when list_method is :list_by_user" do @@ -193,9 +191,9 @@ describe Chef::Knife::KeyList do let(:list_method) { :list_by_user } let(:http_response) { [ - {"uri"=>"https://api.opscode.piab/users/charmander/keys/non-expired1", "name"=>"non-expired1", "expired"=>false}, - {"uri"=>"https://api.opscode.piab/users/charmander/keys/non-expired2", "name"=>"non-expired2", "expired"=>false}, - {"uri"=>"https://api.opscode.piab/users/mary/keys/out-of-date", "name"=>"out-of-date", "expired"=>true}, + { "uri" => "https://api.opscode.piab/users/charmander/keys/non-expired1", "name" => "non-expired1", "expired" => false }, + { "uri" => "https://api.opscode.piab/users/charmander/keys/non-expired2", "name" => "non-expired2", "expired" => false }, + { "uri" => "https://api.opscode.piab/users/mary/keys/out-of-date", "name" => "out-of-date", "expired" => true }, ] } end @@ -206,9 +204,9 @@ describe Chef::Knife::KeyList do let(:list_method) { :list_by_client } let(:http_response) { [ - {"uri"=>"https://api.opscode.piab/organizations/pokemon/clients/charmander/keys/non-expired1", "name"=>"non-expired1", "expired"=>false}, - {"uri"=>"https://api.opscode.piab/organizations/pokemon/clients/charmander/keys/non-expired2", "name"=>"non-expired2", "expired"=>false}, - {"uri"=>"https://api.opscode.piab/organizations/pokemon/clients/mary/keys/out-of-date", "name"=>"out-of-date", "expired"=>true}, + { "uri" => "https://api.opscode.piab/organizations/pokemon/clients/charmander/keys/non-expired1", "name" => "non-expired1", "expired" => false }, + { "uri" => "https://api.opscode.piab/organizations/pokemon/clients/charmander/keys/non-expired2", "name" => "non-expired2", "expired" => false }, + { "uri" => "https://api.opscode.piab/organizations/pokemon/clients/mary/keys/out-of-date", "name" => "out-of-date", "expired" => true }, ] } end diff --git a/spec/unit/knife/key_show_spec.rb b/spec/unit/knife/key_show_spec.rb index 0681ad8b72..c161efbe0d 100644 --- a/spec/unit/knife/key_show_spec.rb +++ b/spec/unit/knife/key_show_spec.rb @@ -45,8 +45,8 @@ describe "key show commands that inherit knife" do context "when the service object is called" do it "creates a new instance of Chef::Knife::KeyShow with the correct args" do expect(Chef::Knife::KeyShow).to receive(:new). - with("charmander-key", "charmander", command.load_method, command.ui). - and_return(service_object) + with("charmander-key", "charmander", command.load_method, command.ui). + and_return(service_object) command.service_object end end # when the service object is called diff --git a/spec/unit/knife/node_bulk_delete_spec.rb b/spec/unit/knife/node_bulk_delete_spec.rb index 8744787ef6..5d18be1819 100644 --- a/spec/unit/knife/node_bulk_delete_spec.rb +++ b/spec/unit/knife/node_bulk_delete_spec.rb @@ -22,7 +22,7 @@ describe Chef::Knife::NodeBulkDelete do before(:each) do Chef::Log.logger = Logger.new(StringIO.new) - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::NodeBulkDelete.new @knife.name_args = ["."] @stdout = StringIO.new @@ -37,14 +37,14 @@ 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)| - inflatedish[name] = Chef::Node.new.tap {|n| n.name(name)} + 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 expect(actual.keys).to match_array(expected.keys) - expect(actual.values.map {|n| n.name }).to match_array(%w{adam brent jacob}) + expect(actual.values.map { |n| n.name }).to match_array(%w{adam brent jacob}) end end @@ -89,9 +89,5 @@ describe Chef::Knife::NodeBulkDelete do @knife.name_args = [] expect { @knife.run }.to raise_error(SystemExit) end - end end - - - diff --git a/spec/unit/knife/node_delete_spec.rb b/spec/unit/knife/node_delete_spec.rb index da4c44a651..e2cda8751f 100644 --- a/spec/unit/knife/node_delete_spec.rb +++ b/spec/unit/knife/node_delete_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::Knife::NodeDelete do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::NodeDelete.new @knife.config = { :print_after => nil diff --git a/spec/unit/knife/node_edit_spec.rb b/spec/unit/knife/node_edit_spec.rb index 2cf6633574..11a69b49eb 100644 --- a/spec/unit/knife/node_edit_spec.rb +++ b/spec/unit/knife/node_edit_spec.rb @@ -20,14 +20,13 @@ require "spec_helper" Chef::Knife::NodeEdit.load_deps describe Chef::Knife::NodeEdit do - # helper to convert the view from Chef objects into Ruby objects representing JSON def deserialized_json_view actual = Chef::JSONCompat.from_json(Chef::JSONCompat.to_json_pretty(@knife.node_editor.send(:view))) end before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::NodeEdit.new @knife.config = { :editor => "cat", @@ -46,10 +45,10 @@ describe Chef::Knife::NodeEdit do describe "after loading the node" do before do allow(@knife).to receive(:node).and_return(@node) - @node.automatic_attrs = {:go => :away} - @node.default_attrs = {:hide => :me} - @node.override_attrs = {:dont => :show} - @node.normal_attrs = {:do_show => :these} + @node.automatic_attrs = { :go => :away } + @node.default_attrs = { :hide => :me } + @node.override_attrs = { :dont => :show } + @node.normal_attrs = { :do_show => :these } @node.chef_environment("prod") @node.run_list("recipe[foo]") end @@ -59,7 +58,7 @@ describe Chef::Knife::NodeEdit do expect(actual).not_to have_key("automatic") expect(actual).not_to have_key("override") expect(actual).not_to have_key("default") - expect(actual["normal"]).to eq({"do_show" => "these"}) + expect(actual["normal"]).to eq({ "do_show" => "these" }) expect(actual["run_list"]).to eq(["recipe[foo]"]) expect(actual["chef_environment"]).to eq("prod") end @@ -68,10 +67,10 @@ describe Chef::Knife::NodeEdit do @knife.config[:all_attributes] = true actual = deserialized_json_view - expect(actual["automatic"]).to eq({"go" => "away"}) - expect(actual["override"]).to eq({"dont" => "show"}) - expect(actual["default"]).to eq({"hide" => "me"}) - expect(actual["normal"]).to eq({"do_show" => "these"}) + expect(actual["automatic"]).to eq({ "go" => "away" }) + expect(actual["override"]).to eq({ "dont" => "show" }) + expect(actual["default"]).to eq({ "hide" => "me" }) + expect(actual["normal"]).to eq({ "do_show" => "these" }) expect(actual["run_list"]).to eq(["recipe[foo]"]) expect(actual["chef_environment"]).to eq("prod") end @@ -88,11 +87,9 @@ describe Chef::Knife::NodeEdit do @knife.node_editor.send(:apply_updates, view) expect(@knife.node_editor).to be_updated end - end describe "edit_node" do - before do allow(@knife).to receive(:node).and_return(@node) end @@ -101,15 +98,12 @@ describe Chef::Knife::NodeEdit do it "raises an exception when editing is disabled" do @knife.config[:disable_editing] = true - expect{ subject }.to raise_error(SystemExit) + expect { subject }.to raise_error(SystemExit) end it "raises an exception when the editor is not set" do @knife.config[:editor] = nil - expect{ subject }.to raise_error(SystemExit) + expect { subject }.to raise_error(SystemExit) end - end - end - diff --git a/spec/unit/knife/node_environment_set_spec.rb b/spec/unit/knife/node_environment_set_spec.rb index 7fba0cf841..13dd3762a2 100644 --- a/spec/unit/knife/node_environment_set_spec.rb +++ b/spec/unit/knife/node_environment_set_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::Knife::NodeEnvironmentSet do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::NodeEnvironmentSet.new @knife.name_args = [ "adam", "bar" ] allow(@knife).to receive(:output).and_return(true) diff --git a/spec/unit/knife/node_from_file_spec.rb b/spec/unit/knife/node_from_file_spec.rb index 728483e22d..89b2b8156f 100644 --- a/spec/unit/knife/node_from_file_spec.rb +++ b/spec/unit/knife/node_from_file_spec.rb @@ -22,7 +22,7 @@ Chef::Knife::NodeFromFile.load_deps describe Chef::Knife::NodeFromFile do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::NodeFromFile.new @knife.config = { :print_after => nil diff --git a/spec/unit/knife/node_list_spec.rb b/spec/unit/knife/node_list_spec.rb index 3112e0b804..ab17a45795 100644 --- a/spec/unit/knife/node_list_spec.rb +++ b/spec/unit/knife/node_list_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::Knife::NodeList do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" Chef::Config[:environment] = nil # reset this value each time, as it is not reloaded @knife = Chef::Knife::NodeList.new allow(@knife).to receive(:output).and_return(true) @@ -60,4 +60,3 @@ describe Chef::Knife::NodeList do end end end - diff --git a/spec/unit/knife/node_run_list_add_spec.rb b/spec/unit/knife/node_run_list_add_spec.rb index 6bdaee6915..eb897c146b 100644 --- a/spec/unit/knife/node_run_list_add_spec.rb +++ b/spec/unit/knife/node_run_list_add_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::Knife::NodeRunListAdd do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::NodeRunListAdd.new @knife.config = { :after => nil @@ -143,6 +143,3 @@ describe Chef::Knife::NodeRunListAdd do end end end - - - diff --git a/spec/unit/knife/node_run_list_remove_spec.rb b/spec/unit/knife/node_run_list_remove_spec.rb index 54f8625898..e741f513eb 100644 --- a/spec/unit/knife/node_run_list_remove_spec.rb +++ b/spec/unit/knife/node_run_list_remove_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::Knife::NodeRunListRemove do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::NodeRunListRemove.new @knife.config[:print_after] = nil @knife.name_args = [ "adam", "role[monkey]" ] diff --git a/spec/unit/knife/node_run_list_set_spec.rb b/spec/unit/knife/node_run_list_set_spec.rb index 11d3be7e84..29c554d23e 100644 --- a/spec/unit/knife/node_run_list_set_spec.rb +++ b/spec/unit/knife/node_run_list_set_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::Knife::NodeRunListSet do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::NodeRunListSet.new @knife.config = {} @knife.name_args = [ "adam", "role[monkey]" ] @@ -135,6 +135,5 @@ describe Chef::Knife::NodeRunListSet do expect(@stderr.string).to eq "FATAL: You must supply both a node name and a run list.\n" end end - end end diff --git a/spec/unit/knife/node_show_spec.rb b/spec/unit/knife/node_show_spec.rb index b3fc78c954..c2ba781f26 100644 --- a/spec/unit/knife/node_show_spec.rb +++ b/spec/unit/knife/node_show_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Knife::NodeShow do - let(:node) do node = Chef::Node.new() node.name("adam") diff --git a/spec/unit/knife/raw_spec.rb b/spec/unit/knife/raw_spec.rb index a69c133a0e..9202998fb9 100644 --- a/spec/unit/knife/raw_spec.rb +++ b/spec/unit/knife/raw_spec.rb @@ -36,7 +36,7 @@ describe Chef::Knife::Raw do knife.config[:proxy_auth] = true expect(rest).to receive(:request).with(:GET, "/nodes", { "Content-Type" => "application/json", - "x-ops-request-source" => "web"}, false) + "x-ops-request-source" => "web" }, false) knife.run end end diff --git a/spec/unit/knife/role_bulk_delete_spec.rb b/spec/unit/knife/role_bulk_delete_spec.rb index 75edab8aa9..bbbec91278 100644 --- a/spec/unit/knife/role_bulk_delete_spec.rb +++ b/spec/unit/knife/role_bulk_delete_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::Knife::RoleBulkDelete do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::RoleBulkDelete.new @knife.config = { :print_after => nil @@ -40,7 +40,6 @@ describe Chef::Knife::RoleBulkDelete do end describe "run" do - it "should get the list of the roles" do expect(Chef::Role).to receive(:list).and_return(@roles) @knife.run @@ -75,6 +74,5 @@ describe Chef::Knife::RoleBulkDelete do @knife.name_args = [] expect { @knife.run }.to raise_error(SystemExit) end - end end diff --git a/spec/unit/knife/role_create_spec.rb b/spec/unit/knife/role_create_spec.rb index 765cec7882..d414e5a18d 100644 --- a/spec/unit/knife/role_create_spec.rb +++ b/spec/unit/knife/role_create_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::Knife::RoleCreate do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::RoleCreate.new @knife.config = { :description => nil diff --git a/spec/unit/knife/role_delete_spec.rb b/spec/unit/knife/role_delete_spec.rb index 3251ddd81c..cc65674a08 100644 --- a/spec/unit/knife/role_delete_spec.rb +++ b/spec/unit/knife/role_delete_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::Knife::RoleDelete do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::RoleDelete.new @knife.config = { :print_after => nil diff --git a/spec/unit/knife/role_edit_spec.rb b/spec/unit/knife/role_edit_spec.rb index 5f4ed1eb8e..c5b6f81976 100644 --- a/spec/unit/knife/role_edit_spec.rb +++ b/spec/unit/knife/role_edit_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::Knife::RoleEdit do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::RoleEdit.new @knife.config[:print_after] = nil @knife.name_args = [ "adam" ] @@ -58,7 +58,6 @@ describe Chef::Knife::RoleEdit do expect(@knife.ui).to receive(:edit_data).with(@role).and_return(pansy) expect(pansy).not_to receive(:save) @knife.run - end it "should not print the role" do @@ -75,5 +74,3 @@ describe Chef::Knife::RoleEdit do end end end - - diff --git a/spec/unit/knife/role_env_run_list_add_spec.rb b/spec/unit/knife/role_env_run_list_add_spec.rb index 0831abd845..3e4a108577 100644 --- a/spec/unit/knife/role_env_run_list_add_spec.rb +++ b/spec/unit/knife/role_env_run_list_add_spec.rb @@ -7,9 +7,9 @@ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,13 +29,12 @@ describe Chef::Knife::RoleEnvRunListAdd do } @knife.name_args = [ "will", "QA", "role[monkey]" ] allow(@knife).to receive(:output).and_return(true) - @role = Chef::Role.new() + @role = Chef::Role.new() allow(@role).to receive(:save).and_return(true) allow(Chef::Role).to receive(:load).and_return(@role) end describe "run" do - # it "should display all the things" do # @knife.run # @role.to_json.should == 'show all the things' @@ -180,7 +179,7 @@ describe Chef::Knife::RoleEnvRunListAdd do expect(@role.run_list[1]).to be_nil end end - + describe "with more than one command" do it "should be able to the environment run list by running multiple knife commands" do @knife.name_args = [ "will", "QA", "role[blue]," ] @@ -212,6 +211,5 @@ describe Chef::Knife::RoleEnvRunListAdd do expect(@role.run_list[1]).to be_nil end end - end end diff --git a/spec/unit/knife/role_env_run_list_clear_spec.rb b/spec/unit/knife/role_env_run_list_clear_spec.rb index 831a23b71b..d0565497ca 100644 --- a/spec/unit/knife/role_env_run_list_clear_spec.rb +++ b/spec/unit/knife/role_env_run_list_clear_spec.rb @@ -21,8 +21,8 @@ require "spec_helper" describe Chef::Knife::RoleEnvRunListClear do before(:each) do - Chef::Config[:role_name] = "will" - Chef::Config[:env_name] = "QA" + Chef::Config[:role_name] = "will" + Chef::Config[:env_name] = "QA" @setup = Chef::Knife::RoleEnvRunListAdd.new @setup.name_args = [ "will", "QA", "role[monkey]", "role[person]" ] @@ -39,14 +39,9 @@ describe Chef::Knife::RoleEnvRunListClear do allow(@knife.ui).to receive(:confirm).and_return(true) allow(Chef::Role).to receive(:load).and_return(@role) - end - - describe "run" do - - # it "should display all the things" do # @knife.run # @role.to_json.should == 'show all the things' @@ -57,44 +52,41 @@ describe Chef::Knife::RoleEnvRunListClear do @knife.run end - it "should remove the item from the run list" do - @setup.run - @knife.run - expect(@role.run_list_for("QA")[0]).to be_nil - expect(@role.run_list[0]).to be_nil - end + it "should remove the item from the run list" do + @setup.run + @knife.run + expect(@role.run_list_for("QA")[0]).to be_nil + expect(@role.run_list[0]).to be_nil + end - it "should save the node" do - expect(@role).to receive(:save).and_return(true) - @knife.run - end + it "should save the node" do + expect(@role).to receive(:save).and_return(true) + @knife.run + end - it "should print the run list" do - expect(@knife).to receive(:output).and_return(true) - @knife.config[:print_after] = true - @setup.run - @knife.run - end + it "should print the run list" do + expect(@knife).to receive(:output).and_return(true) + @knife.config[:print_after] = true + @setup.run + @knife.run + end - describe "should clear an environmental run list of roles and recipes" do - it "should remove the items from the run list" do - @setup.name_args = [ "will", "QA", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] - @setup.run - @setup.name_args = [ "will", "PRD", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] - @setup.run - @knife.name_args = [ "will", "QA" ] - @knife.run - expect(@role.run_list_for("QA")[0]).to be_nil - expect(@role.run_list_for("PRD")[0]).to eq("recipe[orange::chicken]") - expect(@role.run_list_for("PRD")[1]).to eq("role[monkey]") - expect(@role.run_list_for("PRD")[2]).to eq("recipe[duck::type]") - expect(@role.run_list_for("PRD")[3]).to eq("role[person]") - expect(@role.run_list_for("PRD")[4]).to eq("role[bird]") - expect(@role.run_list_for("PRD")[5]).to eq("role[town]") - end - end + describe "should clear an environmental run list of roles and recipes" do + it "should remove the items from the run list" do + @setup.name_args = [ "will", "QA", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] + @setup.run + @setup.name_args = [ "will", "PRD", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] + @setup.run + @knife.name_args = [ "will", "QA" ] + @knife.run + expect(@role.run_list_for("QA")[0]).to be_nil + expect(@role.run_list_for("PRD")[0]).to eq("recipe[orange::chicken]") + expect(@role.run_list_for("PRD")[1]).to eq("role[monkey]") + expect(@role.run_list_for("PRD")[2]).to eq("recipe[duck::type]") + expect(@role.run_list_for("PRD")[3]).to eq("role[person]") + expect(@role.run_list_for("PRD")[4]).to eq("role[bird]") + expect(@role.run_list_for("PRD")[5]).to eq("role[town]") + end + end end end - - - diff --git a/spec/unit/knife/role_env_run_list_remove_spec.rb b/spec/unit/knife/role_env_run_list_remove_spec.rb index 39f4a78e28..ba07677e9d 100644 --- a/spec/unit/knife/role_env_run_list_remove_spec.rb +++ b/spec/unit/knife/role_env_run_list_remove_spec.rb @@ -21,8 +21,8 @@ require "spec_helper" describe Chef::Knife::RoleEnvRunListRemove do before(:each) do - Chef::Config[:role_name] = "will" - Chef::Config[:env_name] = "QA" + Chef::Config[:role_name] = "will" + Chef::Config[:env_name] = "QA" @setup = Chef::Knife::RoleEnvRunListAdd.new @setup.name_args = [ "will", "QA", "role[monkey]", "role[person]" ] @@ -39,14 +39,9 @@ describe Chef::Knife::RoleEnvRunListRemove do allow(@knife.ui).to receive(:confirm).and_return(true) allow(Chef::Role).to receive(:load).and_return(@role) - end - - describe "run" do - - # it "should display all the things" do # @knife.run # @role.to_json.should == 'show all the things' @@ -57,52 +52,49 @@ describe Chef::Knife::RoleEnvRunListRemove do @knife.run end - it "should remove the item from the run list" do - @setup.run - @knife.run - expect(@role.run_list_for("QA")[0]).not_to eq("role[monkey]") - expect(@role.run_list_for("QA")[0]).to eq("role[person]") - expect(@role.run_list[0]).to be_nil - end + it "should remove the item from the run list" do + @setup.run + @knife.run + expect(@role.run_list_for("QA")[0]).not_to eq("role[monkey]") + expect(@role.run_list_for("QA")[0]).to eq("role[person]") + expect(@role.run_list[0]).to be_nil + end - it "should save the node" do - expect(@role).to receive(:save).and_return(true) - @knife.run - end + it "should save the node" do + expect(@role).to receive(:save).and_return(true) + @knife.run + end - it "should print the run list" do - expect(@knife).to receive(:output).and_return(true) - @knife.config[:print_after] = true - @setup.run - @knife.run - end + it "should print the run list" do + expect(@knife).to receive(:output).and_return(true) + @knife.config[:print_after] = true + @setup.run + @knife.run + end - describe "run with a list of roles and recipes" do - it "should remove the items from the run list" do - @setup.name_args = [ "will", "QA", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] - @setup.run - @setup.name_args = [ "will", "PRD", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] - @setup.run - @knife.name_args = [ "will", "QA", "role[monkey]" ] - @knife.run - @knife.name_args = [ "will", "QA", "recipe[duck::type]" ] - @knife.run - expect(@role.run_list_for("QA")).not_to include("role[monkey]") - expect(@role.run_list_for("QA")).not_to include("recipe[duck::type]") - expect(@role.run_list_for("QA")[0]).to eq("recipe[orange::chicken]") - expect(@role.run_list_for("QA")[1]).to eq("role[person]") - expect(@role.run_list_for("QA")[2]).to eq("role[bird]") - expect(@role.run_list_for("QA")[3]).to eq("role[town]") - expect(@role.run_list_for("PRD")[0]).to eq("recipe[orange::chicken]") - expect(@role.run_list_for("PRD")[1]).to eq("role[monkey]") - expect(@role.run_list_for("PRD")[2]).to eq("recipe[duck::type]") - expect(@role.run_list_for("PRD")[3]).to eq("role[person]") - expect(@role.run_list_for("PRD")[4]).to eq("role[bird]") - expect(@role.run_list_for("PRD")[5]).to eq("role[town]") - end - end + describe "run with a list of roles and recipes" do + it "should remove the items from the run list" do + @setup.name_args = [ "will", "QA", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] + @setup.run + @setup.name_args = [ "will", "PRD", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] + @setup.run + @knife.name_args = [ "will", "QA", "role[monkey]" ] + @knife.run + @knife.name_args = [ "will", "QA", "recipe[duck::type]" ] + @knife.run + expect(@role.run_list_for("QA")).not_to include("role[monkey]") + expect(@role.run_list_for("QA")).not_to include("recipe[duck::type]") + expect(@role.run_list_for("QA")[0]).to eq("recipe[orange::chicken]") + expect(@role.run_list_for("QA")[1]).to eq("role[person]") + expect(@role.run_list_for("QA")[2]).to eq("role[bird]") + expect(@role.run_list_for("QA")[3]).to eq("role[town]") + expect(@role.run_list_for("PRD")[0]).to eq("recipe[orange::chicken]") + expect(@role.run_list_for("PRD")[1]).to eq("role[monkey]") + expect(@role.run_list_for("PRD")[2]).to eq("recipe[duck::type]") + expect(@role.run_list_for("PRD")[3]).to eq("role[person]") + expect(@role.run_list_for("PRD")[4]).to eq("role[bird]") + expect(@role.run_list_for("PRD")[5]).to eq("role[town]") + end + end end end - - - diff --git a/spec/unit/knife/role_env_run_list_replace_spec.rb b/spec/unit/knife/role_env_run_list_replace_spec.rb index 537ede29ce..fea6782a33 100644 --- a/spec/unit/knife/role_env_run_list_replace_spec.rb +++ b/spec/unit/knife/role_env_run_list_replace_spec.rb @@ -21,8 +21,8 @@ require "spec_helper" describe Chef::Knife::RoleEnvRunListReplace do before(:each) do - Chef::Config[:role_name] = "will" - Chef::Config[:env_name] = "QA" + Chef::Config[:role_name] = "will" + Chef::Config[:env_name] = "QA" @setup = Chef::Knife::RoleEnvRunListAdd.new @setup.name_args = [ "will", "QA", "role[monkey]", "role[dude]", "role[fixer]" ] @@ -39,14 +39,9 @@ describe Chef::Knife::RoleEnvRunListReplace do allow(@knife.ui).to receive(:confirm).and_return(true) allow(Chef::Role).to receive(:load).and_return(@role) - end - - describe "run" do - - # it "should display all the things" do # @knife.run # @role.to_json.should == 'show all the things' @@ -57,52 +52,52 @@ describe Chef::Knife::RoleEnvRunListReplace do @knife.run end - it "should remove the item from the run list" do - @setup.run - @knife.run - expect(@role.run_list_for("QA")[1]).not_to eq("role[dude]") - expect(@role.run_list_for("QA")[1]).to eq("role[person]") - expect(@role.run_list[0]).to be_nil - end + it "should remove the item from the run list" do + @setup.run + @knife.run + expect(@role.run_list_for("QA")[1]).not_to eq("role[dude]") + expect(@role.run_list_for("QA")[1]).to eq("role[person]") + expect(@role.run_list[0]).to be_nil + end - it "should save the node" do - expect(@role).to receive(:save).and_return(true) - @knife.run - end + it "should save the node" do + expect(@role).to receive(:save).and_return(true) + @knife.run + end - it "should print the run list" do - expect(@knife).to receive(:output).and_return(true) - @knife.config[:print_after] = true - @setup.run - @knife.run - end + it "should print the run list" do + expect(@knife).to receive(:output).and_return(true) + @knife.config[:print_after] = true + @setup.run + @knife.run + end - describe "run with a list of roles and recipes" do - it "should replace the items from the run list" do - @setup.name_args = [ "will", "QA", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] - @setup.run - @setup.name_args = [ "will", "PRD", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] - @setup.run - @knife.name_args = [ "will", "QA", "role[monkey]", "role[gibbon]" ] - @knife.run - @knife.name_args = [ "will", "QA", "recipe[duck::type]", "recipe[duck::mallard]" ] - @knife.run - expect(@role.run_list_for("QA")).not_to include("role[monkey]") - expect(@role.run_list_for("QA")).not_to include("recipe[duck::type]") - expect(@role.run_list_for("QA")[0]).to eq("recipe[orange::chicken]") - expect(@role.run_list_for("QA")[1]).to eq("role[gibbon]") - expect(@role.run_list_for("QA")[2]).to eq("recipe[duck::mallard]") - expect(@role.run_list_for("QA")[3]).to eq("role[person]") - expect(@role.run_list_for("QA")[4]).to eq("role[bird]") - expect(@role.run_list_for("QA")[5]).to eq("role[town]") - expect(@role.run_list_for("PRD")[0]).to eq("recipe[orange::chicken]") - expect(@role.run_list_for("PRD")[1]).to eq("role[monkey]") - expect(@role.run_list_for("PRD")[2]).to eq("recipe[duck::type]") - expect(@role.run_list_for("PRD")[3]).to eq("role[person]") - expect(@role.run_list_for("PRD")[4]).to eq("role[bird]") - expect(@role.run_list_for("PRD")[5]).to eq("role[town]") - expect(@role.run_list[0]).to be_nil - end - end + describe "run with a list of roles and recipes" do + it "should replace the items from the run list" do + @setup.name_args = [ "will", "QA", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] + @setup.run + @setup.name_args = [ "will", "PRD", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] + @setup.run + @knife.name_args = [ "will", "QA", "role[monkey]", "role[gibbon]" ] + @knife.run + @knife.name_args = [ "will", "QA", "recipe[duck::type]", "recipe[duck::mallard]" ] + @knife.run + expect(@role.run_list_for("QA")).not_to include("role[monkey]") + expect(@role.run_list_for("QA")).not_to include("recipe[duck::type]") + expect(@role.run_list_for("QA")[0]).to eq("recipe[orange::chicken]") + expect(@role.run_list_for("QA")[1]).to eq("role[gibbon]") + expect(@role.run_list_for("QA")[2]).to eq("recipe[duck::mallard]") + expect(@role.run_list_for("QA")[3]).to eq("role[person]") + expect(@role.run_list_for("QA")[4]).to eq("role[bird]") + expect(@role.run_list_for("QA")[5]).to eq("role[town]") + expect(@role.run_list_for("PRD")[0]).to eq("recipe[orange::chicken]") + expect(@role.run_list_for("PRD")[1]).to eq("role[monkey]") + expect(@role.run_list_for("PRD")[2]).to eq("recipe[duck::type]") + expect(@role.run_list_for("PRD")[3]).to eq("role[person]") + expect(@role.run_list_for("PRD")[4]).to eq("role[bird]") + expect(@role.run_list_for("PRD")[5]).to eq("role[town]") + expect(@role.run_list[0]).to be_nil + end + end end end diff --git a/spec/unit/knife/role_env_run_list_set_spec.rb b/spec/unit/knife/role_env_run_list_set_spec.rb index 83a665c34f..e8696efc10 100644 --- a/spec/unit/knife/role_env_run_list_set_spec.rb +++ b/spec/unit/knife/role_env_run_list_set_spec.rb @@ -21,8 +21,8 @@ require "spec_helper" describe Chef::Knife::RoleEnvRunListSet do before(:each) do - Chef::Config[:role_name] = "will" - Chef::Config[:env_name] = "QA" + Chef::Config[:role_name] = "will" + Chef::Config[:env_name] = "QA" @setup = Chef::Knife::RoleEnvRunListAdd.new @setup.name_args = [ "will", "QA", "role[monkey]", "role[person]", "role[bucket]" ] @@ -39,14 +39,9 @@ describe Chef::Knife::RoleEnvRunListSet do allow(@knife.ui).to receive(:confirm).and_return(true) allow(Chef::Role).to receive(:load).and_return(@role) - end - - describe "run" do - - # it "should display all the things" do # @knife.run # @role.to_json.should == 'show all the things' @@ -60,8 +55,8 @@ describe Chef::Knife::RoleEnvRunListSet do it "should replace all the items in the runlist with what is specified" do @setup.run @knife.run - expect(@role.run_list_for("QA")[0]).to eq("role[owen]") - expect(@role.run_list_for("QA")[1]).to eq("role[mauntel]") + expect(@role.run_list_for("QA")[0]).to eq("role[owen]") + expect(@role.run_list_for("QA")[1]).to eq("role[mauntel]") expect(@role.run_list_for("QA")[2]).to be_nil expect(@role.run_list[0]).to be_nil end diff --git a/spec/unit/knife/role_from_file_spec.rb b/spec/unit/knife/role_from_file_spec.rb index 1660026b1a..056902f093 100644 --- a/spec/unit/knife/role_from_file_spec.rb +++ b/spec/unit/knife/role_from_file_spec.rb @@ -22,7 +22,7 @@ Chef::Knife::RoleFromFile.load_deps describe Chef::Knife::RoleFromFile do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::RoleFromFile.new @knife.config = { :print_after => nil @@ -65,5 +65,4 @@ describe Chef::Knife::RoleFromFile do @knife.run end end - end diff --git a/spec/unit/knife/role_list_spec.rb b/spec/unit/knife/role_list_spec.rb index daf2645aef..bfbba30288 100644 --- a/spec/unit/knife/role_list_spec.rb +++ b/spec/unit/knife/role_list_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::Knife::RoleList do before(:each) do - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::RoleList.new allow(@knife).to receive(:output).and_return(true) @list = { @@ -52,5 +52,3 @@ describe Chef::Knife::RoleList do end end end - - diff --git a/spec/unit/knife/role_run_list_add_spec.rb b/spec/unit/knife/role_run_list_add_spec.rb index ac5202da22..4f686ed755 100644 --- a/spec/unit/knife/role_run_list_add_spec.rb +++ b/spec/unit/knife/role_run_list_add_spec.rb @@ -7,9 +7,9 @@ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,13 +29,12 @@ describe Chef::Knife::RoleRunListAdd do } @knife.name_args = [ "will", "role[monkey]" ] allow(@knife).to receive(:output).and_return(true) - @role = Chef::Role.new() + @role = Chef::Role.new() allow(@role).to receive(:save).and_return(true) allow(Chef::Role).to receive(:load).and_return(@role) end describe "run" do - # it "should display all the things" do # @knife.run # @role.to_json.should == 'show all the things' @@ -162,7 +161,7 @@ describe Chef::Knife::RoleRunListAdd do expect(@role.run_list[2]).to be_nil end end - + describe "with more than one command" do it "should be able to the environment run list by running multiple knife commands" do @knife.name_args = [ "will", "role[blue]," ] @@ -174,6 +173,5 @@ describe Chef::Knife::RoleRunListAdd do expect(@role.run_list[2]).to be_nil end end - end end diff --git a/spec/unit/knife/role_run_list_clear_spec.rb b/spec/unit/knife/role_run_list_clear_spec.rb index 5e1a388c75..7559d73676 100644 --- a/spec/unit/knife/role_run_list_clear_spec.rb +++ b/spec/unit/knife/role_run_list_clear_spec.rb @@ -21,7 +21,7 @@ require "spec_helper" describe Chef::Knife::RoleRunListClear do before(:each) do - Chef::Config[:role_name] = "will" + Chef::Config[:role_name] = "will" @setup = Chef::Knife::RoleRunListAdd.new @setup.name_args = [ "will", "role[monkey]", "role[person]" ] @@ -38,14 +38,9 @@ describe Chef::Knife::RoleRunListClear do allow(@knife.ui).to receive(:confirm).and_return(true) allow(Chef::Role).to receive(:load).and_return(@role) - end - - describe "run" do - - # it "should display all the things" do # @knife.run # @role.to_json.should == 'show all the things' @@ -56,35 +51,32 @@ describe Chef::Knife::RoleRunListClear do @knife.run end - it "should remove the item from the run list" do - @setup.run - @knife.run - expect(@role.run_list[0]).to be_nil - end + it "should remove the item from the run list" do + @setup.run + @knife.run + expect(@role.run_list[0]).to be_nil + end - it "should save the node" do - expect(@role).to receive(:save).and_return(true) - @knife.run - end + it "should save the node" do + expect(@role).to receive(:save).and_return(true) + @knife.run + end - it "should print the run list" do - expect(@knife).to receive(:output).and_return(true) - @knife.config[:print_after] = true - @setup.run - @knife.run - end + it "should print the run list" do + expect(@knife).to receive(:output).and_return(true) + @knife.config[:print_after] = true + @setup.run + @knife.run + end - describe "should clear an environmental run list of roles and recipes" do - it "should remove the items from the run list" do - @setup.name_args = [ "will", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] - @setup.run - @knife.name_args = [ "will" ] - @knife.run - expect(@role.run_list[0]).to be_nil - end - end + describe "should clear an environmental run list of roles and recipes" do + it "should remove the items from the run list" do + @setup.name_args = [ "will", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] + @setup.run + @knife.name_args = [ "will" ] + @knife.run + expect(@role.run_list[0]).to be_nil + end + end end end - - - diff --git a/spec/unit/knife/role_run_list_remove_spec.rb b/spec/unit/knife/role_run_list_remove_spec.rb index f3cc38e616..ee792553cd 100644 --- a/spec/unit/knife/role_run_list_remove_spec.rb +++ b/spec/unit/knife/role_run_list_remove_spec.rb @@ -21,7 +21,7 @@ require "spec_helper" describe Chef::Knife::RoleRunListRemove do before(:each) do - Chef::Config[:role_name] = "will" + Chef::Config[:role_name] = "will" @setup = Chef::Knife::RoleRunListAdd.new @setup.name_args = [ "will", "role[monkey]", "role[person]" ] @@ -38,14 +38,9 @@ describe Chef::Knife::RoleRunListRemove do allow(@knife.ui).to receive(:confirm).and_return(true) allow(Chef::Role).to receive(:load).and_return(@role) - end - - describe "run" do - - # it "should display all the things" do # @knife.run # @role.to_json.should == 'show all the things' @@ -56,43 +51,40 @@ describe Chef::Knife::RoleRunListRemove do @knife.run end - it "should remove the item from the run list" do - @setup.run - @knife.run - expect(@role.run_list[0]).to eq("role[person]") - expect(@role.run_list[1]).to be_nil - end + it "should remove the item from the run list" do + @setup.run + @knife.run + expect(@role.run_list[0]).to eq("role[person]") + expect(@role.run_list[1]).to be_nil + end - it "should save the node" do - expect(@role).to receive(:save).and_return(true) - @knife.run - end + it "should save the node" do + expect(@role).to receive(:save).and_return(true) + @knife.run + end - it "should print the run list" do - expect(@knife).to receive(:output).and_return(true) - @knife.config[:print_after] = true - @setup.run - @knife.run - end + it "should print the run list" do + expect(@knife).to receive(:output).and_return(true) + @knife.config[:print_after] = true + @setup.run + @knife.run + end - describe "run with a list of roles and recipes" do - it "should remove the items from the run list" do - @setup.name_args = [ "will", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] - @setup.run - @knife.name_args = [ "will", "role[monkey]" ] - @knife.run - @knife.name_args = [ "will", "recipe[duck::type]" ] - @knife.run - expect(@role.run_list).not_to include("role[monkey]") - expect(@role.run_list).not_to include("recipe[duck::type]") - expect(@role.run_list[0]).to eq("recipe[orange::chicken]") - expect(@role.run_list[1]).to eq("role[person]") - expect(@role.run_list[2]).to eq("role[bird]") - expect(@role.run_list[3]).to eq("role[town]") - end - end + describe "run with a list of roles and recipes" do + it "should remove the items from the run list" do + @setup.name_args = [ "will", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] + @setup.run + @knife.name_args = [ "will", "role[monkey]" ] + @knife.run + @knife.name_args = [ "will", "recipe[duck::type]" ] + @knife.run + expect(@role.run_list).not_to include("role[monkey]") + expect(@role.run_list).not_to include("recipe[duck::type]") + expect(@role.run_list[0]).to eq("recipe[orange::chicken]") + expect(@role.run_list[1]).to eq("role[person]") + expect(@role.run_list[2]).to eq("role[bird]") + expect(@role.run_list[3]).to eq("role[town]") + end + end end end - - - diff --git a/spec/unit/knife/role_run_list_replace_spec.rb b/spec/unit/knife/role_run_list_replace_spec.rb index 74f648a372..dcf9007416 100644 --- a/spec/unit/knife/role_run_list_replace_spec.rb +++ b/spec/unit/knife/role_run_list_replace_spec.rb @@ -21,7 +21,7 @@ require "spec_helper" describe Chef::Knife::RoleRunListReplace do before(:each) do - Chef::Config[:role_name] = "will" + Chef::Config[:role_name] = "will" @setup = Chef::Knife::RoleRunListAdd.new @setup.name_args = [ "will", "role[monkey]", "role[dude]", "role[fixer]" ] @@ -38,14 +38,9 @@ describe Chef::Knife::RoleRunListReplace do allow(@knife.ui).to receive(:confirm).and_return(true) allow(Chef::Role).to receive(:load).and_return(@role) - end - - describe "run" do - - # it "should display all the things" do # @knife.run # @role.to_json.should == 'show all the things' @@ -56,46 +51,46 @@ describe Chef::Knife::RoleRunListReplace do @knife.run end - it "should remove the item from the run list" do - @setup.run - @knife.run - expect(@role.run_list[0]).to eq("role[monkey]") - expect(@role.run_list[1]).not_to eq("role[dude]") - expect(@role.run_list[1]).to eq("role[person]") - expect(@role.run_list[2]).to eq("role[fixer]") - expect(@role.run_list[3]).to be_nil - end + it "should remove the item from the run list" do + @setup.run + @knife.run + expect(@role.run_list[0]).to eq("role[monkey]") + expect(@role.run_list[1]).not_to eq("role[dude]") + expect(@role.run_list[1]).to eq("role[person]") + expect(@role.run_list[2]).to eq("role[fixer]") + expect(@role.run_list[3]).to be_nil + end - it "should save the node" do - expect(@role).to receive(:save).and_return(true) - @knife.run - end + it "should save the node" do + expect(@role).to receive(:save).and_return(true) + @knife.run + end - it "should print the run list" do - expect(@knife).to receive(:output).and_return(true) - @knife.config[:print_after] = true - @setup.run - @knife.run - end + it "should print the run list" do + expect(@knife).to receive(:output).and_return(true) + @knife.config[:print_after] = true + @setup.run + @knife.run + end - describe "run with a list of roles and recipes" do - it "should replace the items from the run list" do - @setup.name_args = [ "will", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] - @setup.run - @knife.name_args = [ "will", "role[monkey]", "role[gibbon]" ] - @knife.run - @knife.name_args = [ "will", "recipe[duck::type]", "recipe[duck::mallard]" ] - @knife.run - expect(@role.run_list).not_to include("role[monkey]") - expect(@role.run_list).not_to include("recipe[duck::type]") - expect(@role.run_list[0]).to eq("recipe[orange::chicken]") - expect(@role.run_list[1]).to eq("role[gibbon]") - expect(@role.run_list[2]).to eq("recipe[duck::mallard]") - expect(@role.run_list[3]).to eq("role[person]") - expect(@role.run_list[4]).to eq("role[bird]") - expect(@role.run_list[5]).to eq("role[town]") - expect(@role.run_list[6]).to be_nil - end - end + describe "run with a list of roles and recipes" do + it "should replace the items from the run list" do + @setup.name_args = [ "will", "recipe[orange::chicken]", "role[monkey]", "recipe[duck::type]", "role[person]", "role[bird]", "role[town]" ] + @setup.run + @knife.name_args = [ "will", "role[monkey]", "role[gibbon]" ] + @knife.run + @knife.name_args = [ "will", "recipe[duck::type]", "recipe[duck::mallard]" ] + @knife.run + expect(@role.run_list).not_to include("role[monkey]") + expect(@role.run_list).not_to include("recipe[duck::type]") + expect(@role.run_list[0]).to eq("recipe[orange::chicken]") + expect(@role.run_list[1]).to eq("role[gibbon]") + expect(@role.run_list[2]).to eq("recipe[duck::mallard]") + expect(@role.run_list[3]).to eq("role[person]") + expect(@role.run_list[4]).to eq("role[bird]") + expect(@role.run_list[5]).to eq("role[town]") + expect(@role.run_list[6]).to be_nil + end + end end end diff --git a/spec/unit/knife/role_run_list_set_spec.rb b/spec/unit/knife/role_run_list_set_spec.rb index 5207f631d4..8215be9dde 100644 --- a/spec/unit/knife/role_run_list_set_spec.rb +++ b/spec/unit/knife/role_run_list_set_spec.rb @@ -21,7 +21,7 @@ require "spec_helper" describe Chef::Knife::RoleRunListSet do before(:each) do - Chef::Config[:role_name] = "will" + Chef::Config[:role_name] = "will" @setup = Chef::Knife::RoleRunListAdd.new @setup.name_args = [ "will", "role[monkey]", "role[person]", "role[bucket]" ] @@ -38,14 +38,9 @@ describe Chef::Knife::RoleRunListSet do allow(@knife.ui).to receive(:confirm).and_return(true) allow(Chef::Role).to receive(:load).and_return(@role) - end - - describe "run" do - - # it "should display all the things" do # @knife.run # @role.to_json.should == 'show all the things' @@ -59,8 +54,8 @@ describe Chef::Knife::RoleRunListSet do it "should replace all the items in the runlist with what is specified" do @setup.run @knife.run - expect(@role.run_list[0]).to eq("role[owen]") - expect(@role.run_list[1]).to eq("role[mauntel]") + expect(@role.run_list[0]).to eq("role[owen]") + expect(@role.run_list[1]).to eq("role[mauntel]") expect(@role.run_list[2]).to be_nil end diff --git a/spec/unit/knife/role_show_spec.rb b/spec/unit/knife/role_show_spec.rb index 657c508f10..fe48e2f940 100644 --- a/spec/unit/knife/role_show_spec.rb +++ b/spec/unit/knife/role_show_spec.rb @@ -40,14 +40,14 @@ describe Chef::Knife::RoleShow do knife.config[:format] = "json" stdout = StringIO.new allow(knife.ui).to receive(:stdout).and_return(stdout) - fake_role_contents = {"foo"=>"bar", "baz"=>"qux"} + fake_role_contents = { "foo" => "bar", "baz" => "qux" } expect(Chef::Role).to receive(:load).with("base").and_return(fake_role_contents) knife.run expect(stdout.string).to eql("{\n \"foo\": \"bar\",\n \"baz\": \"qux\"\n}\n") end context "without a role name" do - let(:role) { } + let(:role) {} it "should print usage and exit when a role name is not provided" do expect(knife).to receive(:show_usage) diff --git a/spec/unit/knife/ssh_spec.rb b/spec/unit/knife/ssh_spec.rb index 5fed92ffa5..3a8728515d 100644 --- a/spec/unit/knife/ssh_spec.rb +++ b/spec/unit/knife/ssh_spec.rb @@ -114,10 +114,10 @@ describe Chef::Knife::Ssh do end it "should raise an error if no host are found" do - configure_query([ ]) - expect(@knife.ui).to receive(:fatal) - expect(@knife).to receive(:exit).with(10) - @knife.configure_session + configure_query([ ]) + expect(@knife.ui).to receive(:fatal) + expect(@knife).to receive(:exit).with(10) + @knife.configure_session end context "when there are some hosts found but they do not have an attribute to connect with" do @@ -170,26 +170,26 @@ describe Chef::Knife::Ssh do expect(@knife.get_ssh_attribute(@node_foo)).to eq("cloud.public_hostname") end - it "should favor to attribute_from_cli over config file and cloud" do + it "should favor to attribute_from_cli over config file and cloud" do @knife.config[:attribute] = "command_line" Chef::Config[:knife][:ssh_attribute] = "config_file" expect( @knife.get_ssh_attribute(@node_foo)).to eq("command_line") end - it "should favor config file over cloud and default" do + it "should favor config file over cloud and default" do Chef::Config[:knife][:ssh_attribute] = "config_file" expect( @knife.get_ssh_attribute(@node_foo)).to eq("config_file") end it "should return fqdn if cloud.hostname is empty" do - expect( @knife.get_ssh_attribute(@node_bar)).to eq("fqdn") + expect( @knife.get_ssh_attribute(@node_bar)).to eq("fqdn") end end describe "#session_from_list" do before :each do @knife.instance_variable_set(:@longest, 0) - ssh_config = {:timeout => 50, :user => "locutus", :port => 23 } + ssh_config = { :timeout => 50, :user => "locutus", :port => 23 } allow(Net::SSH).to receive(:configuration_for).with("the.b.org").and_return(ssh_config) end @@ -211,10 +211,10 @@ describe Chef::Knife::Ssh do describe "#ssh_command" do let(:execution_channel) { double(:execution_channel, :on_data => nil) } - let(:session_channel) { double(:session_channel, :request_pty => nil)} + let(:session_channel) { double(:session_channel, :request_pty => nil) } let(:execution_channel2) { double(:execution_channel, :on_data => nil) } - let(:session_channel2) { double(:session_channel, :request_pty => nil)} + let(:session_channel2) { double(:session_channel, :request_pty => nil) } let(:session) { double(:session, :loop => nil) } @@ -309,14 +309,14 @@ describe Chef::Knife::Ssh do context "when setting ssh_password_ng from knife ssh" do # in this case ssh_password_ng exists, but ssh_password does not - it "should prompt for a password when ssh_passsword_ng is nil" do + it "should prompt for a password when ssh_passsword_ng is nil" do @knife.config[:ssh_password_ng] = nil expect(@knife).to receive(:get_password).and_return("mysekretpassw0rd") @knife.configure_password expect(@knife.config[:ssh_password]).to eq("mysekretpassw0rd") end - it "should set ssh_password to false if ssh_password_ng is false" do + it "should set ssh_password to false if ssh_password_ng is false" do @knife.config[:ssh_password_ng] = false expect(@knife).not_to receive(:get_password) @knife.configure_password @@ -360,14 +360,14 @@ describe Chef::Knife::Ssh do end context "when setting ssh_password_ng from knife ssh" do # in this case ssh_password_ng exists, but ssh_password does not - it "should prompt for a password when ssh_passsword_ng is nil" do + it "should prompt for a password when ssh_passsword_ng is nil" do @knife.config[:ssh_password_ng] = nil expect(@knife).to receive(:get_password).and_return("mysekretpassw0rd") @knife.configure_password expect(@knife.config[:ssh_password]).to eq("mysekretpassw0rd") end - it "should set ssh_password to the configured knife.rb value if ssh_password_ng is false" do + it "should set ssh_password to the configured knife.rb value if ssh_password_ng is false" do @knife.config[:ssh_password_ng] = false expect(@knife).not_to receive(:get_password) @knife.configure_password diff --git a/spec/unit/knife/ssl_check_spec.rb b/spec/unit/knife/ssl_check_spec.rb index c7ca98d2dc..d2c33d3ab8 100644 --- a/spec/unit/knife/ssl_check_spec.rb +++ b/spec/unit/knife/ssl_check_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "stringio" describe Chef::Knife::SslCheck do - let(:name_args) { [] } let(:stdout_io) { StringIO.new } let(:stderr_io) { StringIO.new } @@ -62,15 +61,14 @@ describe Chef::Knife::SslCheck do end context "when an invalid URI is given" do - let(:name_args) { %w{foo.test} } it "prints an error and exits" do expect { ssl_check.run }.to raise_error(SystemExit) - expected_stdout=<<-E + expected_stdout = <<-E USAGE: knife ssl check [URL] (options) E - expected_stderr=<<-E + expected_stderr = <<-E ERROR: Given URI: `foo.test' is invalid E expect(stdout_io.string).to eq(expected_stdout) @@ -78,15 +76,14 @@ E end context "and its malformed enough to make URI.parse barf" do - let(:name_args) { %w{ftp://lkj\\blah:example.com/blah} } it "prints an error and exits" do expect { ssl_check.run }.to raise_error(SystemExit) - expected_stdout=<<-E + expected_stdout = <<-E USAGE: knife ssl check [URL] (options) E - expected_stderr=<<-E + expected_stderr = <<-E ERROR: Given URI: `#{name_args[0]}' is invalid E expect(stdout_io.string).to eq(expected_stdout) @@ -158,7 +155,6 @@ E end context "when the remote host's certificate is valid" do - before do expect(ssl_check).to receive(:verify_X509).and_return(true) # X509 valid certs (no warn) expect(ssl_socket).to receive(:connect) # no error @@ -173,7 +169,6 @@ E end describe "and the certificate is not valid" do - let(:tcp_socket_for_debug) { double(TCPSocket) } let(:ssl_socket_for_debug) { double(OpenSSL::SSL::SSLSocket) } @@ -213,7 +208,6 @@ E expect(stderr).to include("You are attempting to connect to: 'foo.example.com'") expect(stderr).to include("The server's certificate belongs to 'example.local'") end - end context "when the cert is not signed by any trusted authority" do @@ -231,10 +225,7 @@ E expect { run }.to raise_error(SystemExit) expect(stderr).to include("The SSL certificate of foo.example.com could not be verified") end - end end - end - end diff --git a/spec/unit/knife/ssl_fetch_spec.rb b/spec/unit/knife/ssl_fetch_spec.rb index 4f31285fca..355df9e35a 100644 --- a/spec/unit/knife/ssl_fetch_spec.rb +++ b/spec/unit/knife/ssl_fetch_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "chef/knife/ssl_fetch" describe Chef::Knife::SslFetch do - let(:name_args) { [] } let(:stdout_io) { StringIO.new } let(:stderr_io) { StringIO.new } @@ -42,7 +41,6 @@ describe Chef::Knife::SslFetch do end context "when no arguments are given" do - before do Chef::Config.chef_server_url = "https://example.com:8443/chef-server" end @@ -63,15 +61,14 @@ describe Chef::Knife::SslFetch do end context "when an invalid URI is given" do - let(:name_args) { %w{foo.test} } it "prints an error and exits" do expect { ssl_fetch.run }.to raise_error(SystemExit) - expected_stdout=<<-E + expected_stdout = <<-E USAGE: knife ssl fetch [URL] (options) E - expected_stderr=<<-E + expected_stderr = <<-E ERROR: Given URI: `foo.test' is invalid E expect(stdout_io.string).to eq(expected_stdout) @@ -79,15 +76,14 @@ E end context "and its malformed enough to make URI.parse barf" do - let(:name_args) { %w{ftp://lkj\\blah:example.com/blah} } it "prints an error and exits" do expect { ssl_fetch.run }.to raise_error(SystemExit) - expected_stdout=<<-E + expected_stdout = <<-E USAGE: knife ssl fetch [URL] (options) E - expected_stderr=<<-E + expected_stderr = <<-E ERROR: Given URI: `#{name_args[0]}' is invalid E expect(stdout_io.string).to eq(expected_stdout) @@ -97,7 +93,6 @@ E end describe "normalizing CNs for use as paths" do - it "normalizes '*' to 'wildcard'" do expect(ssl_fetch.normalize_cn("*.example.com")).to eq("wildcard_example_com") end @@ -105,11 +100,9 @@ E it "normalizes non-alnum and hyphen characters to underscores" do expect(ssl_fetch.normalize_cn("Billy-Bob's Super Awesome CA!")).to eq("Billy-Bob_s_Super_Awesome_CA_") end - end describe "fetching the remote cert chain" do - let(:name_args) { %w{https://foo.example.com:8443} } let(:tcp_socket) { double(TCPSocket) } @@ -137,7 +130,6 @@ E end context "when the TLS connection is successful" do - before do expect(ssl_fetch).to receive(:proxified_socket).with("foo.example.com", 8443).and_return(tcp_socket) expect(OpenSSL::SSL::SSLSocket).to receive(:new).with(tcp_socket, ssl_fetch.noverify_peer_ssl_context).and_return(ssl_socket) @@ -151,11 +143,9 @@ E expect(File).to exist(stored_cert_path) expect(File.read(stored_cert_path)).to eq(File.read(self_signed_crt_path)) end - end context "when connecting to a non-SSL service (like HTTP)" do - let(:name_args) { %w{http://foo.example.com} } let(:unknown_protocol_error) { OpenSSL::SSL::SSLError.new("SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: unknown protocol") } @@ -177,8 +167,6 @@ ERROR_TEXT run expect(stderr).to include(expected_error_text) end - end - end end diff --git a/spec/unit/knife/status_spec.rb b/spec/unit/knife/status_spec.rb index 536a5c317a..473598fd85 100644 --- a/spec/unit/knife/status_spec.rb +++ b/spec/unit/knife/status_spec.rb @@ -34,10 +34,10 @@ describe Chef::Knife::Status do end describe "run" do - let(:opts) {{filter_result: + let(:opts) {{ filter_result: { name: ["name"], ipaddress: ["ipaddress"], ohai_time: ["ohai_time"], - ec2: ["ec2"], run_list: ["run_list"], platform: ["platform"], - platform_version: ["platform_version"], chef_environment: ["chef_environment"]}}} + ec2: ["ec2"], run_list: ["run_list"], platform: ["platform"], + platform_version: ["platform_version"], chef_environment: ["chef_environment"] } }} it "should default to searching for everything" do expect(@query).to receive(:search).with(:node, "*:*", opts) diff --git a/spec/unit/knife/user_create_spec.rb b/spec/unit/knife/user_create_spec.rb index 7983df8b41..ce4286a186 100644 --- a/spec/unit/knife/user_create_spec.rb +++ b/spec/unit/knife/user_create_spec.rb @@ -47,14 +47,13 @@ describe Chef::Knife::UserCreate do it "displays the osc warning" do expect(knife.ui).to receive(:warn).with(knife.osc_11_warning) - expect{ knife.run }.to raise_error(SystemExit) + expect { knife.run }.to raise_error(SystemExit) end it "calls knife osc_user create" do expect(knife).to receive(:run_osc_11_user_create) - expect{ knife.run }.to raise_error(SystemExit) + expect { knife.run }.to raise_error(SystemExit) end - end context "when USERNAME isn't specified" do @@ -186,7 +185,7 @@ describe Chef::Knife::UserCreate do context "when a private_key is returned" do before do - allow(knife).to receive(:create_user_from_hash).and_return(Chef::UserV1.from_hash(knife.user.to_hash.merge({"private_key" => "some_private_key"}))) + allow(knife).to receive(:create_user_from_hash).and_return(Chef::UserV1.from_hash(knife.user.to_hash.merge({ "private_key" => "some_private_key" }))) end context "when --file is passed" do @@ -209,6 +208,5 @@ describe Chef::Knife::UserCreate do end end end - end # when all mandatory fields are validly specified end diff --git a/spec/unit/knife/user_delete_spec.rb b/spec/unit/knife/user_delete_spec.rb index de37797d3c..0f71b39a41 100644 --- a/spec/unit/knife/user_delete_spec.rb +++ b/spec/unit/knife/user_delete_spec.rb @@ -41,12 +41,12 @@ describe Chef::Knife::UserDelete do it "displays the osc warning" do expect(knife.ui).to receive(:warn).with(knife.osc_11_warning) - expect{ knife.run }.to raise_error(SystemExit) + expect { knife.run }.to raise_error(SystemExit) end it "forwards the command to knife osc_user edit" do expect(knife).to receive(:run_osc_11_user_delete) - expect{ knife.run }.to raise_error(SystemExit) + expect { knife.run }.to raise_error(SystemExit) end end diff --git a/spec/unit/knife/user_edit_spec.rb b/spec/unit/knife/user_edit_spec.rb index d7db1aac29..ec118ed181 100644 --- a/spec/unit/knife/user_edit_spec.rb +++ b/spec/unit/knife/user_edit_spec.rb @@ -36,17 +36,17 @@ describe Chef::Knife::UserEdit do context "when the username field is not supported by the server" do before do allow(knife).to receive(:run_osc_11_user_edit).and_raise(SystemExit) - allow(Chef::UserV1).to receive(:load).and_return({"username" => nil}) + allow(Chef::UserV1).to receive(:load).and_return({ "username" => nil }) end it "displays the osc warning" do expect(knife.ui).to receive(:warn).with(knife.osc_11_warning) - expect{ knife.run }.to raise_error(SystemExit) + expect { knife.run }.to raise_error(SystemExit) end it "forwards the command to knife osc_user edit" do expect(knife).to receive(:run_osc_11_user_edit) - expect{ knife.run }.to raise_error(SystemExit) + expect { knife.run }.to raise_error(SystemExit) end end diff --git a/spec/unit/knife/user_reregister_spec.rb b/spec/unit/knife/user_reregister_spec.rb index cc85578bf6..d650ff9fb8 100644 --- a/spec/unit/knife/user_reregister_spec.rb +++ b/spec/unit/knife/user_reregister_spec.rb @@ -41,12 +41,12 @@ describe Chef::Knife::UserReregister do it "displays the osc warning" do expect(knife.ui).to receive(:warn).with(knife.osc_11_warning) - expect{ knife.run }.to raise_error(SystemExit) + expect { knife.run }.to raise_error(SystemExit) end it "forwards the command to knife osc_user edit" do expect(knife).to receive(:run_osc_11_user_reregister) - expect{ knife.run }.to raise_error(SystemExit) + expect { knife.run }.to raise_error(SystemExit) end end diff --git a/spec/unit/knife/user_show_spec.rb b/spec/unit/knife/user_show_spec.rb index b82e3e2640..3a38161b34 100644 --- a/spec/unit/knife/user_show_spec.rb +++ b/spec/unit/knife/user_show_spec.rb @@ -41,12 +41,12 @@ describe Chef::Knife::UserShow do it "displays the osc warning" do expect(knife.ui).to receive(:warn).with(knife.osc_11_warning) - expect{ knife.run }.to raise_error(SystemExit) + expect { knife.run }.to raise_error(SystemExit) end it "forwards the command to knife osc_user edit" do expect(knife).to receive(:run_osc_11_user_show) - expect{ knife.run }.to raise_error(SystemExit) + expect { knife.run }.to raise_error(SystemExit) end end diff --git a/spec/unit/knife_spec.rb b/spec/unit/knife_spec.rb index 62c1b4c4eb..ff03ae2794 100644 --- a/spec/unit/knife_spec.rb +++ b/spec/unit/knife_spec.rb @@ -25,7 +25,6 @@ require "spec_helper" require "uri" describe Chef::Knife do - let(:stderr) { StringIO.new } let(:knife) { Chef::Knife.new } @@ -42,7 +41,7 @@ describe Chef::Knife do before(:each) do Chef::Log.logger = Logger.new(StringIO.new) - Chef::Config[:node_name] = "webmonkey.example.com" + Chef::Config[:node_name] = "webmonkey.example.com" allow(Chef::WorkstationConfigLoader).to receive(:new).and_return(config_loader) allow(config_loader).to receive(:explicit_config_file=) @@ -147,19 +146,17 @@ describe Chef::Knife do Chef::Knife.subcommands["cookbook"] = :Cookbook expect(Chef::Knife.subcommand_class_from(%w{cookbook site vendor --help foo bar baz})).to eq(:CookbookSiteVendor) end - end describe "the headers include X-Remote-Request-Id" do - - let(:headers) {{"Accept"=>"application/json", - "Accept-Encoding"=>"gzip;q=1.0,deflate;q=0.6,identity;q=0.3", - "X-Chef-Version" => Chef::VERSION, - "Host"=>"api.opscode.piab", - "X-REMOTE-REQUEST-ID"=>request_id, + let(:headers) {{ "Accept" => "application/json", + "Accept-Encoding" => "gzip;q=1.0,deflate;q=0.6,identity;q=0.3", + "X-Chef-Version" => Chef::VERSION, + "Host" => "api.opscode.piab", + "X-REMOTE-REQUEST-ID" => request_id, }} - let(:request_id) {"1234"} + let(:request_id) { "1234" } let(:request_mock) { {} } @@ -216,10 +213,10 @@ describe Chef::Knife do it "merges the global knife CLI options" do extra_opts = {} - extra_opts[:editor] = {:long=>"--editor EDITOR", - :description=>"Set the editor to use for interactive commands", - :short=>"-e EDITOR", - :default=>"/usr/bin/vim"} + extra_opts[:editor] = { :long => "--editor EDITOR", + :description => "Set the editor to use for interactive commands", + :short => "-e EDITOR", + :default => "/usr/bin/vim" } # there is special hackery to return the subcommand instance going on here. command = Chef::Knife.run(%w{test yourself}, extra_opts) @@ -252,7 +249,7 @@ describe Chef::Knife do allow(Chef::Knife.ui).to receive(:stderr).and_return(stderr) allow(Chef::Knife.ui).to receive(:stdout).and_return(stdout) expect(Chef::Knife.ui).to receive(:fatal) - expect {Chef::Knife.run(%w{fuuu uuuu fuuuu})}.to raise_error(SystemExit) { |e| expect(e.status).not_to eq(0) } + expect { Chef::Knife.run(%w{fuuu uuuu fuuuu}) }.to raise_error(SystemExit) { |e| expect(e.status).not_to eq(0) } end it "loads lazy dependencies" do @@ -344,7 +341,6 @@ describe Chef::Knife do end describe "when first created" do - let(:knife) { KnifeSpecs::TestYourself.new(%w{with some args -s scrogramming}) } before do @@ -367,7 +363,6 @@ describe Chef::Knife do end describe "when formatting exceptions" do - let(:stdout) { StringIO.new } let(:stderr) { StringIO.new } let(:stdin) { StringIO.new } @@ -508,7 +503,7 @@ describe Chef::Knife do knife.run_with_pretty_exceptions - expected_message=<<-MSG + expected_message = <<-MSG ERROR: Could not establish a secure connection to the server. Use `knife ssl check` to troubleshoot your SSL configuration. If your Chef Server uses a self-signed certificate, you can use @@ -516,7 +511,5 @@ If your Chef Server uses a self-signed certificate, you can use MSG expect(stderr.string).to include(expected_message) end - end - end diff --git a/spec/unit/log/winevt_spec.rb b/spec/unit/log/winevt_spec.rb index 288962863c..71a4558535 100644 --- a/spec/unit/log/winevt_spec.rb +++ b/spec/unit/log/winevt_spec.rb @@ -20,12 +20,11 @@ require "spec_helper" describe Chef::Log::WinEvt do - let(:evtlog) { instance_double("Win32::EventLog")} + let(:evtlog) { instance_double("Win32::EventLog") } let(:winevt) { Chef::Log::WinEvt.new(evtlog) } let(:app) { Chef::Application.new } before do - Chef::Log.init(MonoLogger.new(winevt)) @old_log_level = Chef::Log.level Chef::Log.level = :info diff --git a/spec/unit/lwrp_spec.rb b/spec/unit/lwrp_spec.rb index e18ab135a5..5a3b71db33 100644 --- a/spec/unit/lwrp_spec.rb +++ b/spec/unit/lwrp_spec.rb @@ -119,7 +119,6 @@ describe "LWRP" do # The test is that this should not raise an error: Chef::Resource::LWRPBase.build_from_file("lwrp_const_scoping", conflicting_lwrp_file, nil) end - end context "When an LWRP resource in cookbook l-w-r-p is loaded" do @@ -170,7 +169,6 @@ describe "LWRP" do end describe "Lightweight Chef::Resource" do - before do Dir[File.expand_path(File.join(File.dirname(__FILE__), "..", "data", "lwrp", "resources", "*"))].each do |file| Chef::Resource::LWRPBase.build_from_file("lwrp", file, nil) @@ -202,7 +200,7 @@ describe "LWRP" do end it "should create a method for each attribute" do - expect(get_lwrp(:lwrp_foo).new("blah").methods.map{ |m| m.to_sym}).to include(:monkey) + expect(get_lwrp(:lwrp_foo).new("blah").methods.map { |m| m.to_sym }).to include(:monkey) end it "should build attribute methods that respect validation rules" do @@ -246,8 +244,8 @@ describe "LWRP" do let(:klass) do Class.new(Chef::Resource::LWRPBase) do self.resource_name = :sample_resource - attribute :food, :default => lazy { "BACON!"*3 } - attribute :drink, :default => lazy { |r| "Drink after #{r.food}!"} + attribute :food, :default => lazy { "BACON!" * 3 } + attribute :drink, :default => lazy { |r| "Drink after #{r.food}!" } end end @@ -379,7 +377,6 @@ describe "LWRP" do end describe "Lightweight Chef::Provider" do - let(:node) do Chef::Node.new.tap do |n| n.automatic[:platform] = :ubuntu @@ -447,7 +444,6 @@ describe "LWRP" do end context "with a cookbook with an underscore in the name" do - let(:lwrp_cookbok_name) { "l_w_r_p" } it "sets itself as a provider for a resource of the same name" do @@ -458,7 +454,6 @@ describe "LWRP" do end context "with a cookbook with a hypen in the name" do - let(:lwrp_cookbok_name) { "l-w-r-p" } it "sets itself as a provider for a resource of the same name" do @@ -577,7 +572,6 @@ describe "LWRP" do expect(@resource).not_to be_updated_by_last_action end end - end end @@ -718,5 +712,3 @@ describe "LWRP" do end end end - - diff --git a/spec/unit/mash_spec.rb b/spec/unit/mash_spec.rb index 838aabbd73..e58f6b85a1 100644 --- a/spec/unit/mash_spec.rb +++ b/spec/unit/mash_spec.rb @@ -21,7 +21,7 @@ require "chef/mash" describe Mash do it "should duplicate a simple key/value mash to a new mash" do - data = {:x=>"one", :y=>"two", :z=>"three"} + data = { :x => "one", :y => "two", :z => "three" } @orig = Mash.new(data) @copy = @orig.dup expect(@copy.to_hash).to eq(Mash.new(data).to_hash) @@ -30,21 +30,21 @@ describe Mash do end it "should duplicate a mash with an array to a new mash" do - data = {:x=>"one", :y=>"two", :z=>[1,2,3]} + data = { :x => "one", :y => "two", :z => [1, 2, 3] } @orig = Mash.new(data) @copy = @orig.dup expect(@copy.to_hash).to eq(Mash.new(data).to_hash) @copy[:z] << 4 - expect(@orig[:z]).to eq([1,2,3]) + expect(@orig[:z]).to eq([1, 2, 3]) end it "should duplicate a nested mash to a new mash" do - data = {:x=>"one", :y=>"two", :z=>Mash.new({:a=>[1,2,3]})} + data = { :x => "one", :y => "two", :z => Mash.new({ :a => [1, 2, 3] }) } @orig = Mash.new(data) @copy = @orig.dup expect(@copy.to_hash).to eq(Mash.new(data).to_hash) @copy[:z][:a] << 4 - expect(@orig[:z][:a]).to eq([1,2,3]) + expect(@orig[:z][:a]).to eq([1, 2, 3]) end # add more! diff --git a/spec/unit/mixin/api_version_request_handling_spec.rb b/spec/unit/mixin/api_version_request_handling_spec.rb index 0768072814..c569c54039 100644 --- a/spec/unit/mixin/api_version_request_handling_spec.rb +++ b/spec/unit/mixin/api_version_request_handling_spec.rb @@ -23,8 +23,7 @@ describe Chef::Mixin::ApiVersionRequestHandling do let(:object) { dummy_class.new } describe ".server_client_api_version_intersection" do - let(:default_supported_client_versions) { [0,1,2] } - + let(:default_supported_client_versions) { [0, 1, 2] } context "when the response code is not 406" do let(:response) { OpenStruct.new(:code => "405") } @@ -34,7 +33,6 @@ describe Chef::Mixin::ApiVersionRequestHandling do expect(object.server_client_api_version_intersection(exception, default_supported_client_versions)). to be_nil end - end # when the response code is not 406 context "when the response code is 406" do @@ -73,35 +71,33 @@ describe Chef::Mixin::ApiVersionRequestHandling do expect(object.server_client_api_version_intersection(exception, supported_client_versions).length). to eq(0) end - end context "when all the versions are higher than the max" do it_should_behave_like "no intersection between client and server versions" do - let(:supported_client_versions) { [5,6,7] } + let(:supported_client_versions) { [5, 6, 7] } end end context "when all the versions are lower than the min" do it_should_behave_like "no intersection between client and server versions" do - let(:supported_client_versions) { [0,1] } + let(:supported_client_versions) { [0, 1] } end end - end # when there is no intersection between client and server versions context "when there is an intersection between client and server versions" do context "when multiple versions intersect" do - let(:supported_client_versions) { [1,2,3,4,5] } + let(:supported_client_versions) { [1, 2, 3, 4, 5] } it "includes all of the intersection" do expect(object.server_client_api_version_intersection(exception, supported_client_versions)). - to eq([2,3,4]) + to eq([2, 3, 4]) end end # when multiple versions intersect context "when only the min client version intersects" do - let(:supported_client_versions) { [0,1,2] } + let(:supported_client_versions) { [0, 1, 2] } it "includes the intersection" do expect(object.server_client_api_version_intersection(exception, supported_client_versions)). @@ -110,18 +106,15 @@ describe Chef::Mixin::ApiVersionRequestHandling do end # when only the min client version intersects context "when only the max client version intersects" do - let(:supported_client_versions) { [4,5,6] } + let(:supported_client_versions) { [4, 5, 6] } it "includes the intersection" do expect(object.server_client_api_version_intersection(exception, supported_client_versions)). to eq([4]) end end # when only the max client version intersects - end # when there is an intersection between client and server versions - end # when x-ops-server-api-version header exists end # when the response code is 406 - end # .server_client_api_version_intersection end # Chef::Mixin::ApiVersionRequestHandling diff --git a/spec/unit/mixin/checksum_spec.rb b/spec/unit/mixin/checksum_spec.rb index 8b8284a867..81b76f0fda 100644 --- a/spec/unit/mixin/checksum_spec.rb +++ b/spec/unit/mixin/checksum_spec.rb @@ -36,6 +36,4 @@ describe Chef::Mixin::Checksum do it "gets the checksum of a file" do expect(@checksum_user.checksum(@file)).to eq("09ee9c8cc70501763563bcf9c218d71b2fbf4186bf8e1e0da07f0f42c80a3394") end - end - diff --git a/spec/unit/mixin/command_spec.rb b/spec/unit/mixin/command_spec.rb index dfe7b148ec..36e39b6139 100644 --- a/spec/unit/mixin/command_spec.rb +++ b/spec/unit/mixin/command_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Mixin::Command, :volatile do - if windows? skip("TODO MOVE: this is a platform specific integration test.") @@ -43,32 +42,29 @@ describe Chef::Mixin::Command, :volatile do end it "should respect locale when specified explicitly" do - popen4("echo $LC_ALL", :environment => {"LC_ALL" => "es"}) do |pid, stdin, stdout, stderr| + popen4("echo $LC_ALL", :environment => { "LC_ALL" => "es" }) do |pid, stdin, stdout, stderr| expect(stdout.read.strip).to eq("es") end end it "should end when the child process reads from STDIN and a block is given" do expect {Timeout.timeout(10) do - popen4("ruby -e 'while gets; end'", :waitlast => true) do |pid, stdin, stdout, stderr| - (1..5).each { |i| stdin.puts "#{i}" } - end + popen4("ruby -e 'while gets; end'", :waitlast => true) do |pid, stdin, stdout, stderr| + (1..5).each { |i| stdin.puts "#{i}" } + end end }.not_to raise_error end describe "when a process detaches but doesn't close STDOUT and STDERR [CHEF-584]" do - it "returns immediately after the first child process exits" do expect {Timeout.timeout(10) do - evil_forker="exit if fork; 10.times { sleep 1}" - popen4("ruby -e '#{evil_forker}'") do |pid,stdin,stdout,stderr| + evil_forker = "exit if fork; 10.times { sleep 1}" + popen4("ruby -e '#{evil_forker}'") do |pid, stdin, stdout, stderr| end end}.not_to raise_error end - end - end describe "run_command" do @@ -93,11 +89,10 @@ describe Chef::Mixin::Command, :volatile do # Serdar - During Solaris tests, we've seen that processes # are taking a long time to exit. Bumping timeout now to 10. expect {Timeout.timeout(10) do - evil_forker="exit if fork; 10.times { sleep 1}" + evil_forker = "exit if fork; 10.times { sleep 1}" run_command(:command => "ruby -e '#{evil_forker}'") end}.not_to raise_error end - end end end diff --git a/spec/unit/mixin/convert_to_class_name_spec.rb b/spec/unit/mixin/convert_to_class_name_spec.rb index 27c9ac651a..d3c5305f5d 100644 --- a/spec/unit/mixin/convert_to_class_name_spec.rb +++ b/spec/unit/mixin/convert_to_class_name_spec.rb @@ -23,7 +23,6 @@ class ConvertToClassTestHarness end describe Chef::Mixin::ConvertToClassName do - before do @convert = ConvertToClassTestHarness.new end diff --git a/spec/unit/mixin/deep_merge_spec.rb b/spec/unit/mixin/deep_merge_spec.rb index 6ce9a1cb2d..be11f0cad4 100644 --- a/spec/unit/mixin/deep_merge_spec.rb +++ b/spec/unit/mixin/deep_merge_spec.rb @@ -34,14 +34,14 @@ describe Chef::Mixin::DeepMerge, "deep_merge!" do # deep_merge core tests - moving from basic to more complex it "tests merging an hash w/array into blank hash" do - hash_src = {"id" => "2"} + hash_src = { "id" => "2" } hash_dst = {} @dm.deep_merge!(hash_src.dup, hash_dst) expect(hash_dst).to eq(hash_src) end it "tests merging an hash w/array into blank hash" do - hash_src = {"region" => {"id" => ["227", "2"]}} + hash_src = { "region" => { "id" => ["227", "2"] } } hash_dst = {} @dm.deep_merge!(hash_src, hash_dst) expect(hash_dst).to eq(hash_src) @@ -49,192 +49,192 @@ describe Chef::Mixin::DeepMerge, "deep_merge!" do it "tests merge from empty hash" do hash_src = {} - hash_dst = {"property" => ["2","4"]} + hash_dst = { "property" => ["2", "4"] } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => ["2","4"]}) + expect(hash_dst).to eq({ "property" => ["2", "4"] }) end it "tests merge to empty hash" do - hash_src = {"property" => ["2","4"]} + hash_src = { "property" => ["2", "4"] } hash_dst = {} @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => ["2","4"]}) + expect(hash_dst).to eq({ "property" => ["2", "4"] }) end it "tests simple string overwrite" do - hash_src = {"name" => "value"} - hash_dst = {"name" => "value1"} + hash_src = { "name" => "value" } + hash_dst = { "name" => "value1" } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"name" => "value"}) + expect(hash_dst).to eq({ "name" => "value" }) end it "tests simple string overwrite of empty hash" do - hash_src = {"name" => "value"} + hash_src = { "name" => "value" } hash_dst = {} @dm.deep_merge!(hash_src, hash_dst) expect(hash_dst).to eq(hash_src) end it "tests hashes holding array" do - hash_src = {"property" => ["1","3"]} - hash_dst = {"property" => ["2","4"]} + hash_src = { "property" => ["1", "3"] } + hash_dst = { "property" => ["2", "4"] } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => ["2","4","1","3"]}) + expect(hash_dst).to eq({ "property" => ["2", "4", "1", "3"] }) end it "tests hashes holding hashes holding arrays (array with duplicate elements is merged with dest then src" do - hash_src = {"property" => {"bedroom_count" => ["1", "2"], "bathroom_count" => ["1", "4+"]}} - hash_dst = {"property" => {"bedroom_count" => ["3", "2"], "bathroom_count" => ["2"]}} + hash_src = { "property" => { "bedroom_count" => ["1", "2"], "bathroom_count" => ["1", "4+"] } } + hash_dst = { "property" => { "bedroom_count" => ["3", "2"], "bathroom_count" => ["2"] } } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => {"bedroom_count" => ["3","2","1"], "bathroom_count" => ["2", "1", "4+"]}}) + expect(hash_dst).to eq({ "property" => { "bedroom_count" => ["3", "2", "1"], "bathroom_count" => ["2", "1", "4+"] } }) end it "tests hash holding hash holding array v string (string is overwritten by array)" do - hash_src = {"property" => {"bedroom_count" => ["1", "2"], "bathroom_count" => ["1", "4+"]}} - hash_dst = {"property" => {"bedroom_count" => "3", "bathroom_count" => ["2"]}} + hash_src = { "property" => { "bedroom_count" => ["1", "2"], "bathroom_count" => ["1", "4+"] } } + hash_dst = { "property" => { "bedroom_count" => "3", "bathroom_count" => ["2"] } } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => {"bedroom_count" => ["1", "2"], "bathroom_count" => ["2","1","4+"]}}) + expect(hash_dst).to eq({ "property" => { "bedroom_count" => ["1", "2"], "bathroom_count" => ["2", "1", "4+"] } }) end it "tests hash holding hash holding string v array (array is overwritten by string)" do - hash_src = {"property" => {"bedroom_count" => "3", "bathroom_count" => ["1", "4+"]}} - hash_dst = {"property" => {"bedroom_count" => ["1", "2"], "bathroom_count" => ["2"]}} + hash_src = { "property" => { "bedroom_count" => "3", "bathroom_count" => ["1", "4+"] } } + hash_dst = { "property" => { "bedroom_count" => ["1", "2"], "bathroom_count" => ["2"] } } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => {"bedroom_count" => "3", "bathroom_count" => ["2","1","4+"]}}) + expect(hash_dst).to eq({ "property" => { "bedroom_count" => "3", "bathroom_count" => ["2", "1", "4+"] } }) end it "tests hash holding hash holding hash v array (array is overwritten by hash)" do - hash_src = {"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => 1}, "bathroom_count" => ["1", "4+"]}} - hash_dst = {"property" => {"bedroom_count" => ["1", "2"], "bathroom_count" => ["2"]}} + hash_src = { "property" => { "bedroom_count" => { "king_bed" => 3, "queen_bed" => 1 }, "bathroom_count" => ["1", "4+"] } } + hash_dst = { "property" => { "bedroom_count" => ["1", "2"], "bathroom_count" => ["2"] } } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => 1}, "bathroom_count" => ["2","1","4+"]}}) + expect(hash_dst).to eq({ "property" => { "bedroom_count" => { "king_bed" => 3, "queen_bed" => 1 }, "bathroom_count" => ["2", "1", "4+"] } }) end it "tests 3 hash layers holding integers (integers are overwritten by source)" do - hash_src = {"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => 1}, "bathroom_count" => ["1", "4+"]}} - hash_dst = {"property" => {"bedroom_count" => {"king_bed" => 2, "queen_bed" => 4}, "bathroom_count" => ["2"]}} + hash_src = { "property" => { "bedroom_count" => { "king_bed" => 3, "queen_bed" => 1 }, "bathroom_count" => ["1", "4+"] } } + hash_dst = { "property" => { "bedroom_count" => { "king_bed" => 2, "queen_bed" => 4 }, "bathroom_count" => ["2"] } } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => 1}, "bathroom_count" => ["2","1","4+"]}}) + expect(hash_dst).to eq({ "property" => { "bedroom_count" => { "king_bed" => 3, "queen_bed" => 1 }, "bathroom_count" => ["2", "1", "4+"] } }) end it "tests 3 hash layers holding arrays of int (arrays are merged)" do - hash_src = {"property" => {"bedroom_count" => {"king_bed" => [3], "queen_bed" => [1]}, "bathroom_count" => ["1", "4+"]}} - hash_dst = {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} + hash_src = { "property" => { "bedroom_count" => { "king_bed" => [3], "queen_bed" => [1] }, "bathroom_count" => ["1", "4+"] } } + hash_dst = { "property" => { "bedroom_count" => { "king_bed" => [2], "queen_bed" => [4] }, "bathroom_count" => ["2"] } } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => {"bedroom_count" => {"king_bed" => [2,3], "queen_bed" => [4,1]}, "bathroom_count" => ["2","1","4+"]}}) + expect(hash_dst).to eq({ "property" => { "bedroom_count" => { "king_bed" => [2, 3], "queen_bed" => [4, 1] }, "bathroom_count" => ["2", "1", "4+"] } }) end it "tests 1 hash overwriting 3 hash layers holding arrays of int" do - hash_src = {"property" => "1"} - hash_dst = {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} + hash_src = { "property" => "1" } + hash_dst = { "property" => { "bedroom_count" => { "king_bed" => [2], "queen_bed" => [4] }, "bathroom_count" => ["2"] } } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => "1"}) + expect(hash_dst).to eq({ "property" => "1" }) end it "tests 3 hash layers holding arrays of int (arrays are merged) but second hash's array is overwritten" do - hash_src = {"property" => {"bedroom_count" => {"king_bed" => [3], "queen_bed" => [1]}, "bathroom_count" => "1"}} - hash_dst = {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} + hash_src = { "property" => { "bedroom_count" => { "king_bed" => [3], "queen_bed" => [1] }, "bathroom_count" => "1" } } + hash_dst = { "property" => { "bedroom_count" => { "king_bed" => [2], "queen_bed" => [4] }, "bathroom_count" => ["2"] } } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => {"bedroom_count" => {"king_bed" => [2,3], "queen_bed" => [4,1]}, "bathroom_count" => "1"}}) + expect(hash_dst).to eq({ "property" => { "bedroom_count" => { "king_bed" => [2, 3], "queen_bed" => [4, 1] }, "bathroom_count" => "1" } }) end it "tests 3 hash layers holding arrays of int, but one holds int. This one overwrites, but the rest merge" do - hash_src = {"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => [1]}, "bathroom_count" => ["1"]}} - hash_dst = {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} + hash_src = { "property" => { "bedroom_count" => { "king_bed" => 3, "queen_bed" => [1] }, "bathroom_count" => ["1"] } } + hash_dst = { "property" => { "bedroom_count" => { "king_bed" => [2], "queen_bed" => [4] }, "bathroom_count" => ["2"] } } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => [4,1]}, "bathroom_count" => ["2","1"]}}) + expect(hash_dst).to eq({ "property" => { "bedroom_count" => { "king_bed" => 3, "queen_bed" => [4, 1] }, "bathroom_count" => ["2", "1"] } }) end it "tests 3 hash layers holding arrays of int, but source is incomplete." do - hash_src = {"property" => {"bedroom_count" => {"king_bed" => [3]}, "bathroom_count" => ["1"]}} - hash_dst = {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} + hash_src = { "property" => { "bedroom_count" => { "king_bed" => [3] }, "bathroom_count" => ["1"] } } + hash_dst = { "property" => { "bedroom_count" => { "king_bed" => [2], "queen_bed" => [4] }, "bathroom_count" => ["2"] } } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => {"bedroom_count" => {"king_bed" => [2,3], "queen_bed" => [4]}, "bathroom_count" => ["2","1"]}}) + expect(hash_dst).to eq({ "property" => { "bedroom_count" => { "king_bed" => [2, 3], "queen_bed" => [4] }, "bathroom_count" => ["2", "1"] } }) end it "tests 3 hash layers holding arrays of int, but source is shorter and has new 2nd level ints." do - hash_src = {"property" => {"bedroom_count" => {2=>3, "king_bed" => [3]}, "bathroom_count" => ["1"]}} - hash_dst = {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} + hash_src = { "property" => { "bedroom_count" => { 2 => 3, "king_bed" => [3] }, "bathroom_count" => ["1"] } } + hash_dst = { "property" => { "bedroom_count" => { "king_bed" => [2], "queen_bed" => [4] }, "bathroom_count" => ["2"] } } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => {"bedroom_count" => {2=>3, "king_bed" => [2,3], "queen_bed" => [4]}, "bathroom_count" => ["2","1"]}}) + expect(hash_dst).to eq({ "property" => { "bedroom_count" => { 2 => 3, "king_bed" => [2, 3], "queen_bed" => [4] }, "bathroom_count" => ["2", "1"] } }) end it "tests 3 hash layers holding arrays of int, but source is empty" do hash_src = {} - hash_dst = {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} + hash_dst = { "property" => { "bedroom_count" => { "king_bed" => [2], "queen_bed" => [4] }, "bathroom_count" => ["2"] } } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}}) + expect(hash_dst).to eq({ "property" => { "bedroom_count" => { "king_bed" => [2], "queen_bed" => [4] }, "bathroom_count" => ["2"] } }) end it "tests 3 hash layers holding arrays of int, but dest is empty" do - hash_src = {"property" => {"bedroom_count" => {2=>3, "king_bed" => [3]}, "bathroom_count" => ["1"]}} + hash_src = { "property" => { "bedroom_count" => { 2 => 3, "king_bed" => [3] }, "bathroom_count" => ["1"] } } hash_dst = {} @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => {"bedroom_count" => {2=>3, "king_bed" => [3]}, "bathroom_count" => ["1"]}}) + expect(hash_dst).to eq({ "property" => { "bedroom_count" => { 2 => 3, "king_bed" => [3] }, "bathroom_count" => ["1"] } }) end it "tests hash holding arrays of arrays" do - hash_src = {["1", "2", "3"] => ["1", "2"]} - hash_dst = {["4", "5"] => ["3"]} + hash_src = { ["1", "2", "3"] => ["1", "2"] } + hash_dst = { ["4", "5"] => ["3"] } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({["1","2","3"] => ["1", "2"], ["4", "5"] => ["3"]}) + expect(hash_dst).to eq({ ["1", "2", "3"] => ["1", "2"], ["4", "5"] => ["3"] }) end it "tests merging of hash with blank hash, and make sure that source array split does not function when turned off" do - hash_src = {"property" => {"bedroom_count" => ["1","2,3"]}} + hash_src = { "property" => { "bedroom_count" => ["1", "2,3"] } } hash_dst = {} @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"property" => {"bedroom_count" => ["1","2,3"]}}) + expect(hash_dst).to eq({ "property" => { "bedroom_count" => ["1", "2,3"] } }) end it "tests merging into a blank hash" do - hash_src = {"action"=>"browse", "controller"=>"results"} + hash_src = { "action" => "browse", "controller" => "results" } hash_dst = {} @dm.deep_merge!(hash_src, hash_dst) expect(hash_dst).to eq(hash_src) end it "tests are unmerged hashes passed unmodified w/out :unpack_arrays?" do - hash_src = {"amenity"=>{"id"=>["26,27"]}} + hash_src = { "amenity" => { "id" => ["26,27"] } } hash_dst = {} @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"amenity"=>{"id"=>["26,27"]}}) + expect(hash_dst).to eq({ "amenity" => { "id" => ["26,27"] } }) end it "tests hash of array of hashes" do - hash_src = {"item" => [{"1" => "3"}, {"2" => "4"}]} - hash_dst = {"item" => [{"3" => "5"}]} + hash_src = { "item" => [{ "1" => "3" }, { "2" => "4" }] } + hash_dst = { "item" => [{ "3" => "5" }] } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"item" => [{"3" => "5"}, {"1" => "3"}, {"2" => "4"}]}) + expect(hash_dst).to eq({ "item" => [{ "3" => "5" }, { "1" => "3" }, { "2" => "4" }] }) end # Additions since import it "should overwrite true with false when merging boolean values" do - hash_src = {"valid" => false} - hash_dst = {"valid" => true} + hash_src = { "valid" => false } + hash_dst = { "valid" => true } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"valid" => false}) + expect(hash_dst).to eq({ "valid" => false }) end it "should overwrite false with true when merging boolean values" do - hash_src = {"valid" => true} - hash_dst = {"valid" => false} + hash_src = { "valid" => true } + hash_dst = { "valid" => false } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"valid" => true}) + expect(hash_dst).to eq({ "valid" => true }) end it "should overwrite a string with an empty string when merging string values" do - hash_src = {"item" => " "} - hash_dst = {"item" => "orange"} + hash_src = { "item" => " " } + hash_dst = { "item" => "orange" } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"item" => " "}) + expect(hash_dst).to eq({ "item" => " " }) end it "should overwrite an empty string with a string when merging string values" do - hash_src = {"item" => "orange"} - hash_dst = {"item" => " "} + hash_src = { "item" => "orange" } + hash_dst = { "item" => " " } @dm.deep_merge!(hash_src, hash_dst) - expect(hash_dst).to eq({"item" => "orange"}) + expect(hash_dst).to eq({ "item" => "orange" }) end end # deep_merge! @@ -247,53 +247,52 @@ describe Chef::Mixin::DeepMerge do describe "merge" do it "should merge a hash into an empty hash" do hash_dst = {} - hash_src = {"id" => "2"} + hash_src = { "id" => "2" } expect(@dm.merge(hash_dst, hash_src)).to eq(hash_src) end it "should merge a nested hash into an empty hash" do hash_dst = {} - hash_src = {"region" => {"id" => ["227", "2"]}} + hash_src = { "region" => { "id" => ["227", "2"] } } expect(@dm.merge(hash_dst, hash_src)).to eq(hash_src) end it "should overwrite as string value when merging hashes" do - hash_dst = {"name" => "value1"} - hash_src = {"name" => "value"} - expect(@dm.merge(hash_dst, hash_src)).to eq({"name" => "value"}) + hash_dst = { "name" => "value1" } + hash_src = { "name" => "value" } + expect(@dm.merge(hash_dst, hash_src)).to eq({ "name" => "value" }) end it "should merge arrays within hashes" do - hash_dst = {"property" => ["2","4"]} - hash_src = {"property" => ["1","3"]} - expect(@dm.merge(hash_dst, hash_src)).to eq({"property" => ["2","4","1","3"]}) + hash_dst = { "property" => ["2", "4"] } + hash_src = { "property" => ["1", "3"] } + expect(@dm.merge(hash_dst, hash_src)).to eq({ "property" => ["2", "4", "1", "3"] }) end it "should merge deeply nested hashes" do - hash_dst = {"property" => {"values" => {"are" => "falling", "can" => "change"}}} - hash_src = {"property" => {"values" => {"are" => "stable", "may" => "rise"}}} - expect(@dm.merge(hash_dst, hash_src)).to eq({"property" => {"values" => {"are" => "stable", "can" => "change", "may" => "rise"}}}) + hash_dst = { "property" => { "values" => { "are" => "falling", "can" => "change" } } } + hash_src = { "property" => { "values" => { "are" => "stable", "may" => "rise" } } } + expect(@dm.merge(hash_dst, hash_src)).to eq({ "property" => { "values" => { "are" => "stable", "can" => "change", "may" => "rise" } } }) end it "should not modify the source or destination during the merge" do - hash_dst = {"property" => ["1","2","3"]} - hash_src = {"property" => ["4","5","6"]} + hash_dst = { "property" => ["1", "2", "3"] } + hash_src = { "property" => ["4", "5", "6"] } ret = @dm.merge(hash_dst, hash_src) - expect(hash_dst).to eq({"property" => ["1","2","3"]}) - expect(hash_src).to eq({"property" => ["4","5","6"]}) - expect(ret).to eq({"property" => ["1","2","3","4","5","6"]}) + expect(hash_dst).to eq({ "property" => ["1", "2", "3"] }) + expect(hash_src).to eq({ "property" => ["4", "5", "6"] }) + expect(ret).to eq({ "property" => ["1", "2", "3", "4", "5", "6"] }) end it "should not error merging un-dupable objects" do @dm.deep_merge(nil, 4) end - end describe "hash-only merging" do it "merges Hashes like normal deep merge" do - merge_ee_hash = {"top_level_a" => {"1_deep_a" => "1-a-merge-ee", "1_deep_b" => "1-deep-b-merge-ee"}, "top_level_b" => "top-level-b-merge-ee"} - merge_with_hash = {"top_level_a" => {"1_deep_b" => "1-deep-b-merged-onto", "1_deep_c" => "1-deep-c-merged-onto"}, "top_level_b" => "top-level-b-merged-onto" } + merge_ee_hash = { "top_level_a" => { "1_deep_a" => "1-a-merge-ee", "1_deep_b" => "1-deep-b-merge-ee" }, "top_level_b" => "top-level-b-merge-ee" } + merge_with_hash = { "top_level_a" => { "1_deep_b" => "1-deep-b-merged-onto", "1_deep_c" => "1-deep-c-merged-onto" }, "top_level_b" => "top-level-b-merged-onto" } merged_result = @dm.hash_only_merge(merge_ee_hash, merge_with_hash) @@ -304,8 +303,8 @@ describe Chef::Mixin::DeepMerge do end it "replaces arrays rather than merging them" do - merge_ee_hash = {"top_level_a" => {"1_deep_a" => "1-a-merge-ee", "1_deep_b" => %w{A A A}}, "top_level_b" => "top-level-b-merge-ee"} - merge_with_hash = {"top_level_a" => {"1_deep_b" => %w{B B B}, "1_deep_c" => "1-deep-c-merged-onto"}, "top_level_b" => "top-level-b-merged-onto" } + merge_ee_hash = { "top_level_a" => { "1_deep_a" => "1-a-merge-ee", "1_deep_b" => %w{A A A} }, "top_level_b" => "top-level-b-merge-ee" } + merge_with_hash = { "top_level_a" => { "1_deep_b" => %w{B B B}, "1_deep_c" => "1-deep-c-merged-onto" }, "top_level_b" => "top-level-b-merged-onto" } merged_result = @dm.hash_only_merge(merge_ee_hash, merge_with_hash) @@ -315,8 +314,8 @@ describe Chef::Mixin::DeepMerge do end it "replaces non-hash items with hashes when there's a conflict" do - merge_ee_hash = {"top_level_a" => "top-level-a-mergee", "top_level_b" => "top-level-b-merge-ee"} - merge_with_hash = {"top_level_a" => {"1_deep_b" => %w{B B B}, "1_deep_c" => "1-deep-c-merged-onto"}, "top_level_b" => "top-level-b-merged-onto" } + merge_ee_hash = { "top_level_a" => "top-level-a-mergee", "top_level_b" => "top-level-b-merge-ee" } + merge_with_hash = { "top_level_a" => { "1_deep_b" => %w{B B B}, "1_deep_c" => "1-deep-c-merged-onto" }, "top_level_b" => "top-level-b-merged-onto" } merged_result = @dm.hash_only_merge(merge_ee_hash, merge_with_hash) @@ -326,16 +325,16 @@ describe Chef::Mixin::DeepMerge do end it "does not mutate deeply-nested original hashes by default" do - merge_ee_hash = {"top_level_a" => {"1_deep_a" => { "2_deep_a" => { "3_deep_a" => "foo" }}}} - merge_with_hash = {"top_level_a" => {"1_deep_a" => { "2_deep_a" => { "3_deep_b" => "bar" }}}} + merge_ee_hash = { "top_level_a" => { "1_deep_a" => { "2_deep_a" => { "3_deep_a" => "foo" } } } } + merge_with_hash = { "top_level_a" => { "1_deep_a" => { "2_deep_a" => { "3_deep_b" => "bar" } } } } @dm.hash_only_merge(merge_ee_hash, merge_with_hash) - expect(merge_ee_hash).to eq({"top_level_a" => {"1_deep_a" => { "2_deep_a" => { "3_deep_a" => "foo" }}}}) - expect(merge_with_hash).to eq({"top_level_a" => {"1_deep_a" => { "2_deep_a" => { "3_deep_b" => "bar" }}}}) + expect(merge_ee_hash).to eq({ "top_level_a" => { "1_deep_a" => { "2_deep_a" => { "3_deep_a" => "foo" } } } }) + expect(merge_with_hash).to eq({ "top_level_a" => { "1_deep_a" => { "2_deep_a" => { "3_deep_b" => "bar" } } } }) end it "does not error merging un-dupable items" do - merge_ee_hash = {"top_level_a" => 1, "top_level_b" => false} - merge_with_hash = {"top_level_a" => 2, "top_level_b" => true } + merge_ee_hash = { "top_level_a" => 1, "top_level_b" => false } + merge_with_hash = { "top_level_a" => 2, "top_level_b" => true } @dm.hash_only_merge(merge_ee_hash, merge_with_hash) end end diff --git a/spec/unit/mixin/deprecation_spec.rb b/spec/unit/mixin/deprecation_spec.rb index 8f22b09295..d53e7d3c6f 100644 --- a/spec/unit/mixin/deprecation_spec.rb +++ b/spec/unit/mixin/deprecation_spec.rb @@ -53,5 +53,4 @@ describe Chef::Mixin::Deprecation::DeprecatedInstanceVariable do expect(@deprecated_ivar.length).to eq(5) expect(@deprecated_ivar.to_sym).to eq(:value) end - end diff --git a/spec/unit/mixin/enforce_ownership_and_permissions_spec.rb b/spec/unit/mixin/enforce_ownership_and_permissions_spec.rb index 248de0ba95..4e32a646cf 100644 --- a/spec/unit/mixin/enforce_ownership_and_permissions_spec.rb +++ b/spec/unit/mixin/enforce_ownership_and_permissions_spec.rb @@ -21,7 +21,6 @@ require "etc" require "ostruct" describe Chef::Mixin::EnforceOwnershipAndPermissions do - before(:each) do @node = Chef::Node.new @node.name "make_believe" @@ -66,7 +65,6 @@ describe Chef::Mixin::EnforceOwnershipAndPermissions do allow_any_instance_of(Chef::FileAccessControl).to receive(:set_all) @provider.run_action(:create) end - end context "when something was modified" do @@ -92,5 +90,4 @@ describe Chef::Mixin::EnforceOwnershipAndPermissions do @provider.run_action(:create) end end - end diff --git a/spec/unit/mixin/homebrew_user_spec.rb b/spec/unit/mixin/homebrew_user_spec.rb index de72f6b935..cc7051baa7 100644 --- a/spec/unit/mixin/homebrew_user_spec.rb +++ b/spec/unit/mixin/homebrew_user_spec.rb @@ -44,7 +44,6 @@ describe Chef::Mixin::HomebrewUser do allow(Etc).to receive_message_chain(:getpwnam, :uid).and_return(uid) expect(homebrew_user.find_homebrew_uid(user)).to eq(uid) end - end shared_examples "successfully find executable" do @@ -58,7 +57,6 @@ describe Chef::Mixin::HomebrewUser do } context "debug statement prints owner name" do - before do expect(Etc).to receive(:getpwuid).with(brew_owner).and_return(OpenStruct.new(:name => "name")) end @@ -75,12 +73,10 @@ describe Chef::Mixin::HomebrewUser do expect(File).to receive(:stat).with("/foo").and_return(stat_double) expect(homebrew_user.find_homebrew_uid(user)).to eq(brew_owner) end - end end describe "when the homebrew user is not provided" do - it "raises an error if no executable is found" do expect(File).to receive(:exist?).with(default_brew_path).and_return(false) allow(homebrew_user).to receive_message_chain(:shell_out, :stdout, :strip).and_return("") @@ -94,7 +90,5 @@ describe Chef::Mixin::HomebrewUser do let(:brew_owner) { 0 } end end - end - end diff --git a/spec/unit/mixin/params_validate_spec.rb b/spec/unit/mixin/params_validate_spec.rb index a08584baf9..3148e9593b 100644 --- a/spec/unit/mixin/params_validate_spec.rb +++ b/spec/unit/mixin/params_validate_spec.rb @@ -23,18 +23,18 @@ class TinyClass attr_reader :name - def music(is_good=true) + def music(is_good = true) is_good end end describe Chef::Mixin::ParamsValidate do before(:each) do - @vo = TinyClass.new() + @vo = TinyClass.new() end it "should allow a hash and a hash as arguments to validate" do - expect { @vo.validate({:one => "two"}, {}) }.not_to raise_error + expect { @vo.validate({ :one => "two" }, {}) }.not_to raise_error end it "should raise an argument error if validate is called incorrectly" do @@ -42,23 +42,23 @@ describe Chef::Mixin::ParamsValidate do end it "should require validation map keys to be symbols or strings" do - expect { @vo.validate({:one => "two"}, { :one => true }) }.not_to raise_error - expect { @vo.validate({:one => "two"}, { "one" => true }) }.not_to raise_error - expect { @vo.validate({:one => "two"}, { Hash.new => true }) }.to raise_error(ArgumentError) + expect { @vo.validate({ :one => "two" }, { :one => true }) }.not_to raise_error + expect { @vo.validate({ :one => "two" }, { "one" => true }) }.not_to raise_error + expect { @vo.validate({ :one => "two" }, { Hash.new => true }) }.to raise_error(ArgumentError) end it "should allow options to be required with true" do - expect { @vo.validate({:one => "two"}, { :one => true }) }.not_to raise_error + expect { @vo.validate({ :one => "two" }, { :one => true }) }.not_to raise_error end it "should allow options to be optional with false" do - expect { @vo.validate({}, {:one => false})}.not_to raise_error + expect { @vo.validate({}, { :one => false }) }.not_to raise_error end it "should allow you to check what kind_of? thing an argument is with kind_of" do expect { @vo.validate( - {:one => "string"}, + { :one => "string" }, { :one => { :kind_of => String @@ -69,7 +69,7 @@ describe Chef::Mixin::ParamsValidate do expect { @vo.validate( - {:one => "string"}, + { :one => "string" }, { :one => { :kind_of => Array @@ -82,7 +82,7 @@ describe Chef::Mixin::ParamsValidate do it "should allow you to specify an argument is required with required" do expect { @vo.validate( - {:one => "string"}, + { :one => "string" }, { :one => { :required => true @@ -93,7 +93,7 @@ describe Chef::Mixin::ParamsValidate do expect { @vo.validate( - {:two => "string"}, + { :two => "string" }, { :one => { :required => true @@ -104,7 +104,7 @@ describe Chef::Mixin::ParamsValidate do expect { @vo.validate( - {:two => "string"}, + { :two => "string" }, { :one => { :required => false @@ -117,7 +117,7 @@ describe Chef::Mixin::ParamsValidate do it "should allow you to specify whether an object has a method with respond_to" do expect { @vo.validate( - {:one => @vo}, + { :one => @vo }, { :one => { :respond_to => "validate" @@ -128,7 +128,7 @@ describe Chef::Mixin::ParamsValidate do expect { @vo.validate( - {:one => @vo}, + { :one => @vo }, { :one => { :respond_to => "monkey" @@ -141,7 +141,7 @@ describe Chef::Mixin::ParamsValidate do it "should allow you to specify whether an object has all the given methods with respond_to and an array" do expect { @vo.validate( - {:one => @vo}, + { :one => @vo }, { :one => { :respond_to => ["validate", "music"] @@ -152,7 +152,7 @@ describe Chef::Mixin::ParamsValidate do expect { @vo.validate( - {:one => @vo}, + { :one => @vo }, { :one => { :respond_to => ["monkey", "validate"] @@ -165,10 +165,10 @@ describe Chef::Mixin::ParamsValidate do it "should let you set a default value with default => value" do arguments = Hash.new @vo.validate(arguments, { - :one => { - :default => "is the loneliest number" - } - },) + :one => { + :default => "is the loneliest number" + } + },) expect(arguments[:one]).to eq("is the loneliest number") end @@ -293,14 +293,14 @@ describe Chef::Mixin::ParamsValidate do it "should accept keys that are strings in the options" do expect { - @vo.validate({ "one" => "two" }, { :one => { :regex => /^two$/ }}) + @vo.validate({ "one" => "two" }, { :one => { :regex => /^two$/ } }) }.not_to raise_error end it "should allow an array to kind_of" do expect { @vo.validate( - {:one => "string"}, + { :one => "string" }, { :one => { :kind_of => [ String, Array ] @@ -310,7 +310,7 @@ describe Chef::Mixin::ParamsValidate do }.not_to raise_error expect { @vo.validate( - {:one => ["string"]}, + { :one => ["string"] }, { :one => { :kind_of => [ String, Array ] @@ -320,7 +320,7 @@ describe Chef::Mixin::ParamsValidate do }.not_to raise_error expect { @vo.validate( - {:one => Hash.new}, + { :one => Hash.new }, { :one => { :kind_of => [ String, Array ] @@ -332,12 +332,12 @@ describe Chef::Mixin::ParamsValidate do it "asserts that a value returns false from a predicate method" do expect do - @vo.validate({:not_blank => "should pass"}, - {:not_blank => {:cannot_be => [ :nil, :empty ]}}) + @vo.validate({ :not_blank => "should pass" }, + { :not_blank => { :cannot_be => [ :nil, :empty ] } }) end.not_to raise_error expect do - @vo.validate({:not_blank => ""}, - {:not_blank => {:cannot_be => [ :nil, :empty ]}}) + @vo.validate({ :not_blank => "" }, + { :not_blank => { :cannot_be => [ :nil, :empty ] } }) end.to raise_error(Chef::Exceptions::ValidationFailed) end @@ -367,31 +367,31 @@ describe Chef::Mixin::ParamsValidate do it "should set and return @name, then return @name for foo when argument is nil" do value = "meow" - expect(@vo.set_or_return(:name, value, { }).object_id).to eq(value.object_id) + expect(@vo.set_or_return(:name, value, {}).object_id).to eq(value.object_id) expect(@vo.set_or_return(:foo, nil, { :name_attribute => true }).object_id).to eq(value.object_id) end it "should allow DelayedEvaluator instance to be set for value regardless of restriction" do - value = Chef::DelayedEvaluator.new{ "test" } - @vo.set_or_return(:test, value, {:kind_of => Numeric}) + value = Chef::DelayedEvaluator.new { "test" } + @vo.set_or_return(:test, value, { :kind_of => Numeric }) end 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}) + value = Chef::DelayedEvaluator.new { "test" } + @vo.set_or_return(:test, value, { :kind_of => Numeric }) expect do - @vo.set_or_return(:test, nil, {:kind_of => Numeric}) + @vo.set_or_return(:test, nil, { :kind_of => Numeric }) end.to raise_error(Chef::Exceptions::ValidationFailed) end it "should create DelayedEvaluator instance when #lazy is used" do - @vo.set_or_return(:delayed, @vo.lazy{ "test" }, {}) + @vo.set_or_return(:delayed, @vo.lazy { "test" }, {}) expect(@vo.instance_variable_get(:@delayed)).to be_a(Chef::DelayedEvaluator) end it "should execute block on each call when DelayedEvaluator" do value = "fubar" - @vo.set_or_return(:test, @vo.lazy{ value }, {}) + @vo.set_or_return(:test, @vo.lazy { value }, {}) expect(@vo.set_or_return(:test, nil, {})).to eq("fubar") value = "foobar" expect(@vo.set_or_return(:test, nil, {})).to eq("foobar") @@ -400,10 +400,9 @@ describe Chef::Mixin::ParamsValidate do end it "should not evaluate non DelayedEvaluator instances" do - value = lambda{ "test" } + value = lambda { "test" } @vo.set_or_return(:test, value, {}) expect(@vo.set_or_return(:test, nil, {}).object_id).to eq(value.object_id) expect(@vo.set_or_return(:test, nil, {})).to be_a(Proc) end - end diff --git a/spec/unit/mixin/path_sanity_spec.rb b/spec/unit/mixin/path_sanity_spec.rb index 2679780c76..0cf893054d 100644 --- a/spec/unit/mixin/path_sanity_spec.rb +++ b/spec/unit/mixin/path_sanity_spec.rb @@ -23,7 +23,6 @@ class PathSanityTestHarness end describe Chef::Mixin::PathSanity do - before do @sanity = PathSanityTestHarness.new end @@ -39,25 +38,25 @@ describe Chef::Mixin::PathSanity do end it "adds all useful PATHs even if environment is an empty hash" do - env={} + env = {} @sanity.enforce_path_sanity(env) expect(env["PATH"]).to eq("#{@ruby_bindir}:#{@gem_bindir}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") end it "adds all useful PATHs that are not yet in PATH to PATH" do - env = {"PATH" => ""} + env = { "PATH" => "" } @sanity.enforce_path_sanity(env) expect(env["PATH"]).to eq("#{@ruby_bindir}:#{@gem_bindir}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") end it "does not re-add paths that already exist in PATH" do - env = {"PATH" => "/usr/bin:/sbin:/bin"} + env = { "PATH" => "/usr/bin:/sbin:/bin" } @sanity.enforce_path_sanity(env) expect(env["PATH"]).to eq("/usr/bin:/sbin:/bin:#{@ruby_bindir}:#{@gem_bindir}:/usr/local/sbin:/usr/local/bin:/usr/sbin") end it "adds the current executing Ruby's bindir and Gem bindir to the PATH" do - env = {"PATH" => ""} + env = { "PATH" => "" } @sanity.enforce_path_sanity(env) expect(env["PATH"]).to eq("#{@ruby_bindir}:#{@gem_bindir}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") end @@ -67,7 +66,7 @@ describe Chef::Mixin::PathSanity do gem_bindir = "/yo/gabba/gabba" allow(Gem).to receive(:bindir).and_return(gem_bindir) allow(RbConfig::CONFIG).to receive(:[]).with("bindir").and_return(ruby_bindir) - env = {"PATH" => gem_bindir} + env = { "PATH" => gem_bindir } @sanity.enforce_path_sanity(env) expect(env["PATH"]).to eq("/yo/gabba/gabba:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") end @@ -78,7 +77,7 @@ describe Chef::Mixin::PathSanity do allow(Gem).to receive(:bindir).and_return(gem_bindir) allow(RbConfig::CONFIG).to receive(:[]).with("bindir").and_return(ruby_bindir) allow(ChefConfig).to receive(:windows?).and_return(true) - env = {"PATH" => 'C:\Windows\system32;C:\mr\softie'} + env = { "PATH" => 'C:\Windows\system32;C:\mr\softie' } @sanity.enforce_path_sanity(env) expect(env["PATH"]).to eq("C:\\Windows\\system32;C:\\mr\\softie;#{ruby_bindir};#{gem_bindir}") end diff --git a/spec/unit/mixin/powershell_out_spec.rb b/spec/unit/mixin/powershell_out_spec.rb index 8e2e4e2b45..b586be7fdc 100644 --- a/spec/unit/mixin/powershell_out_spec.rb +++ b/spec/unit/mixin/powershell_out_spec.rb @@ -21,9 +21,9 @@ require "chef/mixin/powershell_out" describe Chef::Mixin::PowershellOut do let(:shell_out_class) { Class.new { include Chef::Mixin::PowershellOut } } subject(:object) { shell_out_class.new } - let(:architecture) { "something" } + let(:architecture) { "something" } let(:flags) { - "-NoLogo -NonInteractive -NoProfile -ExecutionPolicy Unrestricted -InputFormat None" + "-NoLogo -NonInteractive -NoProfile -ExecutionPolicy Unrestricted -InputFormat None" } describe "#powershell_out" do diff --git a/spec/unit/mixin/powershell_type_coercions_spec.rb b/spec/unit/mixin/powershell_type_coercions_spec.rb index f7b4fcd723..7f2ecb94e2 100644 --- a/spec/unit/mixin/powershell_type_coercions_spec.rb +++ b/spec/unit/mixin/powershell_type_coercions_spec.rb @@ -55,17 +55,17 @@ describe Chef::Mixin::PowershellTypeCoercions do end it "translates all members of a hash and wrap them in @{} separated by ;" do - expect(test_class.translate_type({"a" => 1, "b" => 1.2, "c" => false, "d" => true + expect(test_class.translate_type({ "a" => 1, "b" => 1.2, "c" => false, "d" => true })).to eq("@{a=1;b=1.2;c=$false;d=$true}") end it "translates all members of an array and them by a ," do expect(test_class.translate_type([true, false])).to eq("@($true,$false)") end - + it "translates a Chef::Node::ImmutableMash like a hash" do - test_mash = Chef::Node::ImmutableMash.new({"a" => 1, "b" => 1.2, - "c" => false, "d" => true}) + test_mash = Chef::Node::ImmutableMash.new({ "a" => 1, "b" => 1.2, + "c" => false, "d" => true }) expect(test_class.translate_type(test_mash)).to eq("@{a=1;b=1.2;c=$false;d=$true}") end diff --git a/spec/unit/mixin/proxified_socket_spec.rb b/spec/unit/mixin/proxified_socket_spec.rb index d8cc762210..f0bbeef59b 100644 --- a/spec/unit/mixin/proxified_socket_spec.rb +++ b/spec/unit/mixin/proxified_socket_spec.rb @@ -25,7 +25,6 @@ class TestProxifiedSocket end describe Chef::Mixin::ProxifiedSocket do - before do @original_env = ENV.to_hash end @@ -38,7 +37,7 @@ describe Chef::Mixin::ProxifiedSocket do let(:host) { "host" } let(:port) { 7979 } let(:test_instance) { TestProxifiedSocket.new } - let(:socket_double) { instance_double(TCPSocket)} + let(:socket_double) { instance_double(TCPSocket) } let(:proxifier_double) { instance_double(Proxifier::Proxy) } let(:http_uri) { "http://somehost:1" } let(:https_uri) { "https://somehost:1" } @@ -90,5 +89,4 @@ describe Chef::Mixin::ProxifiedSocket do let(:proxy_uri) { http_uri } include_examples "proxified socket" end - end diff --git a/spec/unit/mixin/securable_spec.rb b/spec/unit/mixin/securable_spec.rb index 50bfe84b27..38e549fca3 100644 --- a/spec/unit/mixin/securable_spec.rb +++ b/spec/unit/mixin/securable_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Mixin::Securable do - before(:each) do @securable = Object.new @securable.send(:extend, Chef::Mixin::Securable) @@ -253,7 +252,7 @@ describe Chef::Mixin::Securable do it "should accept a principal as a string or an array" do expect { @securable.rights :read, "The Dude" }.not_to raise_error - expect { @securable.rights :read, ["The Dude","Donny"] }.not_to raise_error + expect { @securable.rights :read, ["The Dude", "Donny"] }.not_to raise_error expect { @securable.rights :read, 3 }.to raise_error(ArgumentError) end diff --git a/spec/unit/mixin/shell_out_spec.rb b/spec/unit/mixin/shell_out_spec.rb index 6d7e12af4b..3984315213 100644 --- a/spec/unit/mixin/shell_out_spec.rb +++ b/spec/unit/mixin/shell_out_spec.rb @@ -31,7 +31,7 @@ describe Chef::Mixin::ShellOut do let(:cmd) { "echo '#{rand(1000)}'" } let(:output) { StringIO.new } - let!(:capture_log_output) { Chef::Log.logger = Logger.new(output) } + let!(:capture_log_output) { Chef::Log.logger = Logger.new(output) } let(:assume_deprecation_log_level) { allow(Chef::Log).to receive(:level).and_return(:warn) } context "without options" do @@ -120,7 +120,6 @@ describe Chef::Mixin::ShellOut do let(:cmd) { "echo '#{rand(1000)}'" } describe "#shell_out" do - describe "when the last argument is a Hash" do describe "and environment is an option" do it "should not change environment language settings when they are set to nil" do @@ -138,26 +137,26 @@ describe Chef::Mixin::ShellOut do it "should set environment language settings to the configured internal locale when they are not present" do options = { :environment => { "HOME" => "/Users/morty" } } expect(shell_out_obj).to receive(:shell_out_command).with(cmd, { - :environment => { - "HOME" => "/Users/morty", - "LC_ALL" => Chef::Config[:internal_locale], - "LANG" => Chef::Config[:internal_locale], - "LANGUAGE" => Chef::Config[:internal_locale], - } - },).and_return(true) + :environment => { + "HOME" => "/Users/morty", + "LC_ALL" => Chef::Config[:internal_locale], + "LANG" => Chef::Config[:internal_locale], + "LANGUAGE" => Chef::Config[:internal_locale], + } + },).and_return(true) shell_out_obj.shell_out(cmd, options) end it "should not mutate the options hash when it adds language settings" do options = { :environment => { "HOME" => "/Users/morty" } } expect(shell_out_obj).to receive(:shell_out_command).with(cmd, { - :environment => { - "HOME" => "/Users/morty", - "LC_ALL" => Chef::Config[:internal_locale], - "LANG" => Chef::Config[:internal_locale], - "LANGUAGE" => Chef::Config[:internal_locale], - } - },).and_return(true) + :environment => { + "HOME" => "/Users/morty", + "LC_ALL" => Chef::Config[:internal_locale], + "LANG" => Chef::Config[:internal_locale], + "LANGUAGE" => Chef::Config[:internal_locale], + } + },).and_return(true) shell_out_obj.shell_out(cmd, options) expect(options[:environment].has_key?("LC_ALL")).to be false end @@ -171,7 +170,7 @@ describe Chef::Mixin::ShellOut do end it "should not change env when language options are set to non-nil" do - options = { :env => { "LC_ALL" => "de_DE.UTF-8", "LANG" => "de_DE.UTF-8", "LANGUAGE" => "de_DE.UTF-8" }} + options = { :env => { "LC_ALL" => "de_DE.UTF-8", "LANG" => "de_DE.UTF-8", "LANGUAGE" => "de_DE.UTF-8" } } expect(shell_out_obj).to receive(:shell_out_command).with(cmd, options).and_return(true) shell_out_obj.shell_out(cmd, options) end @@ -179,26 +178,26 @@ describe Chef::Mixin::ShellOut do it "should set environment language settings to the configured internal locale when they are not present" do options = { :env => { "HOME" => "/Users/morty" } } expect(shell_out_obj).to receive(:shell_out_command).with(cmd, { - :env => { - "HOME" => "/Users/morty", - "LC_ALL" => Chef::Config[:internal_locale], - "LANG" => Chef::Config[:internal_locale], - "LANGUAGE" => Chef::Config[:internal_locale], - } - },).and_return(true) + :env => { + "HOME" => "/Users/morty", + "LC_ALL" => Chef::Config[:internal_locale], + "LANG" => Chef::Config[:internal_locale], + "LANGUAGE" => Chef::Config[:internal_locale], + } + },).and_return(true) shell_out_obj.shell_out(cmd, options) end it "should not mutate the options hash when it adds language settings" do options = { :env => { "HOME" => "/Users/morty" } } expect(shell_out_obj).to receive(:shell_out_command).with(cmd, { - :env => { - "HOME" => "/Users/morty", - "LC_ALL" => Chef::Config[:internal_locale], - "LANG" => Chef::Config[:internal_locale], - "LANGUAGE" => Chef::Config[:internal_locale], - } - },).and_return(true) + :env => { + "HOME" => "/Users/morty", + "LC_ALL" => Chef::Config[:internal_locale], + "LANG" => Chef::Config[:internal_locale], + "LANGUAGE" => Chef::Config[:internal_locale], + } + },).and_return(true) shell_out_obj.shell_out(cmd, options) expect(options[:env].has_key?("LC_ALL")).to be false end @@ -208,13 +207,13 @@ describe Chef::Mixin::ShellOut do it "should set environment language settings to the configured internal locale" do options = { :user => "morty" } expect(shell_out_obj).to receive(:shell_out_command).with(cmd, { - :user => "morty", - :environment => { - "LC_ALL" => Chef::Config[:internal_locale], - "LANG" => Chef::Config[:internal_locale], - "LANGUAGE" => Chef::Config[:internal_locale], - }, - },).and_return(true) + :user => "morty", + :environment => { + "LC_ALL" => Chef::Config[:internal_locale], + "LANG" => Chef::Config[:internal_locale], + "LANGUAGE" => Chef::Config[:internal_locale], + }, + },).and_return(true) shell_out_obj.shell_out(cmd, options) end end @@ -223,20 +222,18 @@ describe Chef::Mixin::ShellOut do describe "when the last argument is not a Hash" do it "should set environment language settings to the configured internal locale" do expect(shell_out_obj).to receive(:shell_out_command).with(cmd, { - :environment => { - "LC_ALL" => Chef::Config[:internal_locale], - "LANG" => Chef::Config[:internal_locale], - "LANGUAGE" => Chef::Config[:internal_locale], - } - },).and_return(true) + :environment => { + "LC_ALL" => Chef::Config[:internal_locale], + "LANG" => Chef::Config[:internal_locale], + "LANGUAGE" => Chef::Config[:internal_locale], + } + },).and_return(true) shell_out_obj.shell_out(cmd) end end - end describe "#shell_out_with_systems_locale" do - describe "when the last argument is a Hash" do describe "and environment is an option" do it "should not change environment['LC_ALL'] when set to nil" do @@ -266,7 +263,7 @@ describe Chef::Mixin::ShellOut do end it "should not change env when set to non-nil" do - options = { :env => { "LC_ALL" => "en_US.UTF-8"}} + options = { :env => { "LC_ALL" => "en_US.UTF-8" } } expect(shell_out_obj).to receive(:shell_out_command).with(cmd, options).and_return(true) shell_out_obj.shell_out_with_systems_locale(cmd, options) end @@ -294,6 +291,5 @@ describe Chef::Mixin::ShellOut do end end end - end end diff --git a/spec/unit/mixin/template_spec.rb b/spec/unit/mixin/template_spec.rb index 41e2174eb0..9e9c4a404c 100644 --- a/spec/unit/mixin/template_spec.rb +++ b/spec/unit/mixin/template_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "cgi" describe Chef::Mixin::Template, "render_template" do - let(:sep) { Chef::Platform.windows? ? "\r\n" : "\n" } before :each do @@ -172,7 +171,7 @@ describe Chef::Mixin::Template, "render_template" do expect(output).to eq("before {super secret is } after") output = @template_context.render_template_from_string("before {<%= render 'openldap_variable_stuff.conf.erb' %>} after") - expect(output).to eq("before {super secret is } after") + expect(output).to eq("before {super secret is } after") end it "should render nested partials" do @@ -183,7 +182,6 @@ describe Chef::Mixin::Template, "render_template" do end describe "when customizing the template context" do - it "extends the context to include modules" do mod = Module.new do def hello @@ -199,10 +197,13 @@ describe Chef::Mixin::Template, "render_template" do mod = Module.new do def render end + def node end + def render_template end + def render_template_from_string end end @@ -212,7 +213,6 @@ describe Chef::Mixin::Template, "render_template" do @template_context._extend_modules([mod]) end end - end describe "when an exception is raised in the template" do @@ -225,7 +225,7 @@ describe Chef::Mixin::Template, "render_template" do end it "should raise an error if an attempt is made to access node but it is nil" do - expect {@context.render_template_from_string("<%= node %>") {|r| r}}.to raise_error(Chef::Mixin::Template::TemplateError) + expect { @context.render_template_from_string("<%= node %>") { |r| r } }.to raise_error(Chef::Mixin::Template::TemplateError) end describe "the raised TemplateError" do diff --git a/spec/unit/mixin/unformatter_spec.rb b/spec/unit/mixin/unformatter_spec.rb index b2b57c150c..5c39cfb320 100644 --- a/spec/unit/mixin/unformatter_spec.rb +++ b/spec/unit/mixin/unformatter_spec.rb @@ -24,7 +24,6 @@ class Chef::UnformatterTest def foo end - end describe Chef::Mixin::Unformatter do @@ -55,7 +54,5 @@ describe Chef::Mixin::Unformatter do unformatter.write("FOO: #{message}") end end - end - end diff --git a/spec/unit/mixin/uris_spec.rb b/spec/unit/mixin/uris_spec.rb index 13012617bc..8a8775e0c8 100644 --- a/spec/unit/mixin/uris_spec.rb +++ b/spec/unit/mixin/uris_spec.rb @@ -46,12 +46,11 @@ describe Chef::Mixin::Uris do describe "#as_uri" do it "parses a file scheme uri with spaces" do - expect{ uris.as_uri("file:///c:/foo bar.txt") }.not_to raise_exception + expect { uris.as_uri("file:///c:/foo bar.txt") }.not_to raise_exception end it "returns a URI object" do expect( uris.as_uri("file:///c:/foo bar.txt") ).to be_a(URI) end end - end diff --git a/spec/unit/mixin/windows_architecture_helper_spec.rb b/spec/unit/mixin/windows_architecture_helper_spec.rb index 25064678fa..aaf9fa4b2b 100644 --- a/spec/unit/mixin/windows_architecture_helper_spec.rb +++ b/spec/unit/mixin/windows_architecture_helper_spec.rb @@ -16,12 +16,9 @@ # limitations under the License. # - require "spec_helper" require "chef/mixin/windows_architecture_helper" - - describe Chef::Mixin::WindowsArchitectureHelper do include Chef::Mixin::WindowsArchitectureHelper @@ -34,25 +31,25 @@ describe Chef::Mixin::WindowsArchitectureHelper do end it "returns true when valid architectures are passed to valid_windows_architecture?" do - @valid_architectures.each do | architecture | + @valid_architectures.each do |architecture| expect(valid_windows_architecture?(architecture)).to eq(true) end end it "returns false when invalid architectures are passed to valid_windows_architecture?" do - @invalid_architectures.each do | architecture | + @invalid_architectures.each do |architecture| expect(valid_windows_architecture?(architecture)).to eq(false) end end it "does not raise an exception when a valid architecture is passed to assert_valid_windows_architecture!" do - @valid_architectures.each do | architecture | + @valid_architectures.each do |architecture| assert_valid_windows_architecture!(architecture) end end it "raises an error if an invalid architecture is passed to assert_valid_windows_architecture!" do - @invalid_architectures.each do | architecture | + @invalid_architectures.each do |architecture| begin expect(assert_valid_windows_architecture!(architecture)).to raise_error Chef::Exceptions::Win32ArchitectureIncorrect rescue Chef::Exceptions::Win32ArchitectureIncorrect @@ -61,26 +58,26 @@ describe Chef::Mixin::WindowsArchitectureHelper do end it "returns true only for supported desired architecture passed to node_supports_windows_architecture" do - with_node_architecture_combinations do | node, desired_arch | - expect(node_supports_windows_architecture?(node, desired_arch)).to be true if (node_windows_architecture(node) == :x86_64 || desired_arch == :i386 ) - expect(node_supports_windows_architecture?(node, desired_arch)).to be false if (node_windows_architecture(node) == :i386 && desired_arch == :x86_64 ) + with_node_architecture_combinations do |node, desired_arch| + expect(node_supports_windows_architecture?(node, desired_arch)).to be true if (node_windows_architecture(node) == :x86_64 || desired_arch == :i386 ) + expect(node_supports_windows_architecture?(node, desired_arch)).to be false if (node_windows_architecture(node) == :i386 && desired_arch == :x86_64 ) end end it "returns true only when forced_32bit_override_required? has 64-bit node architecture and 32-bit desired architecture" do - with_node_architecture_combinations do | node, desired_arch | + with_node_architecture_combinations do |node, desired_arch| expect(forced_32bit_override_required?(node, desired_arch)).to be true if ((node_windows_architecture(node) == :x86_64) && (desired_arch == :i386) && !is_i386_process_on_x86_64_windows?) expect(forced_32bit_override_required?(node, desired_arch)).to be false if ! ((node_windows_architecture(node) == :x86_64) && (desired_arch == :i386)) end end def with_node_architecture_combinations - @valid_architectures.each do | node_architecture | + @valid_architectures.each do |node_architecture| new_node = Chef::Node.new new_node.default["kernel"] = Hash.new new_node.default["kernel"][:machine] = node_architecture.to_s - @valid_architectures.each do | architecture | + @valid_architectures.each do |architecture| yield new_node, architecture if block_given? end end diff --git a/spec/unit/monkey_patches/uri_spec.rb b/spec/unit/monkey_patches/uri_spec.rb index 0679705cf4..82ec9a760c 100644 --- a/spec/unit/monkey_patches/uri_spec.rb +++ b/spec/unit/monkey_patches/uri_spec.rb @@ -18,9 +18,7 @@ require "spec_helper" describe URI do - describe "when a URI contains an IPv6 literal" do - let(:ipv6_uri) do URI.parse("https://[2a00:1450:4009:809::1008]:8443") end @@ -28,7 +26,5 @@ describe URI do it "returns the hostname without brackets" do expect(ipv6_uri.hostname).to eq("2a00:1450:4009:809::1008") end - end - end diff --git a/spec/unit/node/attribute_spec.rb b/spec/unit/node/attribute_spec.rb index 79ef2bf7d7..bf98fc4613 100644 --- a/spec/unit/node/attribute_spec.rb +++ b/spec/unit/node/attribute_spec.rb @@ -23,172 +23,128 @@ require "chef/node/attribute" describe Chef::Node::Attribute do before(:each) do @attribute_hash = - {"dmi"=>{}, - "command"=>{"ps"=>"ps -ef"}, - "platform_version"=>"10.5.7", - "platform"=>"mac_os_x", - "ipaddress"=>"192.168.0.117", - "network"=> - {"default_interface"=>"en1", - "interfaces"=> - {"vmnet1"=> - {"flags"=> - ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"], - "number"=>"1", - "addresses"=> - {"00:50:56:c0:00:01"=>{"family"=>"lladdr"}, - "192.168.110.1"=> - {"broadcast"=>"192.168.110.255", - "netmask"=>"255.255.255.0", - "family"=>"inet"}}, - "mtu"=>"1500", - "type"=>"vmnet", - "arp"=>{"192.168.110.255"=>"ff:ff:ff:ff:ff:ff"}, - "encapsulation"=>"Ethernet"}, - "stf0"=> - {"flags"=>[], - "number"=>"0", - "addresses"=>{}, - "mtu"=>"1280", - "type"=>"stf", - "encapsulation"=>"6to4"}, - "lo0"=> - {"flags"=>["UP", "LOOPBACK", "RUNNING", "MULTICAST"], - "number"=>"0", - "addresses"=> - {"::1"=>{"scope"=>"Node", "prefixlen"=>"128", "family"=>"inet6"}, - "127.0.0.1"=>{"netmask"=>"255.0.0.0", "family"=>"inet"}, - "fe80::1"=>{"scope"=>"Link", "prefixlen"=>"64", "family"=>"inet6"}}, - "mtu"=>"16384", - "type"=>"lo", - "encapsulation"=>"Loopback"}, - "gif0"=> - {"flags"=>["POINTOPOINT", "MULTICAST"], - "number"=>"0", - "addresses"=>{}, - "mtu"=>"1280", - "type"=>"gif", - "encapsulation"=>"IPIP"}, - "vmnet8"=> - {"flags"=> - ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"], - "number"=>"8", - "addresses"=> - {"192.168.4.1"=> - {"broadcast"=>"192.168.4.255", - "netmask"=>"255.255.255.0", - "family"=>"inet"}, - "00:50:56:c0:00:08"=>{"family"=>"lladdr"}}, - "mtu"=>"1500", - "type"=>"vmnet", - "arp"=>{"192.168.4.255"=>"ff:ff:ff:ff:ff:ff"}, - "encapsulation"=>"Ethernet"}, - "en0"=> - {"status"=>"inactive", - "flags"=> - ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"], - "number"=>"0", - "addresses"=>{"00:23:32:b0:32:f2"=>{"family"=>"lladdr"}}, - "mtu"=>"1500", - "media"=> - {"supported"=> - {"autoselect"=>{"options"=>[]}, - "none"=>{"options"=>[]}, - "1000baseT"=> - {"options"=>["full-duplex", "flow-control", "hw-loopback"]}, - "10baseT/UTP"=> - {"options"=> - ["half-duplex", "full-duplex", "flow-control", "hw-loopback"]}, - "100baseTX"=> - {"options"=> - ["half-duplex", "full-duplex", "flow-control", "hw-loopback"]}}, - "selected"=>{"autoselect"=>{"options"=>[]}}}, - "type"=>"en", - "encapsulation"=>"Ethernet"}, - "en1"=> - {"status"=>"active", - "flags"=> - ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"], - "number"=>"1", - "addresses"=> - {"fe80::223:6cff:fe7f:676c"=> - {"scope"=>"Link", "prefixlen"=>"64", "family"=>"inet6"}, - "00:23:6c:7f:67:6c"=>{"family"=>"lladdr"}, - "192.168.0.117"=> - {"broadcast"=>"192.168.0.255", - "netmask"=>"255.255.255.0", - "family"=>"inet"}}, - "mtu"=>"1500", - "media"=> - {"supported"=>{"autoselect"=>{"options"=>[]}}, - "selected"=>{"autoselect"=>{"options"=>[]}}}, - "type"=>"en", - "arp"=> - {"192.168.0.72"=>"0:f:ea:39:fa:d5", - "192.168.0.1"=>"0:1c:fb:fc:6f:20", - "192.168.0.255"=>"ff:ff:ff:ff:ff:ff", - "192.168.0.3"=>"0:1f:33:ea:26:9b", - "192.168.0.77"=>"0:23:12:70:f8:cf", - "192.168.0.152"=>"0:26:8:7d:2:4c"}, - "encapsulation"=>"Ethernet"}, - "en2"=> - {"status"=>"active", - "flags"=> - ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"], - "number"=>"2", - "addresses"=> - {"169.254.206.152"=> - {"broadcast"=>"169.254.255.255", - "netmask"=>"255.255.0.0", - "family"=>"inet"}, - "00:1c:42:00:00:01"=>{"family"=>"lladdr"}, - "fe80::21c:42ff:fe00:1"=> - {"scope"=>"Link", "prefixlen"=>"64", "family"=>"inet6"}}, - "mtu"=>"1500", - "media"=> - {"supported"=>{"autoselect"=>{"options"=>[]}}, - "selected"=>{"autoselect"=>{"options"=>[]}}}, - "type"=>"en", - "encapsulation"=>"Ethernet"}, - "fw0"=> - {"status"=>"inactive", - "flags"=>["BROADCAST", "SIMPLEX", "MULTICAST"], - "number"=>"0", - "addresses"=>{"00:23:32:ff:fe:b0:32:f2"=>{"family"=>"lladdr"}}, - "mtu"=>"4078", - "media"=> - {"supported"=>{"autoselect"=>{"options"=>["full-duplex"]}}, - "selected"=>{"autoselect"=>{"options"=>["full-duplex"]}}}, - "type"=>"fw", - "encapsulation"=>"1394"}, - "en3"=> - {"status"=>"active", - "flags"=> - ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"], - "number"=>"3", - "addresses"=> - {"169.254.206.152"=> - {"broadcast"=>"169.254.255.255", - "netmask"=>"255.255.0.0", - "family"=>"inet"}, - "00:1c:42:00:00:00"=>{"family"=>"lladdr"}, - "fe80::21c:42ff:fe00:0"=> - {"scope"=>"Link", "prefixlen"=>"64", "family"=>"inet6"}}, - "mtu"=>"1500", - "media"=> - {"supported"=>{"autoselect"=>{"options"=>[]}}, - "selected"=>{"autoselect"=>{"options"=>[]}}}, - "type"=>"en", - "encapsulation"=>"Ethernet"}}}, - "fqdn"=>"latte.local", - "ohai_time"=>1249065590.90391, - "domain"=>"local", - "os"=>"darwin", - "platform_build"=>"9J61", - "os_version"=>"9.7.0", - "hostname"=>"latte", - "macaddress"=>"00:23:6c:7f:67:6c", - "music" => { "jimmy_eat_world" => "nice", "apophis" => false }, + { "dmi" => {}, + "command" => { "ps" => "ps -ef" }, + "platform_version" => "10.5.7", + "platform" => "mac_os_x", + "ipaddress" => "192.168.0.117", + "network" => { "default_interface" => "en1", + "interfaces" => { "vmnet1" => { "flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"], + "number" => "1", + "addresses" => { "00:50:56:c0:00:01" => { "family" => "lladdr" }, + "192.168.110.1" => { "broadcast" => "192.168.110.255", + "netmask" => "255.255.255.0", + "family" => "inet" } }, + "mtu" => "1500", + "type" => "vmnet", + "arp" => { "192.168.110.255" => "ff:ff:ff:ff:ff:ff" }, + "encapsulation" => "Ethernet" }, + "stf0" => { "flags" => [], + "number" => "0", + "addresses" => {}, + "mtu" => "1280", + "type" => "stf", + "encapsulation" => "6to4" }, + "lo0" => { "flags" => ["UP", "LOOPBACK", "RUNNING", "MULTICAST"], + "number" => "0", + "addresses" => { "::1" => { "scope" => "Node", "prefixlen" => "128", "family" => "inet6" }, + "127.0.0.1" => { "netmask" => "255.0.0.0", "family" => "inet" }, + "fe80::1" => { "scope" => "Link", "prefixlen" => "64", "family" => "inet6" } }, + "mtu" => "16384", + "type" => "lo", + "encapsulation" => "Loopback" }, + "gif0" => { "flags" => ["POINTOPOINT", "MULTICAST"], + "number" => "0", + "addresses" => {}, + "mtu" => "1280", + "type" => "gif", + "encapsulation" => "IPIP" }, + "vmnet8" => { "flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"], + "number" => "8", + "addresses" => { "192.168.4.1" => { "broadcast" => "192.168.4.255", + "netmask" => "255.255.255.0", + "family" => "inet" }, + "00:50:56:c0:00:08" => { "family" => "lladdr" } }, + "mtu" => "1500", + "type" => "vmnet", + "arp" => { "192.168.4.255" => "ff:ff:ff:ff:ff:ff" }, + "encapsulation" => "Ethernet" }, + "en0" => { "status" => "inactive", + "flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"], + "number" => "0", + "addresses" => { "00:23:32:b0:32:f2" => { "family" => "lladdr" } }, + "mtu" => "1500", + "media" => { "supported" => { "autoselect" => { "options" => [] }, + "none" => { "options" => [] }, + "1000baseT" => { "options" => ["full-duplex", "flow-control", "hw-loopback"] }, + "10baseT/UTP" => { "options" => ["half-duplex", "full-duplex", "flow-control", "hw-loopback"] }, + "100baseTX" => { "options" => ["half-duplex", "full-duplex", "flow-control", "hw-loopback"] } }, + "selected" => { "autoselect" => { "options" => [] } } }, + "type" => "en", + "encapsulation" => "Ethernet" }, + "en1" => { "status" => "active", + "flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"], + "number" => "1", + "addresses" => { "fe80::223:6cff:fe7f:676c" => { "scope" => "Link", "prefixlen" => "64", "family" => "inet6" }, + "00:23:6c:7f:67:6c" => { "family" => "lladdr" }, + "192.168.0.117" => { "broadcast" => "192.168.0.255", + "netmask" => "255.255.255.0", + "family" => "inet" } }, + "mtu" => "1500", + "media" => { "supported" => { "autoselect" => { "options" => [] } }, + "selected" => { "autoselect" => { "options" => [] } } }, + "type" => "en", + "arp" => { "192.168.0.72" => "0:f:ea:39:fa:d5", + "192.168.0.1" => "0:1c:fb:fc:6f:20", + "192.168.0.255" => "ff:ff:ff:ff:ff:ff", + "192.168.0.3" => "0:1f:33:ea:26:9b", + "192.168.0.77" => "0:23:12:70:f8:cf", + "192.168.0.152" => "0:26:8:7d:2:4c" }, + "encapsulation" => "Ethernet" }, + "en2" => { "status" => "active", + "flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"], + "number" => "2", + "addresses" => { "169.254.206.152" => { "broadcast" => "169.254.255.255", + "netmask" => "255.255.0.0", + "family" => "inet" }, + "00:1c:42:00:00:01" => { "family" => "lladdr" }, + "fe80::21c:42ff:fe00:1" => { "scope" => "Link", "prefixlen" => "64", "family" => "inet6" } }, + "mtu" => "1500", + "media" => { "supported" => { "autoselect" => { "options" => [] } }, + "selected" => { "autoselect" => { "options" => [] } } }, + "type" => "en", + "encapsulation" => "Ethernet" }, + "fw0" => { "status" => "inactive", + "flags" => ["BROADCAST", "SIMPLEX", "MULTICAST"], + "number" => "0", + "addresses" => { "00:23:32:ff:fe:b0:32:f2" => { "family" => "lladdr" } }, + "mtu" => "4078", + "media" => { "supported" => { "autoselect" => { "options" => ["full-duplex"] } }, + "selected" => { "autoselect" => { "options" => ["full-duplex"] } } }, + "type" => "fw", + "encapsulation" => "1394" }, + "en3" => { "status" => "active", + "flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"], + "number" => "3", + "addresses" => { "169.254.206.152" => { "broadcast" => "169.254.255.255", + "netmask" => "255.255.0.0", + "family" => "inet" }, + "00:1c:42:00:00:00" => { "family" => "lladdr" }, + "fe80::21c:42ff:fe00:0" => { "scope" => "Link", "prefixlen" => "64", "family" => "inet6" } }, + "mtu" => "1500", + "media" => { "supported" => { "autoselect" => { "options" => [] } }, + "selected" => { "autoselect" => { "options" => [] } } }, + "type" => "en", + "encapsulation" => "Ethernet" } } }, + "fqdn" => "latte.local", + "ohai_time" => 1249065590.90391, + "domain" => "local", + "os" => "darwin", + "platform_build" => "9J61", + "os_version" => "9.7.0", + "hostname" => "latte", + "macaddress" => "00:23:6c:7f:67:6c", + "music" => { "jimmy_eat_world" => "nice", "apophis" => false }, } @default_hash = { "domain" => "opscode.com", @@ -198,7 +154,7 @@ describe Chef::Node::Attribute do "mastodon" => "rocks", "mars_volta" => "is loud and nutty", "deeper" => { "gates_of_ishtar" => nil }, - "this" => {"apparatus" => {"must" => "be unearthed"}}, + "this" => { "apparatus" => { "must" => "be unearthed" } }, }, } @override_hash = { @@ -209,7 +165,7 @@ describe Chef::Node::Attribute do "mars_volta" => "cicatriz" }, } - @automatic_hash = {"week" => "friday"} + @automatic_hash = { "week" => "friday" } @attributes = Chef::Node::Attribute.new(@attribute_hash, @default_hash, @override_hash, @automatic_hash) end @@ -235,7 +191,6 @@ describe Chef::Node::Attribute do end describe "when printing attribute components" do - it "does not cause a type error" do # See CHEF-3799; IO#puts implicitly calls #to_ary on its argument. This # is expected to raise a NoMethodError or return an Array. `to_ary` is @@ -244,7 +199,6 @@ describe Chef::Node::Attribute do # (cf. there is no Hash#to_ary). expect { @attributes.default.to_ary }.to raise_error(NoMethodError) end - end describe "when debugging attributes" do @@ -354,13 +308,13 @@ describe Chef::Node::Attribute do it "merges nested hashes between precedence levels" do @attributes = Chef::Node::Attribute.new({}, {}, {}, {}) - @attributes.env_default = {"a" => {"b" => {"default" => "default"}}} - @attributes.normal = {"a" => {"b" => {"normal" => "normal"}}} - @attributes.override = {"a" => {"override" => "role"}} - @attributes.automatic = {"a" => {"automatic" => "auto"}} - expect(@attributes["a"]).to eq({"b"=>{"default"=>"default", "normal"=>"normal"}, - "override"=>"role", - "automatic"=>"auto"}) + @attributes.env_default = { "a" => { "b" => { "default" => "default" } } } + @attributes.normal = { "a" => { "b" => { "normal" => "normal" } } } + @attributes.override = { "a" => { "override" => "role" } } + @attributes.automatic = { "a" => { "automatic" => "auto" } } + expect(@attributes["a"]).to eq({ "b" => { "default" => "default", "normal" => "normal" }, + "override" => "role", + "automatic" => "auto" }) end end @@ -389,7 +343,6 @@ describe Chef::Node::Attribute do expect(@attributes.combined_default["ed"]).to eq("env default") expect(@attributes.combined_default["fd"]).to eq("force default") end - end describe "[]" do @@ -431,7 +384,7 @@ describe Chef::Node::Attribute do describe "[]=" do it "should error out when the type of attribute to set has not been specified" do - @attributes.normal["the_ghost"] = { } + @attributes.normal["the_ghost"] = {} expect { @attributes["the_ghost"]["exterminate"] = false }.to raise_error(Chef::Exceptions::ImmutableAttributeModification) end @@ -490,29 +443,29 @@ describe Chef::Node::Attribute do it "should create a deep copy of the node attribute" do @attributes.default["foo"]["bar"]["baz"] = "fizz" hash = @attributes["foo"].to_hash - expect(hash).to eql({"bar"=>{"baz"=>"fizz"}}) + expect(hash).to eql({ "bar" => { "baz" => "fizz" } }) hash["bar"]["baz"] = "buzz" - expect(hash).to eql({"bar"=>{"baz"=>"buzz"}}) - expect(@attributes.default["foo"]).to eql({"bar"=>{"baz"=>"fizz"}}) + expect(hash).to eql({ "bar" => { "baz" => "buzz" } }) + expect(@attributes.default["foo"]).to eql({ "bar" => { "baz" => "fizz" } }) end it "should create a deep copy of arrays in the node attribute" do @attributes.default["foo"]["bar"] = ["fizz"] hash = @attributes["foo"].to_hash - expect(hash).to eql({"bar"=>[ "fizz" ]}) + expect(hash).to eql({ "bar" => [ "fizz" ] }) hash["bar"].push("buzz") - expect(hash).to eql({"bar"=>[ "fizz", "buzz" ]}) - expect(@attributes.default["foo"]).to eql({"bar"=>[ "fizz" ]}) + expect(hash).to eql({ "bar" => [ "fizz", "buzz" ] }) + expect(@attributes.default["foo"]).to eql({ "bar" => [ "fizz" ] }) end it "mutating strings should not mutate the attributes" do pending "this is a bug that should be fixed" @attributes.default["foo"]["bar"]["baz"] = "fizz" hash = @attributes["foo"].to_hash - expect(hash).to eql({"bar"=>{"baz"=>"fizz"}}) + expect(hash).to eql({ "bar" => { "baz" => "fizz" } }) hash["bar"]["baz"] << "buzz" - expect(hash).to eql({"bar"=>{"baz"=>"fizzbuzz"}}) - expect(@attributes.default["foo"]).to eql({"bar"=>{"baz"=>"fizz"}}) + expect(hash).to eql({ "bar" => { "baz" => "fizzbuzz" } }) + expect(@attributes.default["foo"]).to eql({ "bar" => { "baz" => "fizz" } }) end end @@ -572,7 +525,6 @@ describe Chef::Node::Attribute do it "should return false if an attribute does not exist" do expect(@attributes.attribute?("ninja")).to eq(false) end - end describe "method_missing" do @@ -592,7 +544,7 @@ describe Chef::Node::Attribute do { "one" => { "two" => "three" }, "hut" => { "two" => "three" }, - "place" => { }, + "place" => {}, }, { "one" => { "four" => "five" }, @@ -820,7 +772,6 @@ describe Chef::Node::Attribute do it "should return false when there are keys" do expect(@attributes.empty?).to eq(false) end - end describe "fetch" do @@ -853,7 +804,7 @@ describe Chef::Node::Attribute do "hut" => "three", "snakes" => "on a plane", "snack" => "cookies", - }.each do |k,v| + }.each do |k, v| expect(@attributes.fetch(k)).to eq(v) end end @@ -963,7 +914,6 @@ describe Chef::Node::Attribute do end end end - end describe "values" do @@ -999,7 +949,6 @@ describe Chef::Node::Attribute do expect(@attributes.values).to include("three") expect(@attributes.values).to include("on a plane") end - end describe "select" do @@ -1031,7 +980,7 @@ describe Chef::Node::Attribute do end else it "should raise a LocalJumpError if no block is given" do - expect{ @attributes.select }.to raise_error(LocalJumpError) + expect { @attributes.select }.to raise_error(LocalJumpError) end end @@ -1070,7 +1019,7 @@ describe Chef::Node::Attribute do {}, ) - @empty = Chef::Node::Attribute.new({},{},{},{}) + @empty = Chef::Node::Attribute.new({}, {}, {}, {}) end it "should respond to size" do @@ -1116,12 +1065,12 @@ describe Chef::Node::Attribute do it "should output merged attributes" do default_hash = { - "a" => 1, - "b" => 2, + "a" => 1, + "b" => 2, } override_hash = { - "b" => 3, - "c" => 4, + "b" => 3, + "c" => 4, } attributes = Chef::Node::Attribute.new(nil, default_hash, override_hash, nil) expect(attributes.to_s).to eq('{"a"=>1, "b"=>3, "c"=>4}') @@ -1138,16 +1087,13 @@ describe Chef::Node::Attribute do end end - describe "when not mutated" do - it "does not reset the cache when dup'd [CHEF-3680]" do @attributes.default[:foo][:bar] = "set on original" subtree = @attributes[:foo] @attributes.default[:foo].dup[:bar] = "set on dup" expect(subtree[:bar]).to eq("set on original") end - end describe "when setting a component attribute to a new value" do @@ -1218,7 +1164,5 @@ describe Chef::Node::Attribute do it "raises an error when using `attr=value`" do expect { @attributes.new_key = "new value" }.to raise_error(Chef::Exceptions::ImmutableAttributeModification) end - end - end diff --git a/spec/unit/node/immutable_collections_spec.rb b/spec/unit/node/immutable_collections_spec.rb index 2a0884f4b2..523b4706c6 100644 --- a/spec/unit/node/immutable_collections_spec.rb +++ b/spec/unit/node/immutable_collections_spec.rb @@ -21,10 +21,10 @@ require "chef/node/immutable_collections" describe Chef::Node::ImmutableMash do before do - @data_in = {:top => {:second_level => "some value"}, - "top_level_2" => %w{array of values}, - :top_level_3 => [{:hash_array => 1, :hash_array_b => 2}], - :top_level_4 => {:level2 => {:key => "value"}}, + @data_in = { :top => { :second_level => "some value" }, + "top_level_2" => %w{array of values}, + :top_level_3 => [{ :hash_array => 1, :hash_array_b => 2 }], + :top_level_4 => { :level2 => { :key => "value" } }, } @immutable_mash = Chef::Node::ImmutableMash.new(@data_in) end @@ -78,7 +78,6 @@ describe Chef::Node::ImmutableMash do it "should allow mutation" do expect { @copy["m"] = "m" }.not_to raise_error end - end [ @@ -106,15 +105,13 @@ describe Chef::Node::ImmutableMash do mutable[:new_key] = :value expect(mutable[:new_key]).to eq(:value) end - end describe Chef::Node::ImmutableArray do - before do @immutable_array = Chef::Node::ImmutableArray.new(%w{foo bar baz} + Array(1..3) + [nil, true, false, [ "el", 0, nil ] ]) - immutable_mash = Chef::Node::ImmutableMash.new({:m => "m"}) - @immutable_nested_array = Chef::Node::ImmutableArray.new(["level1",@immutable_array, immutable_mash]) + immutable_mash = Chef::Node::ImmutableMash.new({ :m => "m" }) + @immutable_nested_array = Chef::Node::ImmutableArray.new(["level1", @immutable_array, immutable_mash]) end ## @@ -154,7 +151,7 @@ describe Chef::Node::ImmutableArray do :unshift, ].each do |mutator| it "does not allow mutation via `#{mutator}" do - expect { @immutable_array.send(mutator)}.to raise_error + expect { @immutable_array.send(mutator) }.to raise_error end end @@ -193,6 +190,4 @@ describe Chef::Node::ImmutableArray do expect { @copy << "m" }.not_to raise_error end end - end - diff --git a/spec/unit/node_map_spec.rb b/spec/unit/node_map_spec.rb index 7d9a85bbb4..e1465d2676 100644 --- a/spec/unit/node_map_spec.rb +++ b/spec/unit/node_map_spec.rb @@ -20,14 +20,13 @@ require "spec_helper" require "chef/node_map" describe Chef::NodeMap do - let(:node_map) { Chef::NodeMap.new } let(:node) { Chef::Node.new } describe "with a bad filter name" do it "should raise an error" do - expect{ node_map.set(node, :thing, on_platform_family: "rhel") }.to raise_error + expect { node_map.set(node, :thing, on_platform_family: "rhel") }.to raise_error end end @@ -166,5 +165,4 @@ describe Chef::NodeMap do expect(node_map.get(node, :link)).to eql(:foo) end end - end diff --git a/spec/unit/node_spec.rb b/spec/unit/node_spec.rb index 234955cc27..109e4ceb36 100644 --- a/spec/unit/node_spec.rb +++ b/spec/unit/node_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "ostruct" describe Chef::Node do - let(:node) { Chef::Node.new() } let(:platform_introspector) { node } @@ -32,7 +31,7 @@ describe Chef::Node do end it "should validate the name of the node" do - expect{Chef::Node.build("solo node")}.to raise_error(Chef::Exceptions::ValidationFailed) + expect { Chef::Node.build("solo node") }.to raise_error(Chef::Exceptions::ValidationFailed) end it "should be sortable" do @@ -107,11 +106,11 @@ describe Chef::Node do end it "cannot be blank" do - expect { node.name("")}.to raise_error(Chef::Exceptions::ValidationFailed) + expect { node.name("") }.to raise_error(Chef::Exceptions::ValidationFailed) end it "should not accept name doesn't match /^[\-[:alnum:]_:.]+$/" do - expect { node.name("space in it")}.to raise_error(Chef::Exceptions::ValidationFailed) + expect { node.name("space in it") }.to raise_error(Chef::Exceptions::ValidationFailed) end end @@ -131,12 +130,11 @@ describe Chef::Node do end it "cannot be blank" do - expect { node.chef_environment("")}.to raise_error(Chef::Exceptions::ValidationFailed) + expect { node.chef_environment("") }.to raise_error(Chef::Exceptions::ValidationFailed) end end describe "policy_name" do - it "defaults to nil" do expect(node.policy_name).to be_nil end @@ -167,12 +165,11 @@ describe Chef::Node do end it "cannot be blank" do - expect { node.policy_name("")}.to raise_error(Chef::Exceptions::ValidationFailed) + expect { node.policy_name("") }.to raise_error(Chef::Exceptions::ValidationFailed) end end describe "policy_group" do - it "defaults to nil" do expect(node.policy_group).to be_nil end @@ -203,7 +200,7 @@ describe Chef::Node do end it "cannot be blank" do - expect { node.policy_group("")}.to raise_error(Chef::Exceptions::ValidationFailed) + expect { node.policy_group("") }.to raise_error(Chef::Exceptions::ValidationFailed) end end @@ -223,7 +220,7 @@ describe Chef::Node do end it "does not allow you to set an attribute via node[]=" do - expect { node["secret"] = "shush" }.to raise_error(Chef::Exceptions::ImmutableAttributeModification) + expect { node["secret"] = "shush" }.to raise_error(Chef::Exceptions::ImmutableAttributeModification) end it "should allow you to query whether an attribute exists with attribute?" do @@ -239,7 +236,7 @@ describe Chef::Node do end it "does not allow you to set an attribute via method_missing" do - expect { node.sunshine = "is bright"}.to raise_error(Chef::Exceptions::ImmutableAttributeModification) + expect { node.sunshine = "is bright" }.to raise_error(Chef::Exceptions::ImmutableAttributeModification) end it "should allow you get get an attribute via method_missing" do @@ -389,7 +386,7 @@ describe Chef::Node do it "deletes nested things correctly" do node.default["mysql"]["client"]["client_setting"] = "foo" - expect( node.rm("mysql", "server") ).to eql( {"port" => 3456} ) + expect( node.rm("mysql", "server") ).to eql( { "port" => 3456 } ) expect( node["mysql"] ).to eql( { "client" => { "client_setting" => "foo" } } ) end @@ -398,7 +395,7 @@ describe Chef::Node do end it "can delete the entire tree" do - expect( node.rm("mysql") ).to eql({"server"=>{"port"=>3456}}) + expect( node.rm("mysql") ).to eql({ "server" => { "port" => 3456 } }) end end @@ -614,8 +611,8 @@ describe Chef::Node do } expect( node["mysql"]["server"] ).to eql({ - "data_dir" => "/my_raid_volume/lib/mysql" - },) + "data_dir" => "/my_raid_volume/lib/mysql" + },) end it "removes all values from the precedence level when setting" do @@ -630,8 +627,8 @@ describe Chef::Node do expect( node["mysql"]["server"]["port"] ).to be_nil expect( node["mysql"]["server"]["data_dir"] ).to eql("/my_raid_volume/lib/mysql") expect( node["mysql"]["server"] ).to eql({ - "data_dir" => "/my_raid_volume/lib/mysql" - },) + "data_dir" => "/my_raid_volume/lib/mysql" + },) end it "higher precedence levels are not removed" do @@ -647,9 +644,9 @@ describe Chef::Node do expect( node["mysql"]["server"]["port"] ).to be_nil expect( node["mysql"]["server"]["data_dir"] ).to eql("/my_raid_volume/lib/mysql") expect( node["mysql"]["server"] ).to eql({ - "service_name" => "fancypants-sql", - "data_dir" => "/my_raid_volume/lib/mysql", - },) + "service_name" => "fancypants-sql", + "data_dir" => "/my_raid_volume/lib/mysql", + },) end it "will autovivify" do @@ -672,9 +669,9 @@ describe Chef::Node do expect( node["mysql"]["server"]["port"] ).to be_nil expect( node["mysql"]["server"]["data_dir"] ).to eql("/my_raid_volume/lib/mysql") expect( node["mysql"]["server"] ).to eql({ - "service_name" => "fancypants-sql", - "data_dir" => "/my_raid_volume/lib/mysql", - },) + "service_name" => "fancypants-sql", + "data_dir" => "/my_raid_volume/lib/mysql", + },) end it "when overwriting a non-hash/array" do @@ -692,8 +689,8 @@ describe Chef::Node do "data_dir" => "/my_raid_volume/lib/mysql" } expect( node["mysql"]["server"] ).to eql({ - "data_dir" => "/my_raid_volume/lib/mysql" - },) + "data_dir" => "/my_raid_volume/lib/mysql" + },) end end @@ -736,7 +733,7 @@ describe Chef::Node do node.default.sunshine = "is bright" node.default.canada = "is a nice place" seen_attributes = Hash.new - node.each_attribute do |a,v| + node.each_attribute do |a, v| seen_attributes[a] = v end expect(seen_attributes).to have_key("sunshine") @@ -747,14 +744,13 @@ describe Chef::Node do end describe "consuming json" do - before do - @ohai_data = {:platform => "foo", :platform_version => "bar"} + @ohai_data = { :platform => "foo", :platform_version => "bar" } end it "consumes the run list portion of a collection of attributes and returns the remainder" do - attrs = {"run_list" => [ "role[base]", "recipe[chef::server]" ], "foo" => "bar"} - expect(node.consume_run_list(attrs)).to eq({"foo" => "bar"}) + attrs = { "run_list" => [ "role[base]", "recipe[chef::server]" ], "foo" => "bar" } + expect(node.consume_run_list(attrs)).to eq({ "foo" => "bar" }) expect(node.run_list).to eq([ "role[base]", "recipe[chef::server]" ]) end @@ -774,7 +770,7 @@ describe Chef::Node do it "should not add duplicate recipes from the json attributes" do node.run_list << "one" node.consume_run_list "recipes" => [ "one", "two", "three" ] - expect(node.run_list).to eq([ "one", "two", "three" ]) + expect(node.run_list).to eq([ "one", "two", "three" ]) end it "doesn't change the run list if no run_list is specified in the json" do @@ -788,7 +784,7 @@ describe Chef::Node do end it "should add json attributes to the node" do - node.consume_external_attrs(@ohai_data, {"one" => "two", "three" => "four"}) + node.consume_external_attrs(@ohai_data, { "one" => "two", "three" => "four" }) expect(node.one).to eql("two") expect(node.three).to eql("four") end @@ -823,25 +819,24 @@ describe Chef::Node do end it "deep merges attributes instead of overwriting them" do - node.consume_external_attrs(@ohai_data, "one" => {"two" => {"three" => "four"}}) - expect(node.one.to_hash).to eq({"two" => {"three" => "four"}}) - node.consume_external_attrs(@ohai_data, "one" => {"abc" => "123"}) - node.consume_external_attrs(@ohai_data, "one" => {"two" => {"foo" => "bar"}}) - expect(node.one.to_hash).to eq({"two" => {"three" => "four", "foo" => "bar"}, "abc" => "123"}) + node.consume_external_attrs(@ohai_data, "one" => { "two" => { "three" => "four" } }) + expect(node.one.to_hash).to eq({ "two" => { "three" => "four" } }) + node.consume_external_attrs(@ohai_data, "one" => { "abc" => "123" }) + node.consume_external_attrs(@ohai_data, "one" => { "two" => { "foo" => "bar" } }) + expect(node.one.to_hash).to eq({ "two" => { "three" => "four", "foo" => "bar" }, "abc" => "123" }) end it "gives attributes from JSON priority when deep merging" do - node.consume_external_attrs(@ohai_data, "one" => {"two" => {"three" => "four"}}) - expect(node.one.to_hash).to eq({"two" => {"three" => "four"}}) - node.consume_external_attrs(@ohai_data, "one" => {"two" => {"three" => "forty-two"}}) - expect(node.one.to_hash).to eq({"two" => {"three" => "forty-two"}}) + node.consume_external_attrs(@ohai_data, "one" => { "two" => { "three" => "four" } }) + expect(node.one.to_hash).to eq({ "two" => { "three" => "four" } }) + node.consume_external_attrs(@ohai_data, "one" => { "two" => { "three" => "forty-two" } }) + expect(node.one.to_hash).to eq({ "two" => { "three" => "forty-two" } }) end - end describe "preparing for a chef client run" do before do - @ohai_data = {:platform => "foobuntu", :platform_version => "23.42"} + @ohai_data = { :platform => "foobuntu", :platform_version => "23.42" } end it "sets its platform according to platform detection" do @@ -851,18 +846,17 @@ describe Chef::Node do end it "consumes the run list from provided json attributes" do - node.consume_external_attrs(@ohai_data, {"run_list" => ["recipe[unicorn]"]}) + node.consume_external_attrs(@ohai_data, { "run_list" => ["recipe[unicorn]"] }) expect(node.run_list).to eq(["recipe[unicorn]"]) end it "saves non-runlist json attrs for later" do expansion = Chef::RunList::RunListExpansion.new("_default", []) allow(node.run_list).to receive(:expand).and_return(expansion) - node.consume_external_attrs(@ohai_data, {"foo" => "bar"}) + node.consume_external_attrs(@ohai_data, { "foo" => "bar" }) node.expand! - expect(node.normal_attrs).to eq({"foo" => "bar", "tags" => []}) + expect(node.normal_attrs).to eq({ "foo" => "bar", "tags" => [] }) end - end describe "when expanding its run list and merging attributes" do @@ -885,7 +879,7 @@ describe Chef::Node do end it "sets the 'roles' automatic attribute to the expanded role list" do - @expansion.instance_variable_set(:@applied_roles, {"arf" => nil, "countersnark" => nil}) + @expansion.instance_variable_set(:@applied_roles, { "arf" => nil, "countersnark" => nil }) node.expand! expect(node.automatic_attrs[:roles].sort).to eq(["arf", "countersnark"]) end @@ -978,19 +972,18 @@ describe Chef::Node do it "leaves normal level attributes untouched" do expect(node[:foo]).to eq("normal") end - end describe "when merging environment attributes" do before do node.chef_environment = "rspec" @expansion = Chef::RunList::RunListExpansion.new("rspec", []) - @expansion.default_attrs.replace({:default => "from role", :d_role => "role only"}) - @expansion.override_attrs.replace({:override => "from role", :o_role => "role only"}) + @expansion.default_attrs.replace({ :default => "from role", :d_role => "role only" }) + @expansion.override_attrs.replace({ :override => "from role", :o_role => "role only" }) @environment = Chef::Environment.new - @environment.default_attributes = {:default => "from env", :d_env => "env only" } - @environment.override_attributes = {:override => "from env", :o_env => "env only"} + @environment.default_attributes = { :default => "from env", :d_env => "env only" } + @environment.override_attributes = { :override => "from env", :o_env => "env only" } allow(Chef::Environment).to receive(:load).and_return(@environment) node.apply_expansion_attributes(@expansion) end @@ -1173,8 +1166,8 @@ describe Chef::Node do it "should serialize valid json with a run list", :json => true do #This test came about because activesupport mucks with Chef json serialization #Test should pass with and without Activesupport - node.run_list << {"type" => "role", "name" => "Cthulu"} - node.run_list << {"type" => "role", "name" => "Hastur"} + node.run_list << { "type" => "role", "name" => "Cthulu" } + node.run_list << { "type" => "role", "name" => "Hastur" } json = Chef::JSONCompat.to_json(node) expect(json).to match(/\"run_list\":\[\"role\[Cthulu\]\",\"role\[Hastur\]\"\]/) end @@ -1211,14 +1204,13 @@ describe Chef::Node do expect(serialized_node).to be_a_kind_of(Chef::Node) expect(serialized_node.name).to eql(node.name) expect(serialized_node.chef_environment).to eql(node.chef_environment) - node.each_attribute do |k,v| + node.each_attribute do |k, v| expect(serialized_node[k]).to eql(v) end expect(serialized_node.run_list).to eq(node.run_list) end context "when policyfile attributes are not present" do - it "does not have a policy_name key in the json" do expect(node.for_json.keys).to_not include("policy_name") end @@ -1229,7 +1221,6 @@ describe Chef::Node do end context "when policyfile attributes are present" do - before do node.policy_name = "my-application" node.policy_group = "staging" @@ -1251,7 +1242,6 @@ describe Chef::Node do expect(round_tripped_node.policy_name).to eq("my-application") expect(round_tripped_node.policy_group).to eq("staging") end - end include_examples "to_json equivalent to Chef::JSONCompat.to_json" do @@ -1457,7 +1447,6 @@ describe Chef::Node do end context "when policyfile attributes are present" do - before do node.name("example-node") node.policy_name = "my-application" @@ -1465,7 +1454,6 @@ describe Chef::Node do end context "and the server supports policyfile attributes in node JSON" do - it "creates the object normally" do expect(@rest).to receive(:post).with("nodes", node.for_json) node.create @@ -1479,7 +1467,6 @@ describe Chef::Node do # Chef Server before 12.3 context "and the Chef Server does not support policyfile attributes in node JSON" do - let(:response_body) { %q[{"error":["Invalid key policy_name in request body"]}] } let(:response) do @@ -1501,11 +1488,9 @@ describe Chef::Node do j.delete("policy_name") j.delete("policy_group") end - end context "on Chef Client 13 and later" do - # Though we normally attempt to provide compatibility with chef # server one major version back, policyfiles were beta when we # added the policyfile attributes to the node JSON, therefore @@ -1514,21 +1499,17 @@ describe Chef::Node do it "lets the 400 pass through", :chef_gte_13_only do expect { node.save }.to raise_error(http_exception) end - end context "when the node exists" do - it "falls back to saving without policyfile attributes" do expect(@rest).to receive(:put).with("nodes/example-node", node.for_json).and_raise(http_exception) expect(@rest).to receive(:put).with("nodes/example-node", trimmed_node).and_return(@node) expect { node.save }.to_not raise_error end - end context "when the node doesn't exist" do - let(:response_404) do Net::HTTPResponse.send(:response_class, "404").new("1.0", "404", "Not Found") end @@ -1554,12 +1535,8 @@ describe Chef::Node do node.create end end - end - end - end end - end diff --git a/spec/unit/org_spec.rb b/spec/unit/org_spec.rb index 7c6fcc9e6c..49557417a5 100644 --- a/spec/unit/org_spec.rb +++ b/spec/unit/org_spec.rb @@ -110,8 +110,8 @@ describe Chef::Org do describe "when deserializing from JSON" do let(:org) do o = { "name" => "turtle", - "full_name" => "turtle_club", - "private_key" => "pandas" } + "full_name" => "turtle_club", + "private_key" => "pandas" } Chef::Org.from_json(o.to_json) end @@ -147,8 +147,8 @@ describe Chef::Org do end describe "list" do - let(:response) { {"foobar" => "http://www.example.com/organizations/foobar"} } - let(:inflated_response) { {"foobar" => org } } + let(:response) { { "foobar" => "http://www.example.com/organizations/foobar" } } + let(:inflated_response) { { "foobar" => org } } it "lists all orgs" do expect(rest).to receive(:get).with("organizations").and_return(response) @@ -164,14 +164,14 @@ describe Chef::Org do describe "create" do it "creates a new org via the API" do - expect(rest).to receive(:post).with("organizations", {:name => "foobar", :full_name => "foo bar bat"}).and_return({}) + expect(rest).to receive(:post).with("organizations", { :name => "foobar", :full_name => "foo bar bat" }).and_return({}) org.create end end describe "read" do it "loads a named org from the API" do - expect(rest).to receive(:get).with("organizations/foobar").and_return({"name" => "foobar", "full_name" => "foo bar bat", "private_key" => "private"}) + expect(rest).to receive(:get).with("organizations/foobar").and_return({ "name" => "foobar", "full_name" => "foo bar bat", "private_key" => "private" }) org = Chef::Org.load("foobar") expect(org.name).to eq("foobar") expect(org.full_name).to eq("foo bar bat") @@ -181,7 +181,7 @@ describe Chef::Org do describe "update" do it "updates an existing org on via the API" do - expect(rest).to receive(:put).with("organizations/foobar", {:name => "foobar", :full_name => "foo bar bat"}).and_return({}) + expect(rest).to receive(:put).with("organizations/foobar", { :name => "foobar", :full_name => "foo bar bat" }).and_return({}) org.update end end diff --git a/spec/unit/platform/query_helpers_spec.rb b/spec/unit/platform/query_helpers_spec.rb index 7eeeb696eb..49da6a95f0 100644 --- a/spec/unit/platform/query_helpers_spec.rb +++ b/spec/unit/platform/query_helpers_spec.rb @@ -103,7 +103,7 @@ describe "Chef::Platform#windows_nano_server?" do end describe "Chef::Platform#supports_msi?" do - include_context "Win32" # clear and restore Win32:: namespace + include_context "Win32" # clear and restore Win32:: namespace let(:key) { "System\\CurrentControlSet\\Services\\msiserver" } let(:key_query_value) { 0x0001 } @@ -198,7 +198,7 @@ end describe 'Chef::Platform#dsc_refresh_mode_disabled?' do let(:node) { instance_double("Chef::Node") } let(:cmdlet) { instance_double("Chef::Util::Powershell::Cmdlet") } - let(:cmdlet_result) { instance_double("Chef::Util::Powershell::CmdletResult")} + let(:cmdlet_result) { instance_double("Chef::Util::Powershell::CmdletResult") } it "returns true when RefreshMode is Disabled" do expect(Chef::Util::Powershell::Cmdlet).to receive(:new). diff --git a/spec/unit/platform_spec.rb b/spec/unit/platform_spec.rb index 4ad2b3e9c0..9770aa05d0 100644 --- a/spec/unit/platform_spec.rb +++ b/spec/unit/platform_spec.rb @@ -19,9 +19,7 @@ require "spec_helper" describe Chef::Platform do - context "while testing with fake data" do - before :all do @original_platform_map = Chef::Platform.platforms end @@ -171,11 +169,11 @@ describe Chef::Platform do it "raises an error when trying to find the provider for a resource with no run context" do file = Chef::Resource::File.new("whateva") - expect {Chef::Platform.provider_for_resource(file)}.to raise_error(ArgumentError) + expect { Chef::Platform.provider_for_resource(file) }.to raise_error(ArgumentError) end it "does not support finding a provider by resource and node -- a run context is required" do - expect {Chef::Platform.provider_for_node("node", "resource")}.to raise_error(NotImplementedError) + expect { Chef::Platform.provider_for_node("node", "resource") }.to raise_error(NotImplementedError) end it "should update the provider map with map" do @@ -223,7 +221,6 @@ describe Chef::Platform do Chef::Platform.platforms = { :neurosis => {} } Chef::Platform.set(:platform => :neurosis, :resource => :package, :provider => "masterful") expect(Chef::Platform.platforms[:neurosis][:default][:package]).to eql("masterful") - end it "does not overwrite the platform map when using :default platform" do @@ -235,7 +232,5 @@ describe Chef::Platform do expect(Chef::Platform.platforms[:default][:file]).to eql("new school") expect(Chef::Platform.platforms[:default][:cat]).to eql("nice") end - end - end diff --git a/spec/unit/policy_builder/dynamic_spec.rb b/spec/unit/policy_builder/dynamic_spec.rb index 19ad057863..aac6c5ad4d 100644 --- a/spec/unit/policy_builder/dynamic_spec.rb +++ b/spec/unit/policy_builder/dynamic_spec.rb @@ -20,10 +20,9 @@ require "spec_helper" require "chef/policy_builder" describe Chef::PolicyBuilder::Dynamic do - let(:node_name) { "joe_node" } - let(:ohai_data) { {"platform" => "ubuntu", "platform_version" => "13.04", "fqdn" => "joenode.example.com"} } - let(:json_attribs) { {"custom_attr" => "custom_attr_value"} } + let(:ohai_data) { { "platform" => "ubuntu", "platform_version" => "13.04", "fqdn" => "joenode.example.com" } } + let(:json_attribs) { { "custom_attr" => "custom_attr_value" } } let(:override_runlist) { nil } let(:events) { Chef::EventDispatch::Dispatcher.new } @@ -40,9 +39,7 @@ describe Chef::PolicyBuilder::Dynamic do subject(:policy_builder) { Chef::PolicyBuilder::Dynamic.new(node_name, ohai_data, json_attribs, override_runlist, events) } describe "loading policy data" do - describe "delegating PolicyBuilder API to the correct implementation" do - let(:implementation) { instance_double("Chef::PolicyBuilder::Policyfile") } before do @@ -99,40 +96,32 @@ describe Chef::PolicyBuilder::Dynamic do expect(implementation).to receive(:temporary_policy?) policy_builder.temporary_policy? end - end describe "selecting a backend implementation" do - let(:implementation) do policy_builder.select_implementation(node) policy_builder.implementation end context "when no policyfile attributes are present on the node" do - context "and json_attribs are not given" do - let(:json_attribs) { {} } it "uses the ExpandNodeObject implementation" do expect(implementation).to be_a(Chef::PolicyBuilder::ExpandNodeObject) end - end context "and no policyfile attributes are present in json_attribs" do - - let(:json_attribs) { {"foo" => "bar"} } + let(:json_attribs) { { "foo" => "bar" } } it "uses the ExpandNodeObject implementation" do expect(implementation).to be_a(Chef::PolicyBuilder::ExpandNodeObject) end - end context "and :use_policyfile is set in Chef::Config" do - before do Chef::Config[:use_policyfile] = true end @@ -140,11 +129,9 @@ describe Chef::PolicyBuilder::Dynamic do it "uses the Policyfile implementation" do expect(implementation).to be_a(Chef::PolicyBuilder::Policyfile) end - end context "and policy_name and policy_group are set on Chef::Config" do - before do Chef::Config[:policy_name] = "example-policy" Chef::Config[:policy_group] = "testing" @@ -153,11 +140,9 @@ describe Chef::PolicyBuilder::Dynamic do it "uses the Policyfile implementation" do expect(implementation).to be_a(Chef::PolicyBuilder::Policyfile) end - end context "and deployment_group and policy_document_native_api are set on Chef::Config" do - before do Chef::Config[:deployment_group] = "example-policy-staging" Chef::Config[:policy_document_native_api] = false @@ -166,23 +151,18 @@ describe Chef::PolicyBuilder::Dynamic do it "uses the Policyfile implementation" do expect(implementation).to be_a(Chef::PolicyBuilder::Policyfile) end - end context "and policyfile attributes are present in json_attribs" do - - let(:json_attribs) { {"policy_name" => "example-policy", "policy_group" => "testing"} } + let(:json_attribs) { { "policy_name" => "example-policy", "policy_group" => "testing" } } it "uses the Policyfile implementation" do expect(implementation).to be_a(Chef::PolicyBuilder::Policyfile) end - end - end context "when policyfile attributes are present on the node" do - let(:node) do base_node.policy_name = "example-policy" base_node.policy_group = "staging" @@ -192,13 +172,10 @@ describe Chef::PolicyBuilder::Dynamic do it "uses the Policyfile implementation" do expect(implementation).to be_a(Chef::PolicyBuilder::Policyfile) end - end - end describe "loading a node" do - let(:implementation) { instance_double("Chef::PolicyBuilder::Policyfile") } before do @@ -206,10 +183,7 @@ describe Chef::PolicyBuilder::Dynamic do end context "when not running chef solo" do - - context "when successful" do - before do expect(Chef::Node).to receive(:find_or_create).with(node_name).and_return(node) expect(policy_builder).to receive(:select_implementation).with(node) @@ -219,11 +193,9 @@ describe Chef::PolicyBuilder::Dynamic do it "selects the backend implementation and continues node loading" do policy_builder.load_node end - end context "when an error occurs finding the node" do - before do expect(Chef::Node).to receive(:find_or_create).with(node_name).and_raise("oops") end @@ -232,29 +204,23 @@ describe Chef::PolicyBuilder::Dynamic do expect(events).to receive(:node_load_failed) expect { policy_builder.load_node }.to raise_error("oops") end - end context "when an error occurs in the implementation's finish_load_node call" do - before do expect(Chef::Node).to receive(:find_or_create).with(node_name).and_return(node) expect(policy_builder).to receive(:select_implementation).with(node) expect(implementation).to receive(:finish_load_node).and_raise("oops") end - it "sends a node_load_failed event and re-raises" do expect(events).to receive(:node_load_failed) expect { policy_builder.load_node }.to raise_error("oops") end - end - end context "when running chef solo" do - before do Chef::Config[:solo] = true expect(Chef::Node).to receive(:build).with(node_name).and_return(node) @@ -265,11 +231,7 @@ describe Chef::PolicyBuilder::Dynamic do it "selects the backend implementation and continues node loading" do policy_builder.load_node end - end - end - end - end diff --git a/spec/unit/policy_builder/expand_node_object_spec.rb b/spec/unit/policy_builder/expand_node_object_spec.rb index 2a1a85e605..94f4b178f8 100644 --- a/spec/unit/policy_builder/expand_node_object_spec.rb +++ b/spec/unit/policy_builder/expand_node_object_spec.rb @@ -20,10 +20,9 @@ require "spec_helper" require "chef/policy_builder" describe Chef::PolicyBuilder::ExpandNodeObject do - let(:node_name) { "joe_node" } - let(:ohai_data) { {"platform" => "ubuntu", "platform_version" => "13.04", "fqdn" => "joenode.example.com"} } - let(:json_attribs) { {"run_list" => []} } + let(:ohai_data) { { "platform" => "ubuntu", "platform_version" => "13.04", "fqdn" => "joenode.example.com" } } + let(:json_attribs) { { "run_list" => [] } } let(:override_runlist) { "recipe[foo::default]" } let(:events) { Chef::EventDispatch::Dispatcher.new } let(:policy_builder) { Chef::PolicyBuilder::ExpandNodeObject.new(node_name, ohai_data, json_attribs, override_runlist, events) } @@ -72,22 +71,18 @@ describe Chef::PolicyBuilder::ExpandNodeObject do end describe "finishing loading the node" do - let(:node) { Chef::Node.new.tap { |n| n.name(node_name) } } it "stores the node" do policy_builder.finish_load_node(node) expect(policy_builder.node).to eq(node) end - end - end # Implementation specific tests describe "when first created" do - it "has a node_name" do expect(policy_builder.node_name).to eq(node_name) end @@ -103,11 +98,9 @@ describe Chef::PolicyBuilder::ExpandNodeObject do it "has an override_runlist" do expect(policy_builder.override_runlist).to eq(override_runlist) end - end context "deprecated #load_node method" do - let(:node) do node = Chef::Node.new node.name(node_name) @@ -124,7 +117,6 @@ describe Chef::PolicyBuilder::ExpandNodeObject do it "loads the node" do expect(policy_builder.node).to eq(node) end - end context "once the node has been loaded" do @@ -144,19 +136,17 @@ describe Chef::PolicyBuilder::ExpandNodeObject do expect(policy_builder.run_list_expansion).to be_a(Chef::RunList::RunListExpansion) expect(policy_builder.run_list_expansion.recipes).to eq(["a::default", "b::server"]) end - end describe "building the node" do - let(:configured_environment) { nil } let(:json_attribs) { nil } let(:override_runlist) { nil } let(:primary_runlist) { ["recipe[primary::default]"] } - let(:original_default_attrs) { {"default_key" => "default_value"} } - let(:original_override_attrs) { {"override_key" => "override_value"} } + let(:original_default_attrs) { { "default_key" => "default_value" } } + let(:original_override_attrs) { { "override_key" => "override_value" } } let(:node) do node = Chef::Node.new @@ -191,7 +181,6 @@ describe Chef::PolicyBuilder::ExpandNodeObject do end describe "when the given run list is not in expanded form" do - # NOTE: for chef-client, the behavior is always to expand the run list, # but this operation is a no-op when none of the run list items are # roles. Because of the amount of mocking required to make this work in @@ -222,12 +211,10 @@ describe Chef::PolicyBuilder::ExpandNodeObject do it "expands run list items via the server API" do expect(node.run_list).to eq(["recipe[from_role::default]"]) end - end context "when JSON attributes are given on the command line" do - - let(:json_attribs) { {"run_list" => ["recipe[json_attribs::default]"], "json_attribs_key" => "json_attribs_value" } } + let(:json_attribs) { { "run_list" => ["recipe[json_attribs::default]"], "json_attribs_key" => "json_attribs_value" } } it "sets the run list according to the given JSON" do expect(node.run_list).to eq(["recipe[json_attribs::default]"]) @@ -236,11 +223,9 @@ describe Chef::PolicyBuilder::ExpandNodeObject do it "sets node attributes according to the given JSON" do expect(node["json_attribs_key"]).to eq("json_attribs_value") end - end context "when an override_runlist is given" do - let(:override_runlist) { "recipe[foo::default]" } it "sets the override run_list on the node" do @@ -251,23 +236,19 @@ describe Chef::PolicyBuilder::ExpandNodeObject do it "reports that a temporary policy is being used" do expect(policy_builder.temporary_policy?).to be_truthy end - end context "when no environment is specified" do - it "does not set the environment" do expect(node.chef_environment).to eq("_default") end - end context "when a custom environment is configured" do - let(:configured_environment) { environment.name } let(:environment) do - environment = Chef::Environment.new.tap {|e| e.name("prod") } + environment = Chef::Environment.new.tap { |e| e.name("prod") } expect(Chef::Environment).to receive(:load).with("prod").and_return(environment) environment end @@ -276,7 +257,6 @@ describe Chef::PolicyBuilder::ExpandNodeObject do expect(node.chef_environment).to eq(environment.name) end end - end describe "configuring the run_context" do @@ -293,7 +273,7 @@ describe Chef::PolicyBuilder::ExpandNodeObject do let(:chef_http) { double("Chef::ServerAPI") } let(:cookbook_resolve_url) { "environments/#{node.chef_environment}/cookbook_versions" } - let(:cookbook_resolve_post_data) { {:run_list=>["first::default", "second::default"]} } + let(:cookbook_resolve_post_data) { { :run_list => ["first::default", "second::default"] } } # cookbook_hash is just a hash, but since we're passing it between mock # objects, we get a little better test strictness by using a double (which @@ -330,7 +310,5 @@ describe Chef::PolicyBuilder::ExpandNodeObject do it "triggers cookbook compilation in the run_context" do # Test condition already covered by `Chef::RunContext.any_instance.should_receive(:load).with(run_list_expansion)` end - end - end diff --git a/spec/unit/policy_builder/policyfile_spec.rb b/spec/unit/policy_builder/policyfile_spec.rb index 1425fe2b70..12e7d8e4d8 100644 --- a/spec/unit/policy_builder/policyfile_spec.rb +++ b/spec/unit/policy_builder/policyfile_spec.rb @@ -20,10 +20,9 @@ require "spec_helper" require "chef/policy_builder" describe Chef::PolicyBuilder::Policyfile do - let(:node_name) { "joe_node" } - let(:ohai_data) { {"platform" => "ubuntu", "platform_version" => "13.04", "fqdn" => "joenode.example.com"} } - let(:json_attribs) { {"custom_attr" => "custom_attr_value"} } + let(:ohai_data) { { "platform" => "ubuntu", "platform_version" => "13.04", "fqdn" => "joenode.example.com" } } + let(:json_attribs) { { "custom_attr" => "custom_attr_value" } } let(:override_runlist) { nil } let(:events) { Chef::EventDispatch::Dispatcher.new } let(:policy_builder) { Chef::PolicyBuilder::Policyfile.new(node_name, ohai_data, json_attribs, override_runlist, events) } @@ -40,11 +39,10 @@ describe Chef::PolicyBuilder::Policyfile do major = sha1_id[0...14] minor = sha1_id[14...28] patch = sha1_id[28..40] - decimal_integers =[major, minor, patch].map {|hex| hex.to_i(16) } + decimal_integers = [major, minor, patch].map { |hex| hex.to_i(16) } decimal_integers.join(".") end - let(:example1_lock_data) do # based on https://github.com/danielsdeleo/chef-workflow2-prototype/blob/master/skeletons/basic_policy/Policyfile.lock.json { @@ -53,10 +51,10 @@ describe Chef::PolicyBuilder::Policyfile do # NOTE: for compatibility mode we include the dotted id in the policyfile to enhance discoverability. "dotted_decimal_identifier" => id_to_dotted("168d2102fb11c9617cd8a981166c8adc30a6e915"), "source" => { "path" => "./cookbooks/demo" }, - "scm_identifier"=> { - "vcs"=> "git", - "rev_id"=> "9d5b09026470c322c3cb5ca8a4157c4d2f16cef3", - "remote"=> nil, + "scm_identifier" => { + "vcs" => "git", + "rev_id" => "9d5b09026470c322c3cb5ca8a4157c4d2f16cef3", + "remote" => nil, }, } end @@ -71,8 +69,8 @@ describe Chef::PolicyBuilder::Policyfile do } end - let(:policyfile_default_attributes) { {"policyfile_default_attr" => "policyfile_default_value"} } - let(:policyfile_override_attributes) { {"policyfile_override_attr" => "policyfile_override_value"} } + let(:policyfile_default_attributes) { { "policyfile_default_attr" => "policyfile_default_value" } } + let(:policyfile_override_attributes) { { "policyfile_override_attr" => "policyfile_override_value" } } let(:policyfile_run_list) { ["recipe[example1::default]", "recipe[example2::server]"] } @@ -106,7 +104,6 @@ describe Chef::PolicyBuilder::Policyfile do end describe "reporting unsupported features" do - def initialize_pb Chef::PolicyBuilder::Policyfile.new(node_name, ohai_data, json_attribs, override_runlist, events) end @@ -132,7 +129,7 @@ describe Chef::PolicyBuilder::Policyfile do end context "when json_attribs contains a run_list" do - let(:json_attribs) { {"run_list" => []} } + let(:json_attribs) { { "run_list" => [] } } it "errors on create" do expect { initialize_pb }.to raise_error(err_namespace::UnsupportedFeature) @@ -146,11 +143,9 @@ describe Chef::PolicyBuilder::Policyfile do expect { initialize_pb }.to raise_error(err_namespace::UnsupportedFeature) end end - end describe "loading policy data" do - let(:http_api) { double("Chef::ServerAPI") } let(:configured_environment) { nil } @@ -158,8 +153,8 @@ describe Chef::PolicyBuilder::Policyfile do let(:override_runlist) { nil } let(:primary_runlist) { nil } - let(:original_default_attrs) { {"default_key" => "default_value"} } - let(:original_override_attrs) { {"override_key" => "override_value"} } + let(:original_default_attrs) { { "default_key" => "default_value" } } + let(:original_override_attrs) { { "override_key" => "override_value" } } let(:node) do node = Chef::Node.new @@ -177,7 +172,6 @@ describe Chef::PolicyBuilder::Policyfile do end describe "when using compatibility mode (policy_document_native_api == false)" do - before do Chef::Config[:deployment_group] = "example-policy-stage" end @@ -194,7 +188,6 @@ describe Chef::PolicyBuilder::Policyfile do it "raises an error" do expect { policy_builder.finish_load_node(node) }.to raise_error(err_namespace::ConfigurationError) end - end context "when the deployment_group is not configured" do @@ -205,11 +198,9 @@ describe Chef::PolicyBuilder::Policyfile do it "errors while loading the node" do expect { policy_builder.finish_load_node(node) }.to raise_error(err_namespace::ConfigurationError) end - end context "when deployment_group is correctly configured" do - let(:policy_relative_url) { "data/policyfiles/example-policy-stage" } before do @@ -223,12 +214,10 @@ describe Chef::PolicyBuilder::Policyfile do it "extracts the run_list from the policyfile" do expect(policy_builder.run_list).to eq(policyfile_run_list) end - end end context "and policy_document_native_api is configured" do - before do Chef::Config[:policy_document_native_api] = true Chef::Config[:policy_group] = "policy-stage" @@ -236,7 +225,6 @@ describe Chef::PolicyBuilder::Policyfile do end context "and policy_name or policy_group are not configured" do - it "raises a Configuration error for policy_group" do Chef::Config[:policy_group] = nil expect { policy_builder.policy }.to raise_error(err_namespace::ConfigurationError) @@ -246,11 +234,9 @@ describe Chef::PolicyBuilder::Policyfile do Chef::Config[:policy_name] = nil expect { policy_builder.policy }.to raise_error(err_namespace::ConfigurationError) end - end context "and policy_name and policy_group are configured" do - let(:policy_relative_url) { "policy_groups/policy-stage/policies/example" } before do @@ -265,12 +251,9 @@ describe Chef::PolicyBuilder::Policyfile do expect(policy_builder.run_list).to eq(policyfile_run_list) end end - end - describe "building policy from the policyfile" do - before do allow(policy_builder).to receive(:policy).and_return(parsed_policyfile_json) end @@ -304,9 +287,7 @@ describe Chef::PolicyBuilder::Policyfile do expect(policy_builder.expand_run_list.roles).to eq([]) end - describe "validating the Policyfile.lock" do - it "errors if the policyfile json contains any non-recipe items" do parsed_policyfile_json["run_list"] = ["role[foo]"] expect { policy_builder.validate_policyfile }.to raise_error(err_namespace::PolicyfileError) @@ -330,11 +311,9 @@ describe Chef::PolicyBuilder::Policyfile do it "accepts a valid policyfile" do policy_builder.validate_policyfile end - end describe "building the node object" do - let(:extra_chef_config) { {} } before do @@ -351,9 +330,7 @@ describe Chef::PolicyBuilder::Policyfile do # -j JSON > config file > node object describe "selecting policy_name and policy_group from the various sources" do - context "when only set in node JSON" do - let(:json_attribs) do { "policy_name" => "policy_name_from_node_json", @@ -370,11 +347,9 @@ describe Chef::PolicyBuilder::Policyfile do expect(node.policy_name).to eq("policy_name_from_node_json") expect(node.policy_group).to eq("policy_group_from_node_json") end - end context "when only set in Chef::Config" do - let(:extra_chef_config) do { policy_name: "policy_name_from_config", @@ -386,11 +361,9 @@ describe Chef::PolicyBuilder::Policyfile do expect(node.policy_name).to eq("policy_name_from_config") expect(node.policy_group).to eq("policy_group_from_config") end - end context "when only set on the node" do - let(:node) do node = Chef::Node.new node.name(node_name) @@ -403,11 +376,9 @@ describe Chef::PolicyBuilder::Policyfile do expect(Chef::Config[:policy_name]).to eq("policy_name_from_node") expect(Chef::Config[:policy_group]).to eq("policy_group_from_node") end - end context "when set in Chef::Config and the fetched node" do - let(:node) do node = Chef::Node.new node.name(node_name) @@ -427,11 +398,9 @@ describe Chef::PolicyBuilder::Policyfile do expect(node.policy_name).to eq("policy_name_from_config") expect(node.policy_group).to eq("policy_group_from_config") end - end context "when set in node json and the fetched node" do - let(:json_attribs) do { "policy_name" => "policy_name_from_node_json", @@ -447,7 +416,6 @@ describe Chef::PolicyBuilder::Policyfile do node end - it "prefers the policy_name and policy_group from the node json" do expect(policy_builder.policy_name).to eq("policy_name_from_node_json") expect(policy_builder.policy_group).to eq("policy_group_from_node_json") @@ -457,11 +425,9 @@ describe Chef::PolicyBuilder::Policyfile do expect(node.policy_name).to eq("policy_name_from_node_json") expect(node.policy_group).to eq("policy_group_from_node_json") end - end context "when set in all sources" do - let(:json_attribs) do { "policy_name" => "policy_name_from_node_json", @@ -493,9 +459,7 @@ describe Chef::PolicyBuilder::Policyfile do expect(node.policy_name).to eq("policy_name_from_node_json") expect(node.policy_group).to eq("policy_group_from_node_json") end - end - end it "resets default and override data" do @@ -504,7 +468,6 @@ describe Chef::PolicyBuilder::Policyfile do end describe "setting attribute values" do - before do policy_builder.build_node end @@ -544,23 +507,19 @@ describe Chef::PolicyBuilder::Policyfile do end context "when a named run_list is given" do - before do Chef::Config[:named_run_list] = "deploy-app" end context "and the named run_list is not present in the policy" do - it "raises a ConfigurationError" do err_class = Chef::PolicyBuilder::Policyfile::ConfigurationError err_text = "Policy 'example-policy' revision '123abc' does not have named_run_list 'deploy-app'(available named_run_lists: [])" expect { policy_builder.build_node }.to raise_error(err_class, err_text) end - end context "and the named run_list is present in the policy" do - let(:parsed_policyfile_json) do basic_valid_policy_data.dup.tap do |p| p["named_run_lists"] = { @@ -586,15 +545,11 @@ describe Chef::PolicyBuilder::Policyfile do it "disables the cookbook cache cleaner" do expect(Chef::CookbookCacheCleaner.instance.skip_removal).to be(true) end - end - end end - describe "fetching the desired cookbook set" do - let(:example1_cookbook_data) { double("CookbookVersion Hash for example1 cookbook") } let(:example2_cookbook_data) { double("CookbookVersion Hash for example2 cookbook") } @@ -615,7 +570,6 @@ describe Chef::PolicyBuilder::Policyfile do shared_examples "fetching cookbooks when they don't exist" do context "and a cookbook is missing" do - let(:error404) { Net::HTTPServerException.new("404 message", :body) } before do @@ -629,7 +583,6 @@ describe Chef::PolicyBuilder::Policyfile do it "raises an error indicating which cookbook is missing" do expect { policy_builder.cookbooks_to_sync }.to raise_error(Chef::Exceptions::CookbookNotFound) end - end end @@ -675,7 +628,6 @@ describe Chef::PolicyBuilder::Policyfile do run_context = policy_builder.setup_run_context expect(Chef.run_context).to eq(run_context) end - end end # shared_examples_for "fetching cookbooks" @@ -688,7 +640,6 @@ describe Chef::PolicyBuilder::Policyfile do end context "when the cookbooks exist on the server" do - before do expect(http_api).to receive(:get).with(cookbook1_url). and_return(example1_cookbook_object) @@ -698,11 +649,9 @@ describe Chef::PolicyBuilder::Policyfile do include_examples "fetching cookbooks when they exist" end - end context "when using native API mode (policy_document_native_api == true)" do - before do Chef::Config[:policy_document_native_api] = true Chef::Config[:policy_group] = "policy-stage" @@ -716,9 +665,7 @@ describe Chef::PolicyBuilder::Policyfile do include_examples "fetching cookbooks when they don't exist" end - context "when the cookbooks exist on the server" do - before do expect(http_api).to receive(:get).with(cookbook1_url). and_return(example1_cookbook_data) @@ -732,15 +679,9 @@ describe Chef::PolicyBuilder::Policyfile do end include_examples "fetching cookbooks when they exist" - end - - end - end end - end - end diff --git a/spec/unit/policy_builder_spec.rb b/spec/unit/policy_builder_spec.rb index 674978ab63..eeb8a71a99 100644 --- a/spec/unit/policy_builder_spec.rb +++ b/spec/unit/policy_builder_spec.rb @@ -20,7 +20,5 @@ require "spec_helper" require "chef/policy_builder" describe Chef::PolicyBuilder do - # TODO: test the strategy method - end diff --git a/spec/unit/property/state_spec.rb b/spec/unit/property/state_spec.rb index 3dce632570..4b94fb058d 100644 --- a/spec/unit/property/state_spec.rb +++ b/spec/unit/property/state_spec.rb @@ -32,9 +32,9 @@ describe "Chef::Resource#identity and #state" do end def self.with_property(*properties, &block) - tags_index = properties.find_index { |p| !p.is_a?(String)} + tags_index = properties.find_index { |p| !p.is_a?(String) } if tags_index - properties, tags = properties[0..tags_index-1], properties[tags_index..-1] + properties, tags = properties[0..tags_index - 1], properties[tags_index..-1] else tags = [] end @@ -203,10 +203,11 @@ describe "Chef::Resource#identity and #state" do before do resource_class.class_eval do def custom_property - @blarghle ? @blarghle*3 : nil + @blarghle ? @blarghle * 3 : nil end + def custom_property=(x) - @blarghle = x*2 + @blarghle = x * 2 end end end @@ -353,10 +354,11 @@ describe "Chef::Resource#identity and #state" do before do resource_class.class_eval do def x - @blah*3 + @blah * 3 end + def x=(value) - @blah = value*2 + @blah = value * 2 end end end @@ -502,5 +504,4 @@ describe "Chef::Resource#identity and #state" do end end end - end diff --git a/spec/unit/property/validation_spec.rb b/spec/unit/property/validation_spec.rb index 5a40cce145..e66b2e3a95 100644 --- a/spec/unit/property/validation_spec.rb +++ b/spec/unit/property/validation_spec.rb @@ -8,12 +8,15 @@ describe "Chef::Resource.property validation" do def self.next_resource_name "chef_resource_property_spec_#{@i += 1}" end + def self.reset_index @current_index = 0 end + def self.current_index @current_index end + def self.next_index @current_index += 1 end @@ -38,6 +41,7 @@ describe "Chef::Resource.property validation" do def blah Namer.next_index end + def self.blah "class#{Namer.next_index}" end @@ -55,9 +59,9 @@ describe "Chef::Resource.property validation" do end def self.with_property(*properties, &block) - tags_index = properties.find_index { |p| !p.is_a?(String)} + tags_index = properties.find_index { |p| !p.is_a?(String) } if tags_index - properties, tags = properties[0..tags_index-1], properties[tags_index..-1] + properties, tags = properties[0..tags_index - 1], properties[tags_index..-1] else tags = [] end @@ -374,7 +378,6 @@ describe "Chef::Resource.property validation" do [], [ :a ], :nil_is_valid - end # kind_of @@ -516,32 +519,32 @@ describe "Chef::Resource.property validation" do context "cannot_be" do validation_test "cannot_be: :empty", - [ 1, [1,2], { a: 10 } ], + [ 1, [1, 2], { a: 10 } ], [ [] ], :nil_is_valid validation_test 'cannot_be: "empty"', - [ 1, [1,2], { a: 10 } ], + [ 1, [1, 2], { a: 10 } ], [ [] ], :nil_is_valid validation_test "cannot_be: [ :empty, :nil ]", - [ 1, [1,2], { a: 10 } ], + [ 1, [1, 2], { a: 10 } ], [ [] ], :nil_is_valid validation_test 'cannot_be: [ "empty", "nil" ]', - [ 1, [1,2], { a: 10 } ], + [ 1, [1, 2], { a: 10 } ], [ [] ], :nil_is_valid validation_test "cannot_be: [ :nil, :empty ]", - [ 1, [1,2], { a: 10 } ], + [ 1, [1, 2], { a: 10 } ], [ [] ], :nil_is_valid validation_test "cannot_be: [ :empty, :nil, :blahblah ]", - [ 1, [1,2], { a: 10 } ], + [ 1, [1, 2], { a: 10 } ], [ [] ], :nil_is_valid @@ -554,7 +557,6 @@ describe "Chef::Resource.property validation" do [ :a ], [], :nil_is_valid - end context "required" do diff --git a/spec/unit/property_spec.rb b/spec/unit/property_spec.rb index dc969ebde2..fc0c942c20 100644 --- a/spec/unit/property_spec.rb +++ b/spec/unit/property_spec.rb @@ -8,12 +8,15 @@ describe "Chef::Resource.property" do def self.next_resource_name "chef_resource_property_spec_#{@i += 1}" end + def self.reset_index @current_index = 0 end + def self.current_index @current_index end + def self.next_index @current_index += 1 end @@ -52,9 +55,9 @@ describe "Chef::Resource.property" do end def self.with_property(*properties, &block) - tags_index = properties.find_index { |p| !p.is_a?(String)} + tags_index = properties.find_index { |p| !p.is_a?(String) } if tags_index - properties, tags = properties[0..tags_index-1], properties[tags_index..-1] + properties, tags = properties[0..tags_index - 1], properties[tags_index..-1] else tags = [] end @@ -551,6 +554,7 @@ describe "Chef::Resource.property" do def self.blah "class" end + def blah "#{name}#{next_index}" end @@ -800,6 +804,7 @@ describe "Chef::Resource.property" do def self.blah "class" end + def blah "#{name}#{Namer.next_index}" end @@ -1081,7 +1086,6 @@ describe "Chef::Resource.property" do end end end - end end @@ -1169,7 +1173,6 @@ describe "Chef::Resource.property" do end end end - end context "with a custom property type" do diff --git a/spec/unit/provider/breakpoint_spec.rb b/spec/unit/provider/breakpoint_spec.rb index 5986083410..cccb490887 100644 --- a/spec/unit/provider/breakpoint_spec.rb +++ b/spec/unit/provider/breakpoint_spec.rb @@ -16,10 +16,8 @@ # limitations under the License. # - require "spec_helper" describe Chef::Provider::Breakpoint do - before do @resource = Chef::Resource::Breakpoint.new @node = Chef::Node.new @@ -50,5 +48,4 @@ describe Chef::Provider::Breakpoint do expect(@iterator).not_to receive(:pause) @provider.action_break end - end diff --git a/spec/unit/provider/cookbook_file/content_spec.rb b/spec/unit/provider/cookbook_file/content_spec.rb index b4116bda12..e42fd87cb1 100644 --- a/spec/unit/provider/cookbook_file/content_spec.rb +++ b/spec/unit/provider/cookbook_file/content_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::CookbookFile::Content do - let(:new_resource) { double("Chef::Resource::CookbookFile (new)", :cookbook_name => "apache2", :cookbook => "apache2") } let(:content) do @run_context = double("Chef::RunContext") @@ -35,6 +34,4 @@ describe Chef::Provider::CookbookFile::Content do it "falls back to the implicit cookbook name on the resource" do expect(content.send(:resource_cookbook)).to eq("apache2") end - end - diff --git a/spec/unit/provider/cookbook_file_spec.rb b/spec/unit/provider/cookbook_file_spec.rb index 810adb52f9..b375784d00 100644 --- a/spec/unit/provider/cookbook_file_spec.rb +++ b/spec/unit/provider/cookbook_file_spec.rb @@ -24,7 +24,7 @@ require "support/shared/unit/provider/file" describe Chef::Provider::CookbookFile do let(:node) { double("Chef::Node") } - let(:events) { double("Chef::Events").as_null_object } # mock all the methods + let(:events) { double("Chef::Events").as_null_object } # mock all the methods let(:run_context) { double("Chef::RunContext", :node => node, :events => events) } let(:enclosing_directory) { canonicalize_path(File.expand_path(File.join(CHEF_SPEC_DATA, "templates"))) diff --git a/spec/unit/provider/cron/unix_spec.rb b/spec/unit/provider/cron/unix_spec.rb index 83e0f431bf..0e3ccafbdd 100644 --- a/spec/unit/provider/cron/unix_spec.rb +++ b/spec/unit/provider/cron/unix_spec.rb @@ -21,7 +21,6 @@ require "spec_helper" describe Chef::Provider::Cron::Unix do - subject(:provider) { Chef::Provider::Cron::Unix.new(new_resource, run_context) } let(:username) { "root" } diff --git a/spec/unit/provider/cron_spec.rb b/spec/unit/provider/cron_spec.rb index 107e4b9645..8fc1925308 100644 --- a/spec/unit/provider/cron_spec.rb +++ b/spec/unit/provider/cron_spec.rb @@ -94,7 +94,7 @@ CRONTAB cron = @provider.load_current_resource expect(cron.mailto).to eq("warn@example.com") - expect(cron.environment).to eq({"TEST" => "lol", "FLAG" => "1"}) + expect(cron.environment).to eq({ "TEST" => "lol", "FLAG" => "1" }) end it "should not break with variables that match the cron resource internals" do @@ -109,7 +109,7 @@ CRONTAB cron = @provider.load_current_resource expect(cron.time).to eq(:reboot) - expect(cron.environment).to eq({"MINUTE" => "40", "REBOOT" => "midnight", "TEST" => "lol", "ENVIRONMENT" => "production"}) + expect(cron.environment).to eq({ "MINUTE" => "40", "REBOOT" => "midnight", "TEST" => "lol", "ENVIRONMENT" => "production" }) end it "should report the match" do @@ -276,7 +276,7 @@ CRONTAB cron = @provider.load_current_resource expect(cron.mailto).to eq("warn@example.com") - expect(cron.environment).to eq({"TEST" => "lol", "FLAG" => "1"}) + expect(cron.environment).to eq({ "TEST" => "lol", "FLAG" => "1" }) end it "should not break with variabels that match the cron resource internals" do @@ -292,7 +292,7 @@ CRONTAB expect(cron.minute).to eq("*") expect(cron.hour).to eq("5") - expect(cron.environment).to eq({"MINUTE" => "40", "HOUR" => "midnight", "TEST" => "lol", "ENVIRONMENT" => "production"}) + expect(cron.environment).to eq({ "MINUTE" => "40", "HOUR" => "midnight", "TEST" => "lol", "ENVIRONMENT" => "production" }) end it "should report the match" do @@ -963,7 +963,6 @@ MAILTO=foo@example.com @provider.send(:write_crontab, "Foo") end.to raise_error(Chef::Exceptions::Cron, "Error updating state of #{@new_resource.name}, exit: 1") end - end describe "weekday_in_crontab" do diff --git a/spec/unit/provider/deploy/revision_spec.rb b/spec/unit/provider/deploy/revision_spec.rb index 5fe0f26a6b..dfd64e7e0b 100644 --- a/spec/unit/provider/deploy/revision_spec.rb +++ b/spec/unit/provider/deploy/revision_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::Deploy::Revision do - before do allow(ChefConfig).to receive(:windows?) { false } @temp_dir = Dir.mktmpdir @@ -41,7 +40,6 @@ describe Chef::Provider::Deploy::Revision do FileUtils.rm_rf @temp_dir if File.directory?( @temp_dir ) end - it "uses the resolved revision from the SCM as the release slug" do allow(@provider.scm_provider).to receive(:revision_slug).and_return("uglySlugly") expect(@provider.send(:release_slug)).to eq("uglySlugly") @@ -60,7 +58,7 @@ describe Chef::Provider::Deploy::Revision do @provider.cleanup! second_release = "/my/deploy/dir/releases/73219b87e977d9c7ba1aa57e9ad1d88fa91a0ec2" - expect(@provider.all_releases).to eq([@expected_release_dir,second_release]) + expect(@provider.all_releases).to eq([@expected_release_dir, second_release]) end it "removes a release from the file cache when it's used again in another release and append it to the end" do @@ -71,7 +69,7 @@ describe Chef::Provider::Deploy::Revision do @provider.load_current_resource @provider.cleanup! second_release = "/my/deploy/dir/releases/73219b87e977d9c7ba1aa57e9ad1d88fa91a0ec2" - expect(@provider.all_releases).to eq([@expected_release_dir,second_release]) + expect(@provider.all_releases).to eq([@expected_release_dir, second_release]) @provider.cleanup! allow(@provider).to receive(:release_slug).and_return("8a3195bf3efa246f743c5dfa83683201880f935c") @@ -82,7 +80,7 @@ describe Chef::Provider::Deploy::Revision do it "removes a release from the file cache when it's deleted by :cleanup!" do release_paths = %w{first second third fourth fifth}.map do |release_name| - "/my/deploy/dir/releases/#{release_name}" + "/my/deploy/dir/releases/#{release_name}" end release_paths.each do |release_path| @provider.send(:release_created, release_path) @@ -93,7 +91,7 @@ describe Chef::Provider::Deploy::Revision do @provider.cleanup! expected_release_paths = (%w{second third fourth fifth} << @resource.revision).map do |release_name| - "/my/deploy/dir/releases/#{release_name}" + "/my/deploy/dir/releases/#{release_name}" end expect(@provider.all_releases).to eq(expected_release_paths) @@ -107,5 +105,4 @@ describe Chef::Provider::Deploy::Revision do expect(::File).to receive(:ctime).with(latest).and_return(Time.now - 1) expect(@provider.all_releases).to eq([oldest, latest]) end - end diff --git a/spec/unit/provider/deploy/timestamped_spec.rb b/spec/unit/provider/deploy/timestamped_spec.rb index fdb90bf438..6923a7db07 100644 --- a/spec/unit/provider/deploy/timestamped_spec.rb +++ b/spec/unit/provider/deploy/timestamped_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::Deploy::Timestamped do - before do @release_time = Time.utc( 2004, 8, 15, 16, 23, 42) allow(Time).to receive(:now).and_return(@release_time) @@ -36,5 +35,4 @@ describe Chef::Provider::Deploy::Timestamped do it "gives a timestamp for release_slug" do expect(@timestamped_deploy.send(:release_slug)).to eq("20040815162342") end - end diff --git a/spec/unit/provider/deploy_spec.rb b/spec/unit/provider/deploy_spec.rb index 7a3c208c9c..22f3e1a1ae 100644 --- a/spec/unit/provider/deploy_spec.rb +++ b/spec/unit/provider/deploy_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::Deploy do - before do allow(ChefConfig).to receive(:windows?) { false } @release_time = Time.utc( 2004, 8, 15, 16, 23, 42) @@ -74,7 +73,6 @@ describe Chef::Provider::Deploy do allow(@provider).to receive(:update_cached_repo) @provider.deploy end - end it "does not create deploy_to dir if it exists" do @@ -164,7 +162,7 @@ describe Chef::Provider::Deploy do it "dont care by default if error happens on deploy" do allow(@provider).to receive(:all_releases).and_return(["previous_release"]) - allow(@provider).to receive(:deploy){ raise "Unexpected error" } + allow(@provider).to receive(:deploy) { raise "Unexpected error" } allow(@provider).to receive(:previous_release_path).and_return("previous_release") expect(@provider).not_to receive(:rollback) expect { @@ -175,7 +173,7 @@ describe Chef::Provider::Deploy do it "rollbacks to previous release if error happens on deploy" do @resource.rollback_on_error true allow(@provider).to receive(:all_releases).and_return(["previous_release"]) - allow(@provider).to receive(:deploy){ raise "Unexpected error" } + allow(@provider).to receive(:deploy) { raise "Unexpected error" } allow(@provider).to receive(:previous_release_path).and_return("previous_release") expect(@provider).to receive(:rollback) expect { @@ -223,7 +221,6 @@ describe Chef::Provider::Deploy do end describe "if there are no releases to fallback to" do - it "an exception is raised when there is only 1 release" do #@provider.unstub(:release_path) -- unstub the release path on top to feed our own release path all_releases = [ "/my/deploy/dir/releases/20040815162342"] @@ -266,7 +263,7 @@ describe Chef::Provider::Deploy do it "raises a runtime error when there's no release to rollback to" do all_releases = [] allow(Dir).to receive(:glob).with("/my/deploy/dir/releases/*").and_return(all_releases) - expect {@provider.run_action(:rollback)}.to raise_error(RuntimeError) + expect { @provider.run_action(:rollback) }.to raise_error(RuntimeError) end it "runs the new resource collection in the runner during a callback" do @@ -286,12 +283,12 @@ describe Chef::Provider::Deploy do end it "raises a runtime error if a callback file is explicitly specified but does not exist" do - baz_callback = "/deploy/baz.rb" + baz_callback = "/deploy/baz.rb" expect(::File).to receive(:exist?).with("#{@expected_release_dir}/#{baz_callback}").and_return(false) - @resource.before_migrate baz_callback + @resource.before_migrate baz_callback @provider.define_resource_requirements @provider.action = :deploy - expect {@provider.process_resource_requirements}.to raise_error(RuntimeError) + expect { @provider.process_resource_requirements }.to raise_error(RuntimeError) end it "runs a default callback if the callback code is nil" do @@ -378,11 +375,11 @@ describe Chef::Provider::Deploy do allow(STDOUT).to receive(:tty?).and_return(true) allow(Chef::Log).to receive(:info?).and_return(true) - expect(@provider).to receive(:shell_out!).with("migration_foo",:cwd => @expected_release_dir, - :user => "deployNinja", :group => "deployNinjas", - :log_level => :info, :live_stream => STDOUT, - :log_tag => "deploy[/my/deploy/dir]", - :environment => {"RAILS_ENV"=>"production"}) + expect(@provider).to receive(:shell_out!).with("migration_foo", :cwd => @expected_release_dir, + :user => "deployNinja", :group => "deployNinjas", + :log_level => :info, :live_stream => STDOUT, + :log_tag => "deploy[/my/deploy/dir]", + :environment => { "RAILS_ENV" => "production" }) @provider.migrate end @@ -416,7 +413,6 @@ describe Chef::Provider::Deploy do end context "with a customized app layout" do - before do @resource.purge_before_symlink(%w{foo bar}) @resource.create_dirs_before_symlink(%w{baz qux}) @@ -441,7 +437,6 @@ describe Chef::Provider::Deploy do expect(@provider).to receive(:enforce_ownership) @provider.link_tempfiles_to_current_release end - end it "does nothing for restart if restart_command is empty" do @@ -511,14 +506,12 @@ describe Chef::Provider::Deploy do allow(@provider).to receive(:run_symlinks_before_migrate) allow(@provider).to receive(:shell_out!) @provider.migrate - end context "using inline recipes for callbacks" do - it "runs an inline recipe with the provided block for :callback_name == {:recipe => &block} " do snitch = nil - recipe_code = Proc.new {snitch = 42} + recipe_code = Proc.new { snitch = 42 } #@provider.should_receive(:instance_eval).with(&recipe_code) @provider.callback(:whateverz, recipe_code) expect(snitch).to eq(42) @@ -533,12 +526,11 @@ describe Chef::Provider::Deploy do it "instance_evals a block/proc for restart command" do snitch = nil - restart_cmd = Proc.new {snitch = 42} + restart_cmd = Proc.new { snitch = 42 } @resource.restart(&restart_cmd) @provider.restart expect(snitch).to eq(42) end - end describe "API bridge to capistrano" do @@ -569,11 +561,10 @@ describe Chef::Provider::Deploy do nil else expect(args.size).to eq(1) - expect(args.first).to eq({"APP_ENV" => "staging"}) + expect(args.first).to eq({ "APP_ENV" => "staging" }) end }.twice @provider.run("iGoToHell4this") - end it "defines run as a forwarder to execute, setting cwd and environment but not override" do @@ -586,7 +577,6 @@ describe Chef::Provider::Deploy do @provider.run("iGoToHell4this") end - it "converts sudo and run to exec resources in hooks" do runner = double("tehRunner") allow(Chef::Runner).to receive(:new).and_return(runner) @@ -610,10 +600,9 @@ describe Chef::Provider::Deploy do end describe "installing gems from a gems.yml" do - before do allow(::File).to receive(:exist?).with("#{@expected_release_dir}/gems.yml").and_return(true) - @gem_list = [{:name=>"eventmachine", :version=>"0.12.9"}] + @gem_list = [{ :name => "eventmachine", :version => "0.12.9" }] end it "reads a gems.yml file, creating gem providers for each with action :upgrade" do @@ -636,7 +625,5 @@ describe Chef::Provider::Deploy do actual = gem_runner.run_context.resource_collection.all_resources.map { |r| [r.name, r.version] } expect(actual).to eq(expected_gem_resources) end - end - end diff --git a/spec/unit/provider/directory_spec.rb b/spec/unit/provider/directory_spec.rb index c4cf070246..a9bce7652a 100644 --- a/spec/unit/provider/directory_spec.rb +++ b/spec/unit/provider/directory_spec.rb @@ -110,7 +110,6 @@ describe Chef::Provider::Directory do expect(directory.current_resource.owner).to eq(nil) end end - end describe "#define_resource_requirements" do @@ -191,7 +190,7 @@ describe Chef::Provider::Directory do end it "raises the right exception when the parent directory is a file and recursive is true" do - pending "this seems to return the wrong error" # FIXME + pending "this seems to return the wrong error" # FIXME FileUtils.touch tmp_dir new_resource.recursive true expect { directory.run_action(:create) }.to raise_error(Chef::Exceptions::EnclosingDirectoryDoesNotExist) @@ -219,7 +218,7 @@ describe Chef::Provider::Directory do allow(node).to receive(:[]).with("platform_version").and_return("10.11") allow(::File).to receive(:directory?).and_return(true) allow(Chef::FileAccessControl).to receive(:writable?).and_return(false) - expect {directory.run_action(:create) }.to raise_error(Chef::Exceptions::InsufficientPermissions) + expect { directory.run_action(:create) }.to raise_error(Chef::Exceptions::InsufficientPermissions) end it "os x 10.11 can write to sip exlcusions" do @@ -269,7 +268,7 @@ describe Chef::Provider::Directory do end it "cannot delete it and raises an exception" do - expect { directory.run_action(:delete) }.to raise_error(RuntimeError) + expect { directory.run_action(:delete) }.to raise_error(RuntimeError) end end @@ -280,7 +279,7 @@ describe Chef::Provider::Directory do end it "cannot delete it and raises an exception" do - expect { directory.run_action(:delete) }.to raise_error(RuntimeError) + expect { directory.run_action(:delete) }.to raise_error(RuntimeError) end end end diff --git a/spec/unit/provider/dsc_resource_spec.rb b/spec/unit/provider/dsc_resource_spec.rb index 6a5063ac60..ca4a345bfd 100644 --- a/spec/unit/provider/dsc_resource_spec.rb +++ b/spec/unit/provider/dsc_resource_spec.rb @@ -35,13 +35,12 @@ describe Chef::Provider::DscResource do } it "raises a ProviderNotFound exception" do expect(provider).not_to receive(:meta_configuration) - expect{provider.run_action(:run)}.to raise_error( + expect { provider.run_action(:run) }.to raise_error( Chef::Exceptions::ProviderNotFound, /5\.0\.10018\.0/) end end context "when Powershell supports Invoke-DscResource" do - context "when RefreshMode is not set to Disabled" do context "and the WMF 5 is a preview release" do let (:node) { @@ -70,7 +69,7 @@ describe Chef::Provider::DscResource do end end end - + context "when the LCM supports Invoke-DscResource" do let (:node) { node = Chef::Node.new @@ -92,27 +91,27 @@ describe Chef::Provider::DscResource do provider.run_action(:run) expect(resource).to be_updated end - + it "flags the resource as reboot required when required" do expect(provider).to receive(:dsc_refresh_mode_disabled?).and_return(true) expect(provider).to receive(:test_resource).and_return(false) expect(provider).to receive(:invoke_resource). - and_return(double(:stdout => "", :return_value =>nil)) + and_return(double(:stdout => "", :return_value => nil)) expect(provider).to receive(:add_dsc_verbose_log) expect(provider).to receive(:return_dsc_resource_result).and_return(true) expect(provider).to receive(:create_reboot_resource) provider.run_action(:run) end - + it "does not flag the resource as reboot required when not required" do expect(provider).to receive(:dsc_refresh_mode_disabled?).and_return(true) expect(provider).to receive(:test_resource).and_return(false) expect(provider).to receive(:invoke_resource). - and_return(double(:stdout => "", :return_value =>nil)) + and_return(double(:stdout => "", :return_value => nil)) expect(provider).to receive(:add_dsc_verbose_log) expect(provider).to receive(:return_dsc_resource_result).and_return(false) expect(provider).to_not receive(:create_reboot_resource) provider.run_action(:run) end end -end \ No newline at end of file +end diff --git a/spec/unit/provider/dsc_script_spec.rb b/spec/unit/provider/dsc_script_spec.rb index 0bea0e596d..37150968be 100644 --- a/spec/unit/provider/dsc_script_spec.rb +++ b/spec/unit/provider/dsc_script_spec.rb @@ -117,7 +117,7 @@ describe Chef::Provider::DscScript do it "should not converge if the script is already converged" do allow(provider).to receive(:run_configuration).with(:test).and_return([]) - + provider.run_action(:run) expect(resource).not_to be_updated end @@ -167,8 +167,6 @@ describe Chef::Provider::DscScript do provider.run_action(:run) }.to raise_error(Chef::Exceptions::ProviderNotFound) end - end end end - diff --git a/spec/unit/provider/env/windows_spec.rb b/spec/unit/provider/env/windows_spec.rb index 0eeac3dba5..ea4156e5b2 100644 --- a/spec/unit/provider/env/windows_spec.rb +++ b/spec/unit/provider/env/windows_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::Provider::Env::Windows, :windows_only do let(:node) { Chef::Node.new } - let(:events) {Chef::EventDispatch::Dispatcher.new } + let(:events) { Chef::EventDispatch::Dispatcher.new } let(:run_context) { Chef::RunContext.new(node, {}, events) } context "when environment variable is not PATH" do @@ -29,8 +29,8 @@ describe Chef::Provider::Env::Windows, :windows_only do new_resource.value("foo") new_resource } - let(:provider) { - provider = Chef::Provider::Env::Windows.new(new_resource, run_context) + let(:provider) { + provider = Chef::Provider::Env::Windows.new(new_resource, run_context) allow(provider).to receive(:env_obj).and_return(double("null object").as_null_object) provider } @@ -74,21 +74,21 @@ describe Chef::Provider::Env::Windows, :windows_only do context "when environment is PATH" do describe "for PATH" do - let(:system_root) {"%SystemRoot%"} + let(:system_root) { "%SystemRoot%" } let(:system_root_value) { 'D:\Windows' } let(:new_resource) { new_resource = Chef::Resource::Env.new("PATH") new_resource.value(system_root) new_resource } - let(:provider) { - provider = Chef::Provider::Env::Windows.new(new_resource, run_context) + let(:provider) { + provider = Chef::Provider::Env::Windows.new(new_resource, run_context) allow(provider).to receive(:env_obj).and_return(double("null object").as_null_object) provider } before do - stub_const("ENV", {"PATH" => ""}) + stub_const("ENV", { "PATH" => "" }) end it "replaces Windows system variables" do @@ -98,6 +98,5 @@ describe Chef::Provider::Env::Windows, :windows_only do expect(ENV["PATH"]).to eql(system_root_value) end end - end end diff --git a/spec/unit/provider/env_spec.rb b/spec/unit/provider/env_spec.rb index a5ea9f1259..04b85a218e 100644 --- a/spec/unit/provider/env_spec.rb +++ b/spec/unit/provider/env_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::Env do - before do @node = Chef::Node.new @events = Chef::EventDispatch::Dispatcher.new @@ -199,12 +198,12 @@ describe Chef::Provider::Env do expect(@new_resource).to be_updated end - context "when new_resource's value contains the delimiter" do + context "when new_resource's value contains the delimiter" do it "should return false if all the elements are deleted" do # This indicates that the entire key needs to be deleted @new_resource.value("C:/foo/bin;C:/bar/bin") expect(@provider.delete_element).to eql(false) - expect(@new_resource).not_to be_updated # This will be updated in action_delete + expect(@new_resource).not_to be_updated # This will be updated in action_delete end it "should return true if any, but not all, of the elements are deleted" do @@ -251,7 +250,7 @@ describe Chef::Provider::Env do expect(@provider.requires_modify_or_create?).to be_truthy end - context "when new_resource's value contains the delimiter" do + context "when new_resource's value contains the delimiter" do it "should return false if all the current values are contained in specified order" do @new_resource.value("C:/biz;C:/baz") @new_resource.delim(";") diff --git a/spec/unit/provider/erl_call_spec.rb b/spec/unit/provider/erl_call_spec.rb index 946d5384d1..175c0d37dd 100644 --- a/spec/unit/provider/erl_call_spec.rb +++ b/spec/unit/provider/erl_call_spec.rb @@ -81,6 +81,4 @@ describe Chef::Provider::ErlCall do expect(@stdin.string).to eq("#{@new_resource.code}\n") end end - end - diff --git a/spec/unit/provider/execute_spec.rb b/spec/unit/provider/execute_spec.rb index 4cc27ef105..b9b347d8c8 100644 --- a/spec/unit/provider/execute_spec.rb +++ b/spec/unit/provider/execute_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::Execute do - let(:node) { Chef::Node.new } let(:events) { Chef::EventDispatch::Dispatcher.new } let(:run_context) { Chef::RunContext.new(node, {}, events) } @@ -130,7 +129,7 @@ describe Chef::Provider::Execute do expect(Chef::Log).to receive(:warn).with(/relative path/) expect(FileTest).to receive(:exist?).with(new_resource.creates).and_return(true) expect(provider).not_to receive(:shell_out!) - expect { provider.run_action(:run) }.to raise_error # @todo: add a real error for Chef-13 + expect { provider.run_action(:run) }.to raise_error # @todo: add a real error for Chef-13 end end @@ -235,9 +234,7 @@ describe Chef::Provider::Execute do provider.run_action(:run) expect(new_resource).to be_updated end - end end - end end diff --git a/spec/unit/provider/file/content_spec.rb b/spec/unit/provider/file/content_spec.rb index 5179b5ce4d..3561799944 100644 --- a/spec/unit/provider/file/content_spec.rb +++ b/spec/unit/provider/file/content_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::File::Content do - # # mock setup # @@ -51,7 +50,6 @@ describe Chef::Provider::File::Content do end describe "when the resource has a content attribute set" do - before do allow(new_resource).to receive(:content).and_return("Do do do do, do do do do, do do do do, do do do do") end @@ -89,7 +87,7 @@ describe Chef::Provider::File::Content do it "fails when :file_desployment_uses_destdir is set" do Chef::Config[:file_staging_uses_destdir] = true - expect{content.tempfile}.to raise_error + expect { content.tempfile }.to raise_error end it "returns a tempfile in the tempdir when :file_desployment_uses_destdir is not set" do @@ -97,11 +95,9 @@ describe Chef::Provider::File::Content do expect(canonicalize_path(content.tempfile.path).start_with?(enclosing_directory)).to be_falsey end end - end describe "when the resource does not have a content attribute set" do - before do allow(new_resource).to receive(:content).and_return(nil) end @@ -109,6 +105,5 @@ describe Chef::Provider::File::Content do it "should return nil instead of a tempfile" do expect(content.tempfile).to be_nil end - end end diff --git a/spec/unit/provider/file_spec.rb b/spec/unit/provider/file_spec.rb index 83cdf21050..aa7f9c022c 100644 --- a/spec/unit/provider/file_spec.rb +++ b/spec/unit/provider/file_spec.rb @@ -20,7 +20,6 @@ require "support/shared/unit/provider/file" describe Chef::Provider::File do - let(:resource) do # need to check for/against mutating state within the new_resource, so don't mock resource = Chef::Resource::File.new("seattle") @@ -33,7 +32,7 @@ describe Chef::Provider::File do end let(:node) { double("Chef::Node") } - let(:events) { double("Chef::Events").as_null_object } # mock all the methods + let(:events) { double("Chef::Events").as_null_object } # mock all the methods let(:run_context) { double("Chef::RunContext", :node => node, :events => events) } let(:enclosing_directory) { canonicalize_path(File.expand_path(File.join(CHEF_SPEC_DATA, "templates"))) @@ -54,4 +53,3 @@ describe Chef::Provider::File do it_behaves_like "a file provider with content field" end - diff --git a/spec/unit/provider/git_spec.rb b/spec/unit/provider/git_spec.rb index 8c55875ce7..8bcb2a8864 100644 --- a/spec/unit/provider/git_spec.rb +++ b/spec/unit/provider/git_spec.rb @@ -16,10 +16,8 @@ # limitations under the License. # - require "spec_helper" describe Chef::Provider::Git do - before(:each) do allow(STDOUT).to receive(:tty?).and_return(true) @original_log_level = Chef::Log.level @@ -44,7 +42,6 @@ describe Chef::Provider::Git do end context "determining the revision of the currently deployed checkout" do - before do @stdout = double("standard out") @stderr = double("standard error") @@ -59,7 +56,7 @@ describe Chef::Provider::Git do it "determines the current revision when there is one" do expect(::File).to receive(:exist?).with("/my/deploy/dir/.git").and_return(true) @stdout = "9b4d8dc38dd471246e7cfb1c3c1ad14b0f2bee13\n" - expect(@provider).to receive(:shell_out!).with("git rev-parse HEAD", {:cwd => "/my/deploy/dir", :returns => [0,128]}).and_return(double("ShellOut result", :stdout => @stdout)) + expect(@provider).to receive(:shell_out!).with("git rev-parse HEAD", { :cwd => "/my/deploy/dir", :returns => [0, 128] }).and_return(double("ShellOut result", :stdout => @stdout)) expect(@provider.find_current_revision).to eql("9b4d8dc38dd471246e7cfb1c3c1ad14b0f2bee13") end @@ -67,7 +64,7 @@ describe Chef::Provider::Git do expect(::File).to receive(:exist?).with("/my/deploy/dir/.git").and_return(true) @stderr = "fatal: Not a git repository (or any of the parent directories): .git" @stdout = "" - expect(@provider).to receive(:shell_out!).with("git rev-parse HEAD", :cwd => "/my/deploy/dir", :returns => [0,128]).and_return(double("ShellOut result", :stdout => "", :stderr => @stderr)) + expect(@provider).to receive(:shell_out!).with("git rev-parse HEAD", :cwd => "/my/deploy/dir", :returns => [0, 128]).and_return(double("ShellOut result", :stdout => "", :stderr => @stderr)) expect(@provider.find_current_revision).to be_nil end end @@ -85,7 +82,6 @@ describe Chef::Provider::Git do end context "resolving revisions to a SHA" do - before do @git_ls_remote = "git ls-remote \"git://github.com/opscode/chef.git\" " end @@ -98,7 +94,7 @@ describe Chef::Provider::Git do @resource.revision "v1.0" @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" + "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0\n") - expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", {:log_tag=>"git[web2.0 app]"}).and_return(double("ShellOut result", :stdout => @stdout)) + expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", { :log_tag => "git[web2.0 app]" }).and_return(double("ShellOut result", :stdout => @stdout)) expect(@provider.target_revision).to eql("503c22a5e41f5ae3193460cca044ed1435029f53") end @@ -107,7 +103,7 @@ describe Chef::Provider::Git do @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" + "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0\n" + "663c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0^{}\n") - expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", {:log_tag=>"git[web2.0 app]"}).and_return(double("ShellOut result", :stdout => @stdout)) + expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", { :log_tag => "git[web2.0 app]" }).and_return(double("ShellOut result", :stdout => @stdout)) expect(@provider.target_revision).to eql("663c22a5e41f5ae3193460cca044ed1435029f53") end @@ -116,7 +112,7 @@ describe Chef::Provider::Git do @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" + "663c22a5e41f5ae3193460cca044ed1435029f53\trefs/tags/releases/v1.0\n" + "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/tags/v1.0\n") - expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", {:log_tag=>"git[web2.0 app]"}).and_return(double("ShellOut result", :stdout => @stdout)) + expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", { :log_tag => "git[web2.0 app]" }).and_return(double("ShellOut result", :stdout => @stdout)) expect(@provider.target_revision).to eql("503c22a5e41f5ae3193460cca044ed1435029f53") end @@ -125,7 +121,7 @@ describe Chef::Provider::Git do @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" + "663c22a5e41f5ae3193460cca044ed1435029f53\trefs/tags/v1.0\n" + "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0\n") - expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", {:log_tag=>"git[web2.0 app]"}).and_return(double("ShellOut result", :stdout => @stdout)) + expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", { :log_tag => "git[web2.0 app]" }).and_return(double("ShellOut result", :stdout => @stdout)) expect(@provider.target_revision).to eql("663c22a5e41f5ae3193460cca044ed1435029f53") end @@ -134,7 +130,7 @@ describe Chef::Provider::Git do @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" + "663c22a5e41f5ae3193460cca044ed1435029f53\trefs/tags/v1.1\n" + "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0\n") - expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", {:log_tag=>"git[web2.0 app]"}).and_return(double("ShellOut result", :stdout => @stdout)) + expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", { :log_tag => "git[web2.0 app]" }).and_return(double("ShellOut result", :stdout => @stdout)) expect(@provider.target_revision).to eql("503c22a5e41f5ae3193460cca044ed1435029f53") end @@ -144,7 +140,7 @@ describe Chef::Provider::Git do "663c22a5e41f5ae3193460cca044ed1435029f53\trefs/tags/v1.0\n" + "805c22a5e41f5ae3193460cca044ed1435029f53\trefs/pulls/v1.0\n" + "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0\n") - expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"refs/pulls/v1.0*\"", {:log_tag=>"git[web2.0 app]"}).and_return(double("ShellOut result", :stdout => @stdout)) + expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"refs/pulls/v1.0*\"", { :log_tag => "git[web2.0 app]" }).and_return(double("ShellOut result", :stdout => @stdout)) expect(@provider.target_revision).to eql("805c22a5e41f5ae3193460cca044ed1435029f53") end @@ -153,7 +149,7 @@ describe Chef::Provider::Git do @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" + "663c22a5e41f5ae3193460cca044ed1435029f53\trefs/tags/v1.0\n" + "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0\n") - expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"refs/heads/v1.0*\"", {:log_tag=>"git[web2.0 app]"}).and_return(double("ShellOut result", :stdout => @stdout)) + expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"refs/heads/v1.0*\"", { :log_tag => "git[web2.0 app]" }).and_return(double("ShellOut result", :stdout => @stdout)) expect(@provider.target_revision).to eql("503c22a5e41f5ae3193460cca044ed1435029f53") end @@ -162,7 +158,7 @@ describe Chef::Provider::Git do @provider.action = :checkout @provider.define_resource_requirements allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) - expect {@provider.process_resource_requirements}.to raise_error(Chef::Exceptions::InvalidRemoteGitReference) + expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::InvalidRemoteGitReference) end it "raises an unresolvable git reference error if the revision can't be resolved to any revision and assertions are run" do @@ -182,7 +178,7 @@ describe Chef::Provider::Git do it "does not raise an error when the revision is valid and assertions are run." do @resource.revision "0.8-alpha" @stdout = "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" - expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"0.8-alpha*\"", {:log_tag=>"git[web2.0 app]"}).and_return(double("ShellOut result", :stdout => @stdout)) + expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"0.8-alpha*\"", { :log_tag => "git[web2.0 app]" }).and_return(double("ShellOut result", :stdout => @stdout)) @provider.action = :checkout allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) @provider.define_resource_requirements @@ -190,7 +186,7 @@ describe Chef::Provider::Git do end it "gives the latest HEAD revision SHA if nothing is specified" do - @stdout =<<-SHAS + @stdout = <<-SHAS 28af684d8460ba4793eda3e7ac238c864a5d029a\tHEAD 503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha 28af684d8460ba4793eda3e7ac238c864a5d029a\trefs/heads/master @@ -207,7 +203,7 @@ b7d19519a1c15f1c1a324e2683bd728b6198ce5a\trefs/tags/0.7.8^{} ebc1b392fe7e8f0fbabc305c299b4d365d2b4d9b\trefs/tags/chef-server-package SHAS @resource.revision "" - expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"HEAD\"", {:log_tag=>"git[web2.0 app]"}).and_return(double("ShellOut result", :stdout => @stdout)) + expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"HEAD\"", { :log_tag => "git[web2.0 app]" }).and_return(double("ShellOut result", :stdout => @stdout)) expect(@provider.target_revision).to eql("28af684d8460ba4793eda3e7ac238c864a5d029a") end end @@ -248,7 +244,7 @@ SHAS end context "with a specific home" do let (:override_home) do - {"HOME" => "/home/masterNinja"} + { "HOME" => "/home/masterNinja" } end let(:overrided_options) do { @@ -275,9 +271,9 @@ SHAS @resource.ssh_wrapper "do_it_this_way.sh" expected_cmd = "git clone \"git://github.com/opscode/chef.git\" \"/Application Support/with/space\"" expect(@provider).to receive(:shell_out!).with(expected_cmd, :user => "deployNinja", - :environment =>{"GIT_SSH"=>"do_it_this_way.sh", - "HOME" => "/home/deployNinja"}, - :log_tag => "git[web2.0 app]") + :environment => { "GIT_SSH" => "do_it_this_way.sh", + "HOME" => "/home/deployNinja" }, + :log_tag => "git[web2.0 app]") @provider.clone end @@ -312,9 +308,9 @@ SHAS it "runs a checkout command with default options" do expect(@provider).to receive(:shell_out!).with("git branch -f deploy d35af14d41ae22b19da05d7d03a0bafc321b244c", :cwd => "/my/deploy/dir", - :log_tag => "git[web2.0 app]").ordered + :log_tag => "git[web2.0 app]").ordered expect(@provider).to receive(:shell_out!).with("git checkout deploy", :cwd => "/my/deploy/dir", - :log_tag => "git[web2.0 app]").ordered + :log_tag => "git[web2.0 app]").ordered @provider.checkout end @@ -322,7 +318,7 @@ SHAS @resource.enable_submodules true expected_cmd = "git submodule sync" expect(@provider).to receive(:shell_out!).with(expected_cmd, :cwd => "/my/deploy/dir", - :log_tag => "git[web2.0 app]") + :log_tag => "git[web2.0 app]") expected_cmd = "git submodule update --init --recursive" expect(@provider).to receive(:shell_out!).with(expected_cmd, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]") @provider.enable_submodules @@ -336,7 +332,7 @@ SHAS it "runs a sync command with default options" do expect(@provider).to receive(:setup_remote_tracking_branches).with(@resource.remote, @resource.repository) expected_cmd = "git fetch origin && git fetch origin --tags && git reset --hard d35af14d41ae22b19da05d7d03a0bafc321b244c" - expect(@provider).to receive(:shell_out!).with(expected_cmd, :cwd=> "/my/deploy/dir", :log_tag => "git[web2.0 app]") + expect(@provider).to receive(:shell_out!).with(expected_cmd, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]") @provider.fetch_updates end @@ -347,9 +343,9 @@ SHAS expect(@provider).to receive(:setup_remote_tracking_branches).with(@resource.remote, @resource.repository) expected_cmd = "git fetch origin && git fetch origin --tags && git reset --hard d35af14d41ae22b19da05d7d03a0bafc321b244c" expect(@provider).to receive(:shell_out!).with(expected_cmd, :cwd => "/my/deploy/dir", - :user => "whois", :group => "thisis", - :log_tag => "git[web2.0 app]", - :environment=>{"HOME"=>"/home/whois"}) + :user => "whois", :group => "thisis", + :log_tag => "git[web2.0 app]", + :environment => { "HOME" => "/home/whois" }) @provider.fetch_updates end @@ -370,7 +366,6 @@ SHAS end context "configuring remote tracking branches" do - it "checks if a remote with this name already exists" do command_response = double("shell_out") allow(command_response).to receive(:exitstatus) { 1 } @@ -378,7 +373,7 @@ SHAS expect(@provider).to receive(:shell_out!).with(expected_command, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]", - :returns => [0,1,2]).and_return(command_response) + :returns => [0, 1, 2]).and_return(command_response) add_remote_command = "git remote add #{@resource.remote} #{@resource.repository}" expect(@provider).to receive(:shell_out!).with(add_remote_command, :cwd => "/my/deploy/dir", @@ -398,15 +393,15 @@ SHAS :log_tag => "git[web2.0 app]", :user => "whois", :group => "thisis", - :environment=>{"HOME"=>"/home/whois"}, - :returns => [0,1,2]).and_return(command_response) + :environment => { "HOME" => "/home/whois" }, + :returns => [0, 1, 2]).and_return(command_response) add_remote_command = "git remote add #{@resource.remote} #{@resource.repository}" expect(@provider).to receive(:shell_out!).with(add_remote_command, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]", :user => "whois", :group => "thisis", - :environment=>{"HOME"=>"/home/whois"}) + :environment => { "HOME" => "/home/whois" }) @provider.setup_remote_tracking_branches(@resource.remote, @resource.repository) end @@ -418,7 +413,7 @@ SHAS expect(@provider).to receive(:shell_out!).with(check_remote_command, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]", - :returns => [0,1,2]).and_return(command_response) + :returns => [0, 1, 2]).and_return(command_response) expected_command = "git remote add #{@resource.remote} #{@resource.repository}" expect(@provider).to receive(:shell_out!).with(expected_command, :cwd => "/my/deploy/dir", @@ -436,7 +431,7 @@ SHAS expect(@provider).to receive(:shell_out!).with(check_remote_command, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]", - :returns => [0,1,2]).and_return(command_response) + :returns => [0, 1, 2]).and_return(command_response) expected_command = "git config --replace-all remote.#{@resource.remote}.url #{@resource.repository}" expect(@provider).to receive(:shell_out!).with(expected_command, :cwd => "/my/deploy/dir", @@ -452,7 +447,7 @@ SHAS expect(@provider).to receive(:shell_out!).with(check_remote_command, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]", - :returns => [0,1,2]).and_return(command_response) + :returns => [0, 1, 2]).and_return(command_response) unexpected_command = "git config --replace-all remote.#{@resource.remote}.url #{@resource.repository}" expect(@provider).not_to receive(:shell_out!).with(unexpected_command, :cwd => "/my/deploy/dir", @@ -467,7 +462,7 @@ SHAS expect(@provider).to receive(:shell_out!).with(check_remote_command, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]", - :returns => [0,1,2]).and_return(command_response) + :returns => [0, 1, 2]).and_return(command_response) expected_command = "git config --replace-all remote.#{@resource.remote}.url #{@resource.repository}" expect(@provider).to receive(:shell_out!).with(expected_command, :cwd => "/my/deploy/dir", @@ -479,7 +474,7 @@ SHAS it "raises an error if the git clone command would fail because the enclosing directory doesn't exist" do allow(@provider).to receive(:shell_out!) - expect {@provider.run_action(:sync)}.to raise_error(Chef::Exceptions::MissingParentDirectory) + expect { @provider.run_action(:sync) }.to raise_error(Chef::Exceptions::MissingParentDirectory) end it "does a checkout by cloning the repo and then enabling submodules" do @@ -488,7 +483,7 @@ SHAS allow(::File).to receive(:exist?).with("/my/deploy/dir").and_return(true) allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) - allow(::Dir).to receive(:entries).with("/my/deploy/dir").and_return([".",".."]) + allow(::Dir).to receive(:entries).with("/my/deploy/dir").and_return([".", ".."]) expect(@provider).to receive(:clone) expect(@provider).to receive(:checkout) expect(@provider).to receive(:enable_submodules) @@ -504,7 +499,7 @@ SHAS allow(::File).to receive(:exist?).with("/my/deploy/dir").and_return(true) allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) - allow(::Dir).to receive(:entries).with("/my/deploy/dir").and_return([".",".."]) + allow(::Dir).to receive(:entries).with("/my/deploy/dir").and_return([".", ".."]) @resource.enable_checkout false expect(@provider).to receive(:clone) @@ -519,7 +514,7 @@ SHAS allow(::File).to receive(:exist?).with("/my/deploy/dir/.git").and_return(false) allow(::File).to receive(:exist?).with("/my/deploy/dir").and_return(false) allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) - allow(::Dir).to receive(:entries).with("/my/deploy/dir").and_return(["..","."]) + allow(::Dir).to receive(:entries).with("/my/deploy/dir").and_return(["..", "."]) expect(@provider).to receive(:clone) expect(@provider).to receive(:checkout) expect(@provider).to receive(:enable_submodules) @@ -534,7 +529,7 @@ SHAS allow(::File).to receive(:exist?).with("/my/deploy/dir").and_return(true) allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) - allow(::Dir).to receive(:entries).with("/my/deploy/dir").and_return([".","..","foo","bar"]) + allow(::Dir).to receive(:entries).with("/my/deploy/dir").and_return([".", "..", "foo", "bar"]) expect(@provider).not_to receive(:clone) expect(@provider).not_to receive(:checkout) expect(@provider).not_to receive(:enable_submodules) @@ -606,8 +601,8 @@ SHAS describe "calling add_remotes" do it "adds a new remote for each entry in additional remotes hash" do - @resource.additional_remotes({:opscode => "opscode_repo_url", - :another_repo => "some_other_repo_url"}) + @resource.additional_remotes({ :opscode => "opscode_repo_url", + :another_repo => "some_other_repo_url" }) allow(STDOUT).to receive(:tty?).and_return(false) command_response = double("shell_out") allow(command_response).to receive(:exitstatus) { 0 } diff --git a/spec/unit/provider/group/dscl_spec.rb b/spec/unit/provider/group/dscl_spec.rb index 44619f891b..755b7aa8d0 100644 --- a/spec/unit/provider/group/dscl_spec.rb +++ b/spec/unit/provider/group/dscl_spec.rb @@ -40,7 +40,7 @@ describe Chef::Provider::Group::Dscl do it "should return an array of four elements - cmd, status, stdout, stderr" do dscl_retval = @provider.dscl("cmd /Path args") expect(dscl_retval).to be_a_kind_of(Array) - expect(dscl_retval).to eq(["dscl . -cmd /Path args",@status,"\n",""]) + expect(dscl_retval).to eq(["dscl . -cmd /Path args", @status, "\n", ""]) end describe "safe_dscl" do @@ -179,7 +179,6 @@ describe Chef::Provider::Group::Dscl do end describe "set_members" do - describe "with existing members in the current resource and append set to false in the new resource" do before do allow(@new_resource).to receive(:members).and_return([]) @@ -317,7 +316,6 @@ GroupMembership: waka bar EOF allow(@provider).to receive(:safe_dscl).with("read /Groups/aj").and_return(@output) @current_resource = @provider.load_current_resource - end it "should parse gid properly" do diff --git a/spec/unit/provider/group/gpasswd_spec.rb b/spec/unit/provider/group/gpasswd_spec.rb index 16e6ad15ea..1292b6cea7 100644 --- a/spec/unit/provider/group/gpasswd_spec.rb +++ b/spec/unit/provider/group/gpasswd_spec.rb @@ -110,7 +110,6 @@ describe Chef::Provider::Group::Gpasswd, "modify_group_members" do @provider.modify_group_members end end - end end end diff --git a/spec/unit/provider/group/groupadd_spec.rb b/spec/unit/provider/group/groupadd_spec.rb index ad9e16ea94..6084f3d920 100644 --- a/spec/unit/provider/group/groupadd_spec.rb +++ b/spec/unit/provider/group/groupadd_spec.rb @@ -43,9 +43,9 @@ describe Chef::Provider::Group::Groupadd, "set_options" do field_list.each do |attribute, option| it "should check for differences in #{attribute} between the current and new resources" do - expect(@new_resource).to receive(attribute) - expect(@current_resource).to receive(attribute) - @provider.set_options + expect(@new_resource).to receive(attribute) + expect(@current_resource).to receive(attribute) + @provider.set_options end it "should set the option for #{attribute} if the new resources #{attribute} is not null" do allow(@new_resource).to receive(attribute).and_return("wowaweea") @@ -55,7 +55,7 @@ describe Chef::Provider::Group::Groupadd, "set_options" do it "should combine all the possible options" do match_string = "" - field_list.sort{ |a,b| a[0] <=> b[0] }.each do |attribute, option| + field_list.sort { |a, b| a[0] <=> b[0] }.each do |attribute, option| allow(@new_resource).to receive(attribute).and_return("hola") match_string << " #{option} 'hola'" end @@ -122,7 +122,6 @@ describe Chef::Provider::Group::Groupadd do end describe "manage group" do - it "should run groupmod with the return of set_options" do allow(@provider).to receive(:modify_group_members).and_return(true) expect(@provider).to receive(:run_command).with({ :command => "groupmod monkey" }).and_return(true) @@ -136,7 +135,6 @@ describe Chef::Provider::Group::Groupadd do end describe "remove_group" do - it "should run groupdel with the new resources group name" do expect(@provider).to receive(:run_command).with({ :command => "groupdel aj" }).and_return(true) @provider.remove_group @@ -169,6 +167,5 @@ describe Chef::Provider::Group::Groupadd do expect(File).to receive(:exists?).with("/usr/sbin/groupdel").and_return(false) expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::Group) end - end end diff --git a/spec/unit/provider/group/groupmod_spec.rb b/spec/unit/provider/group/groupmod_spec.rb index 1cb39ad0c3..21d026409e 100644 --- a/spec/unit/provider/group/groupmod_spec.rb +++ b/spec/unit/provider/group/groupmod_spec.rb @@ -19,16 +19,16 @@ require "spec_helper" describe Chef::Provider::Group::Groupmod do - before do - @node = Chef::Node.new - @events = Chef::EventDispatch::Dispatcher.new - @run_context = Chef::RunContext.new(@node, {}, @events) - @new_resource = Chef::Resource::Group.new("wheel") - @new_resource.gid 123 - @new_resource.members %w{lobster rage fist} - @new_resource.append false - @provider = Chef::Provider::Group::Groupmod.new(@new_resource, @run_context) - end + before do + @node = Chef::Node.new + @events = Chef::EventDispatch::Dispatcher.new + @run_context = Chef::RunContext.new(@node, {}, @events) + @new_resource = Chef::Resource::Group.new("wheel") + @new_resource.gid 123 + @new_resource.members %w{lobster rage fist} + @new_resource.append false + @provider = Chef::Provider::Group::Groupmod.new(@new_resource, @run_context) + end describe "manage_group" do describe "when determining the current group state" do diff --git a/spec/unit/provider/group/pw_spec.rb b/spec/unit/provider/group/pw_spec.rb index 2c563750f3..709456a824 100644 --- a/spec/unit/provider/group/pw_spec.rb +++ b/spec/unit/provider/group/pw_spec.rb @@ -55,7 +55,6 @@ describe Chef::Provider::Group::Pw do end describe "when managing the group" do - it "should run pw groupmod with the return of set_options" do @new_resource.gid(42) @new_resource.members(["someone"]) @@ -63,7 +62,6 @@ describe Chef::Provider::Group::Pw do expect(@provider).to receive(:run_command).with({ :command => "pw groupmod wheel -g '42' -d root,aj" }).and_return(true) @provider.manage_group end - end describe "when removing the group" do @@ -74,7 +72,6 @@ describe Chef::Provider::Group::Pw do end describe "when setting group membership" do - describe "with an empty members array in both the new and current resource" do before do allow(@new_resource).to receive(:members).and_return([]) diff --git a/spec/unit/provider/group/usermod_spec.rb b/spec/unit/provider/group/usermod_spec.rb index 1a718b1d40..817da9923e 100644 --- a/spec/unit/provider/group/usermod_spec.rb +++ b/spec/unit/provider/group/usermod_spec.rb @@ -31,7 +31,6 @@ describe Chef::Provider::Group::Usermod do end describe "modify_group_members" do - describe "with an empty members array" do before do allow(@new_resource).to receive(:append).and_return(true) diff --git a/spec/unit/provider/group/windows_spec.rb b/spec/unit/provider/group/windows_spec.rb index c331e2b021..de1c99b9cf 100644 --- a/spec/unit/provider/group/windows_spec.rb +++ b/spec/unit/provider/group/windows_spec.rb @@ -70,7 +70,6 @@ describe Chef::Provider::Group::Windows do expect(@net_group).to receive(:local_add_members).with(@new_resource.members) @provider.manage_group end - end describe "remove_group" do diff --git a/spec/unit/provider/group_spec.rb b/spec/unit/provider/group_spec.rb index d5512b32cd..2752f32d73 100644 --- a/spec/unit/provider/group_spec.rb +++ b/spec/unit/provider/group_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::User do - before do @node = Chef::Node.new @events = Chef::EventDispatch::Dispatcher.new @@ -49,7 +48,6 @@ describe Chef::Provider::User do end describe "when establishing the current state of the group" do - it "sets the group name of the current resource to the group name of the new resource" do @provider.load_current_resource expect(@provider.current_resource.group_name).to eq("wheel") @@ -120,12 +118,11 @@ 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 { |m| @new_resource.excluded_members << m } @new_resource.members.clear allow(@new_resource).to receive(:append).and_return(true) expect(@provider.compare_group).to be_truthy end - end describe "when creating a group" do @@ -169,7 +166,6 @@ describe Chef::Provider::User do end describe "when removing a group" do - it "should not call remove_group if the group does not exist" do @provider.group_exists = false expect(@provider).not_to receive(:remove_group) @@ -256,25 +252,24 @@ describe Chef::Provider::User do describe "when determining the reason for a change" do it "should report which group members are missing if members are missing and appending to the group" do - @new_resource.members << "user1" - @new_resource.members << "user2" - allow(@new_resource).to receive(:append).and_return true - expect(@provider.compare_group).to be_truthy - expect(@provider.change_desc).to eq([ "add missing member(s): user1, user2" ]) + @new_resource.members << "user1" + @new_resource.members << "user2" + allow(@new_resource).to receive(:append).and_return true + expect(@provider.compare_group).to be_truthy + expect(@provider.change_desc).to eq([ "add missing member(s): user1, user2" ]) end it "should report that the group members will be overwritten if not appending" do - @new_resource.members << "user1" - allow(@new_resource).to receive(:append).and_return false - expect(@provider.compare_group).to be_truthy - expect(@provider.change_desc).to eq([ "replace group members with new list of members" ]) + @new_resource.members << "user1" + allow(@new_resource).to receive(:append).and_return false + expect(@provider.compare_group).to be_truthy + expect(@provider.change_desc).to eq([ "replace group members with new list of members" ]) end it "should report the gid will be changed when it does not match" do allow(@current_resource).to receive(:gid).and_return("BADF00D") expect(@provider.compare_group).to be_truthy expect(@provider.change_desc).to eq([ "change gid #{@current_resource.gid} to #{@new_resource.gid}" ]) - end it "should report no change reason when no change is required" do @@ -282,5 +277,4 @@ describe Chef::Provider::User do expect(@provider.change_desc).to eq([ ]) end end - end diff --git a/spec/unit/provider/http_request_spec.rb b/spec/unit/provider/http_request_spec.rb index f4d415be4d..348a3c6b0b 100644 --- a/spec/unit/provider/http_request_spec.rb +++ b/spec/unit/provider/http_request_spec.rb @@ -33,7 +33,6 @@ describe Chef::Provider::HttpRequest do end describe "load_current_resource" do - it "should set up a Chef::ServerAPI client, with no authentication" do expect(Chef::HTTP::Simple).to receive(:new).with(@new_resource.url) @provider.load_current_resource @@ -50,7 +49,6 @@ describe Chef::Provider::HttpRequest do end describe "action_get" do - it "should inflate a message block at runtime" do @new_resource.message { "return" } expect(@http).to receive(:get).with("http://www.opscode.com/", {}) @@ -138,7 +136,7 @@ describe Chef::Provider::HttpRequest do it "should not update a HEAD request if a not modified response (CHEF-4762)" do if_modified_since = File.mtime(__FILE__).httpdate @new_resource.headers "If-Modified-Since" => if_modified_since - expect(@http).to receive(:head).with("http://www.opscode.com/", {"If-Modified-Since" => if_modified_since}).and_return(false) + expect(@http).to receive(:head).with("http://www.opscode.com/", { "If-Modified-Since" => if_modified_since }).and_return(false) @provider.run_action(:head) expect(@new_resource).not_to be_updated end diff --git a/spec/unit/provider/ifconfig/aix_spec.rb b/spec/unit/provider/ifconfig/aix_spec.rb index 264ef1d205..2d7405213a 100644 --- a/spec/unit/provider/ifconfig/aix_spec.rb +++ b/spec/unit/provider/ifconfig/aix_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "chef/exceptions" describe Chef::Provider::Ifconfig::Aix do - before(:all) do @ifconfig_output = <<-IFCONFIG en1: flags=1e080863,480 @@ -35,7 +34,6 @@ lo0: flags=e08084b,c0 0) @@ -54,7 +53,6 @@ describe Chef::Provider::Ifconfig::Debian do let(:config_filename_ifcfg) { "/etc/network/interfaces.d/ifcfg-#{new_resource.device}" } describe "generate_config" do - context "when writing a file" do let(:tempfile) { Tempfile.new("rspec-chef-ifconfig-debian") } @@ -120,7 +118,7 @@ iface eth0 inet static netmask 255.255.254.0 EOF ) - expect(File.exists?(tempdir_path)).to be_truthy # since the file exists, the enclosing dir must also exist + expect(File.exists?(tempdir_path)).to be_truthy # since the file exists, the enclosing dir must also exist end context "when the /etc/network/interfaces file has the source line" do @@ -143,7 +141,6 @@ EOF provider.run_action(:add) expect(IO.read(tempfile.path)).to eq(expected_string) end - end context "when the /etc/network/interfaces file does not have the source line" do @@ -176,7 +173,6 @@ EOF end describe "when running under why run" do - before do Chef::Config[:why_run] = true end @@ -253,7 +249,7 @@ iface eth0 inet static EOF ) expect(File).not_to receive(:new).with(config_filename_ifcfg, "w") - expect(File.exists?(tempdir_path)).to be_truthy # since the file exists, the enclosing dir must also exist + expect(File.exists?(tempdir_path)).to be_truthy # since the file exists, the enclosing dir must also exist end context "when the /etc/network/interfaces file has the source line" do @@ -274,7 +270,6 @@ another line provider.run_action(:add) expect(IO.read(tempfile.path)).to eq(expected_string) end - end context "when the /etc/network/interfaces file does not have the source line" do @@ -306,7 +301,6 @@ source #{tempdir_path}/* end describe "delete_config for action_delete" do - let(:tempfile) { Tempfile.new("rspec-chef-ifconfig-debian") } let(:tempdir_path) { Dir.mktmpdir("rspec-chef-ifconfig-debian-dir") } @@ -340,5 +334,4 @@ source #{tempdir_path}/* expect(File.exist?(config_filename_ifcfg)).to be_falsey end end - end diff --git a/spec/unit/provider/ifconfig/redhat_spec.rb b/spec/unit/provider/ifconfig/redhat_spec.rb index 0088cef9f9..13a2c41e04 100644 --- a/spec/unit/provider/ifconfig/redhat_spec.rb +++ b/spec/unit/provider/ifconfig/redhat_spec.rb @@ -44,7 +44,6 @@ describe Chef::Provider::Ifconfig::Redhat do end describe "generate_config for action_add" do - it "should write network-script for centos" do allow(@provider).to receive(:load_current_resource) allow(@provider).to receive(:run_command) @@ -60,7 +59,6 @@ describe Chef::Provider::Ifconfig::Redhat do end describe "delete_config for action_delete" do - it "should delete network-script if it exists for centos" do @current_resource.device @new_resource.device allow(@provider).to receive(:load_current_resource) diff --git a/spec/unit/provider/ifconfig_spec.rb b/spec/unit/provider/ifconfig_spec.rb index db45640169..69f29647a0 100644 --- a/spec/unit/provider/ifconfig_spec.rb +++ b/spec/unit/provider/ifconfig_spec.rb @@ -38,7 +38,6 @@ describe Chef::Provider::Ifconfig do status = double("Status", :exitstatus => 0) @provider.instance_variable_set("@status", status) @provider.current_resource = @current_resource - end describe Chef::Provider::Ifconfig, "load_current_resource" do before do @@ -55,7 +54,6 @@ describe Chef::Provider::Ifconfig do end end describe Chef::Provider::Ifconfig, "action_add" do - it "should add an interface if it does not exist" do #@provider.stub(:run_command).and_return(true) allow(@provider).to receive(:load_current_resource) @@ -94,7 +92,6 @@ describe Chef::Provider::Ifconfig do end describe Chef::Provider::Ifconfig, "action_enable" do - it "should enable interface if it does not exist" do allow(@provider).to receive(:load_current_resource) @current_resource.inet_addr nil @@ -128,7 +125,6 @@ describe Chef::Provider::Ifconfig do end describe Chef::Provider::Ifconfig, "action_delete" do - it "should delete interface if it exists" do allow(@provider).to receive(:load_current_resource) @current_resource.device "eth0" @@ -151,7 +147,6 @@ describe Chef::Provider::Ifconfig do end describe Chef::Provider::Ifconfig, "action_disable" do - it "should disable interface if it exists" do allow(@provider).to receive(:load_current_resource) @current_resource.device "eth0" @@ -174,7 +169,6 @@ describe Chef::Provider::Ifconfig do end describe Chef::Provider::Ifconfig, "action_delete" do - it "should delete interface of it exists" do allow(@provider).to receive(:load_current_resource) @current_resource.device "eth0" diff --git a/spec/unit/provider/log_spec.rb b/spec/unit/provider/log_spec.rb index 2e4f9c4e52..5329db317f 100644 --- a/spec/unit/provider/log_spec.rb +++ b/spec/unit/provider/log_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::Log::ChefLog do - let(:log_str) { "this is my test string to log" } let(:node) { Chef::Node.new } diff --git a/spec/unit/provider/mdadm_spec.rb b/spec/unit/provider/mdadm_spec.rb index cf49d651c2..f49dbe4e58 100644 --- a/spec/unit/provider/mdadm_spec.rb +++ b/spec/unit/provider/mdadm_spec.rb @@ -20,13 +20,12 @@ require "spec_helper" require "ostruct" describe Chef::Provider::Mdadm do - before(:each) do @node = Chef::Node.new @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @new_resource = Chef::Resource::Mdadm.new("/dev/md1") - @new_resource.devices ["/dev/sdz1","/dev/sdz2","/dev/sdz3"] + @new_resource.devices ["/dev/sdz1", "/dev/sdz2", "/dev/sdz3"] @provider = Chef::Provider::Mdadm.new(@new_resource, @run_context) end @@ -39,13 +38,13 @@ describe Chef::Provider::Mdadm do end it "determines that the metadevice exists when mdadm exit code is zero" do - allow(@provider).to receive(:shell_out!).with("mdadm --detail --test /dev/md1", :returns => [0,4]).and_return(OpenStruct.new(:status => 0)) + allow(@provider).to receive(:shell_out!).with("mdadm --detail --test /dev/md1", :returns => [0, 4]).and_return(OpenStruct.new(:status => 0)) @provider.load_current_resource expect(@provider.current_resource.exists).to be_truthy end it "determines that the metadevice does not exist when mdadm exit code is 4" do - allow(@provider).to receive(:shell_out!).with("mdadm --detail --test /dev/md1", :returns => [0,4]).and_return(OpenStruct.new(:status => 4)) + allow(@provider).to receive(:shell_out!).with("mdadm --detail --test /dev/md1", :returns => [0, 4]).and_return(OpenStruct.new(:status => 4)) @provider.load_current_resource expect(@provider.current_resource.exists).to be_falsey end @@ -102,16 +101,15 @@ describe Chef::Provider::Mdadm do expect(@new_resource).to be_updated_by_last_action end - it "should not assemble the raid device if it doesnt exist" do + it "should not assemble the raid device if it doesnt exist" do @current_resource.exists(true) expect(@provider).not_to receive(:shell_out!) @provider.run_action(:assemble) expect(@new_resource).not_to be_updated_by_last_action - end + end end describe "when stopping the metadevice" do - it "should stop the raid device if it exists" do @current_resource.exists(true) expected_mdadm_cmd = "yes | mdadm --stop /dev/md1" diff --git a/spec/unit/provider/mount/aix_spec.rb b/spec/unit/provider/mount/aix_spec.rb index 3bd05073ea..995b29db65 100644 --- a/spec/unit/provider/mount/aix_spec.rb +++ b/spec/unit/provider/mount/aix_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "ostruct" describe Chef::Provider::Mount::Aix do - before(:all) do @mounted_output = <<-MOUNT node mounted mounted over vfs date options @@ -40,7 +39,7 @@ UNMOUNTED /dev/sdz3 /tmp/foo jfs2 Jul 17 13:22 rw,log=/dev/hd8 MOUNT - @enabled_output = <<-ENABLED + @enabled_output = <<-ENABLED #MountPoint:Device:Vfs:Nodename:Type:Size:Options:AutoMount:Acct /tmp/foo:/dev/sdz1:jfs2::bootfs:10485760:rw:yes:no ENABLED @@ -156,7 +155,7 @@ ENABLED describe "remount_fs" do it "should remount resource if it is already mounted and it supports remounting" do - @new_resource.supports({:remount => true}) + @new_resource.supports({ :remount => true }) stub_mounted_enabled(@provider, @mounted_output, "") expect(@provider).to receive(:shell_out!).with("mount -o remount #{@new_resource.device} #{@new_resource.mount_point}") @@ -165,7 +164,7 @@ ENABLED end it "should remount with new mount options if it is already mounted and it supports remounting" do - @new_resource.supports({:remount => true}) + @new_resource.supports({ :remount => true }) @new_resource.options("nodev,rw") stub_mounted_enabled(@provider, @mounted_output, "") diff --git a/spec/unit/provider/mount/mount_spec.rb b/spec/unit/provider/mount/mount_spec.rb index 1fbe0c5c89..8d2ee08f52 100644 --- a/spec/unit/provider/mount/mount_spec.rb +++ b/spec/unit/provider/mount/mount_spec.rb @@ -239,11 +239,11 @@ describe Chef::Provider::Mount::Mount do end it "should ignore commented lines in fstab " do - fstab = "\# #{@new_resource.device} #{@new_resource.mount_point} ext3 defaults 1 2\n" - allow(::File).to receive(:foreach).with("/etc/fstab").and_yield fstab + fstab = "\# #{@new_resource.device} #{@new_resource.mount_point} ext3 defaults 1 2\n" + allow(::File).to receive(:foreach).with("/etc/fstab").and_yield fstab - @provider.load_current_resource - expect(@provider.current_resource.enabled).to be_falsey + @provider.load_current_resource + expect(@provider.current_resource.enabled).to be_falsey end it "should set enabled to false if the mount point is not last in fstab" do @@ -328,7 +328,6 @@ describe Chef::Provider::Mount::Mount do expect(@provider).to_not receive(:shell_out!) @provider.mount_fs() end - end describe "umount_fs" do @@ -347,14 +346,14 @@ describe Chef::Provider::Mount::Mount do describe "remount_fs" do it "should use mount -o remount if remount is supported" do - @new_resource.supports({:remount => true}) + @new_resource.supports({ :remount => true }) @current_resource.mounted(true) expect(@provider).to receive(:shell_out!).with("mount -o remount,defaults #{@new_resource.mount_point}") @provider.remount_fs end it "should use mount -o remount with new mount options if remount is supported" do - @new_resource.supports({:remount => true}) + @new_resource.supports({ :remount => true }) options = "rw,noexec,noauto" @new_resource.options(%w{rw noexec noauto}) @current_resource.mounted(true) @@ -363,7 +362,7 @@ describe Chef::Provider::Mount::Mount do end it "should umount and mount if remount is not supported" do - @new_resource.supports({:remount => false}) + @new_resource.supports({ :remount => false }) @current_resource.mounted(true) expect(@provider).to receive(:umount_fs) expect(@provider).to receive(:sleep).with(1) diff --git a/spec/unit/provider/mount/solaris_spec.rb b/spec/unit/provider/mount/solaris_spec.rb index 7304c4290f..7858519261 100644 --- a/spec/unit/provider/mount/solaris_spec.rb +++ b/spec/unit/provider/mount/solaris_spec.rb @@ -103,7 +103,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do describe "#define_resource_requirements" do before do # we're not testing the actual actions so stub them all out - [:mount_fs, :umount_fs, :remount_fs, :enable_fs, :disable_fs].each {|m| allow(provider).to receive(m) } + [:mount_fs, :umount_fs, :remount_fs, :enable_fs, :disable_fs].each { |m| allow(provider).to receive(m) } end it "run_action(:mount) should raise an error if the device does not exist" do @@ -145,12 +145,10 @@ describe Chef::Provider::Mount::Solaris, :unix_only do end end end - end describe "#load_current_resource" do context "when loading a normal UFS filesystem with mount at boot" do - before do provider.load_current_resource end @@ -213,7 +211,6 @@ describe Chef::Provider::Mount::Solaris, :unix_only do describe "#load_current_resource" do context "when loading a normal UFS filesystem with noauto, don't mount at boot" do - let(:vfstab_file_contents) { <<-EOF.gsub /^\s*/, "" #device device mount FS fsck mount mount @@ -327,11 +324,9 @@ describe Chef::Provider::Mount::Solaris, :unix_only do # 0 and - could mean different things for some file systems expect(provider.current_resource.pass).to eql(0) end - end context "when the device is symlink" do - let(:target) { "/dev/mapper/target" } let(:mount_output) { diff --git a/spec/unit/provider/mount/windows_spec.rb b/spec/unit/provider/mount/windows_spec.rb index df7479fd46..ab7a161c08 100644 --- a/spec/unit/provider/mount/windows_spec.rb +++ b/spec/unit/provider/mount/windows_spec.rb @@ -100,9 +100,9 @@ describe Chef::Provider::Mount::Windows do it "should mount the filesystem if it is not mounted" do expect(@vol).to receive(:add).with(:remote => @new_resource.device, - :username => @new_resource.username, - :domainname => @new_resource.domain, - :password => @new_resource.password) + :username => @new_resource.username, + :domainname => @new_resource.domain, + :password => @new_resource.password) @provider.mount_fs end @@ -114,9 +114,9 @@ describe Chef::Provider::Mount::Windows do it "should remount the filesystem if it is mounted and the options have changed" do expect(@vol).to receive(:add).with(:remote => @new_resource.device, - :username => @new_resource.username, - :domainname => @new_resource.domain, - :password => @new_resource.password) + :username => @new_resource.username, + :domainname => @new_resource.domain, + :password => @new_resource.password) @provider.mount_fs end diff --git a/spec/unit/provider/mount_spec.rb b/spec/unit/provider/mount_spec.rb index 5aa247a30f..00cb7291c9 100644 --- a/spec/unit/provider/mount_spec.rb +++ b/spec/unit/provider/mount_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Provider::Mount do - let(:node) { Chef::Node.new } let(:events) { Chef::EventDispatch::Dispatcher.new } @@ -53,7 +52,6 @@ describe Chef::Provider::Mount do end describe "when the target state is a mounted filesystem" do - it "should mount the filesystem if it isn't mounted" do allow(current_resource).to receive(:mounted).and_return(false) expect(provider).to receive(:mount_fs).and_return(true) @@ -78,7 +76,6 @@ describe Chef::Provider::Mount do provider.run_action(:mount) expect(new_resource).not_to be_updated_by_last_action end - end describe "when the target state is an unmounted filesystem" do @@ -135,7 +132,7 @@ describe Chef::Provider::Mount do provider.unmount_retries = 1 expect(provider).to receive(:umount_fs) expect(provider).to receive(:mounted?).and_return(true, true) - expect{ provider.run_action(:remount) }.to raise_error(Chef::Exceptions::Mount) + expect { provider.run_action(:remount) }.to raise_error(Chef::Exceptions::Mount) end end @@ -181,7 +178,6 @@ describe Chef::Provider::Mount do end end - it "should delegates the mount implementation to subclasses" do expect { provider.mount_fs }.to raise_error(Chef::Exceptions::UnsupportedAction) end diff --git a/spec/unit/provider/ohai_spec.rb b/spec/unit/provider/ohai_spec.rb index d04bef146e..100eee59a4 100644 --- a/spec/unit/provider/ohai_spec.rb +++ b/spec/unit/provider/ohai_spec.rb @@ -46,7 +46,7 @@ describe Chef::Provider::Ohai do mock_ohai[:data2]) allow(Ohai::System).to receive(:new).and_return(mock_ohai) allow(Chef::Platform).to receive(:find_platform_and_version).and_return({ "platform" => @platform, - "platform_version" => @platform_version}) + "platform_version" => @platform_version }) # Fake node with a dummy save @node = Chef::Node.new @node.name(@fqdn) @@ -56,7 +56,7 @@ describe Chef::Provider::Ohai do @new_resource = Chef::Resource::Ohai.new("ohai_reload") ohai = Ohai::System.new ohai.all_plugins - @node.consume_external_attrs(ohai.data,{}) + @node.consume_external_attrs(ohai.data, {}) @provider = Chef::Provider::Ohai.new(@new_resource, @run_context) end diff --git a/spec/unit/provider/osx_profile_spec.rb b/spec/unit/provider/osx_profile_spec.rb index 13b65e8cc7..707e652110 100644 --- a/spec/unit/provider/osx_profile_spec.rb +++ b/spec/unit/provider/osx_profile_spec.rb @@ -23,56 +23,47 @@ describe Chef::Provider::OsxProfile do double("shell_out", :exitstatus => 0, :error? => false) end describe "action_create" do - let(:node) { Chef::Node.new } - let(:events) { Chef::EventDispatch::Dispatcher.new } - let(:run_context) { Chef::RunContext.new(node, {}, events) } - let(:new_resource) { Chef::Resource::OsxProfile.new("Profile Test", run_context) } - let(:provider) { Chef::Provider::OsxProfile.new(new_resource, run_context) } - let(:all_profiles) do - {"_computerlevel"=> - [{"ProfileDisplayName"=>"Finder Settings", - "ProfileIdentifier"=>"com.apple.finder", - "ProfileInstallDate"=>"2015-11-08 23:15:21 +0000", - "ProfileItems"=> - [{"PayloadContent"=> - {"PayloadContentManagedPreferences"=> - {"com.apple.finder"=> - {"Forced"=>[{"mcx_preference_settings"=>{"ShowExternalHardDrivesOnDesktop"=>false}}]}}}, - "PayloadDisplayName"=>"Custom: (com.apple.finder)", - "PayloadIdentifier"=>"com.apple.finder", - "PayloadType"=>"com.apple.ManagedClient.preferences", - "PayloadUUID"=>"a017048f-684b-4e81-baa3-43afe316d739", - "PayloadVersion"=>1}], - "ProfileOrganization"=>"Chef", - "ProfileRemovalDisallowed"=>"false", - "ProfileType"=>"Configuration", - "ProfileUUID"=>"e2e09bef-e673-44a6-bcbe-ecb5f1c1b740", - "ProfileVerificationState"=>"unsigned", - "ProfileVersion"=>1}, - {"ProfileDisplayName"=>"ScreenSaver Settings", - "ProfileIdentifier"=>"com.testprofile.screensaver", - "ProfileInstallDate"=>"2015-10-05 23:15:21 +0000", - "ProfileItems"=> - [{"PayloadContent"=> - {"PayloadContentManagedPreferences"=> - {"com.apple.screensaver"=> - {"Forced"=>[{"mcx_preference_settings"=>{"idleTime"=>0}}]}}}, - "PayloadDisplayName"=>"Custom: (com.apple.screensaver)", - "PayloadIdentifier"=>"com.apple.screensaver", - "PayloadType"=>"com.apple.ManagedClient.preferences", - "PayloadUUID"=>"73fc30e0-1e57-0131-c32d-000c2944c110", - "PayloadVersion"=>1}], - "ProfileOrganization"=>"Chef", - "ProfileRemovalDisallowed"=>"false", - "ProfileType"=>"Configuration", - "ProfileUUID"=>"6e95927c-f200-54b4-85c7-52ab99b61c47", - "ProfileVerificationState"=>"unsigned", - "ProfileVersion"=>1}] - } - end + let(:node) { Chef::Node.new } + let(:events) { Chef::EventDispatch::Dispatcher.new } + let(:run_context) { Chef::RunContext.new(node, {}, events) } + let(:new_resource) { Chef::Resource::OsxProfile.new("Profile Test", run_context) } + let(:provider) { Chef::Provider::OsxProfile.new(new_resource, run_context) } + let(:all_profiles) do + { "_computerlevel" => [{ "ProfileDisplayName" => "Finder Settings", + "ProfileIdentifier" => "com.apple.finder", + "ProfileInstallDate" => "2015-11-08 23:15:21 +0000", + "ProfileItems" => [{ "PayloadContent" => { "PayloadContentManagedPreferences" => { "com.apple.finder" => { "Forced" => [{ "mcx_preference_settings" => { "ShowExternalHardDrivesOnDesktop" => false } }] } } }, + "PayloadDisplayName" => "Custom: (com.apple.finder)", + "PayloadIdentifier" => "com.apple.finder", + "PayloadType" => "com.apple.ManagedClient.preferences", + "PayloadUUID" => "a017048f-684b-4e81-baa3-43afe316d739", + "PayloadVersion" => 1 }], + "ProfileOrganization" => "Chef", + "ProfileRemovalDisallowed" => "false", + "ProfileType" => "Configuration", + "ProfileUUID" => "e2e09bef-e673-44a6-bcbe-ecb5f1c1b740", + "ProfileVerificationState" => "unsigned", + "ProfileVersion" => 1 }, + { "ProfileDisplayName" => "ScreenSaver Settings", + "ProfileIdentifier" => "com.testprofile.screensaver", + "ProfileInstallDate" => "2015-10-05 23:15:21 +0000", + "ProfileItems" => [{ "PayloadContent" => { "PayloadContentManagedPreferences" => { "com.apple.screensaver" => { "Forced" => [{ "mcx_preference_settings" => { "idleTime" => 0 } }] } } }, + "PayloadDisplayName" => "Custom: (com.apple.screensaver)", + "PayloadIdentifier" => "com.apple.screensaver", + "PayloadType" => "com.apple.ManagedClient.preferences", + "PayloadUUID" => "73fc30e0-1e57-0131-c32d-000c2944c110", + "PayloadVersion" => 1 }], + "ProfileOrganization" => "Chef", + "ProfileRemovalDisallowed" => "false", + "ProfileType" => "Configuration", + "ProfileUUID" => "6e95927c-f200-54b4-85c7-52ab99b61c47", + "ProfileVerificationState" => "unsigned", + "ProfileVersion" => 1 }] + } + end # If anything is changed within this profile, be sure to update the # ProfileUUID in all_profiles to match the new config specific UUID - let(:test_profile) do + let(:test_profile) do { "PayloadIdentifier" => "com.testprofile.screensaver", "PayloadRemovalDisallowed" => false, @@ -82,7 +73,7 @@ describe Chef::Provider::OsxProfile do "PayloadOrganization" => "Chef", "PayloadVersion" => 1, "PayloadDisplayName" => "Screensaver Settings", - "PayloadContent"=> [ + "PayloadContent" => [ { "PayloadType" => "com.apple.ManagedClient.preferences", "PayloadVersion" => 1, @@ -103,11 +94,11 @@ describe Chef::Provider::OsxProfile do }, }, ], - } - end - let(:no_profiles) do - { } - end + } + end + let(:no_profiles) do + {} + end before(:each) do allow(provider).to receive(:cookbook_file_available?).and_return(true) @@ -181,9 +172,8 @@ describe Chef::Provider::OsxProfile do test_profile.delete("PayloadIdentifier") new_resource.profile test_profile error_message = "The specified profile does not seem to be valid" - expect{provider.run_action(:install)}.to raise_error(RuntimeError, error_message) + expect { provider.run_action(:install) }.to raise_error(RuntimeError, error_message) end - end describe "action_remove" do @@ -194,45 +184,36 @@ describe Chef::Provider::OsxProfile do let(:provider) { Chef::Provider::OsxProfile.new(new_resource, run_context) } let(:current_resource) { Chef::Resource::OsxProfile.new("Profile Test") } let(:all_profiles) do - {"_computerlevel"=> - [{"ProfileDisplayName"=>"ScreenSaver Settings", - "ProfileIdentifier"=>"com.apple.screensaver", - "ProfileInstallDate"=>"2015-10-05 23:15:21 +0000", - "ProfileItems"=> - [{"PayloadContent"=> - {"PayloadContentManagedPreferences"=> - {"com.apple.screensaver"=> - {"Forced"=>[{"mcx_preference_settings"=>{"idleTime"=>0}}]}}}, - "PayloadDisplayName"=>"Custom: (com.apple.screensaver)", - "PayloadIdentifier"=>"com.apple.screensaver", - "PayloadType"=>"com.apple.ManagedClient.preferences", - "PayloadUUID"=>"73fc30e0-1e57-0131-c32d-000c2944c108", - "PayloadVersion"=>1}], - "ProfileOrganization"=>"Chef", - "ProfileRemovalDisallowed"=>"false", - "ProfileType"=>"Configuration", - "ProfileUUID"=>"1781fbec-3325-565f-9022-8aa28135c3cc", - "ProfileVerificationState"=>"unsigned", - "ProfileVersion"=>1}, - {"ProfileDisplayName"=>"ScreenSaver Settings", - "ProfileIdentifier"=>"com.testprofile.screensaver", - "ProfileInstallDate"=>"2015-10-05 23:15:21 +0000", - "ProfileItems"=> - [{"PayloadContent"=> - {"PayloadContentManagedPreferences"=> - {"com.apple.screensaver"=> - {"Forced"=>[{"mcx_preference_settings"=>{"idleTime"=>0}}]}}}, - "PayloadDisplayName"=>"Custom: (com.apple.screensaver)", - "PayloadIdentifier"=>"com.apple.screensaver", - "PayloadType"=>"com.apple.ManagedClient.preferences", - "PayloadUUID"=>"73fc30e0-1e57-0131-c32d-000c2944c110", - "PayloadVersion"=>1}], - "ProfileOrganization"=>"Chef", - "ProfileRemovalDisallowed"=>"false", - "ProfileType"=>"Configuration", - "ProfileUUID"=>"1781fbec-3325-565f-9022-8aa28135c3cc", - "ProfileVerificationState"=>"unsigned", - "ProfileVersion"=>1}] + { "_computerlevel" => [{ "ProfileDisplayName" => "ScreenSaver Settings", + "ProfileIdentifier" => "com.apple.screensaver", + "ProfileInstallDate" => "2015-10-05 23:15:21 +0000", + "ProfileItems" => [{ "PayloadContent" => { "PayloadContentManagedPreferences" => { "com.apple.screensaver" => { "Forced" => [{ "mcx_preference_settings" => { "idleTime" => 0 } }] } } }, + "PayloadDisplayName" => "Custom: (com.apple.screensaver)", + "PayloadIdentifier" => "com.apple.screensaver", + "PayloadType" => "com.apple.ManagedClient.preferences", + "PayloadUUID" => "73fc30e0-1e57-0131-c32d-000c2944c108", + "PayloadVersion" => 1 }], + "ProfileOrganization" => "Chef", + "ProfileRemovalDisallowed" => "false", + "ProfileType" => "Configuration", + "ProfileUUID" => "1781fbec-3325-565f-9022-8aa28135c3cc", + "ProfileVerificationState" => "unsigned", + "ProfileVersion" => 1 }, + { "ProfileDisplayName" => "ScreenSaver Settings", + "ProfileIdentifier" => "com.testprofile.screensaver", + "ProfileInstallDate" => "2015-10-05 23:15:21 +0000", + "ProfileItems" => [{ "PayloadContent" => { "PayloadContentManagedPreferences" => { "com.apple.screensaver" => { "Forced" => [{ "mcx_preference_settings" => { "idleTime" => 0 } }] } } }, + "PayloadDisplayName" => "Custom: (com.apple.screensaver)", + "PayloadIdentifier" => "com.apple.screensaver", + "PayloadType" => "com.apple.ManagedClient.preferences", + "PayloadUUID" => "73fc30e0-1e57-0131-c32d-000c2944c110", + "PayloadVersion" => 1 }], + "ProfileOrganization" => "Chef", + "ProfileRemovalDisallowed" => "false", + "ProfileType" => "Configuration", + "ProfileUUID" => "1781fbec-3325-565f-9022-8aa28135c3cc", + "ProfileVerificationState" => "unsigned", + "ProfileVersion" => 1 }] } end before(:each) do diff --git a/spec/unit/provider/package/aix_spec.rb b/spec/unit/provider/package/aix_spec.rb index b319d87929..8a8f1bab17 100644 --- a/spec/unit/provider/package/aix_spec.rb +++ b/spec/unit/provider/package/aix_spec.rb @@ -33,10 +33,10 @@ describe Chef::Provider::Package::Aix do describe "assessing the current package status" do before do - @bffinfo ="/usr/lib/objrepos:samba.base:3.3.12.0::COMMITTED:I:Samba for AIX: - /etc/objrepos:samba.base:3.3.12.0::COMMITTED:I:Samba for AIX:" + @bffinfo = "/usr/lib/objrepos:samba.base:3.3.12.0::COMMITTED:I:Samba for AIX: + /etc/objrepos:samba.base:3.3.12.0::COMMITTED:I:Samba for AIX:" - @empty_status = double("Status", :stdout => "", :exitstatus => 0) + @empty_status = double("Status", :stdout => "", :exitstatus => 0) end it "should create a current resource with the name of new_resource" do @@ -132,7 +132,6 @@ describe Chef::Provider::Package::Aix do allow(@provider).to receive(:shell_out).and_return(@status) expect { @provider.candidate_version }.to raise_error(Chef::Exceptions::Package) end - end describe "install and upgrade" do @@ -167,6 +166,5 @@ describe Chef::Provider::Package::Aix do expect(@provider).to receive(:shell_out!).with("installp -u -e/tmp/installp.log samba.base", timeout: 900) @provider.remove_package("samba.base", "3.3.12.0") end - end end diff --git a/spec/unit/provider/package/apt_spec.rb b/spec/unit/provider/package/apt_spec.rb index abf128d086..b67583bba7 100644 --- a/spec/unit/provider/package/apt_spec.rb +++ b/spec/unit/provider/package/apt_spec.rb @@ -24,7 +24,6 @@ describe Chef::Provider::Package::Apt do # let blocks and shared examples [ Chef::Resource::Package, Chef::Resource::AptPackage ].each do |resource_klass| describe "when the new_resource is a #{resource_klass}" do - before(:each) do @node = Chef::Node.new @events = Chef::EventDispatch::Dispatcher.new @@ -34,7 +33,7 @@ describe Chef::Provider::Package::Apt do @status = double("Status", :exitstatus => 0) @provider = Chef::Provider::Package::Apt.new(@new_resource, @run_context) @stdin = StringIO.new - @stdout =<<-PKG_STATUS + @stdout = <<-PKG_STATUS irssi: Installed: (none) Candidate: 0.8.14-1ubuntu4 @@ -43,12 +42,11 @@ irssi: 500 http://us.archive.ubuntu.com/ubuntu/ lucid/main Packages PKG_STATUS @stderr = "" - @shell_out = OpenStruct.new(:stdout => @stdout,:stdin => @stdin,:stderr => @stderr,:status => @status,:exitstatus => 0) + @shell_out = OpenStruct.new(:stdout => @stdout, :stdin => @stdin, :stderr => @stderr, :status => @status, :exitstatus => 0) @timeout = 900 end describe "when loading current resource" do - it "should create a current resource with the name of the new_resource" do expect(@provider).to receive(:shell_out!).with( "apt-cache policy #{@new_resource.package_name}", @@ -86,18 +84,18 @@ sudo: # list of virtual packages: http://www.debian.org/doc/packaging-manuals/virtual-package-names-list.txt it "should not install the virtual package there is a single provider package and it is installed" do @new_resource.package_name("libmysqlclient15-dev") - virtual_package_out=<<-VPKG_STDOUT + virtual_package_out = <<-VPKG_STDOUT libmysqlclient15-dev: Installed: (none) Candidate: (none) Version table: VPKG_STDOUT - virtual_package = double(:stdout => virtual_package_out,:exitstatus => 0) + virtual_package = double(:stdout => virtual_package_out, :exitstatus => 0) expect(@provider).to receive(:shell_out!).with( "apt-cache policy libmysqlclient15-dev", :timeout => @timeout, ).and_return(virtual_package) - showpkg_out =<<-SHOWPKG_STDOUT + showpkg_out = <<-SHOWPKG_STDOUT Package: libmysqlclient15-dev Versions: @@ -115,12 +113,12 @@ libmysqlclient-dev 5.1.41-3ubuntu12.7 libmysqlclient-dev 5.1.41-3ubuntu12.10 libmysqlclient-dev 5.1.41-3ubuntu12 SHOWPKG_STDOUT - showpkg = double(:stdout => showpkg_out,:exitstatus => 0) + showpkg = double(:stdout => showpkg_out, :exitstatus => 0) expect(@provider).to receive(:shell_out!).with( "apt-cache showpkg libmysqlclient15-dev", :timeout => @timeout, ).and_return(showpkg) - real_package_out=<<-RPKG_STDOUT + real_package_out = <<-RPKG_STDOUT libmysqlclient-dev: Installed: 5.1.41-3ubuntu12.10 Candidate: 5.1.41-3ubuntu12.10 @@ -133,7 +131,7 @@ libmysqlclient-dev: 5.1.41-3ubuntu12 0 500 http://us.archive.ubuntu.com/ubuntu/ lucid/main Packages RPKG_STDOUT - real_package = double(:stdout => real_package_out,:exitstatus => 0) + real_package = double(:stdout => real_package_out, :exitstatus => 0) expect(@provider).to receive(:shell_out!).with( "apt-cache policy libmysqlclient-dev", :timeout => @timeout, @@ -143,18 +141,18 @@ libmysqlclient-dev: it "should raise an exception if you specify a virtual package with multiple provider packages" do @new_resource.package_name("mp3-decoder") - virtual_package_out=<<-VPKG_STDOUT + virtual_package_out = <<-VPKG_STDOUT mp3-decoder: Installed: (none) Candidate: (none) Version table: VPKG_STDOUT - virtual_package = double(:stdout => virtual_package_out,:exitstatus => 0) + virtual_package = double(:stdout => virtual_package_out, :exitstatus => 0) expect(@provider).to receive(:shell_out!).with( "apt-cache policy mp3-decoder", :timeout => @timeout, ).and_return(virtual_package) - showpkg_out=<<-SHOWPKG_STDOUT + showpkg_out = <<-SHOWPKG_STDOUT Package: mp3-decoder Versions: @@ -175,7 +173,7 @@ opencubicplayer 1:0.1.17-2 mpg321 0.2.10.6 mpg123 1.12.1-0ubuntu1 SHOWPKG_STDOUT - showpkg = double(:stdout => showpkg_out,:exitstatus => 0) + showpkg = double(:stdout => showpkg_out, :exitstatus => 0) expect(@provider).to receive(:shell_out!).with( "apt-cache showpkg mp3-decoder", :timeout => @timeout, @@ -204,7 +202,7 @@ mpg123 1.12.1-0ubuntu1 ).and_return(@shell_out) @provider.load_current_resource @provider.define_resource_requirements - expect(@provider).to receive(:shell_out!).with("apt-cache policy irssi", {:timeout=>900}).and_return(@shell_out) + expect(@provider).to receive(:shell_out!).with("apt-cache policy irssi", { :timeout => 900 }).and_return(@shell_out) expect { @provider.run_action(:install) }.to raise_error(Chef::Exceptions::Package) end end @@ -219,7 +217,7 @@ mpg123 1.12.1-0ubuntu1 it "should run apt-get install with the package name and version" do expect(@provider).to receive(:shell_out!). with( "apt-get -q -y install irssi=0.8.12-7", - :env => { "DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil}, + :env => { "DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }, :timeout => @timeout, ) @provider.install_package("irssi", "0.8.12-7") @@ -228,7 +226,7 @@ mpg123 1.12.1-0ubuntu1 it "should run apt-get install with the package name and version and options if specified" do expect(@provider).to receive(:shell_out!).with( "apt-get -q -y --force-yes install irssi=0.8.12-7", - :env => {"DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }, + :env => { "DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }, :timeout => @timeout, ) @new_resource.options("--force-yes") @@ -244,7 +242,7 @@ mpg123 1.12.1-0ubuntu1 expect(@provider).to receive(:shell_out!).with( "apt-get -q -y -o APT::Default-Release=lenny-backports install irssi=0.8.12-7", - :env => {"DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }, + :env => { "DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }, :timeout => @timeout, ) @@ -253,7 +251,6 @@ mpg123 1.12.1-0ubuntu1 end describe resource_klass, "upgrade_package" do - it "should run install_package with the name and version" do expect(@provider).to receive(:install_package).with("irssi", "0.8.12-7") @provider.upgrade_package("irssi", "0.8.12-7") @@ -261,11 +258,10 @@ mpg123 1.12.1-0ubuntu1 end describe resource_klass, "remove_package" do - it "should run apt-get remove with the package name" do expect(@provider).to receive(:shell_out!).with( "apt-get -q -y remove irssi", - :env => {"DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil}, + :env => { "DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }, :timeout => @timeout, ) @provider.remove_package("irssi", "0.8.12-7") @@ -284,7 +280,6 @@ mpg123 1.12.1-0ubuntu1 end describe "when purging a package" do - it "should run apt-get purge with the package name" do expect(@provider).to receive(:shell_out!).with( "apt-get -q -y purge irssi", @@ -316,7 +311,7 @@ mpg123 1.12.1-0ubuntu1 expect(@provider).to receive(:shell_out!).with( "debconf-set-selections /tmp/irssi-0.8.12-7.seed", - :env => {"DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil}, + :env => { "DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }, :timeout => @timeout, ) @@ -326,7 +321,7 @@ mpg123 1.12.1-0ubuntu1 it "should run debconf-set-selections on the preseed file if it has changed" do expect(@provider).to receive(:shell_out!).with( "debconf-set-selections /tmp/irssi-0.8.12-7.seed", - :env => {"DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil}, + :env => { "DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }, :timeout => @timeout, ) file = @provider.get_preseed_file("irssi", "0.8.12-7") @@ -347,7 +342,7 @@ mpg123 1.12.1-0ubuntu1 it "should run dpkg-reconfigure package" do expect(@provider).to receive(:shell_out!).with( "dpkg-reconfigure irssi", - :env => {"DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }, + :env => { "DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }, :timeout => @timeout, ) @provider.reconfig_package("irssi", "0.8.12-7") @@ -359,7 +354,7 @@ mpg123 1.12.1-0ubuntu1 @provider.is_virtual_package["libmysqlclient-dev"] = true expect(@provider).to receive(:shell_out!).with( "apt-get -q -y install libmysqlclient-dev", - :env => {"DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }, + :env => { "DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }, :timeout => @timeout, ) @provider.install_package("libmysqlclient-dev", "not_a_real_version") @@ -373,13 +368,12 @@ mpg123 1.12.1-0ubuntu1 @provider.is_virtual_package["irssi"] = false expect(@provider).to receive(:shell_out!).with( "apt-get -q -y install libmysqlclient-dev irssi=0.8.12-7", - :env => {"DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }, + :env => { "DEBIAN_FRONTEND" => "noninteractive", "LC_ALL" => nil }, :timeout => @timeout, ) @provider.install_package(["libmysqlclient-dev", "irssi"], ["not_a_real_version", "0.8.12-7"]) end end - end end end diff --git a/spec/unit/provider/package/chocolatey_spec.rb b/spec/unit/provider/package/chocolatey_spec.rb index d550e55445..aeb420fa7a 100644 --- a/spec/unit/provider/package/chocolatey_spec.rb +++ b/spec/unit/provider/package/chocolatey_spec.rb @@ -45,7 +45,7 @@ ConEmu|15.10.25.0 allow(provider).to receive(:choco_install_path).and_return(choco_install_path) allow(provider).to receive(:choco_exe).and_return(choco_exe) local_list_obj = double(:stdout => local_list_stdout) - allow(provider).to receive(:shell_out!).with("#{choco_exe} list -l -r", {:timeout => timeout}).and_return(local_list_obj) + allow(provider).to receive(:shell_out!).with("#{choco_exe} list -l -r", { :timeout => timeout }).and_return(local_list_obj) end def allow_remote_list(package_names, args = nil) @@ -57,7 +57,7 @@ Git|2.6.2 munin-node|1.6.1.20130823 EOF remote_list_obj = double(stdout: remote_list_stdout) - allow(provider).to receive(:shell_out!).with("#{choco_exe} list -ar #{package_names.join ' '}#{args}", {timeout: timeout}).and_return(remote_list_obj) + allow(provider).to receive(:shell_out!).with("#{choco_exe} list -ar #{package_names.join ' '}#{args}", { timeout: timeout }).and_return(remote_list_obj) end describe "#initialize" do @@ -86,7 +86,7 @@ munin-node|1.6.1.20130823 allow_remote_list(["git"]) new_resource.version("2.5.0") expect(provider.candidate_version).to eql([nil]) - end + end it "should set the candidate_version to nil if there is no candidate" do allow_remote_list(["vim"]) @@ -132,7 +132,7 @@ munin-node|1.6.1.20130823 it "should load and downcase names in the installed_packages hash" do provider.load_current_resource expect(provider.send(:installed_packages)).to eql( - {"chocolatey"=>"0.9.9.11", "conemu"=>"15.10.25.0"} + { "chocolatey" => "0.9.9.11", "conemu" => "15.10.25.0" } ) end @@ -140,7 +140,7 @@ munin-node|1.6.1.20130823 allow_remote_list(["git"]) provider.load_current_resource expect(provider.send(:available_packages)).to eql( - {"chocolatey"=>"0.9.9.11", "conemu"=>"15.10.25.1", "git"=>"2.6.2", "munin-node" => "1.6.1.20130823"} + { "chocolatey" => "0.9.9.11", "conemu" => "15.10.25.1", "git" => "2.6.2", "munin-node" => "1.6.1.20130823" } ) end @@ -184,7 +184,7 @@ munin-node|1.6.1.20130823 it "should install a single package" do allow_remote_list(["git"]) provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y git", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y git", { :timeout => timeout }).and_return(double) provider.run_action(:install) expect(new_resource).to be_updated_by_last_action end @@ -195,7 +195,7 @@ munin-node|1.6.1.20130823 allow_remote_list(["git"]) new_resource.timeout(timeout) provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y git", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y git", { :timeout => timeout }).and_return(double) provider.run_action(:install) expect(new_resource).to be_updated_by_last_action end @@ -224,7 +224,7 @@ munin-node|1.6.1.20130823 new_resource.package_name("ConEmu") new_resource.version("15.10.25.1") provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y -version 15.10.25.1 conemu", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y -version 15.10.25.1 conemu", { :timeout => timeout }).and_return(double) provider.run_action(:install) expect(new_resource).to be_updated_by_last_action end @@ -237,7 +237,7 @@ munin-node|1.6.1.20130823 new_resource.package_name(["chocolatey", "ConEmu"]) new_resource.version([nil, "15.10.25.1"]) provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y -version 15.10.25.1 conemu", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y -version 15.10.25.1 conemu", { :timeout => timeout }).and_return(double) provider.run_action(:install) expect(new_resource).to be_updated_by_last_action end @@ -247,7 +247,7 @@ munin-node|1.6.1.20130823 new_resource.package_name("conemu") new_resource.version("15.10.25.1") provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y -version 15.10.25.1 conemu", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y -version 15.10.25.1 conemu", { :timeout => timeout }).and_return(double) provider.run_action(:install) expect(new_resource).to be_updated_by_last_action end @@ -257,8 +257,8 @@ munin-node|1.6.1.20130823 new_resource.package_name(["ConEmu", "git"]) new_resource.version(["15.10.25.1", nil]) provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y -version 15.10.25.1 conemu", {:timeout=>timeout}).and_return(double) - expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y git", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y -version 15.10.25.1 conemu", { :timeout => timeout }).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y git", { :timeout => timeout }).and_return(double) provider.run_action(:install) expect(new_resource).to be_updated_by_last_action end @@ -267,7 +267,7 @@ munin-node|1.6.1.20130823 allow_remote_list(["git", "munin-node"]) new_resource.package_name(["git", "munin-node"]) provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y git munin-node", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y git munin-node", { :timeout => timeout }).and_return(double) provider.run_action(:install) expect(new_resource).to be_updated_by_last_action end @@ -277,7 +277,7 @@ munin-node|1.6.1.20130823 allow_remote_list(["git"], " -source localpackages") new_resource.source("localpackages") provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y -source localpackages git", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y -source localpackages git", { :timeout => timeout }).and_return(double) provider.run_action(:install) expect(new_resource).to be_updated_by_last_action end @@ -287,7 +287,7 @@ munin-node|1.6.1.20130823 allow_remote_list(["git"]) new_resource.options("-force") provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y -force git", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y -force git", { :timeout => timeout }).and_return(double) provider.run_action(:install) expect(new_resource).to be_updated_by_last_action end @@ -329,7 +329,7 @@ munin-node|1.6.1.20130823 it "should install a package that is not installed" do allow_remote_list(["git"]) provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} upgrade -y git", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} upgrade -y git", { :timeout => timeout }).and_return(double) provider.run_action(:upgrade) expect(new_resource).to be_updated_by_last_action end @@ -338,7 +338,7 @@ munin-node|1.6.1.20130823 allow_remote_list(["ConEmu"]) new_resource.package_name("ConEmu") provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} upgrade -y conemu", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} upgrade -y conemu", { :timeout => timeout }).and_return(double) provider.run_action(:upgrade) expect(new_resource).to be_updated_by_last_action end @@ -347,7 +347,7 @@ munin-node|1.6.1.20130823 allow_remote_list(["conemu"]) new_resource.package_name("conemu") provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} upgrade -y conemu", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} upgrade -y conemu", { :timeout => timeout }).and_return(double) provider.run_action(:upgrade) expect(new_resource).to be_updated_by_last_action end @@ -356,7 +356,7 @@ munin-node|1.6.1.20130823 allow_remote_list(["chocolatey"]) new_resource.package_name("chocolatey") provider.load_current_resource - expect(provider).not_to receive(:shell_out!).with("#{choco_exe} upgrade -y chocolatey", {:timeout=>timeout}) + expect(provider).not_to receive(:shell_out!).with("#{choco_exe} upgrade -y chocolatey", { :timeout => timeout }) provider.run_action(:upgrade) expect(new_resource).not_to be_updated_by_last_action end @@ -365,7 +365,7 @@ munin-node|1.6.1.20130823 allow_remote_list(["git"]) new_resource.version("2.6.2") provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} upgrade -y -version 2.6.2 git", {:timeout=>timeout}) + expect(provider).to receive(:shell_out!).with("#{choco_exe} upgrade -y -version 2.6.2 git", { :timeout => timeout }) provider.run_action(:upgrade) expect(new_resource).to be_updated_by_last_action end @@ -373,7 +373,7 @@ munin-node|1.6.1.20130823 it "upgrading multiple packages uses a single command" do allow_remote_list(["conemu", "git"]) new_resource.package_name(["conemu", "git"]) - expect(provider).to receive(:shell_out!).with("#{choco_exe} upgrade -y conemu git", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} upgrade -y conemu git", { :timeout => timeout }).and_return(double) provider.run_action(:upgrade) expect(new_resource).to be_updated_by_last_action end @@ -425,7 +425,7 @@ munin-node|1.6.1.20130823 allow_remote_list(["ConEmu"]) new_resource.package_name("ConEmu") provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} uninstall -y ConEmu", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} uninstall -y ConEmu", { :timeout => timeout }).and_return(double) provider.run_action(:remove) expect(new_resource).to be_updated_by_last_action end @@ -434,7 +434,7 @@ munin-node|1.6.1.20130823 allow_remote_list(["conemu"]) new_resource.package_name("conemu") provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} uninstall -y conemu", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} uninstall -y conemu", { :timeout => timeout }).and_return(double) provider.run_action(:remove) expect(new_resource).to be_updated_by_last_action end @@ -444,7 +444,7 @@ munin-node|1.6.1.20130823 allow_remote_list(["git", "conemu"]) new_resource.package_name(["git", "conemu"]) provider.load_current_resource - expect(provider).to receive(:shell_out!).with("#{choco_exe} uninstall -y conemu", {:timeout=>timeout}).and_return(double) + expect(provider).to receive(:shell_out!).with("#{choco_exe} uninstall -y conemu", { :timeout => timeout }).and_return(double) provider.run_action(:remove) expect(new_resource).to be_updated_by_last_action end diff --git a/spec/unit/provider/package/dpkg_spec.rb b/spec/unit/provider/package/dpkg_spec.rb index a249f24793..f74f87ffb8 100644 --- a/spec/unit/provider/package/dpkg_spec.rb +++ b/spec/unit/provider/package/dpkg_spec.rb @@ -52,7 +52,7 @@ Conflicts: wget-ssl before(:each) do allow(provider).to receive(:shell_out!).with("dpkg-deb -W #{source}", timeout: 900).and_return(dpkg_deb_status) - allow(provider).to receive(:shell_out!).with("dpkg -s #{package}", timeout: 900, returns: [0,1]).and_return(double(stdout: "", exitstatus: 1)) + allow(provider).to receive(:shell_out!).with("dpkg -s #{package}", timeout: 900, returns: [0, 1]).and_return(double(stdout: "", exitstatus: 1)) allow(::File).to receive(:exist?).with(source).and_return(true) end @@ -104,7 +104,6 @@ Conflicts: wget-ssl end describe "when loading the current resource state" do - it "should create a current resource with the name of the new_resource" do provider.load_current_resource expect(provider.current_resource.package_name).to eq(["wget"]) @@ -160,12 +159,12 @@ Conflicts: wget-ssl let(:source) { nil } it "should raise an exception if the source is not set but we are installing" do - expect { provider.run_action(:install)}.to raise_error(Chef::Exceptions::Package) + expect { provider.run_action(:install) }.to raise_error(Chef::Exceptions::Package) end end it "should return the current version installed if found by dpkg" do - allow(provider).to receive(:shell_out!).with("dpkg -s #{package}", timeout: 900, returns: [0,1]).and_return(dpkg_s_status) + allow(provider).to receive(:shell_out!).with("dpkg -s #{package}", timeout: 900, returns: [0, 1]).and_return(dpkg_s_status) provider.load_current_resource expect(provider.current_resource.version).to eq(["1.11.4-1ubuntu1"]) end diff --git a/spec/unit/provider/package/easy_install_spec.rb b/spec/unit/provider/package/easy_install_spec.rb index 8ce485648b..ab64abcc5f 100644 --- a/spec/unit/provider/package/easy_install_spec.rb +++ b/spec/unit/provider/package/easy_install_spec.rb @@ -56,53 +56,51 @@ describe Chef::Provider::Package::EasyInstall do expect(@new_resource).to receive(:easy_install_binary).and_return("/opt/local/bin/custom/easy_install") expect(@provider.easy_install_binary_path).to eql("/opt/local/bin/custom/easy_install") end - end describe "actions_on_package" do it "should run easy_install with the package name and version" do expect(@provider).to receive(:run_command).with({ - :command => "easy_install \"boto==1.8d\"" - },) + :command => "easy_install \"boto==1.8d\"" + },) @provider.install_package("boto", "1.8d") end it "should run easy_install with the package name and version and specified options" do expect(@provider).to receive(:run_command).with({ - :command => "easy_install --always-unzip \"boto==1.8d\"" - },) + :command => "easy_install --always-unzip \"boto==1.8d\"" + },) allow(@new_resource).to receive(:options).and_return("--always-unzip") @provider.install_package("boto", "1.8d") end it "should run easy_install with the package name and version" do expect(@provider).to receive(:run_command).with({ - :command => "easy_install \"boto==1.8d\"" - },) + :command => "easy_install \"boto==1.8d\"" + },) @provider.upgrade_package("boto", "1.8d") end it "should run easy_install -m with the package name and version" do expect(@provider).to receive(:run_command).with({ - :command => "easy_install -m boto" - },) + :command => "easy_install -m boto" + },) @provider.remove_package("boto", "1.8d") end it "should run easy_install -m with the package name and version and specified options" do expect(@provider).to receive(:run_command).with({ - :command => "easy_install -x -m boto" - },) + :command => "easy_install -x -m boto" + },) allow(@new_resource).to receive(:options).and_return("-x") @provider.remove_package("boto", "1.8d") end it "should run easy_install -m with the package name and version" do expect(@provider).to receive(:run_command).with({ - :command => "easy_install -m boto" - },) + :command => "easy_install -m boto" + },) @provider.purge_package("boto", "1.8d") end - end end diff --git a/spec/unit/provider/package/freebsd/pkg_spec.rb b/spec/unit/provider/package/freebsd/pkg_spec.rb index 7c17177bec..43092050ed 100644 --- a/spec/unit/provider/package/freebsd/pkg_spec.rb +++ b/spec/unit/provider/package/freebsd/pkg_spec.rb @@ -77,7 +77,7 @@ describe Chef::Provider::Package::Freebsd::Pkg, "load_current_resource" do it "should return the version number when it is installed" do pkg_info = OpenStruct.new(:stdout => "zsh-4.3.6_7") - expect(@provider).to receive(:shell_out!).with('pkg_info -E "zsh*"', env: nil, returns: [0,1], timeout: 900).and_return(pkg_info) + expect(@provider).to receive(:shell_out!).with('pkg_info -E "zsh*"', env: nil, returns: [0, 1], timeout: 900).and_return(pkg_info) #@provider.should_receive(:popen4).with('pkg_info -E "zsh*"').and_yield(@pid, @stdin, ["zsh-4.3.6_7"], @stderr).and_return(@status) allow(@provider).to receive(:package_name).and_return("zsh") expect(@provider.current_installed_version).to eq("4.3.6_7") @@ -85,7 +85,7 @@ describe Chef::Provider::Package::Freebsd::Pkg, "load_current_resource" do it "does not set the current version number when the package is not installed" do pkg_info = OpenStruct.new(:stdout => "") - expect(@provider).to receive(:shell_out!).with('pkg_info -E "zsh*"', env: nil, returns: [0,1], timeout: 900).and_return(pkg_info) + expect(@provider).to receive(:shell_out!).with('pkg_info -E "zsh*"', env: nil, returns: [0, 1], timeout: 900).and_return(pkg_info) allow(@provider).to receive(:package_name).and_return("zsh") expect(@provider.current_installed_version).to be_nil end @@ -102,7 +102,7 @@ describe Chef::Provider::Package::Freebsd::Pkg, "load_current_resource" do it "should return the ports candidate version when given a valid port path" do allow(@provider).to receive(:port_path).and_return("/usr/ports/shells/zsh") make_v = OpenStruct.new(:stdout => "4.3.6\n", :exitstatus => 0) - expect(@provider).to receive(:shell_out!).with("make -V PORTVERSION", {cwd: "/usr/ports/shells/zsh", returns: [0, 1], env: nil, timeout: 900}).and_return(make_v) + expect(@provider).to receive(:shell_out!).with("make -V PORTVERSION", { cwd: "/usr/ports/shells/zsh", returns: [0, 1], env: nil, timeout: 900 }).and_return(make_v) expect(@provider.ports_candidate_version).to eq("4.3.6") end @@ -110,7 +110,7 @@ describe Chef::Provider::Package::Freebsd::Pkg, "load_current_resource" do allow(::File).to receive(:exist?).with("/usr/ports/Makefile").and_return(true) allow(@provider).to receive(:port_path).and_return("/usr/ports/shells/zsh") make_v = OpenStruct.new(:stdout => "zsh-4.3.6_7\n", :exitstatus => 0) - expect(@provider).to receive(:shell_out!).with("make -V PKGNAME", {cwd: "/usr/ports/shells/zsh", env: nil, returns: [0, 1], timeout: 900}).and_return(make_v) + expect(@provider).to receive(:shell_out!).with("make -V PKGNAME", { cwd: "/usr/ports/shells/zsh", env: nil, returns: [0, 1], timeout: 900 }).and_return(make_v) #@provider.should_receive(:ports_makefile_variable_value).with("PKGNAME").and_return("zsh-4.3.6_7") expect(@provider.package_name).to eq("zsh") end @@ -220,7 +220,7 @@ describe Chef::Provider::Package::Freebsd::Pkg, "load_current_resource" do it "should return the version number when it is installed" do pkg_info = OpenStruct.new(:stdout => "bonnie++-1.96") - expect(@provider).to receive(:shell_out!).with('pkg_info -E "bonnie++*"', env: nil, returns: [0,1], timeout: 900).and_return(pkg_info) + expect(@provider).to receive(:shell_out!).with('pkg_info -E "bonnie++*"', env: nil, returns: [0, 1], timeout: 900).and_return(pkg_info) allow(@provider).to receive(:package_name).and_return("bonnie++") expect(@provider.current_installed_version).to eq("1.96") end @@ -258,7 +258,6 @@ describe Chef::Provider::Package::Freebsd::Pkg, "load_current_resource" do end it "should install the mysql50-server binary package with the correct name" do - @new_resource = Chef::Resource::Package.new("mysql50-server") @current_resource = Chef::Resource::Package.new("mysql50-server") @provider = Chef::Provider::Package::Freebsd::Pkg.new(@new_resource, @run_context) diff --git a/spec/unit/provider/package/freebsd/pkgng_spec.rb b/spec/unit/provider/package/freebsd/pkgng_spec.rb index d89bf24eb8..a2bd833d9e 100644 --- a/spec/unit/provider/package/freebsd/pkgng_spec.rb +++ b/spec/unit/provider/package/freebsd/pkgng_spec.rb @@ -16,7 +16,6 @@ # limitations under the License. # - require "spec_helper" require "ostruct" @@ -30,7 +29,6 @@ describe Chef::Provider::Package::Freebsd::Port do @provider = Chef::Provider::Package::Freebsd::Pkgng.new(@new_resource, @run_context) end - describe "initialization" do it "should create a current resource with the name of the new resource" do expect(@provider.current_resource.is_a?(Chef::Resource::Package)).to be_truthy @@ -38,7 +36,6 @@ describe Chef::Provider::Package::Freebsd::Port do end end - describe "loading current resource" do before(:each) do allow(@provider).to receive(:current_installed_version) @@ -63,7 +60,6 @@ describe Chef::Provider::Package::Freebsd::Port do end end - describe "determining current installed version" do before(:each) do allow(@provider).to receive(:supports_pkgng?) @@ -71,12 +67,11 @@ describe Chef::Provider::Package::Freebsd::Port do end it "should query pkg database" do - expect(@provider).to receive(:shell_out!).with('pkg info "zsh"', env: nil, returns: [0,70], timeout: 900).and_return(@pkg_info) + expect(@provider).to receive(:shell_out!).with('pkg info "zsh"', env: nil, returns: [0, 70], timeout: 900).and_return(@pkg_info) expect(@provider.current_installed_version).to eq("3.1.7") end end - describe "determining candidate version" do it "should query repository" do pkg_query = OpenStruct.new(:stdout => "5.0.5\n", :exitstatus => 0) @@ -97,7 +92,6 @@ describe Chef::Provider::Package::Freebsd::Port do end end - describe "installing a binary package" do before(:each) do @install_result = OpenStruct.new(:status => true) @@ -133,7 +127,6 @@ describe Chef::Provider::Package::Freebsd::Port do end end - describe "removing a binary package" do before(:each) do @install_result = OpenStruct.new(:status => true) diff --git a/spec/unit/provider/package/freebsd/port_spec.rb b/spec/unit/provider/package/freebsd/port_spec.rb index b12d4eb063..b593da4ff1 100644 --- a/spec/unit/provider/package/freebsd/port_spec.rb +++ b/spec/unit/provider/package/freebsd/port_spec.rb @@ -16,7 +16,6 @@ # limitations under the License. # - require "spec_helper" require "ostruct" @@ -30,7 +29,6 @@ describe Chef::Provider::Package::Freebsd::Port do @provider = Chef::Provider::Package::Freebsd::Port.new(@new_resource, @run_context) end - describe "initialization" do it "should create a current resource with the name of the new resource" do expect(@provider.current_resource.is_a?(Chef::Resource::Package)).to be_truthy @@ -38,7 +36,6 @@ describe Chef::Provider::Package::Freebsd::Port do end end - describe "loading current resource" do before(:each) do allow(@provider).to receive(:current_installed_version) @@ -63,7 +60,6 @@ describe Chef::Provider::Package::Freebsd::Port do end end - describe "determining current installed version" do before(:each) do @pkg_info = OpenStruct.new(:stdout => "zsh-3.1.7\n") @@ -72,7 +68,7 @@ describe Chef::Provider::Package::Freebsd::Port do it "should check 'pkg_info' if system uses pkg_* tools" do allow(@new_resource).to receive(:supports_pkgng?) expect(@new_resource).to receive(:supports_pkgng?).and_return(false) - expect(@provider).to receive(:shell_out!).with('pkg_info -E "zsh*"', env: nil, returns: [0,1], timeout: 900).and_return(@pkg_info) + expect(@provider).to receive(:shell_out!).with('pkg_info -E "zsh*"', env: nil, returns: [0, 1], timeout: 900).and_return(@pkg_info) expect(@provider.current_installed_version).to eq("3.1.7") end @@ -81,7 +77,7 @@ describe Chef::Provider::Package::Freebsd::Port do [1000016, 1000000, 901503, 902506, 802511].each do |__freebsd_version| @node.automatic_attrs[:os_version] = __freebsd_version expect(@new_resource).to receive(:shell_out!).with("make -V WITH_PKGNG", env: nil).and_return(pkg_enabled) - expect(@provider).to receive(:shell_out!).with('pkg info "zsh"', env: nil, returns: [0,70], timeout: 900).and_return(@pkg_info) + expect(@provider).to receive(:shell_out!).with('pkg info "zsh"', env: nil, returns: [0, 70], timeout: 900).and_return(@pkg_info) expect(@provider.current_installed_version).to eq("3.1.7") end end @@ -89,7 +85,7 @@ describe Chef::Provider::Package::Freebsd::Port do it "should check 'pkg info' if the freebsd version is greater than or equal to 1000017" do __freebsd_version = 1000017 @node.automatic_attrs[:os_version] = __freebsd_version - expect(@provider).to receive(:shell_out!).with('pkg info "zsh"', env: nil, returns: [0,70], timeout: 900).and_return(@pkg_info) + expect(@provider).to receive(:shell_out!).with('pkg info "zsh"', env: nil, returns: [0, 70], timeout: 900).and_return(@pkg_info) expect(@provider.current_installed_version).to eq("3.1.7") end end @@ -102,7 +98,7 @@ describe Chef::Provider::Package::Freebsd::Port do it "should return candidate version if port exists" do allow(::File).to receive(:exist?).with("/usr/ports/Makefile").and_return(true) allow(@provider).to receive(:port_dir).and_return("/usr/ports/shells/zsh") - expect(@provider).to receive(:shell_out!).with("make -V PORTVERSION", cwd: "/usr/ports/shells/zsh", env: nil, returns: [0,1], timeout: 900). + expect(@provider).to receive(:shell_out!).with("make -V PORTVERSION", cwd: "/usr/ports/shells/zsh", env: nil, returns: [0, 1], timeout: 900). and_return(@port_version) expect(@provider.candidate_version).to eq("5.0.5") end @@ -113,7 +109,6 @@ describe Chef::Provider::Package::Freebsd::Port do end end - describe "determining port directory" do it "should return name if package name is absolute path" do allow(@provider.new_resource).to receive(:package_name).and_return("/var/ports/shells/zsh") @@ -138,7 +133,6 @@ describe Chef::Provider::Package::Freebsd::Port do end end - describe "building a binary package" do before(:each) do @install_result = OpenStruct.new(:status => true) @@ -153,7 +147,6 @@ describe Chef::Provider::Package::Freebsd::Port do end end - describe "removing a binary package" do before(:each) do @install_result = OpenStruct.new(:status => true) diff --git a/spec/unit/provider/package/homebrew_spec.rb b/spec/unit/provider/package/homebrew_spec.rb index ab842eea60..6a171278b6 100644 --- a/spec/unit/provider/package/homebrew_spec.rb +++ b/spec/unit/provider/package/homebrew_spec.rb @@ -22,7 +22,7 @@ describe Chef::Provider::Package::Homebrew do let(:events) { double("Chef::Events").as_null_object } let(:run_context) { double("Chef::RunContext", node: node, events: events) } let(:new_resource) { Chef::Resource::HomebrewPackage.new("emacs") } - let(:current_resource) { Chef::Resource::HomebrewPackage.new("emacs")} + let(:current_resource) { Chef::Resource::HomebrewPackage.new("emacs") } let(:provider) do Chef::Provider::Package::Homebrew.new(new_resource, run_context) @@ -115,7 +115,6 @@ describe Chef::Provider::Package::Homebrew do end before(:each) do - end describe "load_current_resource" do diff --git a/spec/unit/provider/package/ips_spec.rb b/spec/unit/provider/package/ips_spec.rb index 732e42a7bc..f47385da09 100644 --- a/spec/unit/provider/package/ips_spec.rb +++ b/spec/unit/provider/package/ips_spec.rb @@ -35,17 +35,16 @@ describe Chef::Provider::Package::Ips do def local_output stdin = StringIO.new stdout = "" - stderr =<<-PKG_STATUS + stderr = <<-PKG_STATUS pkg: info: no packages matching the following patterns you specified are installed on the system. Try specifying -r to query remotely: crypto/gnupg PKG_STATUS - return OpenStruct.new(:stdout => stdout,:stdin => stdin,:stderr => stderr,:status => @status,:exitstatus => 1) + return OpenStruct.new(:stdout => stdout, :stdin => stdin, :stderr => stderr, :status => @status, :exitstatus => 1) end def remote_output - stdout = <<-PKG_STATUS Name: security/sudo Summary: sudo - authority delegation tool @@ -58,9 +57,9 @@ Packaging Date: April 1, 2012 05:55:52 PM Size: 2.57 MB FMRI: pkg://omnios/security/sudo@1.8.4.1,5.11-0.151002:20120401T175552Z PKG_STATUS - stdin = StringIO.new - stderr = "" - return OpenStruct.new(:stdout => stdout,:stdin => stdin,:stderr => stderr,:status => @status,:exitstatus => 0) + stdin = StringIO.new + stderr = "" + return OpenStruct.new(:stdout => stdout, :stdin => stdin, :stderr => stderr, :status => @status, :exitstatus => 0) end context "when loading current resource" do diff --git a/spec/unit/provider/package/macports_spec.rb b/spec/unit/provider/package/macports_spec.rb index ff9e669aa8..b90cf89047 100644 --- a/spec/unit/provider/package/macports_spec.rb +++ b/spec/unit/provider/package/macports_spec.rb @@ -70,7 +70,7 @@ describe Chef::Provider::Package::Macports do describe "current_installed_version" do it "should return the current version if the package is installed" do - stdout = < "OpenBSD", "release" => "5.5", "machine" => "amd64"} + node.default["kernel"] = { "name" => "OpenBSD", "release" => "5.5", "machine" => "amd64" } node end @@ -33,7 +32,7 @@ describe Chef::Provider::Package::Openbsd do Chef::Provider::Package::Openbsd.new(new_resource, run_context) end - let(:new_resource) { Chef::Resource::Package.new(name)} + let(:new_resource) { Chef::Resource::Package.new(name) } before(:each) do ENV["PKG_PATH"] = nil @@ -41,7 +40,7 @@ describe Chef::Provider::Package::Openbsd do describe "install a package" do let(:name) { "ihavetoes" } - let(:version) {"0.0"} + let(:version) { "0.0" } context "when not already installed" do before do @@ -49,15 +48,14 @@ describe Chef::Provider::Package::Openbsd do end context "when there is a single candidate" do - context "when source is not provided" do it "should run the installation command" do expect(provider).to receive(:shell_out!).with("pkg_info -I \"#{name}\"", anything()).and_return( instance_double("shellout", :stdout => "#{name}-#{version}\n")) expect(provider).to receive(:shell_out!).with( "pkg_add -r #{name}-#{version}", - {:env => {"PKG_PATH" => "http://ftp.OpenBSD.org/pub/OpenBSD/5.5/packages/amd64/"}, timeout: 900} - ) {OpenStruct.new :status => true} + { :env => { "PKG_PATH" => "http://ftp.OpenBSD.org/pub/OpenBSD/5.5/packages/amd64/" }, timeout: 900 } + ) { OpenStruct.new :status => true } provider.run_action(:install) end end @@ -76,9 +74,8 @@ describe Chef::Provider::Package::Openbsd do end context "if a flavor is specified" do - let(:flavor) { "flavora" } - let(:package_name) {"ihavetoes" } + let(:package_name) { "ihavetoes" } let(:name) { "#{package_name}--#{flavor}" } context "if no version is specified" do @@ -88,12 +85,11 @@ describe Chef::Provider::Package::Openbsd do instance_double("shellout", :stdout => "#{name}-#{version}-#{flavor}\n")) expect(provider).to receive(:shell_out!).with( "pkg_add -r #{name}-#{version}-#{flavor}", - {env: {"PKG_PATH" => "http://ftp.OpenBSD.org/pub/OpenBSD/5.5/packages/amd64/"}, timeout: 900} - ) {OpenStruct.new :status => true} + { env: { "PKG_PATH" => "http://ftp.OpenBSD.org/pub/OpenBSD/5.5/packages/amd64/" }, timeout: 900 } + ) { OpenStruct.new :status => true } provider.run_action(:install) end end - end context "if a version is specified" do @@ -104,8 +100,8 @@ describe Chef::Provider::Package::Openbsd do new_resource.version("#{version}-#{flavor_b}") expect(provider).to receive(:shell_out!).with( "pkg_add -r #{name}-#{version}-#{flavor_b}", - {env: {"PKG_PATH" => "http://ftp.OpenBSD.org/pub/OpenBSD/5.5/packages/amd64/"}, timeout: 900} - ) {OpenStruct.new :status => true} + { env: { "PKG_PATH" => "http://ftp.OpenBSD.org/pub/OpenBSD/5.5/packages/amd64/" }, timeout: 900 } + ) { OpenStruct.new :status => true } provider.run_action(:install) end end @@ -124,9 +120,8 @@ describe Chef::Provider::Package::Openbsd do it "should run the command to delete the installed package" do expect(@provider).to receive(:shell_out!).with( "pkg_delete #{@name}", env: nil, timeout: 900 - ) {OpenStruct.new :status => true} + ) { OpenStruct.new :status => true } @provider.remove_package(@name, nil) end end - end diff --git a/spec/unit/provider/package/pacman_spec.rb b/spec/unit/provider/package/pacman_spec.rb index 4d3339767c..38bc25acf2 100644 --- a/spec/unit/provider/package/pacman_spec.rb +++ b/spec/unit/provider/package/pacman_spec.rb @@ -51,7 +51,7 @@ ERR end it "should run pacman query with the package name" do - expect(@provider).to receive(:shell_out).with("pacman -Qi #{@new_resource.package_name}", {timeout: 900}).and_return(@status) + expect(@provider).to receive(:shell_out).with("pacman -Qi #{@new_resource.package_name}", { timeout: 900 }).and_return(@status) @provider.load_current_resource end @@ -102,7 +102,7 @@ PACMAN end it "should use pacman.conf to determine valid repo names for package versions" do - @pacman_conf = <<-PACMAN_CONF + @pacman_conf = <<-PACMAN_CONF [options] HoldPkg = pacman glibc Architecture = auto @@ -151,12 +151,12 @@ PACMAN_CONF describe Chef::Provider::Package::Pacman, "install_package" do it "should run pacman install with the package name and version" do - expect(@provider).to receive(:shell_out!).with("pacman --sync --noconfirm --noprogressbar nano", {timeout: 900}) + expect(@provider).to receive(:shell_out!).with("pacman --sync --noconfirm --noprogressbar nano", { timeout: 900 }) @provider.install_package("nano", "1.0") end it "should run pacman install with the package name and version and options if specified" do - expect(@provider).to receive(:shell_out!).with("pacman --sync --noconfirm --noprogressbar --debug nano", {timeout: 900}) + expect(@provider).to receive(:shell_out!).with("pacman --sync --noconfirm --noprogressbar --debug nano", { timeout: 900 }) allow(@new_resource).to receive(:options).and_return("--debug") @provider.install_package("nano", "1.0") @@ -172,12 +172,12 @@ PACMAN_CONF describe Chef::Provider::Package::Pacman, "remove_package" do it "should run pacman remove with the package name" do - expect(@provider).to receive(:shell_out!).with("pacman --remove --noconfirm --noprogressbar nano", {timeout: 900}) + expect(@provider).to receive(:shell_out!).with("pacman --remove --noconfirm --noprogressbar nano", { timeout: 900 }) @provider.remove_package("nano", "1.0") end it "should run pacman remove with the package name and options if specified" do - expect(@provider).to receive(:shell_out!).with("pacman --remove --noconfirm --noprogressbar --debug nano", {timeout: 900}) + expect(@provider).to receive(:shell_out!).with("pacman --remove --noconfirm --noprogressbar --debug nano", { timeout: 900 }) allow(@new_resource).to receive(:options).and_return("--debug") @provider.remove_package("nano", "1.0") @@ -189,6 +189,5 @@ PACMAN_CONF expect(@provider).to receive(:remove_package).with("nano", "1.0") @provider.purge_package("nano", "1.0") end - end end diff --git a/spec/unit/provider/package/paludis_spec.rb b/spec/unit/provider/package/paludis_spec.rb index 8ca6a881e1..8641a7cf5c 100644 --- a/spec/unit/provider/package/paludis_spec.rb +++ b/spec/unit/provider/package/paludis_spec.rb @@ -33,7 +33,7 @@ describe Chef::Provider::Package::Paludis do @stdin = StringIO.new @stderr = StringIO.new - @stdout =<<-PKG_STATUS + @stdout = <<-PKG_STATUS group/ntp 0 accounts group/ntp 0 installed-accounts net/ntp 4.2.6_p5-r2 arbor @@ -42,7 +42,7 @@ user/ntp 0 installed-accounts net/ntp 4.2.6_p5-r1 installed PKG_STATUS @pid = 12345 - @shell_out = OpenStruct.new(:stdout => @stdout,:stdin => @stdin,:stderr => @stderr,:status => @status,:exitstatus => 0) + @shell_out = OpenStruct.new(:stdout => @stdout, :stdin => @stdin, :stderr => @stderr, :status => @status, :exitstatus => 0) end context "when loading current resource" do @@ -86,13 +86,12 @@ INSTALLED context "when installing a package" do it "should run pkg install with the package name and version" do - expect(@provider).to receive(:shell_out!).with("cave -L warning resolve -x \"=net/ntp-4.2.6_p5-r2\"", {:timeout=>@new_resource.timeout}) + expect(@provider).to receive(:shell_out!).with("cave -L warning resolve -x \"=net/ntp-4.2.6_p5-r2\"", { :timeout => @new_resource.timeout }) @provider.install_package("net/ntp", "4.2.6_p5-r2") end - it "should run pkg install with the package name and version and options if specified" do - expect(@provider).to receive(:shell_out!).with("cave -L warning resolve -x --preserve-world \"=net/ntp-4.2.6_p5-r2\"", {:timeout=>@new_resource.timeout}) + expect(@provider).to receive(:shell_out!).with("cave -L warning resolve -x --preserve-world \"=net/ntp-4.2.6_p5-r2\"", { :timeout => @new_resource.timeout }) allow(@new_resource).to receive(:options).and_return("--preserve-world") @provider.install_package("net/ntp", "4.2.6_p5-r2") end @@ -102,7 +101,7 @@ INSTALLED sys-process/lsof 4.87 arbor sys-process/lsof 4.87 x86_64 PKG_STATUS - expect(@provider).to receive(:shell_out!).with("cave -L warning resolve -x \"=sys-process/lsof-4.87\"", {:timeout=>@new_resource.timeout}) + expect(@provider).to receive(:shell_out!).with("cave -L warning resolve -x \"=sys-process/lsof-4.87\"", { :timeout => @new_resource.timeout }) @provider.install_package("sys-process/lsof", "4.87") end @@ -120,7 +119,7 @@ PKG_STATUS context "when upgrading a package" do it "should run pkg install with the package name and version" do - expect(@provider).to receive(:shell_out!).with("cave -L warning resolve -x \"=net/ntp-4.2.6_p5-r2\"", {:timeout=>@new_resource.timeout}) + expect(@provider).to receive(:shell_out!).with("cave -L warning resolve -x \"=net/ntp-4.2.6_p5-r2\"", { :timeout => @new_resource.timeout }) @provider.upgrade_package("net/ntp", "4.2.6_p5-r2") end end @@ -130,6 +129,5 @@ PKG_STATUS expect(@provider).to receive(:shell_out!).with("cave -L warning uninstall -x \"=net/ntp-4.2.6_p5-r2\"") @provider.remove_package("net/ntp", "4.2.6_p5-r2") end - end end diff --git a/spec/unit/provider/package/portage_spec.rb b/spec/unit/provider/package/portage_spec.rb index c2ff1cc952..3509d6545a 100644 --- a/spec/unit/provider/package/portage_spec.rb +++ b/spec/unit/provider/package/portage_spec.rb @@ -31,7 +31,6 @@ describe Chef::Provider::Package::Portage, "load_current_resource" do end describe "when determining the current state of the package" do - it "should create a current resource with the name of new_resource" do allow(::Dir).to receive(:[]).with("/var/db/pkg/dev-util/git-*").and_return(["/var/db/pkg/dev-util/git-1.0.0"]) expect(Chef::Resource::Package).to receive(:new).and_return(@current_resource) @@ -98,7 +97,6 @@ describe Chef::Provider::Package::Portage, "load_current_resource" do end describe "once the state of the package is known" do - describe Chef::Provider::Package::Portage, "candidate_version" do it "should return the candidate_version variable if already set" do @provider.candidate_version = "1.0.0" diff --git a/spec/unit/provider/package/rpm_spec.rb b/spec/unit/provider/package/rpm_spec.rb index 2f2c44a5d5..b70002f655 100644 --- a/spec/unit/provider/package/rpm_spec.rb +++ b/spec/unit/provider/package/rpm_spec.rb @@ -49,7 +49,6 @@ describe Chef::Provider::Package::Rpm do end describe "when the package source is not valid" do - context "when source is not defiend" do let(:new_resource) { Chef::Resource::Package.new("ImageMagick-c++") } @@ -59,7 +58,6 @@ describe Chef::Provider::Package::Rpm do end context "when the source is a file that doesn't exist" do - it "should raise an exception when attempting any action" do allow(::File).to receive(:exists?).with(package_source).and_return(false) expect { provider.run_action(:any) }.to raise_error(Chef::Exceptions::Package) @@ -67,7 +65,6 @@ describe Chef::Provider::Package::Rpm do end context "when the source is an unsupported URI scheme" do - let(:package_source) { "foobar://example.com/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm" } it "should raise an exception if an uri formed source is non-supported scheme" do @@ -79,11 +76,9 @@ describe Chef::Provider::Package::Rpm do expect { provider.run_action(:any) }.to raise_error(Chef::Exceptions::Package) end end - end describe "when the package source is valid" do - before do expect(provider).to receive(:shell_out!). with("rpm -qp --queryformat '%{NAME} %{VERSION}-%{RELEASE}\n' #{package_source}", timeout: 900). @@ -95,7 +90,6 @@ describe Chef::Provider::Package::Rpm do end context "when rpm fails when querying package installed state" do - before do allow(::File).to receive(:exists?).with(package_source).and_return(true) end @@ -116,9 +110,7 @@ describe Chef::Provider::Package::Rpm do end end - context "when the package is installed" do - let(:rpm_qp_stdout) { "ImageMagick-c++ 6.5.4.7-7.el6_5" } let(:rpm_q_stdout) { "ImageMagick-c++ 6.5.4.7-7.el6_5" } @@ -128,7 +120,6 @@ describe Chef::Provider::Package::Rpm do let(:action) { :install } context "when the source is a file system path" do - before do allow(::File).to receive(:exists?).with(package_source).and_return(true) @@ -149,7 +140,6 @@ describe Chef::Provider::Package::Rpm do end describe "action install" do - context "when at the desired version already" do it "does nothing when the correct version is installed" do expect(provider).to_not receive(:shell_out!).with("rpm -i /tmp/imagemagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900) @@ -159,7 +149,6 @@ describe Chef::Provider::Package::Rpm do end context "when a newer version is desired" do - let(:rpm_q_stdout) { "imagemagick-c++ 0.5.4.7-7.el6_5" } it "runs rpm -u with the package source to upgrade" do @@ -182,13 +171,10 @@ describe Chef::Provider::Package::Rpm do expect(provider).to receive(:shell_out!).with("rpm -U --oldpackage /tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900) provider.action_install end - end - end describe "action upgrade" do - let(:action) { :upgrade } context "when at the desired version already" do @@ -200,7 +186,6 @@ describe Chef::Provider::Package::Rpm do end context "when a newer version is desired" do - let(:rpm_q_stdout) { "imagemagick-c++ 0.5.4.7-7.el6_5" } it "runs rpm -u with the package source to upgrade" do @@ -223,12 +208,10 @@ describe Chef::Provider::Package::Rpm do expect(provider).to receive(:shell_out!).with("rpm -U --oldpackage /tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900) provider.action_upgrade end - end end describe "action :remove" do - let(:action) { :remove } it "should remove the package" do @@ -237,9 +220,7 @@ describe Chef::Provider::Package::Rpm do end end - context "when the package name contains a tilde (chef#3503)" do - let(:package_name) { "supermarket" } let(:package_source) { "/tmp/supermarket-1.10.1~alpha.0-1.el5.x86_64.rpm" } @@ -257,7 +238,6 @@ describe Chef::Provider::Package::Rpm do end context "when the package name contains a plus symbol (chef#3671)" do - let(:package_name) { "chef-server-core" } let(:package_source) { "/tmp/chef-server-core-12.2.0+20150713220422-1.el6.x86_64.rpm" } @@ -273,7 +253,6 @@ describe Chef::Provider::Package::Rpm do expect(provider.new_resource.version).to eq("12.2.0+20150713220422-1.el6") end end - end context "when the source is given as an URI" do @@ -288,9 +267,7 @@ describe Chef::Provider::Package::Rpm do end %w{http HTTP https HTTPS ftp FTP file FILE}.each do |scheme| - context "when the source URI uses protocol scheme '#{scheme}'" do - let(:package_source) { "#{scheme}://example.com/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm" } it "should get the source package version from rpm if provided" do @@ -301,16 +278,12 @@ describe Chef::Provider::Package::Rpm do it "should return the current version installed if found by rpm" do expect(provider.current_resource.version).to eq("6.5.4.7-7.el6_5") end - end end - end - end context "when the package is not installed" do - let(:package_name) { "openssh-askpass" } let(:package_source) { "/tmp/openssh-askpass-1.2.3-4.el6_5.x86_64.rpm" } @@ -338,7 +311,6 @@ describe Chef::Provider::Package::Rpm do end context "when the package name contains a tilde (chef#3503)" do - let(:package_name) { "supermarket" } let(:package_source) { "/tmp/supermarket-1.10.1~alpha.0-1.el5.x86_64.rpm" } @@ -355,9 +327,7 @@ describe Chef::Provider::Package::Rpm do end describe "managing the package" do - describe "action install" do - it "installs the package" do expect(provider).to receive(:shell_out!).with("rpm -i #{package_source}", timeout: 900) @@ -374,7 +344,6 @@ describe Chef::Provider::Package::Rpm do end describe "action upgrade" do - let(:action) { :upgrade } it "installs the package" do @@ -385,7 +354,6 @@ describe Chef::Provider::Package::Rpm do end describe "when removing the package" do - let(:action) { :remove } it "should do nothing" do @@ -393,15 +361,11 @@ describe Chef::Provider::Package::Rpm do provider.action_remove end end - end - - end end context "when the resource name is the path to the package" do - let(:new_resource) do # When we pass a source in as the name, then #initialize in the # provider will call File.exists?. Because of the ordering in our @@ -428,6 +392,4 @@ describe Chef::Provider::Package::Rpm do provider.upgrade_package("/tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", "6.5.4.7-7.el6_5") end end - - end diff --git a/spec/unit/provider/package/rubygems_spec.rb b/spec/unit/provider/package/rubygems_spec.rb index 4ae0e22fba..5bedbdb293 100644 --- a/spec/unit/provider/package/rubygems_spec.rb +++ b/spec/unit/provider/package/rubygems_spec.rb @@ -161,7 +161,6 @@ describe Chef::Provider::Package::Rubygems::CurrentGemEnvironment do expect(@gem_env).to receive(:uninstaller).with("rspec", :version => "1.2.3").and_return(uninstaller) @gem_env.uninstall("rspec", "1.2.3") end - end describe Chef::Provider::Package::Rubygems::AlternateGemEnvironment do @@ -192,7 +191,7 @@ describe Chef::Provider::Package::Rubygems::AlternateGemEnvironment do it "uses the cached result for gem paths when available" do expect(@gem_env).not_to receive(:shell_out!) expected = ["/path/to/gems", "/another/path/to/gems"] - Chef::Provider::Package::Rubygems::AlternateGemEnvironment.gempath_cache["/usr/weird/bin/gem"]= expected + Chef::Provider::Package::Rubygems::AlternateGemEnvironment.gempath_cache["/usr/weird/bin/gem"] = expected expect(@gem_env.gem_paths).to eq(["/path/to/gems", "/another/path/to/gems"]) end @@ -235,7 +234,7 @@ describe Chef::Provider::Package::Rubygems::AlternateGemEnvironment do end it "detects when the target gem environment is the jruby platform" do - gem_env_out=<<-JRUBY_GEM_ENV + gem_env_out = <<-JRUBY_GEM_ENV RubyGems Environment: - RUBYGEMS VERSION: 1.3.6 - RUBY VERSION: 1.8.7 (2010-05-12 patchlevel 249) [java] @@ -272,12 +271,12 @@ RubyGems Environment: it "uses the cached result for gem platforms if available" do expect(@gem_env).not_to receive(:shell_out!) expected = ["ruby", Gem::Platform.new("universal-java-1.6")] - Chef::Provider::Package::Rubygems::AlternateGemEnvironment.platform_cache["/usr/weird/bin/gem"]= expected + Chef::Provider::Package::Rubygems::AlternateGemEnvironment.platform_cache["/usr/weird/bin/gem"] = expected expect(@gem_env.gem_platforms).to eq(expected) end it "uses the current gem platforms when the target env is not jruby" do - gem_env_out=<<-RBX_GEM_ENV + gem_env_out = <<-RBX_GEM_ENV RubyGems Environment: - RUBYGEMS VERSION: 1.3.6 - RUBY VERSION: 1.8.7 (2010-05-14 patchlevel 174) [x86_64-apple-darwin10.3.0] @@ -322,7 +321,6 @@ RubyGems Environment: expect(platforms_in_block).to eq(["ruby", Gem::Platform.new("sparc64-java-1.7")]) expect(Gem.platforms).to eq(original_platforms) end - end describe Chef::Provider::Package::Rubygems do @@ -416,7 +414,7 @@ describe Chef::Provider::Package::Rubygems do it "smites you when you try to use a hash of install options with an explicit gem binary" do @new_resource.gem_binary("/foo/bar") @new_resource.options(:fail => :burger) - expect {Chef::Provider::Package::Rubygems.new(@new_resource, @run_context)}.to raise_error(ArgumentError) + expect { Chef::Provider::Package::Rubygems.new(@new_resource, @run_context) }.to raise_error(ArgumentError) end it "converts the new resource into a gem dependency" do @@ -426,7 +424,6 @@ describe Chef::Provider::Package::Rubygems do end describe "when determining the currently installed version" do - it "sets the current version to the version specified by the new resource if that version is installed" do @provider.load_current_resource expect(@provider.current_resource.version).to eq(@spec_version) @@ -443,11 +440,9 @@ describe Chef::Provider::Package::Rubygems do @provider.load_current_resource expect(@provider.current_resource.version).to be_nil end - end describe "when determining the candidate version to install" do - it "does not query for available versions when the current version is the target version" do @provider.current_resource = @new_resource.dup expect(@provider.candidate_version).to be_nil @@ -471,7 +466,6 @@ describe Chef::Provider::Package::Rubygems do @provider.load_current_resource expect(@provider.candidate_version).to eq("0.1.0") end - end describe "when installing a gem" do @@ -525,7 +519,7 @@ describe Chef::Provider::Package::Rubygems do it "installs the gem by shelling out when options are provided as a String" do @new_resource.options("-i /alt/install/location") - expected ="gem install rspec-core -q --no-rdoc --no-ri -v \"#{@spec_version}\" -i /alt/install/location" + expected = "gem install rspec-core -q --no-rdoc --no-ri -v \"#{@spec_version}\" -i /alt/install/location" expect(@provider).to receive(:shell_out!).with(expected, env: nil, timeout: 900) @provider.run_action(:install) expect(@new_resource).to be_updated_by_last_action @@ -534,7 +528,7 @@ describe Chef::Provider::Package::Rubygems do it "installs the gem with rubygems.org as an added source" do @new_resource.gem_binary("/foo/bar") @new_resource.source("http://mirror.ops.rhcloud.com/mirror/ruby") - expected ="/foo/bar install rspec-core -q --no-rdoc --no-ri -v \"#{@spec_version}\" --source=#{@new_resource.source} --source=https://rubygems.org" + expected = "/foo/bar install rspec-core -q --no-rdoc --no-ri -v \"#{@spec_version}\" --source=#{@new_resource.source} --source=https://rubygems.org" expect(@provider).to receive(:shell_out!).with(expected, env: nil, timeout: 900) @provider.run_action(:install) expect(@new_resource).to be_updated_by_last_action @@ -544,7 +538,7 @@ describe Chef::Provider::Package::Rubygems do @new_resource.gem_binary("/foo/bar") @new_resource.source("http://mirror.ops.rhcloud.com/mirror/ruby") @new_resource.clear_sources(true) - expected ="/foo/bar install rspec-core -q --no-rdoc --no-ri -v \"#{@spec_version}\" --clear-sources --source=#{@new_resource.source}" + expected = "/foo/bar install rspec-core -q --no-rdoc --no-ri -v \"#{@spec_version}\" --clear-sources --source=#{@new_resource.source}" expect(@provider).to receive(:shell_out!).with(expected, env: nil, timeout: 900) @provider.run_action(:install) expect(@new_resource).to be_updated_by_last_action @@ -555,7 +549,7 @@ describe Chef::Provider::Package::Rubygems do it "installs the gem by shelling out when options are provided but no version is given" do @new_resource.options("-i /alt/install/location") - expected ="gem install rspec-core -q --no-rdoc --no-ri -v \"#{@provider.candidate_version}\" -i /alt/install/location" + expected = "gem install rspec-core -q --no-rdoc --no-ri -v \"#{@provider.candidate_version}\" -i /alt/install/location" expect(@provider).to receive(:shell_out!).with(expected, env: nil, timeout: 900) @provider.run_action(:install) expect(@new_resource).to be_updated_by_last_action @@ -628,7 +622,6 @@ describe Chef::Provider::Package::Rubygems do expect(@new_resource).to be_updated_by_last_action end end - end describe "when uninstalling a gem" do diff --git a/spec/unit/provider/package/smartos_spec.rb b/spec/unit/provider/package/smartos_spec.rb index 6746395dd2..5c86fbefe8 100644 --- a/spec/unit/provider/package/smartos_spec.rb +++ b/spec/unit/provider/package/smartos_spec.rb @@ -28,7 +28,6 @@ describe Chef::Provider::Package::SmartOS, "load_current_resource" do @new_resource = Chef::Resource::Package.new("varnish") @current_resource = Chef::Resource::Package.new("varnish") - @status = double("Status", :exitstatus => 0) @provider = Chef::Provider::Package::SmartOS.new(@new_resource, @run_context) allow(Chef::Resource::Package).to receive(:new).and_return(@current_resource) @@ -40,7 +39,6 @@ describe Chef::Provider::Package::SmartOS, "load_current_resource" do end describe "when loading current resource" do - it "should create a current resource with the name of the new_resource" do expect(@provider).to receive(:shell_out!).and_return(@shell_out) expect(Chef::Resource::Package).to receive(:new).and_return(@current_resource) @@ -65,8 +63,6 @@ describe Chef::Provider::Package::SmartOS, "load_current_resource" do @provider.load_current_resource expect(@current_resource.version).to eq(nil) end - - end describe "candidate_version" do @@ -82,7 +78,7 @@ describe Chef::Provider::Package::SmartOS, "load_current_resource" do and_yield("something-varnish-1.1.1 something varnish like\n"). and_yield("varnish-2.3.4 actual varnish\n") @shell_out = double("shell_out!", :stdout => search) - expect(@provider).to receive(:shell_out!).with("/opt/local/bin/pkgin", "se", "varnish", :env => nil, :returns => [0,1], :timeout=>900).and_return(@shell_out) + expect(@provider).to receive(:shell_out!).with("/opt/local/bin/pkgin", "se", "varnish", :env => nil, :returns => [0, 1], :timeout => 900).and_return(@shell_out) expect(@provider.candidate_version).to eq("2.3.4") end @@ -92,21 +88,18 @@ describe Chef::Provider::Package::SmartOS, "load_current_resource" do and_yield("something-varnish-1.1.1;;something varnish like\n"). and_yield("varnish-2.3.4;;actual varnish\n") @shell_out = double("shell_out!", :stdout => search) - expect(@provider).to receive(:shell_out!).with("/opt/local/bin/pkgin", "se", "varnish", :env => nil, :returns => [0,1], :timeout=>900).and_return(@shell_out) + expect(@provider).to receive(:shell_out!).with("/opt/local/bin/pkgin", "se", "varnish", :env => nil, :returns => [0, 1], :timeout => 900).and_return(@shell_out) expect(@provider.candidate_version).to eq("2.3.4") end end describe "when manipulating a resource" do - it "run pkgin and install the package" do out = OpenStruct.new(:stdout => nil) - expect(@provider).to receive(:shell_out!).with("/opt/local/sbin/pkg_info", "-E", "varnish*", {:env => nil, :returns=>[0,1], :timeout=>900}).and_return(@shell_out) - expect(@provider).to receive(:shell_out!).with("/opt/local/bin/pkgin", "-y", "install", "varnish-2.1.5nb2", {:env=>nil, :timeout=>900}).and_return(out) + expect(@provider).to receive(:shell_out!).with("/opt/local/sbin/pkg_info", "-E", "varnish*", { :env => nil, :returns => [0, 1], :timeout => 900 }).and_return(@shell_out) + expect(@provider).to receive(:shell_out!).with("/opt/local/bin/pkgin", "-y", "install", "varnish-2.1.5nb2", { :env => nil, :timeout => 900 }).and_return(out) @provider.load_current_resource @provider.install_package("varnish", "2.1.5nb2") end - end - end diff --git a/spec/unit/provider/package/solaris_spec.rb b/spec/unit/provider/package/solaris_spec.rb index b0a007b0cf..ba0b74dac6 100644 --- a/spec/unit/provider/package/solaris_spec.rb +++ b/spec/unit/provider/package/solaris_spec.rb @@ -32,7 +32,7 @@ describe Chef::Provider::Package::Solaris do describe "assessing the current package status" do before do - @pkginfo =<<-PKGINFO + @pkginfo = <<-PKGINFO PKGINST: SUNWbash NAME: GNU Bourne-Again shell (bash) CATEGORY: system @@ -46,7 +46,7 @@ INSTDATE: Nov 04 2009 01:02 HOTLINE: Please contact your local service provider PKGINFO - @status = double("Status",:stdout => "", :exitstatus => 0) + @status = double("Status", :stdout => "", :exitstatus => 0) end it "should create a current resource with the name of new_resource" do @@ -127,7 +127,6 @@ PKGINFO allow(@provider).to receive(:shell_out).and_return(status) expect { @provider.candidate_version }.to raise_error(Chef::Exceptions::Package) end - end describe "install and upgrade" do @@ -162,6 +161,5 @@ PKGINFO expect(@provider).to receive(:shell_out!).with("pkgrm -n -a /tmp/myadmin SUNWbash", { timeout: 900 }) @provider.remove_package("SUNWbash", "11.10.0,REV=2005.01.08.05.16") end - end end diff --git a/spec/unit/provider/package/windows/exe_spec.rb b/spec/unit/provider/package/windows/exe_spec.rb index 23a54601c2..0a56197761 100644 --- a/spec/unit/provider/package/windows/exe_spec.rb +++ b/spec/unit/provider/package/windows/exe_spec.rb @@ -121,12 +121,12 @@ describe Chef::Provider::Package::Windows::Exe do let(:uninstall_hash) do [ { - "DisplayVersion" => "v1", - "UninstallString" => File.join("uninst_dir1", "uninst_file1"), + "DisplayVersion" => "v1", + "UninstallString" => File.join("uninst_dir1", "uninst_file1"), }, { - "DisplayVersion" => "v2", - "UninstallString" => File.join("uninst_dir2", "uninst_file2"), + "DisplayVersion" => "v2", + "UninstallString" => File.join("uninst_dir2", "uninst_file2"), }, ] end diff --git a/spec/unit/provider/package/windows/msi_spec.rb b/spec/unit/provider/package/windows/msi_spec.rb index 22be2d3497..e29508ca7b 100644 --- a/spec/unit/provider/package/windows/msi_spec.rb +++ b/spec/unit/provider/package/windows/msi_spec.rb @@ -21,7 +21,7 @@ require "chef/provider/package/windows/msi" describe Chef::Provider::Package::Windows::MSI do let(:node) { double("Chef::Node") } - let(:events) { double("Chef::Events").as_null_object } # mock all the methods + let(:events) { double("Chef::Events").as_null_object } # mock all the methods let(:run_context) { double("Chef::RunContext", :node => node, :events => events) } let(:package_name) { "calculator" } let(:resource_source) { "calculator.msi" } @@ -85,7 +85,7 @@ describe Chef::Provider::Package::Windows::MSI do context "version is explicitly provided" do let(:resource_version) { "given_version" } - + it "returns the given version" do expect(provider.package_version).to eql("given_version") end @@ -95,7 +95,7 @@ describe Chef::Provider::Package::Windows::MSI do before do allow(::File).to receive(:exist?).with(Chef::Util::PathHelper.canonical_path(resource_source, false)).and_return(false) end - + it "returns nil" do expect(provider.package_version).to eql(nil) end diff --git a/spec/unit/provider/package/windows_spec.rb b/spec/unit/provider/package/windows_spec.rb index 948e138ae2..eb17511aa1 100644 --- a/spec/unit/provider/package/windows_spec.rb +++ b/spec/unit/provider/package/windows_spec.rb @@ -27,7 +27,7 @@ describe Chef::Provider::Package::Windows, :windows_only do end let(:node) { double("Chef::Node") } - let(:events) { double("Chef::Events").as_null_object } # mock all the methods + let(:events) { double("Chef::Events").as_null_object } # mock all the methods let(:run_context) { double("Chef::RunContext", :node => node, :events => events) } let(:resource_source) { "calculator.msi" } let(:resource_name) { "calculator" } @@ -96,7 +96,6 @@ describe Chef::Provider::Package::Windows, :windows_only do describe "package_provider" do shared_examples "a local file" do - it "checks that the source path is valid" do expect(Chef::Util::PathHelper).to receive(:validate_path).and_call_original provider.package_provider @@ -327,7 +326,7 @@ describe Chef::Provider::Package::Windows, :windows_only do new_resource.version("5.5.5") allow(provider).to receive(:current_version_array).and_return([ ["5.5.5", "4.3.0", "1.1.1"] ]) end - + it "does not install" do expect(provider).not_to receive(:install_package) provider.run_action(:install) @@ -339,7 +338,7 @@ describe Chef::Provider::Package::Windows, :windows_only do new_resource.version("5.5.5") allow(provider).to receive(:current_version_array).and_return([ ["5.5.0", "4.3.0", "1.1.1"] ]) end - + it "installs given version" do expect(provider).to receive(:install_package).with("blah", "5.5.5") provider.run_action(:install) @@ -353,7 +352,7 @@ describe Chef::Provider::Package::Windows, :windows_only do new_resource.version("5.5.5") 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) provider.run_action(:install) @@ -365,7 +364,7 @@ describe Chef::Provider::Package::Windows, :windows_only do new_resource.version("5.5.5") allow(provider).to receive(:current_version_array).and_return(["5.5.0"]) end - + it "installs given version" do expect(provider).to receive(:install_package).with("blah", "5.5.5") provider.run_action(:install) diff --git a/spec/unit/provider/package/yum_spec.rb b/spec/unit/provider/package/yum_spec.rb index f60bcd1405..e532467de0 100644 --- a/spec/unit/provider/package/yum_spec.rb +++ b/spec/unit/provider/package/yum_spec.rb @@ -258,10 +258,10 @@ describe Chef::Provider::Package::Yum do @yum_cache = double( "Chef::Provider::Yum::YumCache" ) - allow(@yum_cache).to receive(:installed_version) do |package_name, arch| - # nothing installed for package_name/new_package_name - nil - end + allow(@yum_cache).to receive(:installed_version) do |package_name, arch| + # nothing installed for package_name/new_package_name + nil + end allow(@yum_cache).to receive(:candidate_version) do |package_name, arch| if package_name == "testing.noarch" nil @@ -282,13 +282,13 @@ describe Chef::Provider::Package::Yum do end it "should flush the cache if :before is true" do - allow(@new_resource).to receive(:flush_cache).and_return({:after => false, :before => true}) + allow(@new_resource).to receive(:flush_cache).and_return({ :after => false, :before => true }) expect(@yum_cache).to receive(:reload).once @provider.load_current_resource end it "should flush the cache if :before is false" do - allow(@new_resource).to receive(:flush_cache).and_return({:after => false, :before => false}) + allow(@new_resource).to receive(:flush_cache).and_return({ :after => false, :before => false }) expect(@yum_cache).not_to receive(:reload) @provider.load_current_resource end @@ -346,7 +346,6 @@ describe Chef::Provider::Package::Yum do expect(@new_resource.version).to eq("2.0.1.el5") end - it "should search provides then set version to match if a requirement was passed in the version" do @new_resource = Chef::Resource::YumPackage.new("test-package") @new_resource.version("= 2.0.1.el5") @@ -356,7 +355,6 @@ describe Chef::Provider::Package::Yum do expect(@new_resource.version).to eq("2.0.1.el5") end - it "should search provides and not set the version to match if a specific version was requested" do @new_resource = Chef::Resource::YumPackage.new("test-package") @new_resource.version("3.0.1.el5") @@ -382,7 +380,6 @@ describe Chef::Provider::Package::Yum do expect(@new_resource.package_name).to eq(["test-package"]) expect(@new_resource.version).to eq(["3.0.1.el5"]) end - end it "should not return an error if no version number is specified in the resource" do @@ -398,7 +395,7 @@ describe Chef::Provider::Package::Yum do :disable_extra_repo_control => true, ) allow(Chef::Provider::Package::Yum::YumCache).to receive(:instance).and_return(@yum_cache) - allow(@yum_cache).to receive(:yum_binary=).with("yum") + allow(@yum_cache).to receive(:yum_binary=).with("yum") pkg = Chef::Provider::Package::Yum::RPMPackage.new("test-package", "2.0.1.el5", "x86_64", []) expect(@yum_cache).to receive(:packages_from_require).and_return([pkg]) @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context) @@ -420,7 +417,7 @@ describe Chef::Provider::Package::Yum do :disable_extra_repo_control => true, ) allow(Chef::Provider::Package::Yum::YumCache).to receive(:instance).and_return(@yum_cache) - allow(@yum_cache).to receive(:yum_binary=).with("yum") + allow(@yum_cache).to receive(:yum_binary=).with("yum") pkg = Chef::Provider::Package::Yum::RPMPackage.new("test-package", "2.0.1.el5", "x86_64", []) expect(@yum_cache).to receive(:packages_from_require).and_return([pkg]) @new_resource = Chef::Resource::YumPackage.new("test-package = 2.0.1.el5") @@ -448,12 +445,12 @@ describe Chef::Provider::Package::Yum do expect(@yum_cache).to receive(:packages_from_require).exactly(4).times.and_return([]) expect(@yum_cache).to receive(:reload_provides).twice - @new_resource = Chef::Resource::YumPackage.new(["test-package","test-package2"]) - @new_resource.version(["2.0.1.el5","3.0.1.el5"]) + @new_resource = Chef::Resource::YumPackage.new(["test-package", "test-package2"]) + @new_resource.version(["2.0.1.el5", "3.0.1.el5"]) @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context) @provider.load_current_resource - expect(@new_resource.package_name).to eq(["test-package","test-package2"]) - expect(@new_resource.version).to eq(["2.0.1.el5","3.0.1.el5"]) + expect(@new_resource.package_name).to eq(["test-package", "test-package2"]) + expect(@new_resource.version).to eq(["2.0.1.el5", "3.0.1.el5"]) end it "should search provides if no package is available - if no match in installed provides then load the complete set" do @@ -656,7 +653,7 @@ describe Chef::Provider::Package::Yum do end it "should run yum install then flush the cache if :after is true" do - allow(@new_resource).to receive(:flush_cache).and_return({:after => true, :before => false}) + allow(@new_resource).to receive(:flush_cache).and_return({ :after => true, :before => false }) @provider.load_current_resource allow(Chef::Provider::Package::Yum::RPMUtils).to receive(:rpmvercmp).and_return(-1) expect(@provider).to receive(:yum_command).with( @@ -667,7 +664,7 @@ describe Chef::Provider::Package::Yum do end it "should run yum install then not flush the cache if :after is false" do - allow(@new_resource).to receive(:flush_cache).and_return({:after => false, :before => false}) + allow(@new_resource).to receive(:flush_cache).and_return({ :after => false, :before => false }) @provider.load_current_resource allow(Chef::Provider::Package::Yum::RPMUtils).to receive(:rpmvercmp).and_return(-1) expect(@provider).to receive(:yum_command).with( @@ -792,7 +789,7 @@ describe Chef::Provider::Package::Yum do allow(@provider).to receive(:shell_out).and_return(@status) expect(@provider).to receive(:shell_out).once.with( "yum -d0 -e0 -y install emacs-1.0", - {:timeout => Chef::Config[:yum_timeout]}, + { :timeout => Chef::Config[:yum_timeout] }, ) @provider.yum_command("-d0 -e0 -y install emacs-1.0") end @@ -802,18 +799,18 @@ describe Chef::Provider::Package::Yum do allow(@provider).to receive(:shell_out).and_return(@status) expect(@provider).to receive(:shell_out).once.with( "yum -d0 -e0 -y install emacs-1.0", - {:timeout => Chef::Config[:yum_timeout]}, + { :timeout => Chef::Config[:yum_timeout] }, ) expect { @provider.yum_command("-d0 -e0 -y install emacs-1.0") }.to raise_error(Chef::Exceptions::Exec) end it "should run yum once if it exits with a return code of 1 and %pre scriptlet failures" do @status = double("Status", :exitstatus => 1, :stdout => "error: %pre(demo-1-1.el5.centos.x86_64) scriptlet failed, exit status 2", - :stderr => "") + :stderr => "") allow(@provider).to receive(:shell_out).and_return(@status) expect(@provider).to receive(:shell_out).once.with( "yum -d0 -e0 -y install emacs-1.0", - {:timeout => Chef::Config[:yum_timeout]}, + { :timeout => Chef::Config[:yum_timeout] }, ) # will still raise an exception, can't stub out the subsequent call expect { @provider.yum_command("-d0 -e0 -y install emacs-1.0") }.to raise_error(Chef::Exceptions::Exec) @@ -821,11 +818,11 @@ describe Chef::Provider::Package::Yum do it "should run yum twice if it exits with a return code of 1 and %post scriptlet failures" do @status = double("Status", :exitstatus => 1, :stdout => "error: %post(demo-1-1.el5.centos.x86_64) scriptlet failed, exit status 2", - :stderr => "") + :stderr => "") allow(@provider).to receive(:shell_out).and_return(@status) expect(@provider).to receive(:shell_out).twice.with( "yum -d0 -e0 -y install emacs-1.0", - {:timeout => Chef::Config[:yum_timeout]}, + { :timeout => Chef::Config[:yum_timeout] }, ) # will still raise an exception, can't stub out the subsequent call expect { @provider.yum_command("-d0 -e0 -y install emacs-1.0") }.to raise_error(Chef::Exceptions::Exec) @@ -839,7 +836,7 @@ describe Chef::Provider::Package::Yum do allow(@provider).to receive(:shell_out).and_return(@status) expect(@provider).to receive(:shell_out).once.with( "yum-deprecated -d0 -e0 -y install emacs-1.0", - {:timeout => Chef::Config[:yum_timeout]}, + { :timeout => Chef::Config[:yum_timeout] }, ) @provider.yum_command("-d0 -e0 -y install emacs-1.0") end @@ -965,7 +962,7 @@ describe Chef::Provider::Package::Yum::RPMUtils do [ "0.0.1aa", "0.0.1aa", 0 ], [ "0.0.1a", "0.0.1aa", -1 ], ].each do |x, y, result| - expect(@rpmutils.rpmvercmp(x,y)).to eq(result) + expect(@rpmutils.rpmvercmp(x, y)).to eq(result) end end @@ -984,7 +981,7 @@ describe Chef::Provider::Package::Yum::RPMUtils do [ "", "", 0 ], [ "", "1.0.1", -1 ], ].each do |x, y, result| - expect(@rpmutils.rpmvercmp(x,y)).to eq(result) + expect(@rpmutils.rpmvercmp(x, y)).to eq(result) end end @@ -1024,7 +1021,6 @@ describe Chef::Provider::Package::Yum::RPMUtils do end end end - end describe Chef::Provider::Package::Yum::RPMVersion do @@ -1209,7 +1205,6 @@ describe Chef::Provider::Package::Yum::RPMVersion do end end end - end describe Chef::Provider::Package::Yum::RPMPackage do @@ -1327,7 +1322,6 @@ describe Chef::Provider::Package::Yum::RPMPackage do end end end - end describe Chef::Provider::Package::Yum::RPMDbPackage do @@ -1539,7 +1533,6 @@ describe Chef::Provider::Package::Yum::RPMDependency do end end end - end # thanks resource_collection_spec.rb! @@ -1737,7 +1730,6 @@ describe Chef::Provider::Package::Yum::RPMDb do expect(x[1]).to eq(@rpm_z) end end - end describe Chef::Provider::Package::Yum::YumCache do @@ -1840,19 +1832,19 @@ EOF end it "should return the default python if the yum-executable doesn't start with #!" do - allow(::File).to receive(:open).with("/usr/bin/yum", "r") { |&b| r = b.call(bin_exe); bin_exe.rewind; r} + allow(::File).to receive(:open).with("/usr/bin/yum", "r") { |&b| r = b.call(bin_exe); bin_exe.rewind; r } expect(@yc.python_bin).to eq("/usr/bin/python") end it "should return /usr/bin/python if the interpreter is /bin/bash" do other = StringIO.new("#!/bin/bash\n# The yum executable redirecting to dnf from dnf-yum compatible package.") - allow(::File).to receive(:open).with("/usr/bin/yum", "r") { |&b| r = b.call(other); other.rewind; r} + allow(::File).to receive(:open).with("/usr/bin/yum", "r") { |&b| r = b.call(other); other.rewind; r } expect(@yc.python_bin).to eq("/usr/bin/python") end it "should return the interpreter for yum" do other = StringIO.new("#!/usr/bin/super_python\n\nlasjdfdsaljf\nlasdjfs") - allow(::File).to receive(:open).with("/usr/bin/yum", "r") { |&b| r = b.call(other); other.rewind; r} + allow(::File).to receive(:open).with("/usr/bin/yum", "r") { |&b| r = b.call(other); other.rewind; r } expect(@yc.python_bin).to eq("/usr/bin/super_python") end end @@ -1867,32 +1859,32 @@ EOF it "should run yum-dump.py using the system python when next_refresh is for :all" do @yc.reload - expect(@yc).to receive(:shell_out!).with(%r{^/usr/bin/python .*/yum-dump.py --options --installed-provides --yum-lock-timeout 30$}, :timeout=>Chef::Config[:yum_timeout]) + expect(@yc).to receive(:shell_out!).with(%r{^/usr/bin/python .*/yum-dump.py --options --installed-provides --yum-lock-timeout 30$}, :timeout => Chef::Config[:yum_timeout]) @yc.refresh end it "should run yum-dump.py with the installed flag when next_refresh is for :installed" do @yc.reload_installed - expect(@yc).to receive(:shell_out!).with(%r{^/usr/bin/python .*/yum-dump.py --installed --yum-lock-timeout 30$}, :timeout=>Chef::Config[:yum_timeout]) + expect(@yc).to receive(:shell_out!).with(%r{^/usr/bin/python .*/yum-dump.py --installed --yum-lock-timeout 30$}, :timeout => Chef::Config[:yum_timeout]) @yc.refresh end it "should run yum-dump.py with the all-provides flag when next_refresh is for :provides" do @yc.reload_provides - expect(@yc).to receive(:shell_out!).with(%r{^/usr/bin/python .*/yum-dump.py --options --all-provides --yum-lock-timeout 30$}, :timeout=>Chef::Config[:yum_timeout]) + expect(@yc).to receive(:shell_out!).with(%r{^/usr/bin/python .*/yum-dump.py --options --all-provides --yum-lock-timeout 30$}, :timeout => Chef::Config[:yum_timeout]) @yc.refresh end it "should pass extra_repo_control args to yum-dump.py" do @yc.enable_extra_repo_control("--enablerepo=foo --disablerepo=bar") - expect(@yc).to receive(:shell_out!).with(%r{^/usr/bin/python .*/yum-dump.py --options --installed-provides --enablerepo=foo --disablerepo=bar --yum-lock-timeout 30$}, :timeout=>Chef::Config[:yum_timeout]) + expect(@yc).to receive(:shell_out!).with(%r{^/usr/bin/python .*/yum-dump.py --options --installed-provides --enablerepo=foo --disablerepo=bar --yum-lock-timeout 30$}, :timeout => Chef::Config[:yum_timeout]) @yc.refresh end it "should pass extra_repo_control args and configured yum lock timeout to yum-dump.py" do Chef::Config[:yum_lock_timeout] = 999 @yc.enable_extra_repo_control("--enablerepo=foo --disablerepo=bar") - expect(@yc).to receive(:shell_out!).with(%r{^/usr/bin/python .*/yum-dump.py --options --installed-provides --enablerepo=foo --disablerepo=bar --yum-lock-timeout 999$}, :timeout=>Chef::Config[:yum_timeout]) + expect(@yc).to receive(:shell_out!).with(%r{^/usr/bin/python .*/yum-dump.py --options --installed-provides --enablerepo=foo --disablerepo=bar --yum-lock-timeout 999$}, :timeout => Chef::Config[:yum_timeout]) @yc.refresh end @@ -1920,7 +1912,7 @@ EOF it "should raise exception yum-dump.py exits with a non zero status" do @status = double("Status", :exitstatus => 1, :stdin => @stdin, :stdout => @stdout_no_output, :stderr => @stderr) allow(@yc).to receive(:shell_out!).and_return(@status) - expect { @yc.refresh}.to raise_error(Chef::Exceptions::Package, %r{CentOS-Base.repo, line: 12}) + expect { @yc.refresh }.to raise_error(Chef::Exceptions::Package, %r{CentOS-Base.repo, line: 12}) end it "should parse type 'i' into an installed state for a package" do @@ -2107,7 +2099,6 @@ EOF @yc.disable_extra_repo_control end end - end describe "Chef::Provider::Package::Yum - Multi" do @@ -2264,6 +2255,5 @@ describe "Chef::Provider::Package::Yum - Multi" do ) @provider.install_package(["cups", "vim"], ["1.2.4-11.19.el5", "1.0"]) end - end end diff --git a/spec/unit/provider/package/zypper_spec.rb b/spec/unit/provider/package/zypper_spec.rb index f5e2c5e8a5..0dce51a203 100644 --- a/spec/unit/provider/package/zypper_spec.rb +++ b/spec/unit/provider/package/zypper_spec.rb @@ -38,12 +38,12 @@ describe Chef::Provider::Package::Zypper do allow(provider).to receive(:`).and_return("2.0") end - def shell_out_expectation(command, options=nil) + def shell_out_expectation(command, options = nil) options ||= { timeout: 900 } expect(provider).to receive(:shell_out).with(command, options) end - def shell_out_expectation!(command, options=nil) + def shell_out_expectation!(command, options = nil) options ||= { timeout: 900 } expect(provider).to receive(:shell_out!).with(command, options) end @@ -104,8 +104,7 @@ describe Chef::Provider::Package::Zypper do it "should run zypper install without gpg checks" do allow(Chef::Config).to receive(:[]).with(:zypper_check_gpg).and_return(false) shell_out_expectation!( - "zypper --non-interactive --no-gpg-checks install "+ - "--auto-agree-with-licenses emacs=1.0" + "zypper --non-interactive --no-gpg-checks install " + "--auto-agree-with-licenses emacs=1.0" ) provider.install_package(["emacs"], ["1.0"]) end @@ -114,8 +113,7 @@ describe Chef::Provider::Package::Zypper do /All packages will be installed without gpg signature checks/ ) shell_out_expectation!( - "zypper --non-interactive --no-gpg-checks install "+ - "--auto-agree-with-licenses emacs=1.0" + "zypper --non-interactive --no-gpg-checks install " + "--auto-agree-with-licenses emacs=1.0" ) provider.install_package(["emacs"], ["1.0"]) end @@ -132,8 +130,7 @@ describe Chef::Provider::Package::Zypper do it "should run zypper update without gpg checks" do allow(Chef::Config).to receive(:[]).with(:zypper_check_gpg).and_return(false) shell_out_expectation!( - "zypper --non-interactive --no-gpg-checks install "+ - "--auto-agree-with-licenses emacs=1.0" + "zypper --non-interactive --no-gpg-checks install " + "--auto-agree-with-licenses emacs=1.0" ) provider.upgrade_package(["emacs"], ["1.0"]) end @@ -142,22 +139,19 @@ describe Chef::Provider::Package::Zypper do /All packages will be installed without gpg signature checks/ ) shell_out_expectation!( - "zypper --non-interactive --no-gpg-checks install "+ - "--auto-agree-with-licenses emacs=1.0" + "zypper --non-interactive --no-gpg-checks install " + "--auto-agree-with-licenses emacs=1.0" ) provider.upgrade_package(["emacs"], ["1.0"]) end it "should run zypper upgrade without gpg checks" do shell_out_expectation!( - "zypper --non-interactive --no-gpg-checks install "+ - "--auto-agree-with-licenses emacs=1.0" + "zypper --non-interactive --no-gpg-checks install " + "--auto-agree-with-licenses emacs=1.0" ) provider.upgrade_package(["emacs"], ["1.0"]) end end describe "remove_package" do - context "when package version is not explicitly specified" do it "should run zypper remove with the package name" do allow(Chef::Config).to receive(:[]).with(:zypper_check_gpg).and_return(true) @@ -257,8 +251,7 @@ describe Chef::Provider::Package::Zypper do it "should install an array of package names and versions" do allow(Chef::Config).to receive(:[]).with(:zypper_check_gpg).and_return(false) shell_out_expectation!( - "zypper --non-interactive --no-gpg-checks install "+ - "--auto-agree-with-licenses emacs=1.0 vim=2.0" + "zypper --non-interactive --no-gpg-checks install " + "--auto-agree-with-licenses emacs=1.0 vim=2.0" ) provider.install_package(["emacs", "vim"], ["1.0", "2.0"]) end diff --git a/spec/unit/provider/package_spec.rb b/spec/unit/provider/package_spec.rb index 50016c623d..38bc963367 100644 --- a/spec/unit/provider/package_spec.rb +++ b/spec/unit/provider/package_spec.rb @@ -133,7 +133,6 @@ describe Chef::Provider::Package do provider.run_action(:install) expect(new_resource).to be_updated end - end describe "when upgrading the package" do @@ -225,7 +224,6 @@ describe Chef::Provider::Package do provider.run_action(:remove) expect(new_resource).to be_updated end - end describe "When purging the package" do @@ -271,7 +269,6 @@ describe Chef::Provider::Package do provider.run_action(:purge) expect(new_resource).to be_updated end - end describe "when reconfiguring the package" do @@ -428,9 +425,7 @@ describe Chef::Provider::Package do expect(response_file_resource).to receive(:run_action).with(:create) expect(provider.get_preseed_file("java", "6")).to be(false) end - end - end end @@ -776,7 +771,6 @@ describe "Chef::Provider::Package - Multi" do provider.run_action(:remove) expect(new_resource).not_to be_updated_by_last_action end - end describe "When purging multiple packages " do diff --git a/spec/unit/provider/powershell_script_spec.rb b/spec/unit/provider/powershell_script_spec.rb index c0361eaea1..5a49bcc5fa 100644 --- a/spec/unit/provider/powershell_script_spec.rb +++ b/spec/unit/provider/powershell_script_spec.rb @@ -18,7 +18,6 @@ require "spec_helper" describe Chef::Provider::PowershellScript, "action_run" do - let(:powershell_version) { nil } let(:node) { node = Chef::Node.new @@ -72,7 +71,7 @@ describe Chef::Provider::PowershellScript, "action_run" do provider_flags = provider.flags.split(" ") execution_policy_specified = false - provider_flags.find do | value | + provider_flags.find do |value| execution_policy_index += 1 execution_policy_specified = value.downcase == "-ExecutionPolicy".downcase end @@ -92,7 +91,7 @@ describe Chef::Provider::PowershellScript, "action_run" do "3.0" => "Bypass", "3.6" => "Bypass", "4.0" => "Bypass", - "5.0" => "Bypass" }.each do | version_policy | + "5.0" => "Bypass" }.each do |version_policy| let(:powershell_version) { version_policy[0].to_f } context "when running PowerShell version #{version_policy[0]}" do let(:powershell_version) { version_policy[0].to_f } diff --git a/spec/unit/provider/registry_key_spec.rb b/spec/unit/provider/registry_key_spec.rb index 41bc5b33d3..b3d725e585 100644 --- a/spec/unit/provider/registry_key_spec.rb +++ b/spec/unit/provider/registry_key_spec.rb @@ -269,7 +269,6 @@ shared_examples_for "a registry key" do end end end - end describe Chef::Provider::RegistryKey do diff --git a/spec/unit/provider/remote_directory_spec.rb b/spec/unit/provider/remote_directory_spec.rb index e91bd22739..b4cb07bd0c 100644 --- a/spec/unit/provider/remote_directory_spec.rb +++ b/spec/unit/provider/remote_directory_spec.rb @@ -110,7 +110,7 @@ describe Chef::Provider::RemoteDirectory do @resource.path(@destination_dir) end - after {FileUtils.rm_rf(@destination_dir)} + after { FileUtils.rm_rf(@destination_dir) } # CHEF-3552 it "creates the toplevel directory without error " do @@ -134,8 +134,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") { |f| f.puts "blah blah blah" } + File.open(@destination_dir + "/remotesubdir/remote_subdir_file1.txt", "a") { |f| f.puts "blah blah blah" } 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")) @@ -147,7 +147,7 @@ describe Chef::Provider::RemoteDirectory do end describe "with purging enabled" do - before {@resource.purge(true)} + before { @resource.purge(true) } it "removes existing files if purge is true" do @provider.run_action(:create) @@ -202,13 +202,13 @@ describe Chef::Provider::RemoteDirectory do end describe "with overwrite disabled" do - before {@resource.purge(false)} - before {@resource.overwrite(false)} + before { @resource.purge(false) } + before { @resource.overwrite(false) } 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") { |f| f.puts "blah blah blah" } + ::File.open(@destination_dir + "/remotesubdir/remote_subdir_file1.txt", "a") { |f| f.puts "blah blah blah" } 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) @@ -216,6 +216,5 @@ describe Chef::Provider::RemoteDirectory do expect(subdirfile1md5.eql?(Digest::MD5.hexdigest(::File.read(@destination_dir + "/remotesubdir/remote_subdir_file1.txt")))).to be_truthy end end - end end diff --git a/spec/unit/provider/remote_file/cache_control_data_spec.rb b/spec/unit/provider/remote_file/cache_control_data_spec.rb index 5d31863274..2109894890 100644 --- a/spec/unit/provider/remote_file/cache_control_data_spec.rb +++ b/spec/unit/provider/remote_file/cache_control_data_spec.rb @@ -29,7 +29,6 @@ CACHE_FILE_PATH_LIMIT = CACHE_FILE_JSON_FILE_EXTENSION_LENGTH # {friendly}-{md5hex}.json == 102 describe Chef::Provider::RemoteFile::CacheControlData do - let(:uri) { URI.parse("http://www.google.com/robots.txt") } subject(:cache_control_data) do @@ -43,7 +42,6 @@ describe Chef::Provider::RemoteFile::CacheControlData do let(:current_file_checksum) { "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" } context "when loading data for an unknown URI" do - before do expect(Chef::FileCache).to receive(:has_key?).with(cache_path).and_return(false) expect(Chef::FileCache).to receive(:has_key?).with(old_cache_path).and_return(false) @@ -64,7 +62,6 @@ describe Chef::Provider::RemoteFile::CacheControlData do end context "and the URI contains a password" do - let(:uri) { URI.parse("http://bob:password@example.org/") } let(:cache_path) { "remote_file/http___bob_XXXX_example_org_-44be109aa176a165ef599c12d97af792.json" } let(:old_cache_path) { "remote_file/http___bob_XXXX_example_org_-f121caacb74c05a35bcefdf578ed5fc9.json" } @@ -76,7 +73,6 @@ describe Chef::Provider::RemoteFile::CacheControlData do end describe "when loading data for a known URI" do - # the checksum of the file last we fetched it. let(:last_fetched_checksum) { "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" } @@ -163,7 +159,6 @@ describe Chef::Provider::RemoteFile::CacheControlData do end describe "when saving to disk" do - let(:etag) { "\"a-strong-identifier\"" } let(:mtime) { "Tue, 21 May 2013 19:19:23 GMT" } let(:fetched_file_checksum) { "e2a8938cc31754f6c067b35aab1d0d4864272e9bf8504536ef3e79ebf8432305" } @@ -197,7 +192,6 @@ describe Chef::Provider::RemoteFile::CacheControlData do end context "and the URI contains a password" do - let(:uri) { URI.parse("http://bob:password@example.org/") } let(:cache_path) { "remote_file/http___bob_XXXX_example_org_-44be109aa176a165ef599c12d97af792.json" } let(:old_cache_path) { "remote_file/http___bob_XXXX_example_org_-f121caacb74c05a35bcefdf578ed5fc9.json" } @@ -214,7 +208,7 @@ describe Chef::Provider::RemoteFile::CacheControlData do # local file system path limits resulting in exceptions from # file system API's on both Windows and Unix systems. context "and the URI results in a file cache path that exceeds #{CACHE_FILE_PATH_LIMIT} characters in length" do - let(:long_remote_path) { "http://www.bing.com/" + ("0" * (CACHE_FILE_TRUNCATED_FRIENDLY_FILE_NAME_LENGTH * 2 )) } + let(:long_remote_path) { "http://www.bing.com/" + ("0" * (CACHE_FILE_TRUNCATED_FRIENDLY_FILE_NAME_LENGTH * 2 )) } let(:uri) { URI.parse(long_remote_path) } let(:truncated_remote_uri) { URI.parse(long_remote_path[0...CACHE_FILE_TRUNCATED_FRIENDLY_FILE_NAME_LENGTH]) } let(:truncated_file_cache_path) do @@ -239,8 +233,5 @@ describe Chef::Provider::RemoteFile::CacheControlData do expect(normalized_cache_path.start_with?(truncated_file_cache_path)).to eq(true) end end - end - end - diff --git a/spec/unit/provider/remote_file/content_spec.rb b/spec/unit/provider/remote_file/content_spec.rb index a562c1c742..de8d860f7e 100644 --- a/spec/unit/provider/remote_file/content_spec.rb +++ b/spec/unit/provider/remote_file/content_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::RemoteFile::Content do - # # mock setup # @@ -94,7 +93,6 @@ describe Chef::Provider::RemoteFile::Content do end describe "when the fetcher returns a valid tempfile" do - let(:mtime) { Time.now } let(:tempfile) { double("Tempfile") } let(:http_fetcher) { double("Chef::Provider::RemoteFile::HTTP", :fetch => tempfile) } @@ -106,7 +104,6 @@ describe Chef::Provider::RemoteFile::Content do it "should return the tempfile object to the caller" do expect(content.tempfile).to eq(tempfile) end - end end describe "when the checksum are both nil" do @@ -141,7 +138,6 @@ describe Chef::Provider::RemoteFile::Content do it_behaves_like "the resource needs fetching" end - describe "when the fetcher throws an exception" do before do allow(new_resource).to receive(:checksum).and_return(nil) @@ -159,11 +155,10 @@ describe Chef::Provider::RemoteFile::Content do end describe "when there is an array of sources and the first fails" do - # https://github.com/opscode/chef/pull/1358#issuecomment-40853299 def create_exception(exception_class) if [ Net::HTTPServerException, Net::HTTPFatalError ].include? exception_class - exception_class.new("message", {"something" => 1}) + exception_class.new("message", { "something" => 1 }) else exception_class.new end @@ -249,5 +244,4 @@ describe Chef::Provider::RemoteFile::Content do expect(new_resource.source.length).to eq(2) end end - end diff --git a/spec/unit/provider/remote_file/fetcher_spec.rb b/spec/unit/provider/remote_file/fetcher_spec.rb index 0fa213cdb2..153e4740e6 100644 --- a/spec/unit/provider/remote_file/fetcher_spec.rb +++ b/spec/unit/provider/remote_file/fetcher_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::RemoteFile::Fetcher do - let(:current_resource) { double("current resource") } let(:new_resource) { double("new resource") } let(:fetcher_instance) { double("fetcher") } @@ -90,5 +89,4 @@ describe Chef::Provider::RemoteFile::Fetcher do expect { described_class.for_resource(uri, new_resource, current_resource) }.to raise_error(ArgumentError) end end - end diff --git a/spec/unit/provider/remote_file/ftp_spec.rb b/spec/unit/provider/remote_file/ftp_spec.rb index a8d65b0156..d46256b1d1 100644 --- a/spec/unit/provider/remote_file/ftp_spec.rb +++ b/spec/unit/provider/remote_file/ftp_spec.rb @@ -38,7 +38,7 @@ describe Chef::Provider::RemoteFile::FTP do end let(:ftp) do - ftp = double(Net::FTP, { }) + ftp = double(Net::FTP, {}) allow(ftp).to receive(:connect) allow(ftp).to receive(:login) allow(ftp).to receive(:voidcmd) @@ -65,7 +65,6 @@ describe Chef::Provider::RemoteFile::FTP do end describe "when first created" do - it "throws an argument exception when no path is given" do uri.path = "" expect { Chef::Provider::RemoteFile::FTP.new(uri, new_resource, current_resource) }.to raise_error(ArgumentError) @@ -100,7 +99,6 @@ describe Chef::Provider::RemoteFile::FTP do end describe "when fetching the object" do - let(:cache_control_data) { Chef::Provider::RemoteFile::CacheControlData.new(uri) } let(:current_resource_checksum) { "e2a8938cc31754f6c067b35aab1d0d4864272e9bf8504536ef3e79ebf8432305" } @@ -141,7 +139,6 @@ describe Chef::Provider::RemoteFile::FTP do expect(ftp).to receive(:connect).with("opscode.com", 8021) fetcher.fetch end - end context "and the URI contains a username and password" do @@ -160,7 +157,6 @@ describe Chef::Provider::RemoteFile::FTP do expect(ftp).to receive(:voidcmd).with("TYPE A").once fetcher.fetch end - end context "and the uri sets the typecode to image" do @@ -170,7 +166,6 @@ describe Chef::Provider::RemoteFile::FTP do expect(ftp).to receive(:voidcmd).with("TYPE I").once fetcher.fetch end - end context "and the uri specifies a nested path" do @@ -183,7 +178,6 @@ describe Chef::Provider::RemoteFile::FTP do expect(ftp).to receive(:getbinaryfile).with("seattle.txt", tempfile.path) fetcher.fetch end - end context "when not using last modified based conditional fetching" do @@ -195,7 +189,6 @@ describe Chef::Provider::RemoteFile::FTP do result = fetcher.fetch expect(result).to equal(tempfile) end - end context "and proxying is enabled" do @@ -212,8 +205,6 @@ describe Chef::Provider::RemoteFile::FTP do result = fetcher.fetch expect(result).to equal(tempfile) end - end - end end diff --git a/spec/unit/provider/remote_file/http_spec.rb b/spec/unit/provider/remote_file/http_spec.rb index 89f2964076..12c75d4144 100644 --- a/spec/unit/provider/remote_file/http_spec.rb +++ b/spec/unit/provider/remote_file/http_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::RemoteFile::HTTP do - let(:uri) { URI.parse("http://opscode.com/seattle.txt") } let(:existing_file_source) { nil } @@ -44,9 +43,7 @@ describe Chef::Provider::RemoteFile::HTTP do let(:cache_control_data) { Chef::Provider::RemoteFile::CacheControlData.new(uri) } describe "generating cache control headers" do - context "and there is no valid cache control data for this URI on disk" do - before do expect(Chef::Provider::RemoteFile::CacheControlData).to receive(:load_and_validate).with(uri, current_resource_checksum).and_return(cache_control_data) end @@ -61,14 +58,12 @@ describe Chef::Provider::RemoteFile::HTTP do end it "has the user-specified custom headers" do - expect(fetcher.headers).to eq({"x-myapp-header" => "custom-header-value"}) + expect(fetcher.headers).to eq({ "x-myapp-header" => "custom-header-value" }) end end - end context "and the cache control data matches the existing file" do - # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26 let(:etag) { "\"a-strong-unique-identifier\"" } @@ -120,7 +115,6 @@ describe Chef::Provider::RemoteFile::HTTP do expect(headers["if-modified-since"]).to eq("custom-last-modified") end end - end context "and etag support is enabled" do @@ -149,11 +143,9 @@ describe Chef::Provider::RemoteFile::HTTP do end end end - end describe "when fetching the uri" do - let(:expected_http_opts) { {} } let(:expected_http_args) { [uri, expected_http_opts] } @@ -178,19 +170,15 @@ describe Chef::Provider::RemoteFile::HTTP do expect(Chef::HTTP::Simple).to receive(:new).with(*expected_http_args).and_return(rest) end - describe "and the request does not return new content" do - it "should return a nil tempfile for a 304 HTTPNotModifed" do # Streaming request returns nil for 304 errors allow(rest).to receive(:streaming_request).and_return(nil) expect(fetcher.fetch).to be_nil end - end describe "and the request returns new content" do - let(:fetched_content_checksum) { "e2a8938cc31754f6c067b35aab1d0d4864272e9bf8504536ef3e79ebf8432305" } before do @@ -207,7 +195,7 @@ describe Chef::Provider::RemoteFile::HTTP do end context "and the response does not contain an etag" do - let(:last_response) { {"etag" => nil} } + let(:last_response) { { "etag" => nil } } it "does not include an etag in the result" do fetcher.fetch expect(cache_control_data.etag).to be_nil @@ -217,7 +205,7 @@ describe Chef::Provider::RemoteFile::HTTP do end context "and the response has an etag header" do - let(:last_response) { {"etag" => "abc123"} } + let(:last_response) { { "etag" => "abc123" } } it "includes the etag value in the response" do fetcher.fetch @@ -225,11 +213,10 @@ describe Chef::Provider::RemoteFile::HTTP do expect(cache_control_data.mtime).to be_nil expect(cache_control_data.checksum).to eq(fetched_content_checksum) end - end context "and the response has no Date or Last-Modified header" do - let(:last_response) { {"date" => nil, "last_modified" => nil} } + let(:last_response) { { "date" => nil, "last_modified" => nil } } it "does not set an mtime in the result" do # RFC 2616 suggests that servers that do not set a Date header do not # have a reliable clock, so no use in making them deal with dates. @@ -243,7 +230,7 @@ describe Chef::Provider::RemoteFile::HTTP do context "and the response has a Last-Modified header" do let(:last_response) do # Last-Modified should be preferred to Date if both are set - {"date" => "Fri, 17 May 2013 23:23:23 GMT", "last_modified" => "Fri, 17 May 2013 11:11:11 GMT"} + { "date" => "Fri, 17 May 2013 23:23:23 GMT", "last_modified" => "Fri, 17 May 2013 11:11:11 GMT" } end it "sets the mtime to the Last-Modified time in the response" do @@ -255,7 +242,7 @@ describe Chef::Provider::RemoteFile::HTTP do context "and the response has a Date header but no Last-Modified header" do let(:last_response) do - {"date" => "Fri, 17 May 2013 23:23:23 GMT", "last_modified" => nil} + { "date" => "Fri, 17 May 2013 23:23:23 GMT", "last_modified" => nil } end it "sets the mtime to the Date in the response" do @@ -264,13 +251,11 @@ describe Chef::Provider::RemoteFile::HTTP do expect(cache_control_data.mtime).to eq(last_response["date"]) expect(cache_control_data.checksum).to eq(fetched_content_checksum) end - end context "and the target file is a tarball [CHEF-3140]" do - let(:uri) { URI.parse("http://opscode.com/tarball.tgz") } - let(:expected_http_opts) { {:disable_gzip => true} } + let(:expected_http_opts) { { :disable_gzip => true } } # CHEF-3140 # Some servers return tarballs as content type tar and encoding gzip, which @@ -296,8 +281,5 @@ describe Chef::Provider::RemoteFile::HTTP do end end end - end - end - diff --git a/spec/unit/provider/remote_file/local_file_spec.rb b/spec/unit/provider/remote_file/local_file_spec.rb index 31f14fbe45..d86ada8ef5 100644 --- a/spec/unit/provider/remote_file/local_file_spec.rb +++ b/spec/unit/provider/remote_file/local_file_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::RemoteFile::LocalFile do - let(:uri) { URI.parse("file:///nyan_cat.png") } let(:new_resource) { Chef::Resource::RemoteFile.new("local file backend test (new_resource)") } @@ -27,7 +26,6 @@ describe Chef::Provider::RemoteFile::LocalFile do subject(:fetcher) { Chef::Provider::RemoteFile::LocalFile.new(uri, new_resource, current_resource) } context "when parsing source path on windows" do - before do allow(Chef::Platform).to receive(:windows?).and_return(true) end @@ -69,7 +67,6 @@ describe Chef::Provider::RemoteFile::LocalFile do end context "when first created" do - it "stores the uri it is passed" do expect(fetcher.uri).to eq(uri) end @@ -77,11 +74,9 @@ describe Chef::Provider::RemoteFile::LocalFile do it "stores the new_resource" do expect(fetcher.new_resource).to eq(new_resource) end - end describe "when fetching the object" do - let(:tempfile) { double("Tempfile", :path => "/tmp/foo/bar/nyan.png", :close => nil) } let(:chef_tempfile) { double("Chef::FileContentManagement::Tempfile", :tempfile => tempfile) } @@ -97,7 +92,5 @@ describe Chef::Provider::RemoteFile::LocalFile do result = fetcher.fetch expect(result).to eq(tempfile) end - end - end diff --git a/spec/unit/provider/remote_file/network_file_spec.rb b/spec/unit/provider/remote_file/network_file_spec.rb index de065c83e2..cd2d9c669b 100644 --- a/spec/unit/provider/remote_file/network_file_spec.rb +++ b/spec/unit/provider/remote_file/network_file_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::RemoteFile::NetworkFile do - let(:source) { "\\\\foohost\\fooshare\\Foo.tar.gz" } let(:new_resource) { Chef::Resource::RemoteFile.new("network file (new_resource)") } @@ -27,7 +26,6 @@ describe Chef::Provider::RemoteFile::NetworkFile do subject(:fetcher) { Chef::Provider::RemoteFile::NetworkFile.new(source, new_resource, current_resource) } describe "when fetching the object" do - let(:tempfile) { double("Tempfile", :path => "/tmp/foo/bar/Foo.tar.gz", :close => nil) } let(:chef_tempfile) { double("Chef::FileContentManagement::Tempfile", :tempfile => tempfile) } @@ -39,7 +37,5 @@ describe Chef::Provider::RemoteFile::NetworkFile do result = fetcher.fetch expect(result).to eq(tempfile) end - end - end diff --git a/spec/unit/provider/remote_file_spec.rb b/spec/unit/provider/remote_file_spec.rb index de5036eb41..6107f93c41 100644 --- a/spec/unit/provider/remote_file_spec.rb +++ b/spec/unit/provider/remote_file_spec.rb @@ -21,7 +21,6 @@ require "spec_helper" require "support/shared/unit/provider/file" - describe Chef::Provider::RemoteFile do let(:resource) do resource = Chef::Resource::RemoteFile.new("seattle", @run_context) @@ -36,7 +35,7 @@ describe Chef::Provider::RemoteFile do end let(:node) { double("Chef::Node") } - let(:events) { double("Chef::Events").as_null_object } # mock all the methods + let(:events) { double("Chef::Events").as_null_object } # mock all the methods let(:run_context) { double("Chef::RunContext", :node => node, :events => events) } let(:enclosing_directory) { canonicalize_path(File.expand_path(File.join(CHEF_SPEC_DATA, "templates"))) @@ -60,4 +59,3 @@ describe Chef::Provider::RemoteFile do it_behaves_like "a file provider with source field" end - diff --git a/spec/unit/provider/route_spec.rb b/spec/unit/provider/route_spec.rb index 3ef3affde2..bd1e637570 100644 --- a/spec/unit/provider/route_spec.rb +++ b/spec/unit/provider/route_spec.rb @@ -47,7 +47,6 @@ describe Chef::Provider::Route do end end - describe Chef::Provider::Route, "load_current_resource" do context "on linux" do before do @@ -188,15 +187,15 @@ describe Chef::Provider::Route do describe Chef::Provider::Route, "config_file_contents for action_add" do it "should include a netmask when a one is specified" do allow(@new_resource).to receive(:netmask).and_return("255.255.0.0") - expect(@provider.config_file_contents(:add, { :target => @new_resource.target, :netmask => @new_resource.netmask})).to match(/\/\d{1,2}.*\n$/) + expect(@provider.config_file_contents(:add, { :target => @new_resource.target, :netmask => @new_resource.netmask })).to match(/\/\d{1,2}.*\n$/) end it "should not include a netmask when a one is specified" do - expect(@provider.config_file_contents(:add, { :target => @new_resource.target})).not_to match(/\/\d{1,2}.*\n$/) + expect(@provider.config_file_contents(:add, { :target => @new_resource.target })).not_to match(/\/\d{1,2}.*\n$/) end it "should include ' via $gateway ' when a gateway is specified" do - expect(@provider.config_file_contents(:add, { :target => @new_resource.target, :gateway => @new_resource.gateway})).to match(/\svia\s#{Regexp.escape(@new_resource.gateway.to_s)}\n/) + expect(@provider.config_file_contents(:add, { :target => @new_resource.target, :gateway => @new_resource.gateway })).to match(/\svia\s#{Regexp.escape(@new_resource.gateway.to_s)}\n/) end it "should not include ' via $gateway ' when a gateway is not specified" do diff --git a/spec/unit/provider/ruby_block_spec.rb b/spec/unit/provider/ruby_block_spec.rb index d9fd3e2548..b49aef9243 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 { $evil_global_evil_laugh = :mwahahaha } @provider = Chef::Provider::RubyBlock.new(@new_resource, @run_context) end @@ -43,4 +43,3 @@ describe Chef::Provider::RubyBlock, "initialize" do expect(@new_resource).to be_updated end end - diff --git a/spec/unit/provider/script_spec.rb b/spec/unit/provider/script_spec.rb index ef1ccf4ea5..38ef2c96e7 100644 --- a/spec/unit/provider/script_spec.rb +++ b/spec/unit/provider/script_spec.rb @@ -72,7 +72,7 @@ describe Chef::Provider::Script, "action_run" do describe "when writing the script to the file" do it "should put the contents of the script in the temp file" do - allow(provider).to receive(:unlink_script_file) # stub to avoid remove + allow(provider).to receive(:unlink_script_file) # stub to avoid remove provider.action_run expect(IO.read(tempfile.path)).to eq("$| = 1; print 'i like beans'\n") provider.unlink_script_file @@ -110,5 +110,4 @@ describe Chef::Provider::Script, "action_run" do end end end - end diff --git a/spec/unit/provider/service/aix_service_spec.rb b/spec/unit/provider/service/aix_service_spec.rb index 78c0ed3bb3..802ccee2c7 100644 --- a/spec/unit/provider/service/aix_service_spec.rb +++ b/spec/unit/provider/service/aix_service_spec.rb @@ -193,4 +193,3 @@ describe Chef::Provider::Service::Aix do end end end - diff --git a/spec/unit/provider/service/aixinit_service_spec.rb b/spec/unit/provider/service/aixinit_service_spec.rb index 085652a6a4..09c177903b 100644 --- a/spec/unit/provider/service/aixinit_service_spec.rb +++ b/spec/unit/provider/service/aixinit_service_spec.rb @@ -21,7 +21,7 @@ require "spec_helper" describe Chef::Provider::Service::AixInit do before(:each) do @node = Chef::Node.new - @node.automatic_attrs[:command] = {:ps => "fuuuu"} + @node.automatic_attrs[:command] = { :ps => "fuuuu" } @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @@ -102,7 +102,7 @@ describe Chef::Provider::Service::AixInit do context "when the service doesn't set a priority" do it "creates symlink with status S" do - expect(@provider).to receive(:create_symlink).with(2,"S","") + expect(@provider).to receive(:create_symlink).with(2, "S", "") @provider.enable_service end @@ -114,7 +114,7 @@ describe Chef::Provider::Service::AixInit do end it "creates a symlink with status S and a priority" do - expect(@provider).to receive(:create_symlink).with(2,"S",75) + expect(@provider).to receive(:create_symlink).with(2, "S", 75) @provider.enable_service end @@ -122,13 +122,13 @@ describe Chef::Provider::Service::AixInit do context "when the service sets complex priorities (hash)" do before do - priority = {2 => [:start, 20], 3 => [:stop, 10]} + priority = { 2 => [:start, 20], 3 => [:stop, 10] } @new_resource.priority(priority) end it "create symlink with status start (S) or stop (K) and a priority " do - expect(@provider).to receive(:create_symlink).with(2,"S",20) - expect(@provider).to receive(:create_symlink).with(3,"K",10) + expect(@provider).to receive(:create_symlink).with(2, "S", 20) + expect(@provider).to receive(:create_symlink).with(3, "K", 10) @provider.enable_service end @@ -142,7 +142,7 @@ describe Chef::Provider::Service::AixInit do context "when the service doesn't set a priority" do it "creates symlinks with status stop (K)" do - expect(@provider).to receive(:create_symlink).with(2,"K","") + expect(@provider).to receive(:create_symlink).with(2, "K", "") @provider.disable_service end @@ -154,7 +154,7 @@ describe Chef::Provider::Service::AixInit do end it "create symlink with status stop (k) and a priority " do - expect(@provider).to receive(:create_symlink).with(2,"K",25) + expect(@provider).to receive(:create_symlink).with(2, "K", 25) @provider.disable_service end @@ -162,12 +162,12 @@ describe Chef::Provider::Service::AixInit do context "when the service sets complex priorities (hash)" do before do - @priority = {2 => [:start, 20], 3 => [:stop, 10]} + @priority = { 2 => [:start, 20], 3 => [:stop, 10] } @new_resource.priority(@priority) end it "create symlink with status stop (k) and a priority " do - expect(@provider).to receive(:create_symlink).with(3,"K",90) + expect(@provider).to receive(:create_symlink).with(3, "K", 90) @provider.disable_service end @@ -183,17 +183,17 @@ describe Chef::Provider::Service::AixInit do end it "the service is enabled" do - expect(@provider.current_resource).to receive(:enabled).with(true) - expect(@provider.current_resource).to receive(:priority).with(20) + expect(@provider.current_resource).to receive(:enabled).with(true) + expect(@provider.current_resource).to receive(:priority).with(20) - @provider.set_current_resource_attributes + @provider.set_current_resource_attributes end end context "when rc2.d contains only stop script" do before do files = ["/etc/rc.d/rc2.d/K20apache"] - @priority = {2 => [:stop, 20]} + @priority = { 2 => [:stop, 20] } allow(Dir).to receive(:glob).with(["/etc/rc.d/rc2.d/[SK][0-9][0-9]#{@new_resource.service_name}", "/etc/rc.d/rc2.d/[SK]chef"]).and_return(files) end @@ -210,7 +210,7 @@ describe Chef::Provider::Service::AixInit do @files = ["/etc/rc.d/rc2.d/S20apache", "/etc/rc.d/rc2.d/K80apache"] # FIXME: this is clearly buggy the duplicated keys do not work #@priority = {2 => [:start, 20], 2 => [:stop, 80]} - @priority = {2 => [:stop, 80]} + @priority = { 2 => [:stop, 80] } allow(Dir).to receive(:glob).with(["/etc/rc.d/rc2.d/[SK][0-9][0-9]#{@new_resource.service_name}", "/etc/rc.d/rc2.d/[SK]chef"]).and_return(@files) end @@ -230,17 +230,17 @@ describe Chef::Provider::Service::AixInit do end it "the service is enabled" do - expect(@provider.current_resource).to receive(:enabled).with(true) - expect(@provider.current_resource).to receive(:priority).with("") + expect(@provider.current_resource).to receive(:enabled).with(true) + expect(@provider.current_resource).to receive(:priority).with("") - @provider.set_current_resource_attributes + @provider.set_current_resource_attributes end end context "when rc2.d contains only stop script (without priority)" do before do files = ["/etc/rc.d/rc2.d/Kapache"] - @priority = {2 => [:stop, ""]} + @priority = { 2 => [:stop, ""] } allow(Dir).to receive(:glob).with(["/etc/rc.d/rc2.d/[SK][0-9][0-9]#{@new_resource.service_name}", "/etc/rc.d/rc2.d/[SK]#{@new_resource.service_name}"]).and_return(files) end @@ -257,7 +257,7 @@ describe Chef::Provider::Service::AixInit do files = ["/etc/rc.d/rc2.d/Sapache", "/etc/rc.d/rc2.d/Kapache"] # FIXME: this is clearly buggy the duplicated keys do not work #@priority = {2 => [:start, ''], 2 => [:stop, '']} - @priority = {2 => [:stop, ""]} + @priority = { 2 => [:stop, ""] } allow(Dir).to receive(:glob).with(["/etc/rc.d/rc2.d/[SK][0-9][0-9]#{@new_resource.service_name}", "/etc/rc.d/rc2.d/[SK]#{@new_resource.service_name}"]).and_return(files) end diff --git a/spec/unit/provider/service/arch_service_spec.rb b/spec/unit/provider/service/arch_service_spec.rb index 9272a8bd96..666a0d1fa8 100644 --- a/spec/unit/provider/service/arch_service_spec.rb +++ b/spec/unit/provider/service/arch_service_spec.rb @@ -26,14 +26,14 @@ require "ostruct" describe Chef::Provider::Service::Arch, "load_current_resource" do before(:each) do @node = Chef::Node.new - @node.automatic_attrs[:command] = {:ps => "ps -ef"} + @node.automatic_attrs[:command] = { :ps => "ps -ef" } @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @new_resource = Chef::Resource::Service.new("chef") @new_resource.pattern("chef") - @new_resource.supports({:status => false}) + @new_resource.supports({ :status => false }) @provider = Chef::Provider::Service::Arch.new(@new_resource, @run_context) @@ -51,7 +51,7 @@ describe Chef::Provider::Service::Arch, "load_current_resource" do describe "when the service supports status" do before do - @new_resource.supports({:status => true}) + @new_resource.supports({ :status => true }) end it "should run '/etc/rc.d/service_name status'" do @@ -76,7 +76,6 @@ describe Chef::Provider::Service::Arch, "load_current_resource" do @provider.load_current_resource expect(@provider.current_resource.running).to be_falsey end - end describe "when a status command has been specified" do @@ -88,18 +87,17 @@ describe Chef::Provider::Service::Arch, "load_current_resource" do expect(@provider).to receive(:shell_out).with("/etc/rc.d/chefhasmonkeypants status").and_return(OpenStruct.new(:exitstatus => 0)) @provider.load_current_resource end - end it "should raise error if the node has a nil ps attribute and no other means to get status" do - @node.automatic_attrs[:command] = {:ps => nil} + @node.automatic_attrs[:command] = { :ps => nil } @provider.define_resource_requirements @provider.action = :start expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::Service) end it "should raise error if the node has an empty ps attribute and no other means to get status" do - @node.automatic_attrs[:command] = {:ps => ""} + @node.automatic_attrs[:command] = { :ps => "" } @provider.define_resource_requirements @provider.action = :start expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::Service) @@ -125,7 +123,7 @@ DEFAULT_PS @status = double("Status", :exitstatus => 0, :stdout => @stdout) allow(@provider).to receive(:shell_out!).and_return(@status) - @node.automatic_attrs[:command] = {:ps => "ps -ef"} + @node.automatic_attrs[:command] = { :ps => "ps -ef" } end it "determines the service is running when it appears in ps" do @@ -274,7 +272,7 @@ RUNNING_PS # end it "should call 'restart' on the service_name if the resource supports it" do - allow(@new_resource).to receive(:supports).and_return({:restart => true}) + allow(@new_resource).to receive(:supports).and_return({ :restart => true }) expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/#{@new_resource.service_name} restart") @provider.restart_service() end @@ -309,7 +307,7 @@ RUNNING_PS # end it "should call 'reload' on the service if it supports it" do - allow(@new_resource).to receive(:supports).and_return({:reload => true}) + allow(@new_resource).to receive(:supports).and_return({ :reload => true }) expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/#{@new_resource.service_name} reload") @provider.reload_service() end diff --git a/spec/unit/provider/service/debian_service_spec.rb b/spec/unit/provider/service/debian_service_spec.rb index 2400676b84..b877eb8d7c 100644 --- a/spec/unit/provider/service/debian_service_spec.rb +++ b/spec/unit/provider/service/debian_service_spec.rb @@ -21,7 +21,7 @@ require "spec_helper" describe Chef::Provider::Service::Debian do before(:each) do @node = Chef::Node.new - @node.automatic_attrs[:command] = {:ps => "fuuuu"} + @node.automatic_attrs[:command] = { :ps => "fuuuu" } @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @@ -114,9 +114,9 @@ describe Chef::Provider::Service::Debian do end end - {"Debian/Lenny and older" => { - "linked" => { - "stdout" => <<-STDOUT, + { "Debian/Lenny and older" => { + "linked" => { + "stdout" => <<-STDOUT, Removing any system startup links for /etc/init.d/chef ... /etc/rc0.d/K20chef /etc/rc1.d/K20chef @@ -126,22 +126,22 @@ describe Chef::Provider::Service::Debian do /etc/rc5.d/S20chef /etc/rc6.d/K20chef STDOUT - "stderr" => "", - "priorities" => { - "0"=>[:stop, "20"], - "1"=>[:stop, "20"], - "2"=>[:start, "20"], - "3"=>[:start, "20"], - "4"=>[:start, "20"], - "5"=>[:start, "20"], - "6"=>[:stop, "20"], - }, - }, - "not linked" => { - "stdout" => " Removing any system startup links for /etc/init.d/chef ...", - "stderr" => "", + "stderr" => "", + "priorities" => { + "0" => [:stop, "20"], + "1" => [:stop, "20"], + "2" => [:start, "20"], + "3" => [:start, "20"], + "4" => [:start, "20"], + "5" => [:start, "20"], + "6" => [:stop, "20"], }, }, + "not linked" => { + "stdout" => " Removing any system startup links for /etc/init.d/chef ...", + "stderr" => "", + }, + }, "Debian/Squeeze and earlier" => { "linked" => { "stdout" => "update-rc.d: using dependency based boot sequencing", @@ -156,13 +156,13 @@ insserv: remove service /etc/init.d/../rc0.d/K20chef-client insserv: dryrun, not creating .depend.boot, .depend.start, and .depend.stop STDERR "priorities" => { - "0"=>[:stop, "20"], - "1"=>[:stop, "20"], - "2"=>[:start, "20"], - "3"=>[:start, "20"], - "4"=>[:start, "20"], - "5"=>[:start, "20"], - "6"=>[:stop, "20"], + "0" => [:stop, "20"], + "1" => [:stop, "20"], + "2" => [:start, "20"], + "3" => [:start, "20"], + "4" => [:start, "20"], + "5" => [:start, "20"], + "6" => [:stop, "20"], }, }, "not linked" => { @@ -181,10 +181,10 @@ insserv: remove service /etc/init.d/../rcS.d/S13rpcbind insserv: dryrun, not creating .depend.boot, .depend.start, and .depend.stop STDERR "priorities" => { - "0"=>[:stop, "06"], - "1"=>[:stop, "06"], - "6"=>[:stop, "06"], - "S"=>[:start, "13"], + "0" => [:stop, "06"], + "1" => [:stop, "06"], + "6" => [:stop, "06"], + "S" => [:start, "13"], }, }, "not linked" => { @@ -243,7 +243,6 @@ insserv: dryrun, not creating .depend.boot, .depend.start, and .depend.stop end end end - end describe "action_enable" do @@ -276,7 +275,7 @@ insserv: dryrun, not creating .depend.boot, .depend.start, and .depend.stop context "when the service is enabled" do before do @current_resource.enabled(true) - @current_resource.priority(80) + @current_resource.priority(80) end context "and the service sets no priority" do diff --git a/spec/unit/provider/service/freebsd_service_spec.rb b/spec/unit/provider/service/freebsd_service_spec.rb index 9729c1ddbc..865a71dd9e 100644 --- a/spec/unit/provider/service/freebsd_service_spec.rb +++ b/spec/unit/provider/service/freebsd_service_spec.rb @@ -27,14 +27,14 @@ end describe Chef::Provider::Service::Freebsd do let(:node) do node = Chef::Node.new - node.automatic_attrs[:command] = {:ps => "ps -ax"} + node.automatic_attrs[:command] = { :ps => "ps -ax" } node end let(:new_resource) do new_resource = Chef::Resource::Service.new("apache22") new_resource.pattern("httpd") - new_resource.supports({:status => false}) + new_resource.supports({ :status => false }) new_resource end @@ -46,7 +46,7 @@ describe Chef::Provider::Service::Freebsd do let(:provider) do events = Chef::EventDispatch::Dispatcher.new run_context = Chef::RunContext.new(node, {}, events) - provider = Chef::Provider::Service::Freebsd.new(new_resource,run_context) + provider = Chef::Provider::Service::Freebsd.new(new_resource, run_context) provider.action = :start provider end @@ -115,7 +115,7 @@ describe Chef::Provider::Service::Freebsd do let(:status) { double(:stdout => "", :exitstatus => 0) } before do - new_resource.supports({:status => true}) + new_resource.supports({ :status => true }) end it "should run '/etc/init.d/service_name status'" do @@ -147,7 +147,7 @@ PS_SAMPLE let(:status) { double(:stdout => stdout, :exitstatus => 0) } before do - node.automatic_attrs[:command] = {:ps => "ps -ax"} + node.automatic_attrs[:command] = { :ps => "ps -ax" } end it "should shell_out! the node's ps command" do @@ -191,7 +191,7 @@ PS_SAMPLE context "when ps is empty string" do before do - node.automatic_attrs[:command] = {:ps => ""} + node.automatic_attrs[:command] = { :ps => "" } end it "should set running to nil" do @@ -424,7 +424,6 @@ EOF it "should return the current resource" do expect(provider.load_current_resource).to eql(current_resource) end - end context "when testing actions" do @@ -465,7 +464,7 @@ EOF describe Chef::Provider::Service::Freebsd, "restart_service" do it "should call 'restart' on the service_name if the resource supports it" do - new_resource.supports({:restart => true}) + new_resource.supports({ :restart => true }) expect(provider).to receive(:shell_out_with_systems_locale!).with("/usr/local/etc/rc.d/#{new_resource.service_name} fastrestart") provider.restart_service() end diff --git a/spec/unit/provider/service/gentoo_service_spec.rb b/spec/unit/provider/service/gentoo_service_spec.rb index a00ca7aadd..00d11b2049 100644 --- a/spec/unit/provider/service/gentoo_service_spec.rb +++ b/spec/unit/provider/service/gentoo_service_spec.rb @@ -96,10 +96,8 @@ describe Chef::Provider::Service::Gentoo do @provider.load_current_resource expect(@current_resource.enabled).to be_falsey end - end end - end it "should return the current_resource" do @@ -120,7 +118,6 @@ describe Chef::Provider::Service::Gentoo do @provider.load_current_resource expect(@provider.supports[:reload]).to be_falsey end - end describe "action_methods" do @@ -140,5 +137,4 @@ describe Chef::Provider::Service::Gentoo do end end end - end diff --git a/spec/unit/provider/service/init_service_spec.rb b/spec/unit/provider/service/init_service_spec.rb index 47c1aa7215..262d16d677 100644 --- a/spec/unit/provider/service/init_service_spec.rb +++ b/spec/unit/provider/service/init_service_spec.rb @@ -21,7 +21,7 @@ require "spec_helper" describe Chef::Provider::Service::Init, "load_current_resource" do before(:each) do @node = Chef::Node.new - @node.automatic_attrs[:command] = {:ps => "ps -ef"} + @node.automatic_attrs[:command] = { :ps => "ps -ef" } @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @@ -53,7 +53,7 @@ PS describe "when the service supports status" do before do - @new_resource.supports({:status => true}) + @new_resource.supports({ :status => true }) end it "should run '/etc/init.d/service_name status'" do @@ -90,7 +90,6 @@ PS expect(@provider).to receive(:shell_out).with("/etc/init.d/chefhasmonkeypants status").and_return(@status) @provider.load_current_resource end - end describe "when an init command has been specified" do @@ -103,13 +102,11 @@ PS expect(@provider).to receive(:shell_out_with_systems_locale!).with("/opt/chef-server/service/erchef start") @provider.start_service end - end describe "when the node has not specified a ps command" do - it "should raise an error if the node has a nil ps attribute" do - @node.automatic_attrs[:command] = {:ps => nil} + @node.automatic_attrs[:command] = { :ps => nil } @provider.load_current_resource @provider.action = :start @provider.define_resource_requirements @@ -117,13 +114,12 @@ PS end it "should raise an error if the node has an empty ps attribute" do - @node.automatic_attrs[:command] = {:ps => ""} + @node.automatic_attrs[:command] = { :ps => "" } @provider.load_current_resource @provider.action = :start @provider.define_resource_requirements expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::Service) end - end describe "when we have a 'ps' attribute" do @@ -189,7 +185,7 @@ RUNNING_PS describe "when restarting a service" do it "should call 'restart' on the service_name if the resource supports it" do - @new_resource.supports({:restart => true}) + @new_resource.supports({ :restart => true }) expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/#{@new_resource.service_name} restart") @provider.restart_service() end @@ -210,7 +206,7 @@ RUNNING_PS describe "when reloading a service" do it "should call 'reload' on the service if it supports it" do - @new_resource.supports({:reload => true}) + @new_resource.supports({ :reload => true }) expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/chef reload") @provider.reload_service() end diff --git a/spec/unit/provider/service/insserv_service_spec.rb b/spec/unit/provider/service/insserv_service_spec.rb index de0c546ff1..cf2f3e04d7 100644 --- a/spec/unit/provider/service/insserv_service_spec.rb +++ b/spec/unit/provider/service/insserv_service_spec.rb @@ -23,7 +23,7 @@ describe Chef::Provider::Service::Insserv do @node = Chef::Node.new @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) - @node.automatic_attrs[:command] = {:ps => "ps -ax"} + @node.automatic_attrs[:command] = { :ps => "ps -ax" } @new_resource = Chef::Resource::Service.new("initgrediant") @current_resource = Chef::Resource::Service.new("initgrediant") @@ -55,7 +55,6 @@ describe Chef::Provider::Service::Insserv do expect(@provider.current_resource.enabled).to be_falsey end end - end describe "enable_service" do diff --git a/spec/unit/provider/service/invokercd_service_spec.rb b/spec/unit/provider/service/invokercd_service_spec.rb index 6503e542f9..add74ac183 100644 --- a/spec/unit/provider/service/invokercd_service_spec.rb +++ b/spec/unit/provider/service/invokercd_service_spec.rb @@ -21,7 +21,7 @@ require "spec_helper" describe Chef::Provider::Service::Invokercd, "load_current_resource" do before(:each) do @node = Chef::Node.new - @node.automatic_attrs[:command] = {:ps => "ps -ef"} + @node.automatic_attrs[:command] = { :ps => "ps -ef" } @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @@ -53,7 +53,7 @@ PS describe "when the service supports status" do before do - @new_resource.supports({:status => true}) + @new_resource.supports({ :status => true }) end it "should run '/usr/sbin/invoke-rc.d service_name status'" do @@ -90,24 +90,22 @@ PS expect(@provider).to receive(:shell_out).with("/usr/sbin/invoke-rc.d chefhasmonkeypants status").and_return(@status) @provider.load_current_resource end - end describe "when the node has not specified a ps command" do it "should raise error if the node has a nil ps attribute and no other means to get status" do - @node.automatic_attrs[:command] = {:ps => nil} + @node.automatic_attrs[:command] = { :ps => nil } @provider.action = :start @provider.define_resource_requirements expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::Service) end it "should raise error if the node has an empty ps attribute and no other means to get status" do - @node.automatic_attrs[:command] = {:ps => ""} + @node.automatic_attrs[:command] = { :ps => "" } @provider.action = :start @provider.define_resource_requirements expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::Service) end - end describe "when we have a 'ps' attribute" do @@ -176,7 +174,7 @@ RUNNING_PS describe "when restarting a service" do it "should call 'restart' on the service_name if the resource supports it" do - @new_resource.supports({:restart => true}) + @new_resource.supports({ :restart => true }) expect(@provider).to receive(:shell_out_with_systems_locale!).with("/usr/sbin/invoke-rc.d #{@new_resource.service_name} restart") @provider.restart_service() end @@ -197,7 +195,7 @@ RUNNING_PS describe "when reloading a service" do it "should call 'reload' on the service if it supports it" do - @new_resource.supports({:reload => true}) + @new_resource.supports({ :reload => true }) expect(@provider).to receive(:shell_out_with_systems_locale!).with("/usr/sbin/invoke-rc.d chef reload") @provider.reload_service() end diff --git a/spec/unit/provider/service/macosx_spec.rb b/spec/unit/provider/service/macosx_spec.rb index fab7a11248..ffff558e88 100644 --- a/spec/unit/provider/service/macosx_spec.rb +++ b/spec/unit/provider/service/macosx_spec.rb @@ -43,7 +43,7 @@ describe Chef::Provider::Service::Macosx do context "when service name is given as" do let(:node) { Chef::Node.new } - let(:events) {Chef::EventDispatch::Dispatcher.new} + let(:events) { Chef::EventDispatch::Dispatcher.new } let(:run_context) { Chef::RunContext.new(node, {}, events) } let(:provider) { described_class.new(new_resource, run_context) } let(:launchctl_stdout) { StringIO.new } @@ -61,30 +61,30 @@ XML ["Daemon", "Agent"].each do |service_type| ["redis-server", "io.redis.redis-server"].each do |service_name| ["10.9", "10.10", "10.11"].each do |platform_version| - let(:plist) {"/Library/LaunchDaemons/io.redis.redis-server.plist"} + let(:plist) { "/Library/LaunchDaemons/io.redis.redis-server.plist" } let(:session) { StringIO.new } if service_type == "Agent" - let(:plist) {"/Library/LaunchAgents/io.redis.redis-server.plist"} - let(:session) {"-S Aqua "} - let(:su_cmd) {"su -l igor -c"} + let(:plist) { "/Library/LaunchAgents/io.redis.redis-server.plist" } + let(:session) { "-S Aqua " } + let(:su_cmd) { "su -l igor -c" } if platform_version == "10.9" - let(:su_cmd) {"su igor -c"} + let(:su_cmd) { "su igor -c" } end end - let(:service_label) {"io.redis.redis-server"} + let(:service_label) { "io.redis.redis-server" } before do allow(Dir).to receive(:glob).and_return([plist], []) allow(Etc).to receive(:getlogin).and_return("igor") allow(node).to receive(:[]).with("platform_version").and_return(platform_version) cmd = "launchctl list #{service_label}" allow(provider).to receive(:shell_out_with_systems_locale). - with(/(#{su_cmd} '#{cmd}'|#{cmd})/). - and_return(double("Status", + with(/(#{su_cmd} '#{cmd}'|#{cmd})/). + and_return(double("Status", :stdout => launchctl_stdout, :exitstatus => 0)) allow(File).to receive(:exists?).and_return([true], []) allow(provider).to receive(:shell_out_with_systems_locale!). - with(/plutil -convert xml1 -o/). - and_return(double("Status", :stdout => plutil_stdout)) + with(/plutil -convert xml1 -o/). + and_return(double("Status", :stdout => plutil_stdout)) end context "#{service_name} that is a #{service_type} running Osx #{platform_version}" do @@ -92,11 +92,9 @@ XML let!(:current_resource) { Chef::Resource::MacosxService.new(service_name) } describe "#load_current_resource" do - # CHEF-5223 "you can't glob for a file that hasn't been converged # onto the node yet." context "when the plist doesn't exist" do - def run_resource_setup_for_action(action) new_resource.action(action) provider.action = action @@ -109,8 +107,8 @@ XML allow(Dir).to receive(:glob).and_return([]) allow(File).to receive(:exists?).and_return([true], []) allow(provider).to receive(:shell_out!). - with(/plutil -convert xml1 -o/). - and_raise(Mixlib::ShellOut::ShellCommandFailed) + with(/plutil -convert xml1 -o/). + and_raise(Mixlib::ShellOut::ShellCommandFailed) end it "works for action :nothing" do @@ -166,7 +164,7 @@ SVC_LIST allow(File).to receive(:exists?).and_return([true], []) end it "should throw an exception when reload action is attempted" do - expect {provider.run_action(:reload)}.to raise_error(Chef::Exceptions::UnsupportedAction) + expect { provider.run_action(:reload) }.to raise_error(Chef::Exceptions::UnsupportedAction) end end context "when launchctl returns empty service pid" do @@ -265,8 +263,8 @@ SVC_LIST it "starts service via launchctl if service found" do cmd = "launchctl load -w " + session + plist expect(provider).to receive(:shell_out_with_systems_locale). - with(/(#{su_cmd} .#{cmd}.|#{cmd})/). - and_return(0) + with(/(#{su_cmd} .#{cmd}.|#{cmd})/). + and_return(0) provider.start_service end @@ -295,10 +293,10 @@ SVC_LIST end it "stops the service via launchctl if service found" do - cmd = "launchctl unload -w "+ plist + cmd = "launchctl unload -w " + plist expect(provider).to receive(:shell_out_with_systems_locale). - with(/(#{su_cmd} .#{cmd}.|#{cmd})/). - and_return(0) + with(/(#{su_cmd} .#{cmd}.|#{cmd})/). + and_return(0) provider.stop_service end diff --git a/spec/unit/provider/service/openbsd_service_spec.rb b/spec/unit/provider/service/openbsd_service_spec.rb index 73e0960901..dc1496ff26 100644 --- a/spec/unit/provider/service/openbsd_service_spec.rb +++ b/spec/unit/provider/service/openbsd_service_spec.rb @@ -31,11 +31,11 @@ end describe Chef::Provider::Service::Openbsd do let(:node) do node = Chef::Node.new - node.automatic_attrs[:command] = {:ps => "ps -ax"} + node.automatic_attrs[:command] = { :ps => "ps -ax" } node end - let(:supports) { {:status => false} } + let(:supports) { { :status => false } } let(:new_resource) do new_resource = Chef::Resource::Service.new("sndiod") @@ -54,7 +54,7 @@ describe Chef::Provider::Service::Openbsd do run_context = Chef::RunContext.new(node, {}, events) allow(::File).to receive(:read).with("/etc/rc.conf").and_return("") allow(::File).to receive(:read).with("/etc/rc.conf.local").and_return("") - provider = Chef::Provider::Service::Openbsd.new(new_resource,run_context) + provider = Chef::Provider::Service::Openbsd.new(new_resource, run_context) provider.action = :start provider end @@ -265,7 +265,6 @@ describe Chef::Provider::Service::Openbsd do it "should return the current resource" do expect(provider.load_current_resource).to eql(current_resource) end - end context "when testing actions" do @@ -541,5 +540,4 @@ describe Chef::Provider::Service::Openbsd do end end end - end diff --git a/spec/unit/provider/service/redhat_spec.rb b/spec/unit/provider/service/redhat_spec.rb index 110a38d04b..ac96464b6a 100644 --- a/spec/unit/provider/service/redhat_spec.rb +++ b/spec/unit/provider/service/redhat_spec.rb @@ -23,7 +23,7 @@ shared_examples_for "define_resource_requirements_common" do it "should raise an error if /sbin/chkconfig does not exist" do allow(File).to receive(:exists?).with("/sbin/chkconfig").and_return(false) allow(@provider).to receive(:shell_out).with("/sbin/service chef status").and_raise(Errno::ENOENT) - allow(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_raise(Errno::ENOENT) + allow(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0, 1]).and_raise(Errno::ENOENT) @provider.load_current_resource @provider.define_resource_requirements expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::Service) @@ -33,7 +33,7 @@ shared_examples_for "define_resource_requirements_common" do status = double("Status", :exitstatus => 0, :stdout => "" , :stderr => "") expect(@provider).to receive(:shell_out).with("/sbin/service chef status").and_return(status) chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "", :stderr => "service chef supports chkconfig, but is not referenced in any runlevel (run 'chkconfig --add chef')") - expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) + expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0, 1]).and_return(chkconfig) @provider.load_current_resource @provider.define_resource_requirements expect { @provider.process_resource_requirements }.not_to raise_error @@ -41,10 +41,9 @@ shared_examples_for "define_resource_requirements_common" do end describe "Chef::Provider::Service::Redhat" do - before(:each) do @node = Chef::Node.new - @node.automatic_attrs[:command] = {:ps => "foo"} + @node.automatic_attrs[:command] = { :ps => "foo" } @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @@ -71,7 +70,7 @@ describe "Chef::Provider::Service::Redhat" do it "sets supports[:status] to true by default" do chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:off 2:off 3:off 4:off 5:on 6:off", :stderr => "") - expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) + expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0, 1]).and_return(chkconfig) expect(@provider.service_missing).to be false @provider.load_current_resource expect(@provider.supports[:status]).to be true @@ -81,7 +80,7 @@ describe "Chef::Provider::Service::Redhat" do @new_resource.supports( { status: false } ) @new_resource.pattern "myservice" chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:off 2:off 3:off 4:off 5:on 6:off", :stderr => "") - expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) + expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0, 1]).and_return(chkconfig) foo_out = double("ps_command", :exitstatus => 0, :stdout => "a line that matches myservice", :stderr => "") expect(@provider).to receive(:shell_out!).with("foo").and_return(foo_out) expect(@provider.service_missing).to be false @@ -92,7 +91,7 @@ describe "Chef::Provider::Service::Redhat" do it "sets the current enabled status to true if the service is enabled for any run level" do chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:off 2:off 3:off 4:off 5:on 6:off", :stderr => "") - expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) + expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0, 1]).and_return(chkconfig) expect(@provider.service_missing).to be false @provider.load_current_resource expect(@current_resource.enabled).to be true @@ -100,7 +99,7 @@ describe "Chef::Provider::Service::Redhat" do it "sets the current enabled status to false if the regex does not match" do chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:off 2:off 3:off 4:off 5:off 6:off", :stderr => "") - expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) + expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0, 1]).and_return(chkconfig) expect(@provider.service_missing).to be false expect(@provider.load_current_resource).to eql(@current_resource) expect(@current_resource.enabled).to be false @@ -109,7 +108,7 @@ describe "Chef::Provider::Service::Redhat" do it "sets the current enabled status to true if the service is enabled at specified run levels" do @new_resource.run_levels([1, 2]) chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:on 2:on 3:off 4:off 5:off 6:off", :stderr => "") - expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) + expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0, 1]).and_return(chkconfig) expect(@provider.service_missing).to be false @provider.load_current_resource expect(@current_resource.enabled).to be true @@ -119,7 +118,7 @@ describe "Chef::Provider::Service::Redhat" do it "sets the current enabled status to false if the service is enabled at a run level it should not" do @new_resource.run_levels([1, 2]) chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:on 2:on 3:on 4:off 5:off 6:off", :stderr => "") - expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) + expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0, 1]).and_return(chkconfig) expect(@provider.service_missing).to be false @provider.load_current_resource expect(@current_resource.enabled).to be false @@ -129,7 +128,7 @@ describe "Chef::Provider::Service::Redhat" do it "sets the current enabled status to false if the service is not enabled at specified run levels" do @new_resource.run_levels([ 2 ]) chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:on 2:off 3:off 4:off 5:off 6:off", :stderr => "") - expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) + expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0, 1]).and_return(chkconfig) expect(@provider.service_missing).to be false @provider.load_current_resource expect(@current_resource.enabled).to be false @@ -144,8 +143,8 @@ describe "Chef::Provider::Service::Redhat" do before do status = double("Status", :exitstatus => 1, :stdout => "", :stderr => "chef: unrecognized service") expect(@provider).to receive(:shell_out).with("/sbin/service chef status").and_return(status) - chkconfig = double("Chkconfig", :existatus=> 1, :stdout => "", :stderr => "error reading information on service chef: No such file or directory") - expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) + chkconfig = double("Chkconfig", :existatus => 1, :stdout => "", :stderr => "error reading information on service chef: No such file or directory") + expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0, 1]).and_return(chkconfig) @provider.load_current_resource @provider.define_resource_requirements end @@ -182,8 +181,8 @@ describe "Chef::Provider::Service::Redhat" do it "should not raise an error if the service does not exist" do status = double("Status", :exitstatus => 1, :stdout => "", :stderr => "chef: unrecognized service") expect(@provider).to receive(:shell_out).with("/sbin/service chef status").and_return(status) - chkconfig = double("Chkconfig", :existatus=> 1, :stdout => "", :stderr => "error reading information on service chef: No such file or directory") - expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) + chkconfig = double("Chkconfig", :existatus => 1, :stdout => "", :stderr => "error reading information on service chef: No such file or directory") + expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0, 1]).and_return(chkconfig) @provider.load_current_resource @provider.define_resource_requirements expect { @provider.process_resource_requirements }.not_to raise_error @@ -232,5 +231,4 @@ describe "Chef::Provider::Service::Redhat" do @provider.disable_service end end - end diff --git a/spec/unit/provider/service/simple_service_spec.rb b/spec/unit/provider/service/simple_service_spec.rb index 2318bed95a..499e0cc2d3 100644 --- a/spec/unit/provider/service/simple_service_spec.rb +++ b/spec/unit/provider/service/simple_service_spec.rb @@ -21,7 +21,7 @@ require "spec_helper" describe Chef::Provider::Service::Simple, "load_current_resource" do before(:each) do @node = Chef::Node.new - @node.automatic_attrs[:command] = {:ps => "ps -ef"} + @node.automatic_attrs[:command] = { :ps => "ps -ef" } @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @@ -51,13 +51,13 @@ NOMOCKINGSTRINGSPLZ end it "should raise error if the node has a nil ps attribute and no other means to get status" do - @node.automatic_attrs[:command] = {:ps => nil} + @node.automatic_attrs[:command] = { :ps => nil } @provider.define_resource_requirements expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::Service) end it "should raise error if the node has an empty ps attribute and no other means to get status" do - @node.automatic_attrs[:command] = {:ps => ""} + @node.automatic_attrs[:command] = { :ps => "" } @provider.define_resource_requirements expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::Service) end diff --git a/spec/unit/provider/service/solaris_smf_service_spec.rb b/spec/unit/provider/service/solaris_smf_service_spec.rb index 94d123ef1a..2a9b609ec6 100644 --- a/spec/unit/provider/service/solaris_smf_service_spec.rb +++ b/spec/unit/provider/service/solaris_smf_service_spec.rb @@ -20,7 +20,7 @@ require "spec_helper" describe Chef::Provider::Service::Solaris do before(:each) do - @node =Chef::Node.new + @node = Chef::Node.new @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @@ -108,7 +108,6 @@ describe Chef::Provider::Service::Solaris do end describe "on a host with /bin/svcs and /usr/sbin/svcadm" do - before do allow(File).to receive(:executable?).with("/bin/svcs").and_return(true) allow(File).to receive(:executable?).with("/usr/sbin/svcadm").and_return(true) @@ -116,18 +115,18 @@ describe Chef::Provider::Service::Solaris do describe "when discovering the current service state" do it "should create a current resource with the name of the new resource" do - expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", {:returns=>[0, 1]}).and_return(@enabled_svc_status) + expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", { :returns => [0, 1] }).and_return(@enabled_svc_status) expect(Chef::Resource::Service).to receive(:new).and_return(@current_resource) @provider.load_current_resource end it "should return the current resource" do - expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", {:returns=>[0, 1]}).and_return(@enabled_svc_status) + expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", { :returns => [0, 1] }).and_return(@enabled_svc_status) expect(@provider.load_current_resource).to eql(@current_resource) end it "should call '/bin/svcs -l service_name'" do - expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", {:returns=>[0, 1]}).and_return(@enabled_svc_status) + expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", { :returns => [0, 1] }).and_return(@enabled_svc_status) @provider.load_current_resource end @@ -162,7 +161,7 @@ describe Chef::Provider::Service::Solaris do end it "should call svcadm enable -s chef" do - expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", {:returns=>[0, 1]}).and_return(@enabled_svc_status) + expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", { :returns => [0, 1] }).and_return(@enabled_svc_status) expect(@provider).not_to receive(:shell_out!).with("/usr/sbin/svcadm", "clear", @current_resource.service_name) expect(@provider).to receive(:shell_out!).with("/usr/sbin/svcadm", "enable", "-s", @current_resource.service_name).and_return(@success) @provider.load_current_resource @@ -172,7 +171,7 @@ describe Chef::Provider::Service::Solaris do end it "should call svcadm enable -s chef for start_service" do - expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", {:returns=>[0, 1]}).and_return(@enabled_svc_status) + expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", { :returns => [0, 1] }).and_return(@enabled_svc_status) expect(@provider).not_to receive(:shell_out!).with("/usr/sbin/svcadm", "clear", @current_resource.service_name) expect(@provider).to receive(:shell_out!).with("/usr/sbin/svcadm", "enable", "-s", @current_resource.service_name).and_return(@success) @provider.load_current_resource @@ -182,7 +181,7 @@ describe Chef::Provider::Service::Solaris do it "should call svcadm clear chef for start_service when state maintenance" do # we are in maint mode - expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", {:returns=>[0, 1]}).and_return(@maintenance_svc_status) + expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", { :returns => [0, 1] }).and_return(@maintenance_svc_status) expect(@provider).to receive(:shell_out!).with("/usr/sbin/svcadm", "clear", @current_resource.service_name).and_return(@success) expect(@provider).to receive(:shell_out!).with("/usr/sbin/svcadm", "enable", "-s", @current_resource.service_name).and_return(@success) @@ -191,7 +190,7 @@ describe Chef::Provider::Service::Solaris do expect(@provider.enable_service).to be_truthy # now we are enabled - expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", {:returns=>[0, 1]}).and_return(@enabled_svc_status) + expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", { :returns => [0, 1] }).and_return(@enabled_svc_status) @provider.load_current_resource expect(@current_resource.enabled).to be_truthy @@ -204,7 +203,7 @@ describe Chef::Provider::Service::Solaris do end it "should call svcadm disable -s chef" do - expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", {:returns=>[0, 1]}).and_return(@disabled_svc_status) + expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", { :returns => [0, 1] }).and_return(@disabled_svc_status) expect(@provider).to receive(:shell_out!).with("/usr/sbin/svcadm", "disable", "-s", "chef").and_return(@success) @provider.load_current_resource expect(@provider.disable_service).to be_truthy @@ -212,32 +211,30 @@ describe Chef::Provider::Service::Solaris do end it "should call svcadm disable -s chef for stop_service" do - expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", {:returns=>[0, 1]}).and_return(@disabled_svc_status) + expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", { :returns => [0, 1] }).and_return(@disabled_svc_status) expect(@provider).to receive(:shell_out!).with("/usr/sbin/svcadm", "disable", "-s", "chef").and_return(@success) @provider.load_current_resource expect(@provider.stop_service).to be_truthy expect(@current_resource.enabled).to be_falsey end - end describe "when reloading the service" do before(:each) do @provider.current_resource = @current_resource - allow(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", {:returns=>[0, 1]}).and_return(@enabled_svc_status) + allow(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", { :returns => [0, 1] }).and_return(@enabled_svc_status) end it "should call svcadm refresh chef" do expect(@provider).to receive(:shell_out!).with("/usr/sbin/svcadm", "refresh", "chef") @provider.reload_service end - end describe "when the service doesn't exist" do before(:each) do @provider.current_resource = @current_resource - expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", {:returns=>[0, 1]}).and_return(@no_svc_status) + expect(@provider).to receive(:shell_out!).with("/bin/svcs", "-l", "chef", { :returns => [0, 1] }).and_return(@no_svc_status) end it "should be marked not running" do @@ -249,7 +246,6 @@ describe Chef::Provider::Service::Solaris do @provider.service_status expect(@current_resource.enabled).to be_falsey end - end end end diff --git a/spec/unit/provider/service/systemd_service_spec.rb b/spec/unit/provider/service/systemd_service_spec.rb index b445d93aeb..416deb5b30 100644 --- a/spec/unit/provider/service/systemd_service_spec.rb +++ b/spec/unit/provider/service/systemd_service_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::Service::Systemd do - let(:node) { Chef::Node.new } let(:events) { Chef::EventDispatch::Dispatcher.new } @@ -47,7 +46,6 @@ describe Chef::Provider::Service::Systemd do end describe "load_current_resource" do - before(:each) do allow(provider).to receive(:is_active?).and_return(false) allow(provider).to receive(:is_enabled?).and_return(false) @@ -145,7 +143,6 @@ describe Chef::Provider::Service::Systemd do end describe "start and stop service" do - it "should call the start command if one is specified" do allow(new_resource).to receive(:start_command).and_return("/sbin/rsyslog startyousillysally") expect(provider).to receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog startyousillysally") diff --git a/spec/unit/provider/service/upstart_service_spec.rb b/spec/unit/provider/service/upstart_service_spec.rb index e98284a8fd..c999c4c483 100644 --- a/spec/unit/provider/service/upstart_service_spec.rb +++ b/spec/unit/provider/service/upstart_service_spec.rb @@ -24,7 +24,7 @@ describe Chef::Provider::Service::Upstart do end before(:each) do - @node =Chef::Node.new + @node = Chef::Node.new @node.name("upstarter") @node.automatic_attrs[:platform] = "ubuntu" @node.automatic_attrs[:platform_version] = "9.10" @@ -66,7 +66,7 @@ describe Chef::Provider::Service::Upstart do describe "load_current_resource" do before(:each) do - @node.automatic_attrs[:command] = {:ps => "ps -ax"} + @node.automatic_attrs[:command] = { :ps => "ps -ax" } @current_resource = Chef::Resource::Service.new("rsyslog") allow(Chef::Resource::Service).to receive(:new).and_return(@current_resource) @@ -223,7 +223,6 @@ describe Chef::Provider::Service::Upstart do it "should return the current resource" do expect(@provider.load_current_resource).to eql(@current_resource) end - end describe "enable and disable service" do @@ -251,7 +250,6 @@ describe Chef::Provider::Service::Upstart do expect(@file).to receive(:write_file) @provider.disable_service() end - end describe "start and stop service" do diff --git a/spec/unit/provider/service/windows_spec.rb b/spec/unit/provider/service/windows_spec.rb index cbda70c9bb..0ff30a5365 100644 --- a/spec/unit/provider/service/windows_spec.rb +++ b/spec/unit/provider/service/windows_spec.rb @@ -177,7 +177,6 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do end describe Chef::Provider::Service::Windows, "stop_service" do - before(:each) do allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return( double("StatusStruct", :current_state => "running"), @@ -252,11 +251,9 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do end expect(new_resource.updated_by_last_action?).to be_falsey end - end describe Chef::Provider::Service::Windows, "restart_service" do - it "calls the restart command if one is specified" do new_resource.restart_command "sc restart" expect(provider).to receive(:shell_out!).with("#{new_resource.restart_command}") @@ -293,7 +290,6 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do provider.restart_service expect(new_resource.updated_by_last_action?).to be_falsey end - end describe Chef::Provider::Service::Windows, "enable_service" do @@ -369,7 +365,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do end describe Chef::Provider::Service::Windows, "action_configure_startup" do - { :automatic => "auto start", :manual => "demand start", :disabled => "disabled" }.each do |type,win32| + { :automatic => "auto start", :manual => "demand start", :disabled => "disabled" }.each do |type, win32| it "sets the startup type to #{type} if it is something else" do new_resource.startup_type(type) allow(provider).to receive(:current_start_type).and_return("fire") @@ -408,7 +404,6 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do end shared_context "testing private methods" do - let(:private_methods) { described_class.private_instance_methods } diff --git a/spec/unit/provider/service_spec.rb b/spec/unit/provider/service_spec.rb index 5746bcde89..d775297658 100644 --- a/spec/unit/provider/service_spec.rb +++ b/spec/unit/provider/service_spec.rb @@ -49,7 +49,6 @@ describe Chef::Provider::Service do end end - describe "when disabling the service" do it "should disable the service if enabled and set the resource as updated" do allow(@current_resource).to receive(:enabled).and_return(true) diff --git a/spec/unit/provider/subversion_spec.rb b/spec/unit/provider/subversion_spec.rb index 1a92c40ab1..2cc831dfc0 100644 --- a/spec/unit/provider/subversion_spec.rb +++ b/spec/unit/provider/subversion_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::Subversion do - before do @resource = Chef::Resource::Subversion.new("my app") @resource.repository "http://svn.example.org/trunk/" @@ -37,11 +36,10 @@ describe Chef::Provider::Subversion do it "converts resource attributes to options for run_command and popen4" do expect(@provider.run_options).to eq({}) @resource.user "deployninja" - expect(@provider.run_options).to eq({:user => "deployninja"}) + expect(@provider.run_options).to eq({ :user => "deployninja" }) end context "determining the revision of the currently deployed code" do - before do @stdout = double("stdout") @stderr = double("stderr") @@ -64,18 +62,18 @@ describe Chef::Provider::Subversion do "Last Changed Rev: 11410\n" + # Last Changed Rev is preferred to Revision "Last Changed Date: 2009-03-25 06:09:56 -0600 (Wed, 25 Mar 2009)\n\n" expect(::File).to receive(:exist?).at_least(1).times.with("/my/deploy/dir/.svn").and_return(true) - expected_command = ["svn info", {:cwd => "/my/deploy/dir", :returns => [0,1]}] + expected_command = ["svn info", { :cwd => "/my/deploy/dir", :returns => [0, 1] }] expect(@provider).to receive(:shell_out!).with(*expected_command). - and_return(double("ShellOut result", :stdout => example_svn_info, :stderr => "")) + and_return(double("ShellOut result", :stdout => example_svn_info, :stderr => "")) expect(@provider.find_current_revision).to eql("11410") end it "gives nil as the current revision if the deploy dir isn't a SVN working copy" do example_svn_info = "svn: '/tmp/deploydir' is not a working copy\n" expect(::File).to receive(:exist?).with("/my/deploy/dir/.svn").and_return(true) - expected_command = ["svn info", {:cwd => "/my/deploy/dir", :returns => [0,1]}] + expected_command = ["svn info", { :cwd => "/my/deploy/dir", :returns => [0, 1] }] expect(@provider).to receive(:shell_out!).with(*expected_command). - and_return(double("ShellOut result", :stdout => example_svn_info, :stderr => "")) + and_return(double("ShellOut result", :stdout => example_svn_info, :stderr => "")) expect(@provider.find_current_revision).to be_nil end @@ -97,7 +95,6 @@ describe Chef::Provider::Subversion do end context "resolving revisions to an integer" do - before do @stdout = double("stdout") @stderr = double("stderr") @@ -119,26 +116,24 @@ describe Chef::Provider::Subversion do "Last Changed Rev: 11410\n" + # Last Changed Rev is preferred to Revision "Last Changed Date: 2009-03-25 06:09:56 -0600 (Wed, 25 Mar 2009)\n\n" @resource.revision "HEAD" - expected_command = ["svn info http://svn.example.org/trunk/ --no-auth-cache -rHEAD", {:cwd => "/my/deploy/dir", :returns => [0,1]}] + expected_command = ["svn info http://svn.example.org/trunk/ --no-auth-cache -rHEAD", { :cwd => "/my/deploy/dir", :returns => [0, 1] }] expect(@provider).to receive(:shell_out!).with(*expected_command). - and_return(double("ShellOut result", :stdout => example_svn_info, :stderr => "")) + and_return(double("ShellOut result", :stdout => example_svn_info, :stderr => "")) expect(@provider.revision_int).to eql("11410") end it "returns a helpful message if data from `svn info` can't be parsed" do example_svn_info = "some random text from an error message\n" @resource.revision "HEAD" - expected_command = ["svn info http://svn.example.org/trunk/ --no-auth-cache -rHEAD", {:cwd => "/my/deploy/dir", :returns => [0,1]}] + expected_command = ["svn info http://svn.example.org/trunk/ --no-auth-cache -rHEAD", { :cwd => "/my/deploy/dir", :returns => [0, 1] }] expect(@provider).to receive(:shell_out!).with(*expected_command). - and_return(double("ShellOut result", :stdout => example_svn_info, :stderr => "")) - expect {@provider.revision_int}.to raise_error(RuntimeError, "Could not parse `svn info` data: some random text from an error message\n") - + and_return(double("ShellOut result", :stdout => example_svn_info, :stderr => "")) + expect { @provider.revision_int }.to raise_error(RuntimeError, "Could not parse `svn info` data: some random text from an error message\n") end it "responds to :revision_slug as an alias for revision_sha" do expect(@provider).to respond_to(:revision_slug) end - end it "generates a checkout command with default options" do @@ -154,8 +149,7 @@ describe Chef::Provider::Subversion do it "generates a checkout command with arbitrary options" do @resource.svn_arguments "--no-auth-cache" - expect(@provider.checkout_command).to eql("svn checkout --no-auth-cache -q -r12345 "+ - "http://svn.example.org/trunk/ /my/deploy/dir") + expect(@provider.checkout_command).to eql("svn checkout --no-auth-cache -q -r12345 " + "http://svn.example.org/trunk/ /my/deploy/dir") end it "generates a sync command with default options" do @@ -195,14 +189,14 @@ describe Chef::Provider::Subversion do end it "raises an error if the svn checkout command would fail because the enclosing directory doesn't exist" do - expect {@provider.run_action(:sync)}.to raise_error(Chef::Exceptions::MissingParentDirectory) + expect { @provider.run_action(:sync) }.to raise_error(Chef::Exceptions::MissingParentDirectory) end it "should not checkout if the destination exists or is a non empty directory" do allow(::File).to receive(:exist?).with("/my/deploy/dir/.svn").and_return(false) allow(::File).to receive(:exist?).with("/my/deploy/dir").and_return(true) allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) - allow(::Dir).to receive(:entries).with("/my/deploy/dir").and_return([".","..","foo","bar"]) + allow(::Dir).to receive(:entries).with("/my/deploy/dir").and_return([".", "..", "foo", "bar"]) expect(@provider).not_to receive(:checkout_command) @provider.run_action(:checkout) expect(@resource).not_to be_updated @@ -213,7 +207,7 @@ describe Chef::Provider::Subversion do @resource.user "whois" @resource.group "thisis" expected_cmd = "svn checkout -q -r12345 http://svn.example.org/trunk/ /my/deploy/dir" - expect(@provider).to receive(:shell_out!).with(expected_cmd, {user: "whois", group: "thisis"}) + expect(@provider).to receive(:shell_out!).with(expected_cmd, { user: "whois", group: "thisis" }) @provider.run_action(:checkout) expect(@resource).to be_updated end @@ -293,7 +287,5 @@ describe Chef::Provider::Subversion do expect(@provider.export_command).to eql( '"c:/program files (x86)/subversion/svn.exe" export --force -q -r12345 http://svn.example.org/trunk/ /my/deploy/dir') end - end - end diff --git a/spec/unit/provider/template/content_spec.rb b/spec/unit/provider/template/content_spec.rb index 5d885267c7..7dd42ba2a1 100644 --- a/spec/unit/provider/template/content_spec.rb +++ b/spec/unit/provider/template/content_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Provider::Template::Content do - let(:enclosing_directory) { canonicalize_path(Dir.mktmpdir) } @@ -113,7 +112,7 @@ describe Chef::Provider::Template::Content do it "fails when :file_desployment_uses_destdir is set" do Chef::Config[:file_staging_uses_destdir] = true - expect{content.tempfile}.to raise_error(Chef::Exceptions::FileContentStagingError) + expect { content.tempfile }.to raise_error(Chef::Exceptions::FileContentStagingError) end it "returns a tempfile in the tempdir when :file_desployment_uses_destdir is not set" do @@ -164,6 +163,5 @@ helpers.erb #{CHEF_SPEC_DATA}/cookbooks/openldap/templates/default/helpers.erb EOF end - end end diff --git a/spec/unit/provider/template_spec.rb b/spec/unit/provider/template_spec.rb index bf1fcd1cc3..e39d4d8464 100644 --- a/spec/unit/provider/template_spec.rb +++ b/spec/unit/provider/template_spec.rb @@ -23,10 +23,9 @@ require "etc" require "ostruct" require "support/shared/unit/provider/file" - describe Chef::Provider::Template do let(:node) { double("Chef::Node") } - let(:events) { double("Chef::Events").as_null_object } # mock all the methods + let(:events) { double("Chef::Events").as_null_object } # mock all the methods let(:run_context) { double("Chef::RunContext", :node => node, :events => events) } let(:enclosing_directory) { canonicalize_path(File.expand_path(File.join(CHEF_SPEC_DATA, "templates"))) @@ -58,9 +57,8 @@ describe Chef::Provider::Template do it_behaves_like Chef::Provider::File context "when creating the template" do - let(:node) { double("Chef::Node") } - let(:events) { double("Chef::Events").as_null_object } # mock all the methods + let(:events) { double("Chef::Events").as_null_object } # mock all the methods let(:run_context) { double("Chef::RunContext", :node => node, :events => events) } let(:enclosing_directory) { canonicalize_path(File.expand_path(File.join(CHEF_SPEC_DATA, "templates"))) @@ -83,7 +81,6 @@ describe Chef::Provider::Template do allow(File).to receive(:exists?).with("/baz/bar/foo").and_return(false) expect { provider.run_action(:create) }.to raise_error Chef::Mixin::WhyRun::ResourceRequirements::Assertion::AssertionFailure end - end it_behaves_like "a file provider with source field" diff --git a/spec/unit/provider/user/dscl_spec.rb b/spec/unit/provider/user/dscl_spec.rb index 5465e3b225..b46a96d7ae 100644 --- a/spec/unit/provider/user/dscl_spec.rb +++ b/spec/unit/provider/user/dscl_spec.rb @@ -230,7 +230,6 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30" provider.dscl_set_home end - it "raises InvalidHomeDirectory when the resource's home directory doesn't look right" do new_resource.home("epic-fail") expect { provider.dscl_set_home }.to raise_error(Chef::Exceptions::InvalidHomeDirectory) @@ -248,16 +247,16 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30" expect(FileUtils).to receive(:mkdir_p).with("/Users/toor").and_return(true) expect(FileUtils).to receive(:rmdir).with(current_home) - expect(::Dir).to receive(:glob).with("#{CHEF_SPEC_DATA}/old_home_dir/*",::File::FNM_DOTMATCH).and_return(current_home_files) + expect(::Dir).to receive(:glob).with("#{CHEF_SPEC_DATA}/old_home_dir/*", ::File::FNM_DOTMATCH).and_return(current_home_files) expect(FileUtils).to receive(:mv).with(current_home_files, "/Users/toor", :force => true) - expect(FileUtils).to receive(:chown_R).with("toor","23","/Users/toor") + expect(FileUtils).to receive(:chown_R).with("toor", "23", "/Users/toor") expect(provider).to receive(:run_dscl).with("create /Users/toor NFSHomeDirectory '/Users/toor'") provider.dscl_set_home end it "should raise an exception when the systems user template dir (skel) cannot be found" do - allow(::File).to receive(:exists?).and_return(false,false,false) + allow(::File).to receive(:exists?).and_return(false, false, false) expect { provider.dscl_set_home }.to raise_error(Chef::Exceptions::User) end @@ -720,7 +719,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30") end it "should sleep and flush the dscl cache before saving the password" do - expect(provider).to receive(:prepare_password_shadow_info).and_return({ }) + expect(provider).to receive(:prepare_password_shadow_info).and_return({}) mock_shellout = double("Mock::Shellout") allow(mock_shellout).to receive(:run_command) expect(Mixlib::ShellOut).to receive(:new).and_return(mock_shellout) @@ -897,5 +896,4 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30") provider.lock_user end end - end diff --git a/spec/unit/provider/user/pw_spec.rb b/spec/unit/provider/user/pw_spec.rb index dd9564ff1a..1e9fda9f7e 100644 --- a/spec/unit/provider/user/pw_spec.rb +++ b/spec/unit/provider/user/pw_spec.rb @@ -67,7 +67,7 @@ describe Chef::Provider::User::Pw do end it "should set the option for #{attribute} if the new resources #{attribute} is not null, without homedir management" do - allow(@new_resource).to receive(:supports).and_return({:manage_home => false}) + allow(@new_resource).to receive(:supports).and_return({ :manage_home => false }) allow(@new_resource).to receive(attribute).and_return("hola") expect(@provider.set_options).to eql(" #{@new_resource.username} #{option} '#{@new_resource.send(attribute)}'") end @@ -75,7 +75,7 @@ describe Chef::Provider::User::Pw do it "should combine all the possible options" do match_string = " adam" - field_list.sort{ |a,b| a[0] <=> b[0] }.each do |attribute, option| + field_list.sort { |a, b| a[0] <=> b[0] }.each do |attribute, option| allow(@new_resource).to receive(attribute).and_return("hola") match_string << " #{option} 'hola'" end @@ -126,7 +126,7 @@ describe Chef::Provider::User::Pw do end it "should run pw userdel with the new resources user name and -r if manage_home is true" do - expect(@provider).to receive(:run_command).with({ :command => "pw userdel #{@new_resource.username} -r"}).and_return(true) + expect(@provider).to receive(:run_command).with({ :command => "pw userdel #{@new_resource.username} -r" }).and_return(true) @provider.remove_user end end @@ -145,14 +145,14 @@ describe Chef::Provider::User::Pw do describe "when locking the user" do it "should run pw lock with the new resources username" do - expect(@provider).to receive(:run_command).with({ :command => "pw lock #{@new_resource.username}"}) + expect(@provider).to receive(:run_command).with({ :command => "pw lock #{@new_resource.username}" }) @provider.lock_user end end describe "when unlocking the user" do it "should run pw unlock with the new resources username" do - expect(@provider).to receive(:run_command).with({ :command => "pw unlock #{@new_resource.username}"}) + expect(@provider).to receive(:run_command).with({ :command => "pw unlock #{@new_resource.username}" }) @provider.unlock_user end end diff --git a/spec/unit/provider/user/solaris_spec.rb b/spec/unit/provider/user/solaris_spec.rb index 984fab5e8b..e2a2599141 100644 --- a/spec/unit/provider/user/solaris_spec.rb +++ b/spec/unit/provider/user/solaris_spec.rb @@ -26,7 +26,6 @@ require "mixlib/shellout" require "spec_helper" describe Chef::Provider::User::Solaris do - subject(:provider) do p = described_class.new(@new_resource, @run_context) p.current_resource = @current_resource @@ -46,7 +45,6 @@ describe Chef::Provider::User::Solaris do @current_resource = Chef::Resource::User.new("adam", @run_context) @new_resource.password "hocus-pocus" - end it "should use its own shadow file writer to set the password" do @@ -86,7 +84,6 @@ describe Chef::Provider::User::Solaris do @provider.current_resource = @current_resource end describe "when determining if the user is locked" do - # locked shadow lines [ "dave:LK:::::::", diff --git a/spec/unit/provider/user/useradd_spec.rb b/spec/unit/provider/user/useradd_spec.rb index 7c67449a86..4ac2f765aa 100644 --- a/spec/unit/provider/user/useradd_spec.rb +++ b/spec/unit/provider/user/useradd_spec.rb @@ -22,7 +22,6 @@ require "spec_helper" require "chef/provider/user/useradd" describe Chef::Provider::User::Useradd do - subject(:provider) do p = described_class.new(@new_resource, @run_context) p.current_resource = @current_resource diff --git a/spec/unit/provider/user/windows_spec.rb b/spec/unit/provider/user/windows_spec.rb index 37c8655416..f161041ba7 100644 --- a/spec/unit/provider/user/windows_spec.rb +++ b/spec/unit/provider/user/windows_spec.rb @@ -84,7 +84,6 @@ describe Chef::Provider::User::Windows do it "doesn't set the password to be updated" do expect(@provider.set_options).not_to have_key(:password) end - end describe "and the attributes do not match" do @@ -127,19 +126,19 @@ describe Chef::Provider::User::Windows do describe "when creating the user" do it "should call @net_user.add with the return of set_options" do - allow(@provider).to receive(:set_options).and_return(:name=> "monkey") - expect(@net_user).to receive(:add).with(:name=> "monkey") + allow(@provider).to receive(:set_options).and_return(:name => "monkey") + expect(@net_user).to receive(:add).with(:name => "monkey") @provider.create_user end end describe "manage_user" do before(:each) do - allow(@provider).to receive(:set_options).and_return(:name=> "monkey") + allow(@provider).to receive(:set_options).and_return(:name => "monkey") end it "should call @net_user.update with the return of set_options" do - expect(@net_user).to receive(:update).with(:name=> "monkey") + expect(@net_user).to receive(:update).with(:name => "monkey") @provider.manage_user end end diff --git a/spec/unit/provider/user_spec.rb b/spec/unit/provider/user_spec.rb index ce10e8b73d..77554359bb 100644 --- a/spec/unit/provider/user_spec.rb +++ b/spec/unit/provider/user_spec.rb @@ -183,9 +183,8 @@ describe Chef::Provider::User do expect(@provider).to receive(:require).with("shadow") { raise LoadError } @provider.load_current_resource @provider.define_resource_requirements - expect {@provider.process_resource_requirements}.to raise_error Chef::Exceptions::MissingLibrary + expect { @provider.process_resource_requirements }.to raise_error Chef::Exceptions::MissingLibrary end - end end @@ -197,8 +196,8 @@ describe Chef::Provider::User do "uid" => [1000, 1001], "gid" => [1000, 1001], "home" => ["/home/adam", "/Users/adam"], - "shell"=> ["/usr/bin/zsh", "/bin/bash"], - "password"=> ["abcd","12345"], + "shell" => ["/usr/bin/zsh", "/bin/bash"], + "password" => ["abcd", "12345"], } } @@ -380,7 +379,6 @@ describe Chef::Provider::User do end end - describe "action_lock" do before(:each) do allow(@provider).to receive(:load_current_resource) diff --git a/spec/unit/provider/whyrun_safe_ruby_block_spec.rb b/spec/unit/provider/whyrun_safe_ruby_block_spec.rb index ccd3358e2a..55d1f4cc51 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 { $evil_global_evil_laugh = :mwahahaha } @provider = Chef::Provider::WhyrunSafeRubyBlock.new(@new_resource, @run_context) end @@ -42,6 +42,4 @@ describe Chef::Provider::WhyrunSafeRubyBlock, "initialize" do expect(@new_resource).to be_updated Chef::Config[:why_run] = false end - end - diff --git a/spec/unit/provider_resolver_spec.rb b/spec/unit/provider_resolver_spec.rb index 3ac7da5880..453f684207 100644 --- a/spec/unit/provider_resolver_spec.rb +++ b/spec/unit/provider_resolver_spec.rb @@ -513,7 +513,6 @@ describe Chef::ProviderResolver do expect(resolved_provider).to eql(Chef::Provider::Service::Freebsd) end end - end PROVIDERS = diff --git a/spec/unit/provider_spec.rb b/spec/unit/provider_spec.rb index 8dd6724192..9c0ce5444f 100644 --- a/spec/unit/provider_spec.rb +++ b/spec/unit/provider_spec.rb @@ -18,15 +18,15 @@ require "spec_helper" - class NoWhyrunDemonstrator < Chef::Provider attr_reader :system_state_altered def whyrun_supported? false end - def load_current_resource + def load_current_resource end + def action_foo @system_state_altered = true end @@ -55,7 +55,6 @@ class CheckResourceSemanticsDemonstrator < ConvergeActionDemonstrator end end - describe Chef::Provider do before(:each) do @cookbook_collection = Chef::CookbookCollection.new([]) @@ -107,7 +106,7 @@ describe Chef::Provider do it "evals embedded recipes with a pristine resource collection" do @provider.run_context.instance_variable_set(:@resource_collection, "doesn't matter what this is") temporary_collection = nil - snitch = Proc.new {temporary_collection = @run_context.resource_collection} + snitch = Proc.new { temporary_collection = @run_context.resource_collection } @provider.send(:recipe_eval, &snitch) expect(temporary_collection).to be_an_instance_of(Chef::ResourceCollection) expect(@provider.run_context.instance_variable_get(:@resource_collection)).to eq("doesn't matter what this is") @@ -115,7 +114,7 @@ describe Chef::Provider do it "does not re-load recipes when creating the temporary run context" do expect_any_instance_of(Chef::RunContext).not_to receive(:load) - snitch = Proc.new {temporary_collection = @run_context.resource_collection} + snitch = Proc.new { temporary_collection = @run_context.resource_collection } @provider.send(:recipe_eval, &snitch) end @@ -192,8 +191,6 @@ describe Chef::Provider do it "fails with InvalidResourceSpecification when run" do expect { provider.run_action(:foo) }.to raise_error(Chef::Exceptions::InvalidResourceSpecification) end - end end - end diff --git a/spec/unit/recipe_spec.rb b/spec/unit/recipe_spec.rb index fd7fb47ea0..4d502c242a 100644 --- a/spec/unit/recipe_spec.rb +++ b/spec/unit/recipe_spec.rb @@ -23,7 +23,6 @@ require "spec_helper" require "chef/platform/resource_priority_map" describe Chef::Recipe do - let(:cookbook_collection) do cookbook_repo = File.expand_path(File.join(File.dirname(__FILE__), "..", "data", "cookbooks")) cookbook_loader = Chef::CookbookLoader.new(cookbook_repo) @@ -100,7 +99,7 @@ describe Chef::Recipe do end end - expect(run_context.resource_collection.map{|r| r.name}).to eql(["monkey", "dog", "cat"]) + expect(run_context.resource_collection.map { |r| r.name }).to eql(["monkey", "dog", "cat"]) end it "should return the new resource after creating it" do @@ -112,7 +111,6 @@ describe Chef::Recipe do end describe "should locate platform mapped resources" do - it "locate resource for particular platform" do ShaunTheSheep = Class.new(Chef::Resource) ShaunTheSheep.resource_name :shaun_the_sheep @@ -165,7 +163,6 @@ describe Chef::Recipe do expect(res1).to be_a_kind_of(Sounders) end end - end end @@ -270,14 +267,11 @@ describe Chef::Recipe do it "validating resources via build_resource" do expect {recipe.build_resource(:remote_file, "klopp") do - source Chef::DelayedEvaluator.new {"http://chef.io"} + source Chef::DelayedEvaluator.new { "http://chef.io" } end}.to_not raise_error end - end - - describe "creating resources via declare_resource" do let(:zm_resource) do recipe.declare_resource(:zen_master, "klopp") do @@ -322,8 +316,8 @@ describe Chef::Recipe do zm_resource recipe.declare_resource(:zen_master, "klopp2", run_context: run_context2) run_context2.resource_collection.lookup("zen_master[klopp2]") - expect {run_context2.resource_collection.lookup("zen_master[klopp]")}.to raise_error(Chef::Exceptions::ResourceNotFound) - expect {run_context.resource_collection.lookup("zen_master[klopp2]")}.to raise_error(Chef::Exceptions::ResourceNotFound) + expect { run_context2.resource_collection.lookup("zen_master[klopp]") }.to raise_error(Chef::Exceptions::ResourceNotFound) + expect { run_context.resource_collection.lookup("zen_master[klopp2]") }.to raise_error(Chef::Exceptions::ResourceNotFound) run_context.resource_collection.lookup("zen_master[klopp]") end end @@ -355,7 +349,6 @@ describe Chef::Recipe do end end - it "defines the resource using the declaration name with long name" do resource_zn_follower expect(run_context.resource_collection.lookup("zen_follower[srst]")).not_to be_nil @@ -363,7 +356,6 @@ describe Chef::Recipe do end 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 recipe.no_such_resource("foo") @@ -386,24 +378,19 @@ describe Chef::Recipe do it "gives a sane error message when using declare_resource" do expect { recipe.declare_resource(:no_such_resource, "bar") }.to raise_error(Chef::Exceptions::NoSuchResourceType) end - end describe "when creating a resource that contains an error in the attributes block" do - it "does not obfuscate the error source" do expect do 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") - end - end describe "resource cloning" do - let(:second_recipe) do Chef::Recipe.new("second_cb", "second_recipe", run_context) end @@ -446,7 +433,6 @@ describe Chef::Recipe do it "sets the recipe name on the cloned resource to that resoure's recipe" do expect(duplicated_resource.recipe_name).to eq("second_recipe") end - end describe "resource definitions" do @@ -494,7 +480,6 @@ describe Chef::Recipe do expect(crow_block).to eql("the return val") end end - end describe "instance_eval" do diff --git a/spec/unit/resource/apt_package_spec.rb b/spec/unit/resource/apt_package_spec.rb index 41cdb04a1e..127b682be4 100644 --- a/spec/unit/resource/apt_package_spec.rb +++ b/spec/unit/resource/apt_package_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::AptPackage, "initialize" do - static_provider_resolution( resource: Chef::Resource::AptPackage, provider: Chef::Provider::Package::Apt, diff --git a/spec/unit/resource/apt_update_spec.rb b/spec/unit/resource/apt_update_spec.rb index 8015cb03b3..d3f21f538e 100644 --- a/spec/unit/resource/apt_update_spec.rb +++ b/spec/unit/resource/apt_update_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::AptUpdate do - let(:resource) { Chef::Resource::AptUpdate.new("update") } it "should create a new Chef::Resource::AptUpdate" do diff --git a/spec/unit/resource/bash_spec.rb b/spec/unit/resource/bash_spec.rb index 56c36df1ce..9b42b189aa 100644 --- a/spec/unit/resource/bash_spec.rb +++ b/spec/unit/resource/bash_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::Bash do - before(:each) do @resource = Chef::Resource::Bash.new("fakey_fakerton") end @@ -36,5 +35,4 @@ describe Chef::Resource::Bash do it "should have an interpreter of bash" do expect(@resource.interpreter).to eql("bash") end - end diff --git a/spec/unit/resource/batch_spec.rb b/spec/unit/resource/batch_spec.rb index e19ea15585..7d3b9eb3f2 100644 --- a/spec/unit/resource/batch_spec.rb +++ b/spec/unit/resource/batch_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::Batch do - before(:each) do node = Chef::Node.new @@ -30,7 +29,6 @@ describe Chef::Resource::Batch do run_context = Chef::RunContext.new(node, nil, nil) @resource = Chef::Resource::Batch.new("batch_unit_test", run_context) - end it "should create a new Chef::Resource::Batch" do @@ -45,5 +43,4 @@ describe Chef::Resource::Batch do it_should_behave_like "a Windows script resource" end - end diff --git a/spec/unit/resource/breakpoint_spec.rb b/spec/unit/resource/breakpoint_spec.rb index 585bcadc68..650c5b82f9 100644 --- a/spec/unit/resource/breakpoint_spec.rb +++ b/spec/unit/resource/breakpoint_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::Breakpoint do - static_provider_resolution( resource: Chef::Resource::Breakpoint, provider: Chef::Provider::Breakpoint, @@ -43,5 +42,4 @@ describe Chef::Resource::Breakpoint do it "names itself after the line number of the file where it's created" do expect(@breakpoint.name).to match(/breakpoint_spec\.rb\:[\d]{2}\:in \`new\'$/) end - end diff --git a/spec/unit/resource/chef_gem_spec.rb b/spec/unit/resource/chef_gem_spec.rb index 1b1439d7f2..c01d2feebc 100644 --- a/spec/unit/resource/chef_gem_spec.rb +++ b/spec/unit/resource/chef_gem_spec.rb @@ -21,14 +21,12 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::ChefGem, "initialize" do - static_provider_resolution( resource: Chef::Resource::ChefGem, provider: Chef::Provider::Package::Rubygems, name: :chef_gem, action: :install, ) - end describe Chef::Resource::ChefGem, "gem_binary" do @@ -127,7 +125,6 @@ describe Chef::Resource::ChefGem, "gem_binary" do end describe "when Chef::Config[:chef_gem_compile_time] is explicitly false" do - let(:chef_gem_compile_time) { false } before do diff --git a/spec/unit/resource/chocolatey_package_spec.rb b/spec/unit/resource/chocolatey_package_spec.rb index dfd6a3e679..b9b0443597 100644 --- a/spec/unit/resource/chocolatey_package_spec.rb +++ b/spec/unit/resource/chocolatey_package_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::ChocolateyPackage do - let(:resource) { Chef::Resource::ChocolateyPackage.new("fakey_fakerton") } it "should create a new Chef::Resource::ChocolateyPackage" do diff --git a/spec/unit/resource/conditional_action_not_nothing_spec.rb b/spec/unit/resource/conditional_action_not_nothing_spec.rb index d8a6190ee7..93db0514be 100644 --- a/spec/unit/resource/conditional_action_not_nothing_spec.rb +++ b/spec/unit/resource/conditional_action_not_nothing_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::ConditionalActionNotNothing do - describe "after running a :nothing action" do before do @action = :nothing @@ -41,5 +40,4 @@ describe Chef::Resource::ConditionalActionNotNothing do expect(@conditional.continue?).to be_truthy end end - end diff --git a/spec/unit/resource/conditional_spec.rb b/spec/unit/resource/conditional_spec.rb index ee4a66f8d5..b34b4200e6 100644 --- a/spec/unit/resource/conditional_spec.rb +++ b/spec/unit/resource/conditional_spec.rb @@ -28,7 +28,7 @@ describe Chef::Resource::Conditional do end it "raises an exception when neither a block or command is given" do - expect { Chef::Resource::Conditional.send(:new, :always, @parent_resource, nil, {})}.to raise_error(ArgumentError, /requires either a command or a block/) + expect { Chef::Resource::Conditional.send(:new, :always, @parent_resource, nil, {}) }.to raise_error(ArgumentError, /requires either a command or a block/) end it "does not evaluate a guard interpreter on initialization of the conditional" do @@ -171,7 +171,7 @@ describe Chef::Resource::Conditional do describe "after running a command which timed out" do before do - @conditional = Chef::Resource::Conditional.not_if(@parent_resource, "false") + @conditional = Chef::Resource::Conditional.not_if(@parent_resource, "false") allow_any_instance_of(Chef::GuardInterpreter::DefaultGuardInterpreter).to receive(:shell_out).and_raise(Chef::Exceptions::CommandTimeout) end diff --git a/spec/unit/resource/cookbook_file_spec.rb b/spec/unit/resource/cookbook_file_spec.rb index ca49320503..6886ce1f31 100644 --- a/spec/unit/resource/cookbook_file_spec.rb +++ b/spec/unit/resource/cookbook_file_spec.rb @@ -48,28 +48,27 @@ describe Chef::Resource::CookbookFile do describe "when it has a backup number, group, mode, owner, source, checksum, and cookbook on nix or path, rights, deny_rights, checksum on windows" do before do - if Chef::Platform.windows? - @cookbook_file.path("C:/temp/origin/file.txt") - @cookbook_file.rights(:read, "Everyone") - @cookbook_file.deny_rights(:full_control, "Clumsy_Sam") - else - @cookbook_file.path("/tmp/origin/file.txt") - @cookbook_file.group("wheel") - @cookbook_file.mode("0664") - @cookbook_file.owner("root") - @cookbook_file.source("/tmp/foo.txt") - @cookbook_file.cookbook("/tmp/cookbooks/cooked.rb") - end + if Chef::Platform.windows? + @cookbook_file.path("C:/temp/origin/file.txt") + @cookbook_file.rights(:read, "Everyone") + @cookbook_file.deny_rights(:full_control, "Clumsy_Sam") + else + @cookbook_file.path("/tmp/origin/file.txt") + @cookbook_file.group("wheel") + @cookbook_file.mode("0664") + @cookbook_file.owner("root") + @cookbook_file.source("/tmp/foo.txt") + @cookbook_file.cookbook("/tmp/cookbooks/cooked.rb") + end @cookbook_file.checksum("1" * 64) end - it "describes the state" do state = @cookbook_file.state if Chef::Platform.windows? puts state - expect(state[:rights]).to eq([{:permissions => :read, :principals => "Everyone"}]) - expect(state[:deny_rights]).to eq([{:permissions => :full_control, :principals => "Clumsy_Sam"}]) + expect(state[:rights]).to eq([{ :permissions => :read, :principals => "Everyone" }]) + expect(state[:deny_rights]).to eq([{ :permissions => :full_control, :principals => "Clumsy_Sam" }]) else expect(state[:group]).to eq("wheel") expect(state[:mode]).to eq("0664") diff --git a/spec/unit/resource/cron_spec.rb b/spec/unit/resource/cron_spec.rb index ad2ec08bb2..c41f40f852 100644 --- a/spec/unit/resource/cron_spec.rb +++ b/spec/unit/resource/cron_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Resource::Cron do - before(:each) do @resource = Chef::Resource::Cron.new("cronify") end @@ -100,7 +99,7 @@ describe Chef::Resource::Cron do end it "should allow you to specify environment variables hash" do - env = {"TEST" => "LOL"} + env = { "TEST" => "LOL" } @resource.environment env expect(@resource.environment).to eql(env) end diff --git a/spec/unit/resource/csh_spec.rb b/spec/unit/resource/csh_spec.rb index 864175fc85..2b02d4a765 100644 --- a/spec/unit/resource/csh_spec.rb +++ b/spec/unit/resource/csh_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::Csh do - before(:each) do @resource = Chef::Resource::Csh.new("fakey_fakerton") end @@ -36,5 +35,4 @@ describe Chef::Resource::Csh do it "should have an interpreter of csh" do expect(@resource.interpreter).to eql("csh") end - end diff --git a/spec/unit/resource/deploy_revision_spec.rb b/spec/unit/resource/deploy_revision_spec.rb index 4cbae68ca2..c9fad58261 100644 --- a/spec/unit/resource/deploy_revision_spec.rb +++ b/spec/unit/resource/deploy_revision_spec.rb @@ -20,23 +20,19 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::DeployRevision do - static_provider_resolution( resource: Chef::Resource::DeployRevision, provider: Chef::Provider::Deploy::Revision, name: :deploy_revision, action: :deploy, ) - end describe Chef::Resource::DeployBranch do - static_provider_resolution( resource: Chef::Resource::DeployBranch, provider: Chef::Provider::Deploy::Revision, name: :deploy_branch, action: :deploy, ) - end diff --git a/spec/unit/resource/deploy_spec.rb b/spec/unit/resource/deploy_spec.rb index bd9d8295a4..28435dac12 100644 --- a/spec/unit/resource/deploy_spec.rb +++ b/spec/unit/resource/deploy_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::Deploy do - static_provider_resolution( resource: Chef::Resource::Deploy, provider: Chef::Provider::Deploy::Timestamped, @@ -28,17 +27,16 @@ describe Chef::Resource::Deploy do action: :deploy, ) - class << self def resource_has_a_string_attribute(attr_name) it "has a String attribute for #{attr_name}" do @resource.send(attr_name, "this is a string") expect(@resource.send(attr_name)).to eql("this is a string") - expect {@resource.send(attr_name, 8675309)}.to raise_error(ArgumentError) + expect { @resource.send(attr_name, 8675309) }.to raise_error(ArgumentError) end end - def resource_has_a_boolean_attribute(attr_name, opts={:defaults_to=>false}) + def resource_has_a_boolean_attribute(attr_name, opts = { :defaults_to => false }) it "has a Boolean attribute for #{attr_name}" do expect(@resource.send(attr_name)).to eql(opts[:defaults_to]) @resource.send(attr_name, !opts[:defaults_to]) @@ -49,12 +47,12 @@ describe Chef::Resource::Deploy do def resource_has_a_callback_attribute(attr_name) it "has a Callback attribute #{attr_name}" do callback_block = lambda { :noop } - expect {@resource.send(attr_name, &callback_block)}.not_to raise_error + expect { @resource.send(attr_name, &callback_block) }.not_to raise_error expect(@resource.send(attr_name)).to eq(callback_block) callback_file = "path/to/callback.rb" - expect {@resource.send(attr_name, callback_file)}.not_to raise_error + expect { @resource.send(attr_name, callback_file) }.not_to raise_error expect(@resource.send(attr_name)).to eq(callback_file) - expect {@resource.send(attr_name, :this_is_fail)}.to raise_error(ArgumentError) + expect { @resource.send(attr_name, :this_is_fail) }.to raise_error(ArgumentError) end end end @@ -80,9 +78,9 @@ describe Chef::Resource::Deploy do resource_has_a_string_attribute(:svn_arguments) resource_has_a_string_attribute(:svn_info_args) - resource_has_a_boolean_attribute(:migrate, :defaults_to=>false) - resource_has_a_boolean_attribute(:enable_submodules, :defaults_to=>false) - resource_has_a_boolean_attribute(:shallow_clone, :defaults_to=>false) + resource_has_a_boolean_attribute(:migrate, :defaults_to => false) + resource_has_a_boolean_attribute(:enable_submodules, :defaults_to => false) + resource_has_a_boolean_attribute(:shallow_clone, :defaults_to => false) it "uses the first argument as the deploy directory" do expect(@resource.deploy_to).to eql("/my/deploy/dir") @@ -118,17 +116,17 @@ describe Chef::Resource::Deploy do expect(@resource.svn_force_export).to be_falsey @resource.svn_force_export true expect(@resource.svn_force_export).to be_truthy - expect {@resource.svn_force_export(10053)}.to raise_error(ArgumentError) + expect { @resource.svn_force_export(10053) }.to raise_error(ArgumentError) end it "takes arbitrary environment variables in a hash" do @resource.environment "RAILS_ENV" => "production" - expect(@resource.environment).to eq({"RAILS_ENV" => "production"}) + expect(@resource.environment).to eq({ "RAILS_ENV" => "production" }) end it "takes string arguments to environment for backwards compat, setting RAILS_ENV, RACK_ENV, and MERB_ENV" do @resource.environment "production" - expect(@resource.environment).to eq({"RAILS_ENV"=>"production", "RACK_ENV"=>"production","MERB_ENV"=>"production"}) + expect(@resource.environment).to eq({ "RAILS_ENV" => "production", "RACK_ENV" => "production", "MERB_ENV" => "production" }) end it "sets destination to $deploy_to/shared/$repository_cache" do @@ -183,16 +181,16 @@ describe Chef::Resource::Deploy do end it 'has a Hash attribute symlinks, default: {"system" => "public/system", "pids" => "tmp/pids", "log" => "log"}' do - default = { "system" => "public/system", "pids" => "tmp/pids", "log" => "log"} + default = { "system" => "public/system", "pids" => "tmp/pids", "log" => "log" } expect(@resource.symlinks).to eq(default) @resource.symlinks "foo" => "bar/baz" - expect(@resource.symlinks).to eq({"foo" => "bar/baz"}) + expect(@resource.symlinks).to eq({ "foo" => "bar/baz" }) end it 'has a Hash attribute symlink_before_migrate, default "config/database.yml" => "config/database.yml"' do - expect(@resource.symlink_before_migrate).to eq({"config/database.yml" => "config/database.yml"}) + expect(@resource.symlink_before_migrate).to eq({ "config/database.yml" => "config/database.yml" }) @resource.symlink_before_migrate "wtf?" => "wtf is going on" - expect(@resource.symlink_before_migrate).to eq({"wtf?" => "wtf is going on"}) + expect(@resource.symlink_before_migrate).to eq({ "wtf?" => "wtf is going on" }) end resource_has_a_callback_attribute :before_migrate @@ -206,7 +204,7 @@ describe Chef::Resource::Deploy do end it "takes a block for the restart parameter" do - restart_like_this = lambda {p :noop} + restart_like_this = lambda { p :noop } @resource.restart(&restart_like_this) expect(@resource.restart).to eq(restart_like_this) end @@ -264,10 +262,9 @@ describe Chef::Resource::Deploy do @resource.group("pokemon") @resource.scm_provider(Chef::Provider::Git) @resource.repository_cache("cached-copy") - @resource.environment({"SUDO" => "TRUE"}) - @resource.symlinks({"system" => "public/system"}) + @resource.environment({ "SUDO" => "TRUE" }) + @resource.symlinks({ "system" => "public/system" }) @resource.migrate(false) - end it "describes its state" do @@ -280,5 +277,4 @@ describe Chef::Resource::Deploy do expect(@resource.identity).to eq("http://uri.org") end end - end diff --git a/spec/unit/resource/directory_spec.rb b/spec/unit/resource/directory_spec.rb index cfb3ade135..8eacb8d001 100644 --- a/spec/unit/resource/directory_spec.rb +++ b/spec/unit/resource/directory_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Resource::Directory do - before(:each) do @resource = Chef::Resource::Directory.new("fakey_fakerton") end diff --git a/spec/unit/resource/dpkg_package_spec.rb b/spec/unit/resource/dpkg_package_spec.rb index 7bfe268d7d..727e52af32 100644 --- a/spec/unit/resource/dpkg_package_spec.rb +++ b/spec/unit/resource/dpkg_package_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::DpkgPackage, "initialize" do - static_provider_resolution( resource: Chef::Resource::DpkgPackage, provider: Chef::Provider::Package::Dpkg, @@ -28,5 +27,4 @@ describe Chef::Resource::DpkgPackage, "initialize" do action: :install, os: "linux", ) - end diff --git a/spec/unit/resource/dsc_resource_spec.rb b/spec/unit/resource/dsc_resource_spec.rb index ebedd55dec..64f5f50e5e 100644 --- a/spec/unit/resource/dsc_resource_spec.rb +++ b/spec/unit/resource/dsc_resource_spec.rb @@ -40,7 +40,7 @@ describe Chef::Resource::DscResource do end it "has an ed_actions attribute with only the `:run` and `:nothing` attributes" do - expect(dsc_test_resource.allowed_actions.to_set).to eq([:run,:nothing].to_set) + expect(dsc_test_resource.allowed_actions.to_set).to eq([:run, :nothing].to_set) end it "allows the resource attribute to be set" do diff --git a/spec/unit/resource/dsc_script_spec.rb b/spec/unit/resource/dsc_script_spec.rb index 7139405f38..55473e3146 100644 --- a/spec/unit/resource/dsc_script_spec.rb +++ b/spec/unit/resource/dsc_script_spec.rb @@ -31,8 +31,8 @@ describe Chef::Resource::DscScript do let(:dsc_test_resource) { Chef::Resource::DscScript.new(dsc_test_resource_name, dsc_test_run_context) } - let(:configuration_code) {'echo "This is supposed to create a configuration document."'} - let(:configuration_path) {"c:/myconfigs/formatc.ps1"} + let(:configuration_code) { 'echo "This is supposed to create a configuration document."' } + let(:configuration_path) { "c:/myconfigs/formatc.ps1" } let(:configuration_name) { "formatme" } let(:configuration_data) { '@{AllNodes = @( @{ NodeName = "localhost"; PSDscAllowPlainTextPassword = $true })}' } let(:configuration_data_script) { "c:/myconfigs/data/safedata.psd1" } @@ -42,7 +42,7 @@ describe Chef::Resource::DscScript do end it "has an allowed_actions attribute with only the `:run` and `:nothing` attributes" do - expect(dsc_test_resource.allowed_actions.to_set).to eq([:run,:nothing].to_set) + expect(dsc_test_resource.allowed_actions.to_set).to eq([:run, :nothing].to_set) end it "allows the code attribute to be set" do diff --git a/spec/unit/resource/easy_install_package_spec.rb b/spec/unit/resource/easy_install_package_spec.rb index 9747e57f65..50cb707c7f 100644 --- a/spec/unit/resource/easy_install_package_spec.rb +++ b/spec/unit/resource/easy_install_package_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::EasyInstallPackage, "initialize" do - static_provider_resolution( resource: Chef::Resource::EasyInstallPackage, provider: Chef::Provider::Package::EasyInstall, diff --git a/spec/unit/resource/env_spec.rb b/spec/unit/resource/env_spec.rb index f9719689c5..f027b25e4d 100644 --- a/spec/unit/resource/env_spec.rb +++ b/spec/unit/resource/env_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Resource::Env do - before(:each) do @resource = Chef::Resource::Env.new("FOO") end @@ -38,7 +37,7 @@ describe Chef::Resource::Env do expect(@resource.action).to eql([:create]) end - { :create => false, :delete => false, :modify => false, :flibber => true }.each do |action,bad_value| + { :create => false, :delete => false, :modify => false, :flibber => true }.each do |action, bad_value| it "should #{bad_value ? 'not' : ''} accept #{action}" do if bad_value expect { @resource.action action }.to raise_error(ArgumentError) @@ -81,5 +80,4 @@ describe Chef::Resource::Env do expect(@resource.identity).to eq("charmander") end end - end diff --git a/spec/unit/resource/erl_call_spec.rb b/spec/unit/resource/erl_call_spec.rb index 6d1f45ec63..1527c372a3 100644 --- a/spec/unit/resource/erl_call_spec.rb +++ b/spec/unit/resource/erl_call_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Resource::ErlCall do - before(:each) do @resource = Chef::Resource::ErlCall.new("fakey_fakerton") end diff --git a/spec/unit/resource/execute_spec.rb b/spec/unit/resource/execute_spec.rb index 70824e9f5b..418587b790 100644 --- a/spec/unit/resource/execute_spec.rb +++ b/spec/unit/resource/execute_spec.rb @@ -31,5 +31,4 @@ describe Chef::Resource::Execute do it "defaults to not being a guard interpreter" do expect(execute_resource.is_guard_interpreter).to eq(false) end - end diff --git a/spec/unit/resource/file/verification_spec.rb b/spec/unit/resource/file/verification_spec.rb index b27d8ca754..f55f6416aa 100644 --- a/spec/unit/resource/file/verification_spec.rb +++ b/spec/unit/resource/file/verification_spec.rb @@ -21,7 +21,7 @@ require "spec_helper" describe Chef::Resource::File::Verification do let(:t_block) { Proc.new { true } } let(:f_block) { Proc.new { false } } - let(:path_block) { Proc.new { |path| path }} + let(:path_block) { Proc.new { |path| path } } let(:temp_path) { "/tmp/foobar" } describe "verification registration" do @@ -33,7 +33,7 @@ describe Chef::Resource::File::Verification do end it "raises an error if a verification can't be found" do - expect{Chef::Resource::File::Verification.lookup(:dne)}.to raise_error(Chef::Exceptions::VerificationNotFound) + expect { Chef::Resource::File::Verification.lookup(:dne) }.to raise_error(Chef::Exceptions::VerificationNotFound) end end @@ -42,13 +42,13 @@ describe Chef::Resource::File::Verification do it "expects a string argument" do v = Chef::Resource::File::Verification.new(parent_resource, nil, {}) {} - expect{ v.verify("/foo/bar") }.to_not raise_error - expect{ v.verify }.to raise_error + expect { v.verify("/foo/bar") }.to_not raise_error + expect { v.verify }.to raise_error end it "accepts an options hash" do v = Chef::Resource::File::Verification.new(parent_resource, nil, {}) {} - expect{ v.verify("/foo/bar", {:future => true}) }.to_not raise_error + expect { v.verify("/foo/bar", { :future => true }) }.to_not raise_error end context "with a verification block" do diff --git a/spec/unit/resource/file_spec.rb b/spec/unit/resource/file_spec.rb index f5b576c0f5..b728e08be9 100644 --- a/spec/unit/resource/file_spec.rb +++ b/spec/unit/resource/file_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::File do - before(:each) do @resource = Chef::Resource::File.new("fakey_fakerton") end @@ -67,11 +66,11 @@ describe Chef::Resource::File do end it "should accept a block, symbol, or string for verify" do - expect {@resource.verify {}}.not_to raise_error - expect {@resource.verify ""}.not_to raise_error - expect {@resource.verify :json}.not_to raise_error - expect {@resource.verify true}.to raise_error - expect {@resource.verify false}.to raise_error + expect { @resource.verify {} }.not_to raise_error + expect { @resource.verify "" }.not_to raise_error + expect { @resource.verify :json }.not_to raise_error + expect { @resource.verify true }.to raise_error + expect { @resource.verify false }.to raise_error end it "should accept multiple verify statements" do @@ -112,7 +111,6 @@ describe Chef::Resource::File do it "returns the file path as its identity" do expect(@resource.identity).to eq("/tmp/foo.txt") end - end describe "when access controls are set on windows", :windows_only => true do @@ -122,9 +120,8 @@ describe Chef::Resource::File do end it "describes its state including windows ACL attributes" do state = @resource.state - expect(state[:rights]).to eq([ {:permissions => :read, :principals => "Everyone"}, - {:permissions => :full_control, :principals => "DOMAIN\User"} ]) + expect(state[:rights]).to eq([ { :permissions => :read, :principals => "Everyone" }, + { :permissions => :full_control, :principals => "DOMAIN\User" } ]) end end - end diff --git a/spec/unit/resource/freebsd_package_spec.rb b/spec/unit/resource/freebsd_package_spec.rb index 97966de2af..0842114c47 100644 --- a/spec/unit/resource/freebsd_package_spec.rb +++ b/spec/unit/resource/freebsd_package_spec.rb @@ -29,7 +29,6 @@ describe Chef::Resource::FreebsdPackage do @resource = Chef::Resource::FreebsdPackage.new("foo", @run_context) end - describe "Initialization" do it "should return a Chef::Resource::FreebsdPackage" do expect(@resource).to be_a_kind_of(Chef::Resource::FreebsdPackage) @@ -44,7 +43,6 @@ describe Chef::Resource::FreebsdPackage do end end - describe "Assigning provider after creation" do describe "if ports specified as source" do it "should be Freebsd::Port" do @@ -87,4 +85,3 @@ describe Chef::Resource::FreebsdPackage do end end end - diff --git a/spec/unit/resource/gem_package_spec.rb b/spec/unit/resource/gem_package_spec.rb index de6341d0ea..f226d2c990 100644 --- a/spec/unit/resource/gem_package_spec.rb +++ b/spec/unit/resource/gem_package_spec.rb @@ -20,14 +20,12 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::GemPackage, "initialize" do - static_provider_resolution( resource: Chef::Resource::GemPackage, provider: Chef::Provider::Package::Rubygems, name: :gem_package, action: :install, ) - end describe Chef::Resource::GemPackage, "gem_binary" do diff --git a/spec/unit/resource/git_spec.rb b/spec/unit/resource/git_spec.rb index 18d6216287..1770d6bee9 100644 --- a/spec/unit/resource/git_spec.rb +++ b/spec/unit/resource/git_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::Git do - static_provider_resolution( resource: Chef::Resource::Git, provider: Chef::Provider::Git, @@ -46,5 +45,4 @@ describe Chef::Resource::Git do @git.reference "v1.0 tag" expect(@git.revision).to eql("v1.0 tag") end - end diff --git a/spec/unit/resource/homebrew_package_spec.rb b/spec/unit/resource/homebrew_package_spec.rb index dad9573971..7e4ad59ff9 100644 --- a/spec/unit/resource/homebrew_package_spec.rb +++ b/spec/unit/resource/homebrew_package_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::HomebrewPackage, "initialize" do - static_provider_resolution( resource: Chef::Resource::HomebrewPackage, provider: Chef::Provider::Package::Homebrew, @@ -46,5 +45,4 @@ describe Chef::Resource::HomebrewPackage, "initialize" do include_examples "home_brew user set and returned" end end - end diff --git a/spec/unit/resource/http_request_spec.rb b/spec/unit/resource/http_request_spec.rb index 8a5745a1af..ab8371bc83 100644 --- a/spec/unit/resource/http_request_spec.rb +++ b/spec/unit/resource/http_request_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Resource::HttpRequest do - before(:each) do @resource = Chef::Resource::HttpRequest.new("fakey_fakerton") end @@ -48,12 +47,11 @@ describe Chef::Resource::HttpRequest do before do @resource.url("http://www.trololol.net") @resource.message("Get sum post brah.") - @resource.headers({"head" => "tail"}) + @resource.headers({ "head" => "tail" }) end it "returns the url as its identity" do expect(@resource.identity).to eq("http://www.trololol.net") end end - end diff --git a/spec/unit/resource/ifconfig_spec.rb b/spec/unit/resource/ifconfig_spec.rb index eceba0c319..b78206db2c 100644 --- a/spec/unit/resource/ifconfig_spec.rb +++ b/spec/unit/resource/ifconfig_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::Ifconfig do - before(:each) do @node = Chef::Node.new @events = Chef::EventDispatch::Dispatcher.new @@ -105,5 +104,4 @@ describe Chef::Resource::Ifconfig do describe "when it is a new Ubuntu platform" do it_should_behave_like "being a platform based on a recent Debian", "ubuntu", "11.10" end - end diff --git a/spec/unit/resource/ips_package_spec.rb b/spec/unit/resource/ips_package_spec.rb index 62656bcf8e..e326699c2c 100644 --- a/spec/unit/resource/ips_package_spec.rb +++ b/spec/unit/resource/ips_package_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::IpsPackage, "initialize" do - static_provider_resolution( resource: Chef::Resource::IpsPackage, provider: Chef::Provider::Package::Ips, diff --git a/spec/unit/resource/ksh_spec.rb b/spec/unit/resource/ksh_spec.rb index 6c3ba291b4..71a6a1c66c 100644 --- a/spec/unit/resource/ksh_spec.rb +++ b/spec/unit/resource/ksh_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::Ksh do - before(:each) do @resource = Chef::Resource::Ksh.new("fakey_fakerton") end @@ -36,5 +35,4 @@ describe Chef::Resource::Ksh do it "should have an interpreter of ksh" do expect(@resource.interpreter).to eql("ksh") end - end diff --git a/spec/unit/resource/link_spec.rb b/spec/unit/resource/link_spec.rb index dfd98eb16e..bde8901264 100644 --- a/spec/unit/resource/link_spec.rb +++ b/spec/unit/resource/link_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Resource::Link do - before(:each) do expect_any_instance_of(Chef::Resource::Link).to receive(:verify_links_supported!).and_return(true) @resource = Chef::Resource::Link.new("fakey_fakerton") @@ -39,7 +38,7 @@ describe Chef::Resource::Link do expect(@resource.action).to eql([:create]) end - { :create => false, :delete => false, :blues => true }.each do |action,bad_value| + { :create => false, :delete => false, :blues => true }.each do |action, bad_value| it "should #{bad_value ? 'not' : ''} accept #{action}" do if bad_value expect { @resource.action action }.to raise_error(ArgumentError) diff --git a/spec/unit/resource/log_spec.rb b/spec/unit/resource/log_spec.rb index 18a1eb65bf..34bdf57162 100644 --- a/spec/unit/resource/log_spec.rb +++ b/spec/unit/resource/log_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Resource::Log do - before(:each) do @log_str = "this is my string to log" @resource = Chef::Resource::Log.new(@log_str) diff --git a/spec/unit/resource/macports_package_spec.rb b/spec/unit/resource/macports_package_spec.rb index 1aee070fdf..9b6131a5b1 100644 --- a/spec/unit/resource/macports_package_spec.rb +++ b/spec/unit/resource/macports_package_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::MacportsPackage, "initialize" do - static_provider_resolution( resource: Chef::Resource::MacportsPackage, provider: Chef::Provider::Package::Macports, @@ -28,5 +27,4 @@ describe Chef::Resource::MacportsPackage, "initialize" do action: :install, os: "mac_os_x", ) - end diff --git a/spec/unit/resource/mdadm_spec.rb b/spec/unit/resource/mdadm_spec.rb index 6a446a2815..33b322daf3 100644 --- a/spec/unit/resource/mdadm_spec.rb +++ b/spec/unit/resource/mdadm_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Resource::Mdadm do - before(:each) do @resource = Chef::Resource::Mdadm.new("fakey_fakerton") end @@ -98,5 +97,4 @@ describe Chef::Resource::Mdadm do expect(@resource.identity).to eq("raider") end end - end diff --git a/spec/unit/resource/mount_spec.rb b/spec/unit/resource/mount_spec.rb index 53efb055e8..c2b5f48622 100644 --- a/spec/unit/resource/mount_spec.rb +++ b/spec/unit/resource/mount_spec.rb @@ -92,12 +92,12 @@ describe Chef::Resource::Mount do end it "should allow options to be sent as a delayed evaluator" do - @resource.options Chef::DelayedEvaluator.new {["rw", "noexec"]} + @resource.options Chef::DelayedEvaluator.new { ["rw", "noexec"] } expect(@resource.options).to eql(["rw", "noexec"]) end it "should allow options to be sent as a delayed evaluator, and convert to array" do - @resource.options Chef::DelayedEvaluator.new {"rw,noexec"} + @resource.options Chef::DelayedEvaluator.new { "rw,noexec" } expect(@resource.options).to be_a_kind_of(Array) expect(@resource.options).to eql(["rw", "noexec"]) end @@ -209,6 +209,5 @@ describe Chef::Resource::Mount do expect(state[:device_type]).to eql(:device) expect(state[:fstype]).to eq("auto") end - end end diff --git a/spec/unit/resource/ohai_spec.rb b/spec/unit/resource/ohai_spec.rb index 0d1d5efd5b..e1937ec414 100644 --- a/spec/unit/resource/ohai_spec.rb +++ b/spec/unit/resource/ohai_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::Ohai do - before(:each) do @resource = Chef::Resource::Ohai.new("ohai_reload") end @@ -57,6 +56,4 @@ describe Chef::Resource::Ohai do expect(@resource.identity).to eq("test") end end - - end diff --git a/spec/unit/resource/openbsd_package_spec.rb b/spec/unit/resource/openbsd_package_spec.rb index 840cabf1fe..9687bc94b5 100644 --- a/spec/unit/resource/openbsd_package_spec.rb +++ b/spec/unit/resource/openbsd_package_spec.rb @@ -23,7 +23,6 @@ require "spec_helper" require "ostruct" describe Chef::Resource::OpenbsdPackage do - before(:each) do @node = Chef::Node.new @events = Chef::EventDispatch::Dispatcher.new @@ -44,6 +43,4 @@ describe Chef::Resource::OpenbsdPackage do expect(@resource.provider).to be_nil end end - end - diff --git a/spec/unit/resource/osx_profile_spec.rb b/spec/unit/resource/osx_profile_spec.rb index a244048878..7bd504d414 100644 --- a/spec/unit/resource/osx_profile_spec.rb +++ b/spec/unit/resource/osx_profile_spec.rb @@ -38,8 +38,8 @@ describe Chef::Resource::OsxProfile do end it "should accept install and remove as actions" do - expect { resource.action :install}.not_to raise_error - expect { resource.action :remove}.not_to raise_error + expect { resource.action :install }.not_to raise_error + expect { resource.action :remove }.not_to raise_error end it "should allow you to set the profile attribute" do diff --git a/spec/unit/resource/package_spec.rb b/spec/unit/resource/package_spec.rb index ef8f6cce53..5157d7ca35 100644 --- a/spec/unit/resource/package_spec.rb +++ b/spec/unit/resource/package_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Resource::Package do - before(:each) do @resource = Chef::Resource::Package.new("emacs") end @@ -50,8 +49,8 @@ describe Chef::Resource::Package do end it "should accept a hash for response file template variables" do - @resource.response_file_variables({:variables => true}) - expect(@resource.response_file_variables).to eql({:variables => true}) + @resource.response_file_variables({ :variables => true }) + expect(@resource.response_file_variables).to eql({ :variables => true }) end it "should accept a string for the source" do @@ -89,5 +88,4 @@ describe Chef::Resource::Package do expect(@resource.timeout).to eql(val) end end - end diff --git a/spec/unit/resource/pacman_package_spec.rb b/spec/unit/resource/pacman_package_spec.rb index 000470b3d1..70791f4716 100644 --- a/spec/unit/resource/pacman_package_spec.rb +++ b/spec/unit/resource/pacman_package_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::PacmanPackage, "initialize" do - static_provider_resolution( resource: Chef::Resource::PacmanPackage, provider: Chef::Provider::Package::Pacman, @@ -28,5 +27,4 @@ describe Chef::Resource::PacmanPackage, "initialize" do action: :install, os: "linux", ) - end diff --git a/spec/unit/resource/perl_spec.rb b/spec/unit/resource/perl_spec.rb index 417d74a8c2..674bd3cc7f 100644 --- a/spec/unit/resource/perl_spec.rb +++ b/spec/unit/resource/perl_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::Perl do - before(:each) do @resource = Chef::Resource::Perl.new("fakey_fakerton") end @@ -36,5 +35,4 @@ describe Chef::Resource::Perl do it "should have an interpreter of perl" do expect(@resource.interpreter).to eql("perl") end - end diff --git a/spec/unit/resource/portage_package_spec.rb b/spec/unit/resource/portage_package_spec.rb index d2336744bf..37ab008f8c 100644 --- a/spec/unit/resource/portage_package_spec.rb +++ b/spec/unit/resource/portage_package_spec.rb @@ -19,7 +19,6 @@ require File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "spec_helper")) describe Chef::Resource::PortagePackage, "initialize" do - before(:each) do @resource = Chef::Resource::PortagePackage.new("foo") end diff --git a/spec/unit/resource/powershell_script_spec.rb b/spec/unit/resource/powershell_script_spec.rb index 3cb5e1b5a9..e7176423a4 100644 --- a/spec/unit/resource/powershell_script_spec.rb +++ b/spec/unit/resource/powershell_script_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::PowershellScript do - before(:each) do node = Chef::Node.new @@ -49,7 +48,7 @@ describe Chef::Resource::PowershellScript do it "raises an error when architecture is i386 on Windows Nano Server" do allow(Chef::Platform).to receive(:windows_nano_server?).and_return(true) - expect{@resource.architecture(:i386)}.to raise_error(Chef::Exceptions::Win32ArchitectureIncorrect, "cannot execute script with requested architecture 'i386' on Windows Nano Server") + expect { @resource.architecture(:i386) }.to raise_error(Chef::Exceptions::Win32ArchitectureIncorrect, "cannot execute script with requested architecture 'i386' on Windows Nano Server") end context "when using guards" do @@ -61,7 +60,7 @@ describe Chef::Resource::PowershellScript do it "inherits exactly the :cwd, :environment, :group, :path, :user, :umask, and :architecture attributes from a parent resource class" do inherited_difference = Chef::Resource::PowershellScript.guard_inherited_attributes - - [:cwd, :environment, :group, :path, :user, :umask, :architecture ] + [:cwd, :environment, :group, :path, :user, :umask, :architecture ] expect(inherited_difference).to eq([]) end @@ -87,7 +86,7 @@ describe Chef::Resource::PowershellScript do it "enables convert_boolean_return by default for guards in the context of powershell_script when no guard params are specified" do allow_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:evaluate_action).and_return(true) allow_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:block_from_attributes).with( - {:convert_boolean_return => true, :code => "$true"}).and_return(Proc.new {}) + { :convert_boolean_return => true, :code => "$true" }).and_return(Proc.new {}) resource.only_if("$true") end @@ -98,27 +97,27 @@ describe Chef::Resource::PowershellScript do file_resource.guard_interpreter :powershell_script allow_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:block_from_attributes).with( - {:convert_boolean_return => true, :code => "$true"}).and_return(Proc.new {}) + { :convert_boolean_return => true, :code => "$true" }).and_return(Proc.new {}) resource.only_if("$true") end it "enables convert_boolean_return by default for guards in the context of powershell_script when guard params are specified" do - guard_parameters = {:cwd => "/etc/chef", :architecture => :x86_64} + guard_parameters = { :cwd => "/etc/chef", :architecture => :x86_64 } allow_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:block_from_attributes).with( - {:convert_boolean_return => true, :code => "$true"}.merge(guard_parameters)).and_return(Proc.new {}) + { :convert_boolean_return => true, :code => "$true" }.merge(guard_parameters)).and_return(Proc.new {}) resource.only_if("$true", guard_parameters) end it "passes convert_boolean_return as true if it was specified as true in a guard parameter" do - guard_parameters = {:cwd => "/etc/chef", :convert_boolean_return => true, :architecture => :x86_64} + guard_parameters = { :cwd => "/etc/chef", :convert_boolean_return => true, :architecture => :x86_64 } allow_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:block_from_attributes).with( - {:convert_boolean_return => true, :code => "$true"}.merge(guard_parameters)).and_return(Proc.new {}) + { :convert_boolean_return => true, :code => "$true" }.merge(guard_parameters)).and_return(Proc.new {}) resource.only_if("$true", guard_parameters) end it "passes convert_boolean_return as false if it was specified as true in a guard parameter" do - other_guard_parameters = {:cwd => "/etc/chef", :architecture => :x86_64} - parameters_with_boolean_disabled = other_guard_parameters.merge({:convert_boolean_return => false, :code => "$true"}) + other_guard_parameters = { :cwd => "/etc/chef", :architecture => :x86_64 } + parameters_with_boolean_disabled = other_guard_parameters.merge({ :convert_boolean_return => false, :code => "$true" }) allow_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:block_from_attributes).with( parameters_with_boolean_disabled).and_return(Proc.new {}) resource.only_if("$true", parameters_with_boolean_disabled) diff --git a/spec/unit/resource/python_spec.rb b/spec/unit/resource/python_spec.rb index aba84c4000..a73e01a656 100644 --- a/spec/unit/resource/python_spec.rb +++ b/spec/unit/resource/python_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::Python do - before(:each) do @resource = Chef::Resource::Python.new("fakey_fakerton") end @@ -36,5 +35,4 @@ describe Chef::Resource::Python do it "should have an interpreter of python" do expect(@resource.interpreter).to eql("python") end - end diff --git a/spec/unit/resource/registry_key_spec.rb b/spec/unit/resource/registry_key_spec.rb index a2ba6f500d..472c511857 100644 --- a/spec/unit/resource/registry_key_spec.rb +++ b/spec/unit/resource/registry_key_spec.rb @@ -130,7 +130,7 @@ describe Chef::Resource::RegistryKey, "recursive" do end it "should not allow a hash" do - expect { @resource.recursive({:sonic => :screwdriver}) }.to raise_error(ArgumentError) + expect { @resource.recursive({ :sonic => :screwdriver }) }.to raise_error(ArgumentError) end it "should not allow an array" do @@ -159,7 +159,7 @@ describe Chef::Resource::RegistryKey, "architecture" do end it "should not allow a hash" do - expect { @resource.architecture({:sonic => :screwdriver}) }.to raise_error(ArgumentError) + expect { @resource.architecture({ :sonic => :screwdriver }) }.to raise_error(ArgumentError) end it "should not allow an array" do @@ -194,6 +194,6 @@ describe Chef::Resource::RegistryKey, "state" do it "should return scrubbed values" do @resource.values([ { :name => "poosh", :type => :binary, :data => 255.chr * 1 } ]) - expect(@resource.state).to eql( { :values => [{ :name => "poosh", :type => :binary, :data => "a8100ae6aa1940d0b663bb31cd466142ebbdbd5187131b92d93818987832eb89"}] } ) + expect(@resource.state).to eql( { :values => [{ :name => "poosh", :type => :binary, :data => "a8100ae6aa1940d0b663bb31cd466142ebbdbd5187131b92d93818987832eb89" }] } ) end end diff --git a/spec/unit/resource/remote_directory_spec.rb b/spec/unit/resource/remote_directory_spec.rb index cdca214db6..456dc6e193 100644 --- a/spec/unit/resource/remote_directory_spec.rb +++ b/spec/unit/resource/remote_directory_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::RemoteDirectory do - before(:each) do @resource = Chef::Resource::RemoteDirectory.new("/etc/dunk") end diff --git a/spec/unit/resource/remote_file_spec.rb b/spec/unit/resource/remote_file_spec.rb index b511377a51..cd6ca9fd59 100644 --- a/spec/unit/resource/remote_file_spec.rb +++ b/spec/unit/resource/remote_file_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Resource::RemoteFile do - before(:each) do @resource = Chef::Resource::RemoteFile.new("fakey_fakerton") end @@ -66,7 +65,7 @@ describe Chef::Resource::RemoteFile do end it "should accept a delayed evalutator (string) for the remote file source" do - @resource.source Chef::DelayedEvaluator.new {"http://opscode.com/"} + @resource.source Chef::DelayedEvaluator.new { "http://opscode.com/" } expect(@resource.source).to eql([ "http://opscode.com/" ]) end @@ -87,13 +86,13 @@ describe Chef::Resource::RemoteFile do it "should only accept a single argument if a delayed evalutor is used" do expect { - @resource.source("http://opscode.com/", Chef::DelayedEvaluator.new {"http://opscode.com/"}) + @resource.source("http://opscode.com/", Chef::DelayedEvaluator.new { "http://opscode.com/" }) }.to raise_error(Chef::Exceptions::InvalidRemoteFileURI) end it "should only accept a single array item if a delayed evalutor is used" do expect { - @resource.source(["http://opscode.com/", Chef::DelayedEvaluator.new {"http://opscode.com/"}]) + @resource.source(["http://opscode.com/", Chef::DelayedEvaluator.new { "http://opscode.com/" }]) }.to raise_error(Chef::Exceptions::InvalidRemoteFileURI) end @@ -103,7 +102,7 @@ describe Chef::Resource::RemoteFile do it "does not accept a non-URI as the source when read from a delayed evaluator" do expect { - @resource.source(Chef::DelayedEvaluator.new {"not-a-uri"}) + @resource.source(Chef::DelayedEvaluator.new { "not-a-uri" }) @resource.source }.to raise_error(Chef::Exceptions::InvalidRemoteFileURI) end @@ -111,7 +110,6 @@ describe Chef::Resource::RemoteFile do it "should raise an exception when source is an empty array" do expect { @resource.source([]) }.to raise_error(ArgumentError) end - end describe "checksum" do @@ -163,7 +161,6 @@ describe Chef::Resource::RemoteFile do expect(@resource.use_last_modified).to be_falsey expect(@resource.use_etags).to be_truthy end - end describe "when it has group, mode, owner, source, and checksum" do @@ -179,20 +176,20 @@ describe Chef::Resource::RemoteFile do @resource.owner("root") end @resource.source("https://www.google.com/images/srpr/logo3w.png") - @resource.checksum("1"*26) + @resource.checksum("1" * 26) end it "describes its state" do state = @resource.state if Chef::Platform.windows? puts state - expect(state[:rights]).to eq([{:permissions => :read, :principals => "Everyone"}]) - expect(state[:deny_rights]).to eq([{:permissions => :full_control, :principals => "Clumsy_Sam"}]) + expect(state[:rights]).to eq([{ :permissions => :read, :principals => "Everyone" }]) + expect(state[:deny_rights]).to eq([{ :permissions => :full_control, :principals => "Clumsy_Sam" }]) else expect(state[:group]).to eq("pokemon") expect(state[:mode]).to eq("0664") expect(state[:owner]).to eq("root") - expect(state[:checksum]).to eq("1"*26) + expect(state[:checksum]).to eq("1" * 26) end end diff --git a/spec/unit/resource/resource_notification_spec.rb b/spec/unit/resource/resource_notification_spec.rb index 5ba6ea35d3..14cf5d8fd0 100644 --- a/spec/unit/resource/resource_notification_spec.rb +++ b/spec/unit/resource/resource_notification_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" require "chef/resource/resource_notification" describe Chef::Resource::Notification do - let(:notification) { Chef::Resource::Notification.new(:service_apache, :restart, :template_httpd_conf) } it "has a resource to be notified" do @@ -50,7 +49,7 @@ describe Chef::Resource::Notification do end it "raises an ArgumentError if you try to check a non-ducktype object for duplication" do - expect {notification.duplicates?(:not_a_notification)}.to raise_error(ArgumentError) + expect { notification.duplicates?(:not_a_notification) }.to raise_error(ArgumentError) end it "takes no action to resolve a resource reference that doesn't need to be resolved" do @@ -65,7 +64,7 @@ describe Chef::Resource::Notification do end it "resolves a lazy reference to a resource" do - notification.resource = {:cat => "keyboard_cat"} + notification.resource = { :cat => "keyboard_cat" } @keyboard_cat = Chef::Resource::Cat.new("keyboard_cat") @resource_collection = Chef::ResourceCollection.new @resource_collection << @keyboard_cat @@ -78,7 +77,7 @@ describe Chef::Resource::Notification do it "resolves a lazy reference to its notifying resource" do @keyboard_cat = Chef::Resource::Cat.new("keyboard_cat") notification.resource = @keyboard_cat - notification.notifying_resource = {:cat => "long_cat"} + notification.notifying_resource = { :cat => "long_cat" } @long_cat = Chef::Resource::Cat.new("long_cat") @resource_collection = Chef::ResourceCollection.new @resource_collection << @long_cat @@ -87,11 +86,11 @@ describe Chef::Resource::Notification do end it "resolves lazy references to both its resource and its notifying resource" do - notification.resource = {:cat => "keyboard_cat"} + notification.resource = { :cat => "keyboard_cat" } @keyboard_cat = Chef::Resource::Cat.new("keyboard_cat") @resource_collection = Chef::ResourceCollection.new @resource_collection << @keyboard_cat - notification.notifying_resource = {:cat => "long_cat"} + notification.notifying_resource = { :cat => "long_cat" } @long_cat = Chef::Resource::Cat.new("long_cat") @resource_collection << @long_cat notification.resolve_resource_reference(@resource_collection) @@ -100,7 +99,7 @@ describe Chef::Resource::Notification do end it "raises a RuntimeError if you try to reference multiple resources" do - notification.resource = {:cat => ["keyboard_cat", "cheez_cat"]} + notification.resource = { :cat => ["keyboard_cat", "cheez_cat"] } @keyboard_cat = Chef::Resource::Cat.new("keyboard_cat") @cheez_cat = Chef::Resource::Cat.new("cheez_cat") @resource_collection = Chef::ResourceCollection.new @@ -108,11 +107,11 @@ describe Chef::Resource::Notification do @resource_collection << @cheez_cat @long_cat = Chef::Resource::Cat.new("long_cat") notification.notifying_resource = @long_cat - expect {notification.resolve_resource_reference(@resource_collection)}.to raise_error(RuntimeError) + expect { notification.resolve_resource_reference(@resource_collection) }.to raise_error(RuntimeError) end it "raises a RuntimeError if you try to reference multiple notifying resources" do - notification.notifying_resource = {:cat => ["long_cat", "cheez_cat"]} + notification.notifying_resource = { :cat => ["long_cat", "cheez_cat"] } @long_cat = Chef::Resource::Cat.new("long_cat") @cheez_cat = Chef::Resource::Cat.new("cheez_cat") @resource_collection = Chef::ResourceCollection.new @@ -120,27 +119,27 @@ describe Chef::Resource::Notification do @resource_collection << @cheez_cat @keyboard_cat = Chef::Resource::Cat.new("keyboard_cat") notification.resource = @keyboard_cat - expect {notification.resolve_resource_reference(@resource_collection)}.to raise_error(RuntimeError) + expect { notification.resolve_resource_reference(@resource_collection) }.to raise_error(RuntimeError) end it "raises a RuntimeError if it can't find a resource in the resource collection when resolving a lazy reference" do - notification.resource = {:cat => "keyboard_cat"} + notification.resource = { :cat => "keyboard_cat" } @cheez_cat = Chef::Resource::Cat.new("cheez_cat") @resource_collection = Chef::ResourceCollection.new @resource_collection << @cheez_cat @long_cat = Chef::Resource::Cat.new("long_cat") notification.notifying_resource = @long_cat - expect {notification.resolve_resource_reference(@resource_collection)}.to raise_error(RuntimeError) + expect { notification.resolve_resource_reference(@resource_collection) }.to raise_error(RuntimeError) end it "raises a RuntimeError if it can't find a notifying resource in the resource collection when resolving a lazy reference" do - notification.notifying_resource = {:cat => "long_cat"} + notification.notifying_resource = { :cat => "long_cat" } @cheez_cat = Chef::Resource::Cat.new("cheez_cat") @resource_collection = Chef::ResourceCollection.new @resource_collection << @cheez_cat @keyboard_cat = Chef::Resource::Cat.new("keyboard_cat") notification.resource = @keyboard_cat - expect {notification.resolve_resource_reference(@resource_collection)}.to raise_error(RuntimeError) + expect { notification.resolve_resource_reference(@resource_collection) }.to raise_error(RuntimeError) end it "raises an ArgumentError if improper syntax is used in the lazy reference to its resource" do @@ -150,7 +149,7 @@ describe Chef::Resource::Notification do @resource_collection << @keyboard_cat @long_cat = Chef::Resource::Cat.new("long_cat") notification.notifying_resource = @long_cat - expect {notification.resolve_resource_reference(@resource_collection)}.to raise_error(ArgumentError) + expect { notification.resolve_resource_reference(@resource_collection) }.to raise_error(ArgumentError) end it "raises an ArgumentError if improper syntax is used in the lazy reference to its notifying resource" do @@ -160,10 +159,9 @@ describe Chef::Resource::Notification do @resource_collection << @long_cat @keyboard_cat = Chef::Resource::Cat.new("keyboard_cat") notification.resource = @keyboard_cat - expect {notification.resolve_resource_reference(@resource_collection)}.to raise_error(ArgumentError) + expect { notification.resolve_resource_reference(@resource_collection) }.to raise_error(ArgumentError) end # Create test to resolve lazy references to both notifying resource and dest. resource # Create tests to check proper error raising - end diff --git a/spec/unit/resource/route_spec.rb b/spec/unit/resource/route_spec.rb index 259ccf7eab..f37675a85f 100644 --- a/spec/unit/resource/route_spec.rb +++ b/spec/unit/resource/route_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Resource::Route do - before(:each) do @resource = Chef::Resource::Route.new("10.0.0.10") end diff --git a/spec/unit/resource/rpm_package_spec.rb b/spec/unit/resource/rpm_package_spec.rb index 1a0089b4cd..80ad0e6e89 100644 --- a/spec/unit/resource/rpm_package_spec.rb +++ b/spec/unit/resource/rpm_package_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::RpmPackage, "initialize" do - %w{linux aix}.each do |os| static_provider_resolution( resource: Chef::Resource::RpmPackage, @@ -30,7 +29,6 @@ describe Chef::Resource::RpmPackage, "initialize" do os: os, ) end - end describe Chef::Resource::RpmPackage, "allow_downgrade" do diff --git a/spec/unit/resource/ruby_block_spec.rb b/spec/unit/resource/ruby_block_spec.rb index f393fbea46..c9afad3bef 100644 --- a/spec/unit/resource/ruby_block_spec.rb +++ b/spec/unit/resource/ruby_block_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Resource::RubyBlock do - before(:each) do @resource = Chef::Resource::RubyBlock.new("fakey_fakerton") end diff --git a/spec/unit/resource/ruby_spec.rb b/spec/unit/resource/ruby_spec.rb index d7b6759462..059f12d5fd 100644 --- a/spec/unit/resource/ruby_spec.rb +++ b/spec/unit/resource/ruby_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::Ruby do - before(:each) do @resource = Chef::Resource::Ruby.new("fakey_fakerton") end @@ -36,5 +35,4 @@ describe Chef::Resource::Ruby do it "should have an interpreter of ruby" do expect(@resource.interpreter).to eql("ruby") end - end diff --git a/spec/unit/resource/scm_spec.rb b/spec/unit/resource/scm_spec.rb index 8667b244d7..d82fb97703 100644 --- a/spec/unit/resource/scm_spec.rb +++ b/spec/unit/resource/scm_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Resource::Scm do - before(:each) do @resource = Chef::Resource::Scm.new("my awesome app") end @@ -101,7 +100,7 @@ describe Chef::Resource::Scm do it "takes the depth as an integer for shallow clones" do @resource.depth 5 expect(@resource.depth).to eq(5) - expect {@resource.depth "five"}.to raise_error(ArgumentError) + expect { @resource.depth "five" }.to raise_error(ArgumentError) end it "defaults to nil depth for a full clone" do @@ -111,7 +110,7 @@ describe Chef::Resource::Scm do it "takes a boolean for #enable_submodules" do @resource.enable_submodules true expect(@resource.enable_submodules).to be_truthy - expect {@resource.enable_submodules "lolz"}.to raise_error(ArgumentError) + expect { @resource.enable_submodules "lolz" }.to raise_error(ArgumentError) end it "defaults to not enabling submodules" do @@ -121,7 +120,7 @@ describe Chef::Resource::Scm do it "takes a boolean for #enable_checkout" do @resource.enable_checkout true expect(@resource.enable_checkout).to be_truthy - expect {@resource.enable_checkout "lolz"}.to raise_error(ArgumentError) + expect { @resource.enable_checkout "lolz" }.to raise_error(ArgumentError) end it "defaults to enabling checkout" do @@ -131,7 +130,7 @@ describe Chef::Resource::Scm do it "takes a string for the remote" do @resource.remote "opscode" expect(@resource.remote).to eql("opscode") - expect {@resource.remote 1337}.to raise_error(ArgumentError) + expect { @resource.remote 1337 }.to raise_error(ArgumentError) end it "defaults to ``origin'' for the remote" do @@ -184,7 +183,7 @@ describe Chef::Resource::Scm do end describe "when it has a environment attribute" do - let(:test_environment) { {"CHEF_ENV" => "/tmp" } } + let(:test_environment) { { "CHEF_ENV" => "/tmp" } } before { @resource.environment(test_environment) } it "stores this environment" do expect(@resource.environment).to eq(test_environment) diff --git a/spec/unit/resource/service_spec.rb b/spec/unit/resource/service_spec.rb index f9953afd53..074dac7787 100644 --- a/spec/unit/resource/service_spec.rb +++ b/spec/unit/resource/service_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Chef::Resource::Service do - before(:each) do @resource = Chef::Resource::Service.new("chef") end @@ -140,7 +139,7 @@ describe Chef::Resource::Service do end it "should default all the feature support to nil" do - support_hash = { :status => nil, :restart => nil, :reload=> nil } + support_hash = { :status => nil, :restart => nil, :reload => nil } expect(@resource.supports).to eq(support_hash) end @@ -175,6 +174,4 @@ describe Chef::Resource::Service do expect(@resource.identity).to eq("superfriend") end end - - end diff --git a/spec/unit/resource/smartos_package_spec.rb b/spec/unit/resource/smartos_package_spec.rb index 8b1fb2e150..2094f7da37 100644 --- a/spec/unit/resource/smartos_package_spec.rb +++ b/spec/unit/resource/smartos_package_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::SmartosPackage, "initialize" do - static_provider_resolution( resource: Chef::Resource::SmartosPackage, provider: Chef::Provider::Package::SmartOS, @@ -29,5 +28,4 @@ describe Chef::Resource::SmartosPackage, "initialize" do os: "solaris2", platform_family: "smartos", ) - end diff --git a/spec/unit/resource/solaris_package_spec.rb b/spec/unit/resource/solaris_package_spec.rb index 80d84c1bf5..ac8c1f4249 100644 --- a/spec/unit/resource/solaris_package_spec.rb +++ b/spec/unit/resource/solaris_package_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::SolarisPackage, "initialize" do - %w{solaris2 nexentacore}.each do |platform_family| static_provider_resolution( resource: Chef::Resource::SolarisPackage, diff --git a/spec/unit/resource/subversion_spec.rb b/spec/unit/resource/subversion_spec.rb index 47b8ddfdeb..f1ab8332a2 100644 --- a/spec/unit/resource/subversion_spec.rb +++ b/spec/unit/resource/subversion_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::Subversion do - static_provider_resolution( resource: Chef::Resource::Subversion, provider: Chef::Provider::Subversion, diff --git a/spec/unit/resource/template_spec.rb b/spec/unit/resource/template_spec.rb index 19d8b1716f..e62e949a54 100644 --- a/spec/unit/resource/template_spec.rb +++ b/spec/unit/resource/template_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::Template do - before(:each) do @resource = Chef::Resource::Template.new("fakey_fakerton") end @@ -107,7 +106,6 @@ describe Chef::Resource::Template do end describe "defining helper methods" do - module ExampleHelpers def static_example "static_example" @@ -127,7 +125,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 { |m| o.extend(m) } expect(o.example_1).to eq("example_1") expect(o.example_2).to eq("example_2") end @@ -136,7 +134,7 @@ describe Chef::Resource::Template do @resource.helper(:shout) { |quiet| quiet.upcase } modules = @resource.helper_modules o = Object.new - modules.each {|m| o.extend(m)} + modules.each { |m| o.extend(m) } expect(o.shout("shout")).to eq("SHOUT") end @@ -167,7 +165,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 { |m| o.extend(m) } expect(o.example_1).to eq("example_1") end @@ -199,13 +197,10 @@ describe Chef::Resource::Template do expect(@resource.helper_modules.size).to eq(3) o = Object.new - @resource.helper_modules.each {|m| o.extend(m)} + @resource.helper_modules.each { |m| o.extend(m) } expect(o.static_example).to eq("static_example") expect(o.inline_module).to eq("inline_module") expect(o.inline_method).to eq("inline_method") end - - end - end diff --git a/spec/unit/resource/timestamped_deploy_spec.rb b/spec/unit/resource/timestamped_deploy_spec.rb index ad7ebe7a2e..69a52415ee 100644 --- a/spec/unit/resource/timestamped_deploy_spec.rb +++ b/spec/unit/resource/timestamped_deploy_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" describe Chef::Resource::TimestampedDeploy, "initialize" do - static_provider_resolution( resource: Chef::Resource::TimestampedDeploy, provider: Chef::Provider::Deploy::Timestamped, @@ -28,5 +27,4 @@ describe Chef::Resource::TimestampedDeploy, "initialize" do os: "linux", platform_family: "rhel", ) - end diff --git a/spec/unit/resource/user_spec.rb b/spec/unit/resource/user_spec.rb index 4b26288715..67f629cd89 100644 --- a/spec/unit/resource/user_spec.rb +++ b/spec/unit/resource/user_spec.rb @@ -68,7 +68,7 @@ describe Chef::Resource::User, "initialize" do expect { @resource.username "domain\@user" }.not_to raise_error expect(@resource.username).to eq("domain\@user") expect { @resource.username "domain\\user" }.not_to raise_error - expect(@resource.username).to eq("domain\\user") + expect(@resource.username).to eq("domain\\user") end end @@ -129,5 +129,4 @@ end expect(@resource.identity).to eq("root") end end - end diff --git a/spec/unit/resource/yum_package_spec.rb b/spec/unit/resource/yum_package_spec.rb index 195f8c56e8..7f9ebb6cfa 100644 --- a/spec/unit/resource/yum_package_spec.rb +++ b/spec/unit/resource/yum_package_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "support/shared/unit/resource/static_provider_resolution" describe Chef::Resource::YumPackage, "initialize" do - static_provider_resolution( resource: Chef::Resource::YumPackage, provider: Chef::Provider::Package::Yum, @@ -29,7 +28,6 @@ describe Chef::Resource::YumPackage, "initialize" do os: "linux", platform_family: "rhel", ) - end describe Chef::Resource::YumPackage, "arch" do diff --git a/spec/unit/resource_collection/resource_list_spec.rb b/spec/unit/resource_collection/resource_list_spec.rb index 9863747bf4..dabb8f037d 100644 --- a/spec/unit/resource_collection/resource_list_spec.rb +++ b/spec/unit/resource_collection/resource_list_spec.rb @@ -24,7 +24,7 @@ describe Chef::ResourceCollection::ResourceList do let(:second_resource) { Chef::Resource::ZenMaster.new("hattori") } def insert_resource(res) - expect{ resource_list.insert(res) }.not_to raise_error + expect { resource_list.insert(res) }.not_to raise_error end describe "initialize" do @@ -47,14 +47,14 @@ describe Chef::ResourceCollection::ResourceList do end it "should raise error when trying to install something other than Chef::Resource" do - expect{ resource_list.insert("not a resource") }.to raise_error(ArgumentError) + expect { resource_list.insert("not a resource") }.to raise_error(ArgumentError) end end describe "accessors" do it "should be able to insert with []=" do - expect{ resource_list[0] = resource }.not_to raise_error - expect{ resource_list[1] = second_resource }.not_to raise_error + expect { resource_list[0] = resource }.not_to raise_error + expect { resource_list[1] = second_resource }.not_to raise_error expect(resource_list[0]).to be(resource) expect(resource_list[1]).to be(second_resource) end diff --git a/spec/unit/resource_collection/resource_set_spec.rb b/spec/unit/resource_collection/resource_set_spec.rb index cacd555b4b..5c6ca9da63 100644 --- a/spec/unit/resource_collection/resource_set_spec.rb +++ b/spec/unit/resource_collection/resource_set_spec.rb @@ -78,13 +78,13 @@ describe Chef::ResourceCollection::ResourceSet do it "should find a resource by type symbol and array of names" do collection.insert_as(zen_master) collection.insert_as(zen_master2) - check_by_names(collection.find(:zen_master => [zen_master_name,zen_master2_name]), zen_master_name, zen_master2_name) + check_by_names(collection.find(:zen_master => [zen_master_name, zen_master2_name]), zen_master_name, zen_master2_name) end it "should find a resource by type symbol and array of names with custom names" do collection.insert_as(zen_master, :zzz, "name1") collection.insert_as(zen_master2, :zzz, "name2") - check_by_names(collection.find( :zzz => ["name1","name2"]), zen_master_name, zen_master2_name) + check_by_names(collection.find( :zzz => ["name1", "name2"]), zen_master_name, zen_master2_name) end it "should find resources of multiple kinds (:zen_master => a, :zen_follower => b)" do @@ -98,7 +98,7 @@ describe Chef::ResourceCollection::ResourceSet do collection.insert_as(zen_master, :zzz, "name1") collection.insert_as(zen_master2, :zzz, "name2") collection.insert_as(zen_follower, :yyy, "name3") - check_by_names(collection.find(:zzz => ["name1","name2"], :yyy => ["name3"]), + check_by_names(collection.find(:zzz => ["name1", "name2"], :yyy => ["name3"]), zen_master_name, zen_follower_name, zen_master2_name) end @@ -138,13 +138,13 @@ describe Chef::ResourceCollection::ResourceSet do collection.insert_as(zen_master2, :zzz, "name2") collection.insert_as(zen_follower, :yyy, "name3") check_by_names(collection.find("zzz[name1,name2]", "yyy[name3]"), - zen_master_name, zen_follower_name,zen_master2_name) + zen_master_name, zen_follower_name, zen_master2_name) end it "should only keep the last copy when multiple instances of a Resource are inserted" do collection.insert_as(zen_master) expect(collection.find("zen_master[#{zen_master_name}]")).to eq(zen_master) - new_zm =zen_master.dup + new_zm = zen_master.dup new_zm.retries = 10 expect(new_zm).to_not eq(zen_master) collection.insert_as(new_zm) @@ -186,14 +186,12 @@ describe Chef::ResourceCollection::ResourceSet do expect { collection.validate_lookup_spec!(Object.new) }.to \ raise_error(Chef::Exceptions::InvalidResourceSpecification) end - end def check_by_names(results, *names) expect(results.size).to eq(names.size) names.each do |name| - expect(results.detect{|r| r.name == name}).to_not eq(nil) + expect(results.detect { |r| r.name == name }).to_not eq(nil) end end - end diff --git a/spec/unit/resource_collection/stepable_iterator_spec.rb b/spec/unit/resource_collection/stepable_iterator_spec.rb index 61d374ab0b..1c81ced48f 100644 --- a/spec/unit/resource_collection/stepable_iterator_spec.rb +++ b/spec/unit/resource_collection/stepable_iterator_spec.rb @@ -26,7 +26,7 @@ describe Chef::ResourceCollection::StepableIterator do describe "doing basic iteration" do before do - @simple_collection = [1,2,3,4] + @simple_collection = [1, 2, 3, 4] @iterator = CRSI.for_collection(@simple_collection) end @@ -57,13 +57,11 @@ describe Chef::ResourceCollection::StepableIterator do @iterator.each_with_index do |element, index| collected[index] = element end - expect(collected).to eq({0=>1, 1=>2, 2=>3, 3=>4}) + expect(collected).to eq({ 0 => 1, 1 => 2, 2 => 3, 3 => 4 }) end - end describe "pausing and resuming iteration" do - before do @collection = [] @snitch_var = nil @@ -117,7 +115,7 @@ describe Chef::ResourceCollection::StepableIterator do it "doesn't step if there are no more steps" do expect(@iterator.step).to eq(3) - expect {@iterator.step}.not_to raise_error + expect { @iterator.step }.not_to raise_error expect(@iterator.step).to be_nil end @@ -131,14 +129,12 @@ describe Chef::ResourceCollection::StepableIterator do end it "should work correctly when elements are added to the collection during iteration" do - @collection.insert(2, lambda { @snitch_var = 815}) + @collection.insert(2, lambda { @snitch_var = 815 }) @collection.insert(3, lambda { @iterator.pause }) @iterator.resume expect(@snitch_var).to eq(815) @iterator.resume expect(@snitch_var).to eq(42) end - end - end diff --git a/spec/unit/resource_collection_spec.rb b/spec/unit/resource_collection_spec.rb index 0ec14200ca..d3cc0cc844 100644 --- a/spec/unit/resource_collection_spec.rb +++ b/spec/unit/resource_collection_spec.rb @@ -65,7 +65,7 @@ describe Chef::ResourceCollection do end it "should accept named arguments in any order" do - rc.insert(resource, :instance_name => "foo", :resource_type =>"bar") + rc.insert(resource, :instance_name => "foo", :resource_type => "bar") expect(rc[0]).to eq(resource) end @@ -163,7 +163,6 @@ describe Chef::ResourceCollection do end describe "resources" do - it "should find a resource by symbol and name (:zen_master => monkey)" do load_up_resources expect(rc.resources(:zen_master => "monkey").name).to eql("monkey") @@ -211,9 +210,8 @@ describe Chef::ResourceCollection do end it "raises an error when attempting to find a resource that does not exist" do - expect {rc.find("script[nonesuch]")}.to raise_error(Chef::Exceptions::ResourceNotFound) + expect { rc.find("script[nonesuch]") }.to raise_error(Chef::Exceptions::ResourceNotFound) end - end describe "when validating a resource query object" do @@ -225,7 +223,6 @@ describe Chef::ResourceCollection do expect(rc.validate_lookup_spec!(:service => "apache2")).to be_truthy end - it "accepts a chef resource object" do res = Chef::Resource.new("foo", nil) expect(rc.validate_lookup_spec!(res)).to be_truthy @@ -242,7 +239,6 @@ describe Chef::ResourceCollection do rc.validate_lookup_spec!(Object.new) end.to raise_error(Chef::Exceptions::InvalidResourceSpecification) end - end describe "to_json" do @@ -286,15 +282,14 @@ describe Chef::ResourceCollection do def check_by_names(results, *names) names.each do |res_name| - expect(results.detect{ |res| res.name == res_name }).not_to eql(nil) + expect(results.detect { |res| res.name == res_name }).not_to eql(nil) end end def load_up_resources %w{dog cat monkey}.each do |n| - rc << Chef::Resource::ZenMaster.new(n) + rc << Chef::Resource::ZenMaster.new(n) end rc << Chef::Resource::File.new("something") end - end diff --git a/spec/unit/resource_definition_spec.rb b/spec/unit/resource_definition_spec.rb index 45dfaffca7..7e9b8f4140 100644 --- a/spec/unit/resource_definition_spec.rb +++ b/spec/unit/resource_definition_spec.rb @@ -113,5 +113,4 @@ describe Chef::ResourceDefinition do defn.name = :woot expect(defn.to_s).to eql("woot") end - end diff --git a/spec/unit/resource_reporter_spec.rb b/spec/unit/resource_reporter_spec.rb index 5517865c8e..1e749ed500 100644 --- a/spec/unit/resource_reporter_spec.rb +++ b/spec/unit/resource_reporter_spec.rb @@ -44,7 +44,7 @@ describe Chef::ResourceReporter do @new_resource.cookbook_name = @cookbook_name @cookbook_version = double("Cookbook::Version", :version => "1.2.3") allow(@new_resource).to receive(:cookbook_version).and_return(@cookbook_version) - @current_resource = Chef::Resource::File.new("/tmp/a-file.txt") + @current_resource = Chef::Resource::File.new("/tmp/a-file.txt") @start_time = Time.new @end_time = Time.new + 20 @events = Chef::EventDispatch::Dispatcher.new @@ -58,7 +58,6 @@ describe Chef::ResourceReporter do end context "when first created" do - it "has no updated resources" do expect(@resource_reporter.updated_resources.size).to eq(0) end @@ -76,11 +75,9 @@ describe Chef::ResourceReporter do # @resource_reporter.error_descriptions.should be_empty # @resource_reporter.should have(0).error_descriptions end - end context "after the chef run completes" do - before do end @@ -92,9 +89,8 @@ describe Chef::ResourceReporter do context "when chef fails" do before do - allow(@rest_client).to receive(:raw_request).and_return({"result"=>"ok"}); - allow(@rest_client).to receive(:post).and_return({"uri"=>"https://example.com/reports/nodes/spitfire/runs/#{@run_id}"}); - + allow(@rest_client).to receive(:raw_request).and_return({ "result" => "ok" }); + allow(@rest_client).to receive(:post).and_return({ "uri" => "https://example.com/reports/nodes/spitfire/runs/#{@run_id}" }); end context "before converging any resources" do @@ -201,12 +197,12 @@ describe Chef::ResourceReporter do context "and a nested resource is updated" do before do @implementation_resource = Chef::Resource::CookbookFile.new("/preseed-file.txt") - @resource_reporter.resource_action_start(@implementation_resource , :create) - @resource_reporter.resource_current_state_loaded(@implementation_resource, :create, @implementation_resource) - @resource_reporter.resource_updated(@implementation_resource, :create) - @resource_reporter.resource_completed(@implementation_resource) - @resource_reporter.resource_updated(@new_resource, :create) - @resource_reporter.resource_completed(@new_resource) + @resource_reporter.resource_action_start(@implementation_resource , :create) + @resource_reporter.resource_current_state_loaded(@implementation_resource, :create, @implementation_resource) + @resource_reporter.resource_updated(@implementation_resource, :create) + @resource_reporter.resource_completed(@implementation_resource) + @resource_reporter.resource_updated(@new_resource, :create) + @resource_reporter.resource_completed(@new_resource) end it "does not collect data about the nested resource" do @@ -252,15 +248,13 @@ describe Chef::ResourceReporter do expect(update_record.current_resource).to eq(@current_resource) end end - end end describe "when generating a report for the server" do - before do - allow(@rest_client).to receive(:raw_request).and_return({"result"=>"ok"}); - allow(@rest_client).to receive(:post).and_return({"uri"=>"https://example.com/reports/nodes/spitfire/runs/#{@run_id}"}); + allow(@rest_client).to receive(:raw_request).and_return({ "result" => "ok" }); + allow(@rest_client).to receive(:post).and_return({ "uri" => "https://example.com/reports/nodes/spitfire/runs/#{@run_id}" }); @resource_reporter.run_started(@run_status) end @@ -293,9 +287,9 @@ describe Chef::ResourceReporter do context "the new_resource name and id are hashes" do before do @bad_resource = Chef::Resource::File.new("/tmp/filename_as_hash.txt") - allow(@bad_resource).to receive(:name).and_return({:foo=>:bar}) - allow(@bad_resource).to receive(:identity).and_return({:foo=>:bar}) - allow(@bad_resource).to receive(:path).and_return({:foo=>:bar}) + allow(@bad_resource).to receive(:name).and_return({ :foo => :bar }) + allow(@bad_resource).to receive(:identity).and_return({ :foo => :bar }) + allow(@bad_resource).to receive(:path).and_return({ :foo => :bar }) @resource_reporter.resource_action_start(@bad_resource, :create) @resource_reporter.resource_current_state_loaded(@bad_resource, :create, @current_resource) @resource_reporter.resource_updated(@bad_resource, :create) @@ -435,7 +429,6 @@ describe Chef::ResourceReporter do expect(@report).to have_key("end_time") expect(@report["end_time"]).to eq(@run_status.end_time.to_s) end - end context "when the resource is a File" do @@ -464,9 +457,8 @@ describe Chef::ResourceReporter do end context "for an unsuccessful run" do - before do - @backtrace = ["foo.rb:1 in `foo!'","bar.rb:2 in `bar!","'baz.rb:3 in `baz!'"] + @backtrace = ["foo.rb:1 in `foo!'", "bar.rb:2 in `bar!", "'baz.rb:3 in `baz!'"] @node = Chef::Node.new @node.name("spitfire") @exception = ArgumentError.new @@ -496,9 +488,8 @@ describe Chef::ResourceReporter do it "includes the error inspector output in the event data" do expect(@report["data"]["exception"]).to have_key("description") - expect(@report["data"]["exception"]["description"]).to include({"title"=>"Error expanding the run_list:", "sections"=>[{"Unexpected Error:" => "ArgumentError: Object not found"}]}) + expect(@report["data"]["exception"]["description"]).to include({ "title" => "Error expanding the run_list:", "sections" => [{ "Unexpected Error:" => "ArgumentError: Object not found" }] }) end - end context "when new_resource does not have a cookbook_name" do @@ -578,7 +569,6 @@ describe Chef::ResourceReporter do expect(@first_update_report["after"]).to eq({}) end end - end describe "when updating resource history on the server" do @@ -593,9 +583,9 @@ describe Chef::ResourceReporter do @response = Net::HTTPNotFound.new("a response body", "404", "Not Found") @error = Net::HTTPServerException.new("404 message", @response) expect(@rest_client).to receive(:post). - with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, - :start_time => @start_time.to_s}, - {"X-Ops-Reporting-Protocol-Version" => Chef::ResourceReporter::PROTOCOL_VERSION}). + with("reports/nodes/spitfire/runs", { :action => :start, :run_id => @run_id, + :start_time => @start_time.to_s }, + { "X-Ops-Reporting-Protocol-Version" => Chef::ResourceReporter::PROTOCOL_VERSION }). and_raise(@error) end @@ -614,7 +604,6 @@ describe Chef::ResourceReporter do expect(Chef::Log).to receive(:debug).with(/404/) @resource_reporter.run_started(@run_status) end - end context "when the server returns a 500 to the client" do @@ -623,8 +612,8 @@ describe Chef::ResourceReporter do @response = Net::HTTPInternalServerError.new("a response body", "500", "Internal Server Error") @error = Net::HTTPServerException.new("500 message", @response) expect(@rest_client).to receive(:post). - with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, :start_time => @start_time.to_s}, - {"X-Ops-Reporting-Protocol-Version" => Chef::ResourceReporter::PROTOCOL_VERSION}). + with("reports/nodes/spitfire/runs", { :action => :start, :run_id => @run_id, :start_time => @start_time.to_s }, + { "X-Ops-Reporting-Protocol-Version" => Chef::ResourceReporter::PROTOCOL_VERSION }). and_raise(@error) end @@ -653,8 +642,8 @@ describe Chef::ResourceReporter do @response = Net::HTTPInternalServerError.new("a response body", "500", "Internal Server Error") @error = Net::HTTPServerException.new("500 message", @response) expect(@rest_client).to receive(:post). - with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, :start_time => @start_time.to_s}, - {"X-Ops-Reporting-Protocol-Version" => Chef::ResourceReporter::PROTOCOL_VERSION}). + with("reports/nodes/spitfire/runs", { :action => :start, :run_id => @run_id, :start_time => @start_time.to_s }, + { "X-Ops-Reporting-Protocol-Version" => Chef::ResourceReporter::PROTOCOL_VERSION }). and_raise(@error) end @@ -672,10 +661,10 @@ describe Chef::ResourceReporter do context "after creating the run history document" do before do - response = {"uri"=>"https://example.com/reports/nodes/spitfire/runs/@run_id"} + response = { "uri" => "https://example.com/reports/nodes/spitfire/runs/@run_id" } expect(@rest_client).to receive(:post). - with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, :start_time => @start_time.to_s}, - {"X-Ops-Reporting-Protocol-Version" => Chef::ResourceReporter::PROTOCOL_VERSION}). + with("reports/nodes/spitfire/runs", { :action => :start, :run_id => @run_id, :start_time => @start_time.to_s }, + { "X-Ops-Reporting-Protocol-Version" => Chef::ResourceReporter::PROTOCOL_VERSION }). and_return(response) @resource_reporter.run_started(@run_status) end @@ -693,12 +682,12 @@ describe Chef::ResourceReporter do allow(@resource_reporter).to receive(:end_time).and_return(@end_time) @expected_data = @resource_reporter.prepare_run_data - response = {"result"=>"ok"} + response = { "result" => "ok" } expect(@rest_client).to receive(:raw_request).ordered do |method, url, headers, data| expect(method).to eq(:POST) - expect(headers).to eq({"Content-Encoding" => "gzip", - "X-Ops-Reporting-Protocol-Version" => Chef::ResourceReporter::PROTOCOL_VERSION, + expect(headers).to eq({ "Content-Encoding" => "gzip", + "X-Ops-Reporting-Protocol-Version" => Chef::ResourceReporter::PROTOCOL_VERSION, },) data_stream = Zlib::GzipReader.new(StringIO.new(data)) data = data_stream.read @@ -743,7 +732,6 @@ describe Chef::ResourceReporter do expect(Chef::Log).to receive(:error).with(/test socket error/) @resource_reporter.post_reporting_data - end it "should raise if an unkwown error happens" do diff --git a/spec/unit/resource_resolver_spec.rb b/spec/unit/resource_resolver_spec.rb index 964886f8b8..f3a20ab0e3 100644 --- a/spec/unit/resource_resolver_spec.rb +++ b/spec/unit/resource_resolver_spec.rb @@ -19,7 +19,6 @@ require "spec_helper" require "chef/resource_resolver" - describe Chef::ResourceResolver do it '#resolve' do expect(described_class.resolve(:execute)).to eq(Chef::Resource::Execute) diff --git a/spec/unit/resource_spec.rb b/spec/unit/resource_spec.rb index d3d6164a69..a3eb807946 100644 --- a/spec/unit/resource_spec.rb +++ b/spec/unit/resource_spec.rb @@ -43,7 +43,6 @@ describe Chef::Resource do end describe "when inherited" do - it "adds an entry to a list of subclasses" do subclass = Class.new(Chef::Resource) expect(Chef::Resource.resource_classes).to include(subclass) @@ -54,7 +53,6 @@ describe Chef::Resource do subclass_of_subclass = Class.new(subclass) expect(Chef::Resource.resource_classes).to include(subclass_of_subclass) end - end describe "when declaring the identity attribute" do @@ -136,13 +134,11 @@ describe Chef::Resource do resource_subclass.state_attrs(:group, :mode) expect(resource_subclass.state_attrs).to match_array([:checksum, :owner, :group, :mode]) end - end describe "when a set of state attributes has been declared" do let(:file_resource) { file_resource_class = Class.new(Chef::Resource) do - state_attrs :checksum, :owner, :group, :mode attr_accessor :checksum @@ -225,13 +221,13 @@ describe Chef::Resource do it "should make notified resources appear in the actions hash" do run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") resource.notifies :reload, run_context.resource_collection.find(:zen_master => "coffee") - expect(resource.delayed_notifications.detect{|e| e.resource.name == "coffee" && e.action == :reload}).not_to be_nil + expect(resource.delayed_notifications.detect { |e| e.resource.name == "coffee" && e.action == :reload }).not_to be_nil end it "should make notified resources be capable of acting immediately" do run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") resource.notifies :reload, run_context.resource_collection.find(:zen_master => "coffee"), :immediate - expect(resource.immediate_notifications.detect{|e| e.resource.name == "coffee" && e.action == :reload}).not_to be_nil + expect(resource.immediate_notifications.detect { |e| e.resource.name == "coffee" && e.action == :reload }).not_to be_nil end it "should raise an exception if told to act in other than :delay or :immediate(ly)" do @@ -244,35 +240,35 @@ describe Chef::Resource do it "should allow multiple notified resources appear in the actions hash" do run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") resource.notifies :reload, run_context.resource_collection.find(:zen_master => "coffee") - expect(resource.delayed_notifications.detect{|e| e.resource.name == "coffee" && e.action == :reload}).not_to be_nil + expect(resource.delayed_notifications.detect { |e| e.resource.name == "coffee" && e.action == :reload }).not_to be_nil run_context.resource_collection << Chef::Resource::ZenMaster.new("beans") resource.notifies :reload, run_context.resource_collection.find(:zen_master => "beans") - expect(resource.delayed_notifications.detect{|e| e.resource.name == "beans" && e.action == :reload}).not_to be_nil + expect(resource.delayed_notifications.detect { |e| e.resource.name == "beans" && e.action == :reload }).not_to be_nil end it "creates a notification for a resource that is not yet in the resource collection" do resource.notifies(:restart, :service => "apache") - expected_notification = Chef::Resource::Notification.new({:service => "apache"}, :restart, resource) + expected_notification = Chef::Resource::Notification.new({ :service => "apache" }, :restart, resource) expect(resource.delayed_notifications).to include(expected_notification) end it "notifies another resource immediately" do resource.notifies_immediately(:restart, :service => "apache") - expected_notification = Chef::Resource::Notification.new({:service => "apache"}, :restart, resource) + expected_notification = Chef::Resource::Notification.new({ :service => "apache" }, :restart, resource) expect(resource.immediate_notifications).to include(expected_notification) end it "notifies a resource to take action at the end of the chef run" do resource.notifies_delayed(:restart, :service => "apache") - expected_notification = Chef::Resource::Notification.new({:service => "apache"}, :restart, resource) + expected_notification = Chef::Resource::Notification.new({ :service => "apache" }, :restart, resource) expect(resource.delayed_notifications).to include(expected_notification) end it "notifies a resource with an array for its name via its prettified string name" do run_context.resource_collection << Chef::Resource::ZenMaster.new(["coffee", "tea"]) resource.notifies :reload, run_context.resource_collection.find(:zen_master => "coffee, tea") - expect(resource.delayed_notifications.detect{|e| e.resource.name == "coffee, tea" && e.action == :reload}).not_to be_nil + expect(resource.delayed_notifications.detect { |e| e.resource.name == "coffee, tea" && e.action == :reload }).not_to be_nil end end @@ -281,26 +277,26 @@ describe Chef::Resource do run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") zr = run_context.resource_collection.find(:zen_master => "coffee") resource.subscribes :reload, zr - expect(zr.delayed_notifications.detect{|e| e.resource.name == "funk" && e.action == :reload}).not_to be_nil + expect(zr.delayed_notifications.detect { |e| e.resource.name == "funk" && e.action == :reload }).not_to be_nil end it "should make resources appear in the actions hash of subscribed nodes" do run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") zr = run_context.resource_collection.find(:zen_master => "coffee") resource.subscribes :reload, zr - expect(zr.delayed_notifications.detect{|e| e.resource.name == resource.name && e.action == :reload}).not_to be_nil + expect(zr.delayed_notifications.detect { |e| e.resource.name == resource.name && e.action == :reload }).not_to be_nil run_context.resource_collection << Chef::Resource::ZenMaster.new("bean") zrb = run_context.resource_collection.find(:zen_master => "bean") zrb.subscribes :reload, zr - expect(zr.delayed_notifications.detect{|e| e.resource.name == resource.name && e.action == :reload}).not_to be_nil + expect(zr.delayed_notifications.detect { |e| e.resource.name == resource.name && e.action == :reload }).not_to be_nil end it "should make subscribed resources be capable of acting immediately" do run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") zr = run_context.resource_collection.find(:zen_master => "coffee") resource.subscribes :reload, zr, :immediately - expect(zr.immediate_notifications.detect{|e| e.resource.name == resource.name && e.action == :reload}).not_to be_nil + expect(zr.immediate_notifications.detect { |e| e.resource.name == resource.name && e.action == :reload }).not_to be_nil end end @@ -548,7 +544,6 @@ describe Chef::Resource do end describe "setting the base provider class for the resource" do - it "defaults to Chef::Provider for the base class" do expect(Chef::Resource.provider_base).to eq(Chef::Provider) end @@ -569,7 +564,6 @@ describe Chef::Resource do end }.to raise_error(Chef::Exceptions::DeprecatedFeatureError) end - end it "runs an action by finding its provider, loading the current resource and then running the action" do @@ -601,9 +595,7 @@ describe Chef::Resource do it "reports that it was not updated by the last action" do expect(resource).not_to be_updated_by_last_action end - end - end describe "when invoking its action" do @@ -644,7 +636,7 @@ describe Chef::Resource do it "accepts command options for only_if conditionals" do expect_any_instance_of(Chef::Resource::Conditional).to receive(:evaluate_command).at_least(1).times resource.only_if("true", :cwd => "/tmp") - expect(resource.only_if.first.command_opts).to eq({:cwd => "/tmp"}) + expect(resource.only_if.first.command_opts).to eq({ :cwd => "/tmp" }) resource.run_action(:purr) end @@ -668,13 +660,13 @@ describe Chef::Resource do it "accepts command options for not_if conditionals" do resource.not_if("pwd" , :cwd => "/tmp") - expect(resource.not_if.first.command_opts).to eq({:cwd => "/tmp"}) + expect(resource.not_if.first.command_opts).to eq({ :cwd => "/tmp" }) end 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 { snitch_var1 = nil } + resource.not_if { snitch_var2 = false } resource.run_action(:purr) expect(snitch_var1).to be_nil expect(snitch_var2).to be_falsey @@ -793,7 +785,6 @@ describe Chef::Resource do expect(fdoc).to receive(:puts).with(" (skipped due to action :nothing)", anything()) resource.should_skip?(:nothing) end - end describe "when resource action is :nothing" do @@ -839,7 +830,6 @@ describe Chef::Resource do end describe "building the platform map" do - let(:klz) { Class.new(Chef::Resource) } before do @@ -859,7 +849,7 @@ describe Chef::Resource do it "adds mappings for multiple platforms" do expect(Chef.resource_handler_map).to receive(:set).with( - :energy, Chef::Resource::Klz, { platform: ["autobots", "decepticons"]} + :energy, Chef::Resource::Klz, { platform: ["autobots", "decepticons"] } ) klz.provides :energy, platform: ["autobots", "decepticons"] end @@ -870,7 +860,6 @@ describe Chef::Resource do ) klz.provides :tape_deck end - end describe "resource_for_node" do @@ -919,13 +908,10 @@ describe Chef::Resource do expect(Chef::Resource.resource_for_node(:dinobot, node)).to eql(klz2) end end - end describe "when creating notifications" do - describe "with a string resource spec" do - it "creates a delayed notification when timing is not specified" do resource.notifies(:run, "execute[foo]") expect(run_context.delayed_notification_collection.size).to eq(1) @@ -947,7 +933,6 @@ describe Chef::Resource do end describe "with a syntax error in the resource spec" do - it "raises an exception immmediately" do expect do resource.notifies(:run, "typo[missing-closing-bracket") @@ -979,7 +964,6 @@ describe Chef::Resource do expect(run_context.immediate_notification_collection.size).to eq(1) end end - end describe "resource sensitive attribute" do @@ -1000,17 +984,16 @@ describe Chef::Resource do it "when set to false should show compiled resource for failed resource" do expect { resource_file.run_action(action) }.to raise_error { |err| - expect(compiled_resource_data(resource_file, action, err)).to match 'path "/nonexistent/CHEF-5098/file"' + expect(compiled_resource_data(resource_file, action, err)).to match 'path "/nonexistent/CHEF-5098/file"' } end it "when set to true should show compiled resource for failed resource" do resource_file.sensitive true expect { resource_file.run_action(action) }.to raise_error { |err| - expect(compiled_resource_data(resource_file, action, err)).to eql("suppressed sensitive resource output") + expect(compiled_resource_data(resource_file, action, err)).to eql("suppressed sensitive resource output") } end - end describe "#action" do @@ -1070,7 +1053,7 @@ describe Chef::Resource do end describe ".default_action" do - let(:default_action) { } + let(:default_action) {} let(:resource_class) do actions = default_action Class.new(described_class) do diff --git a/spec/unit/rest/auth_credentials_spec.rb b/spec/unit/rest/auth_credentials_spec.rb index 2036a3b3e7..99e2a16075 100644 --- a/spec/unit/rest/auth_credentials_spec.rb +++ b/spec/unit/rest/auth_credentials_spec.rb @@ -42,14 +42,14 @@ describe Chef::REST::AuthCredentials do describe "when loading the private key" do it "strips extra whitespace before checking the key" do key_file_fixture = CHEF_SPEC_DATA + "/ssl/private_key_with_whitespace.pem" - expect {Chef::REST::AuthCredentials.new("client-name", @key_file_fixture)}.not_to raise_error + expect { Chef::REST::AuthCredentials.new("client-name", @key_file_fixture) }.not_to raise_error end end describe "generating signature headers for a request" do before do @request_time = Time.at(1270920860) - @request_params = {:http_method => :POST, :path => "/clients", :body => '{"some":"json"}', :host => "localhost"} + @request_params = { :http_method => :POST, :path => "/clients", :body => '{"some":"json"}', :host => "localhost" } allow(Chef::Config).to( receive(:[]).with(:authentication_protocol_version).and_return(protocol_version)) end @@ -60,7 +60,7 @@ describe Chef::REST::AuthCredentials do it "generates signature headers for the request" do allow(Time).to receive(:now).and_return(@request_time) actual = @auth_credentials.signature_headers(@request_params) - expect(actual["HOST"]).to eq("localhost") + expect(actual["HOST"]).to eq("localhost") expect(actual["X-OPS-AUTHORIZATION-1"]).to eq("kBssX1ENEwKtNYFrHElN9vYGWS7OeowepN9EsYc9csWfh8oUovryPKDxytQ/") expect(actual["X-OPS-AUTHORIZATION-2"]).to eq("Wc2/nSSyxdWJjjfHzrE+YrqNQTaArOA7JkAf5p75eTUonCWcvNPjFrZVgKGS") expect(actual["X-OPS-AUTHORIZATION-3"]).to eq("yhzHJQh+lcVA9wwARg5Hu9q+ddS8xBOdm3Vp5atl5NGHiP0loiigMYvAvzPO") @@ -80,7 +80,7 @@ describe Chef::REST::AuthCredentials do it "generates the correct signature for version 1.1" do allow(Time).to receive(:now).and_return(@request_time) actual = @auth_credentials.signature_headers(@request_params) - expect(actual["HOST"]).to eq("localhost") + expect(actual["HOST"]).to eq("localhost") expect(actual["X-OPS-CONTENT-HASH"]).to eq("1tuzs5XKztM1ANrkGNPah6rW9GY=") expect(actual["X-OPS-SIGN"]).to eq("algorithm=sha1;version=1.1;") expect(actual["X-OPS-TIMESTAMP"]).to eq("2010-04-10T17:34:20Z") @@ -94,7 +94,7 @@ describe Chef::REST::AuthCredentials do end describe Chef::REST::RESTRequest do - def new_request(method=nil) + def new_request(method = nil) method ||= :POST Chef::REST::RESTRequest.new(method, @url, @req_body, @headers) end @@ -103,8 +103,8 @@ describe Chef::REST::RESTRequest do @auth_credentials = Chef::REST::AuthCredentials.new("client-name", CHEF_SPEC_DATA + "/ssl/private_key.pem") @url = URI.parse("http://chef.example.com:4000/?q=chef_is_awesome") @req_body = '{"json_data":"as_a_string"}' - @headers = { "Content-type" =>"application/json", - "Accept"=>"application/json", + @headers = { "Content-type" => "application/json", + "Accept" => "application/json", "Accept-Encoding" => Chef::REST::RESTRequest::ENCODING_GZIP_DEFLATE, "Host" => "chef.example.com:4000" } @request = Chef::REST::RESTRequest.new(:POST, @url, @req_body, @headers) @@ -292,5 +292,4 @@ describe Chef::REST::RESTRequest do end end end - end diff --git a/spec/unit/rest_spec.rb b/spec/unit/rest_spec.rb index 5b4b6f2a88..c62331ba16 100644 --- a/spec/unit/rest_spec.rb +++ b/spec/unit/rest_spec.rb @@ -24,7 +24,7 @@ require "uri" require "net/https" require "stringio" -SIGNING_KEY_DOT_PEM="-----BEGIN RSA PRIVATE KEY----- +SIGNING_KEY_DOT_PEM = "-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEA49TA0y81ps0zxkOpmf5V4/c4IeR5yVyQFpX3JpxO4TquwnRh 8VSUhrw8kkTLmB3cS39Db+3HadvhoqCEbqPE6915kXSuk/cWIcNozujLK7tkuPEy YVsyTioQAddSdfe+8EhQVf3oHxaKmUd6waXrWqYCnhxgOjxocenREYNhZ/OETIei @@ -59,7 +59,7 @@ describe Chef::REST do let(:log_stringio) { StringIO.new } - let(:request_id) {"1234"} + let(:request_id) { "1234" } let(:rest) do allow(Chef::REST::CookieJar).to receive(:instance).and_return({}) @@ -69,8 +69,8 @@ describe Chef::REST do rest end - let(:standard_read_headers) {{"Accept"=>"application/json", "Accept-Encoding"=>"gzip;q=1.0,deflate;q=0.6,identity;q=0.3", "X-REMOTE-REQUEST-ID"=>request_id, "X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION}} - let(:standard_write_headers) {{"Accept"=>"application/json", "Content-Type"=>"application/json", "Accept-Encoding"=>"gzip;q=1.0,deflate;q=0.6,identity;q=0.3", "X-REMOTE-REQUEST-ID"=>request_id, "X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION}} + let(:standard_read_headers) { { "Accept" => "application/json", "Accept-Encoding" => "gzip;q=1.0,deflate;q=0.6,identity;q=0.3", "X-REMOTE-REQUEST-ID" => request_id, "X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION } } + let(:standard_write_headers) { { "Accept" => "application/json", "Content-Type" => "application/json", "Accept-Encoding" => "gzip;q=1.0,deflate;q=0.6,identity;q=0.3", "X-REMOTE-REQUEST-ID" => request_id, "X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION } } before(:each) do Chef::Log.init(log_stringio) @@ -100,7 +100,6 @@ describe Chef::REST do end context "when created with a chef zero URL" do - let(:url) { "chefzero://localhost:1" } it "does not load the signing key" do @@ -120,8 +119,8 @@ describe Chef::REST do it "makes a :GET request with the composed url object" do expect(rest).to receive(:send_http_request). with(:GET, monkey_uri, standard_read_headers, false). - and_return([1,2,3]) - expect(rest).to receive(:apply_response_middleware).with(1,2,3).and_return([1,2,3]) + and_return([1, 2, 3]) + expect(rest).to receive(:apply_response_middleware).with(1, 2, 3).and_return([1, 2, 3]) expect(rest).to receive("success_response?".to_sym).with(1).and_return(true) rest.get_rest("monkey") end @@ -134,8 +133,8 @@ describe Chef::REST do it "makes a :DELETE request with the composed url object" do expect(rest).to receive(:send_http_request). with(:DELETE, monkey_uri, standard_read_headers, false). - and_return([1,2,3]) - expect(rest).to receive(:apply_response_middleware).with(1,2,3).and_return([1,2,3]) + and_return([1, 2, 3]) + expect(rest).to receive(:apply_response_middleware).with(1, 2, 3).and_return([1, 2, 3]) expect(rest).to receive("success_response?".to_sym).with(1).and_return(true) rest.delete_rest("monkey") end @@ -143,8 +142,8 @@ describe Chef::REST do it "makes a :POST request with the composed url object and data" do expect(rest).to receive(:send_http_request). with(:POST, monkey_uri, standard_write_headers, "\"data\""). - and_return([1,2,3]) - expect(rest).to receive(:apply_response_middleware).with(1,2,3).and_return([1,2,3]) + and_return([1, 2, 3]) + expect(rest).to receive(:apply_response_middleware).with(1, 2, 3).and_return([1, 2, 3]) expect(rest).to receive("success_response?".to_sym).with(1).and_return(true) rest.post_rest("monkey", "data") end @@ -152,8 +151,8 @@ describe Chef::REST do it "makes a :PUT request with the composed url object and data" do expect(rest).to receive(:send_http_request). with(:PUT, monkey_uri, standard_write_headers, "\"data\""). - and_return([1,2,3]) - expect(rest).to receive(:apply_response_middleware).with(1,2,3).and_return([1,2,3]) + and_return([1, 2, 3]) + expect(rest).to receive(:apply_response_middleware).with(1, 2, 3).and_return([1, 2, 3]) expect(rest).to receive("success_response?".to_sym).with(1).and_return(true) rest.put_rest("monkey", "data") end @@ -176,14 +175,14 @@ describe Chef::REST do it "calls the authn middleware" do data = "\"secure data\"" - auth_headers = standard_write_headers.merge({"auth_done"=>"yep"}) + auth_headers = standard_write_headers.merge({ "auth_done" => "yep" }) expect(rest.authenticator).to receive(:handle_request). with(:POST, monkey_uri, standard_write_headers, data). and_return([:POST, monkey_uri, auth_headers, data]) expect(rest).to receive(:send_http_request). with(:POST, monkey_uri, auth_headers, data). - and_return([1,2,3]) + and_return([1, 2, 3]) expect(rest).to receive("success_response?".to_sym).with(1).and_return(true) rest.raw_http_request(:POST, monkey_uri, standard_write_headers, data) end @@ -194,13 +193,12 @@ describe Chef::REST do expect(rest).to receive(:send_http_request). with(:POST, monkey_uri, auth_headers, data). - and_return([1,2,3]) + and_return([1, 2, 3]) expect(rest).to receive("success_response?".to_sym).with(1).and_return(true) rest.raw_http_request(:POST, monkey_uri, standard_write_headers, data) end end - describe "when configured to authenticate to the Chef server" do let(:base_url) { URI.parse("http://chef.example.com:4000") } @@ -234,12 +232,12 @@ describe Chef::REST do end it "raises PrivateKeyMissing when the key file doesn't exist" do - expect {Chef::REST.new(base_url, "client-name", "/dev/null/nothing_here")}.to raise_error(Chef::Exceptions::PrivateKeyMissing) + expect { Chef::REST.new(base_url, "client-name", "/dev/null/nothing_here") }.to raise_error(Chef::Exceptions::PrivateKeyMissing) end it "raises InvalidPrivateKey when the key file doesnt' look like a key" do invalid_key_file = CHEF_SPEC_DATA + "/bad-config.rb" - expect {Chef::REST.new(base_url, "client-name", invalid_key_file)}.to raise_error(Chef::Exceptions::InvalidPrivateKey) + expect { Chef::REST.new(base_url, "client-name", invalid_key_file) }.to raise_error(Chef::Exceptions::InvalidPrivateKey) end it "can take private key as a sting :raw_key in options during initializaton" do @@ -247,9 +245,8 @@ describe Chef::REST do end it "raises InvalidPrivateKey when the key passed as string :raw_key in options doesnt' look like a key" do - expect {Chef::REST.new(base_url, "client-name", nil, :raw_key => "bad key string")}.to raise_error(Chef::Exceptions::InvalidPrivateKey) + expect { Chef::REST.new(base_url, "client-name", nil, :raw_key => "bad key string") }.to raise_error(Chef::Exceptions::InvalidPrivateKey) end - end context "when making REST requests" do @@ -292,7 +289,7 @@ describe Chef::REST do describe "as JSON API requests" do let(:request_mock) { {} } - let(:base_headers) do #FIXME: huh? + let(:base_headers) do #FIXME: huh? { "Accept" => "application/json", "X-Chef-Version" => Chef::VERSION, @@ -393,15 +390,15 @@ describe Chef::REST do expected_headers = base_headers.merge("Content-Type" => "application/json", "Content-Length" => "13") expect(Net::HTTP::Post).to receive(:new).with("/?foo=bar", expected_headers).and_return(request) - rest.request(:POST, url, {}, {:one=>:two}) + rest.request(:POST, url, {}, { :one => :two }) expect(request.body).to eq('{"one":"two"}') end it "should build a new HTTP PUT request" do request = Net::HTTP::Put.new(url.path) expected_headers = base_headers.merge("Content-Type" => "application/json", "Content-Length" => "13") - expect(Net::HTTP::Put).to receive(:new).with("/?foo=bar",expected_headers).and_return(request) - rest.request(:PUT, url, {}, {:one=>:two}) + expect(Net::HTTP::Put).to receive(:new).with("/?foo=bar", expected_headers).and_return(request) + rest.request(:PUT, url, {}, { :one => :two }) expect(request.body).to eq('{"one":"two"}') end @@ -427,7 +424,7 @@ describe Chef::REST do let(:body) { '{"ohai2u":"json_api"}' } it "should inflate the body as to an object" do http_response.add_field("content-type", "application/json") - expect(rest.request(:GET, url, {})).to eq({"ohai2u"=>"json_api"}) + expect(rest.request(:GET, url, {})).to eq({ "ohai2u" => "json_api" }) end it "should fail if the response is truncated" do @@ -448,7 +445,6 @@ describe Chef::REST do http_response end it "should call request again" do - expect { rest.request(:GET, url) }.to raise_error(Chef::Exceptions::RedirectLimitExceeded) [:PUT, :POST, :DELETE].each do |method| @@ -492,7 +488,7 @@ describe Chef::REST do it "should show the JSON error message" do allow(rest).to receive(:sleep) - expect {rest.request(:GET, url)}.to raise_error(Net::HTTPFatalError) + expect { rest.request(:GET, url) }.to raise_error(Net::HTTPFatalError) expect(log_stringio.string).to match(Regexp.escape("INFO: HTTP Request Returned 500 drooling from inside of mouth: Ears get sore!, Not even four")) end end @@ -517,13 +513,13 @@ describe Chef::REST do end it "decompresses the JSON error message" do - expect {rest.request(:GET, url)}.to raise_error(Net::HTTPFatalError) + expect { rest.request(:GET, url) }.to raise_error(Net::HTTPFatalError) expect(log_stringio.string).to match(Regexp.escape("INFO: HTTP Request Returned 500 drooling from inside of mouth: Ears get sore!, Not even four")) end it "fails when the compressed body is truncated" do http_response["Content-Length"] = (body.bytesize + 99).to_s - expect {rest.request(:GET, url)}.to raise_error(Chef::Exceptions::ContentLengthMismatch) + expect { rest.request(:GET, url) }.to raise_error(Chef::Exceptions::ContentLengthMismatch) end end @@ -537,7 +533,7 @@ describe Chef::REST do it "retries then throws an exception" do allow(rest).to receive(:sleep) - expect {rest.request(:GET, url)}.to raise_error(Net::HTTPFatalError) + expect { rest.request(:GET, url) }.to raise_error(Net::HTTPFatalError) count = Chef::Config[:http_retry_count] expect(log_stringio.string).to match(Regexp.escape("ERROR: Server returned error 500 for #{url}, retrying #{count}/#{count}")) end @@ -551,7 +547,7 @@ describe Chef::REST do let(:request_mock) { {} } let(:http_response) do - http_response = Net::HTTPSuccess.new("1.1","200", "it-works") + http_response = Net::HTTPSuccess.new("1.1", "200", "it-works") allow(http_response).to receive(:read_body) expect(http_response).not_to receive(:body) @@ -577,24 +573,24 @@ describe Chef::REST do end it " build a new HTTP GET request without the application/json accept header" do - expected_headers = {"Accept" => "*/*", - "X-Chef-Version" => Chef::VERSION, - "Accept-Encoding" => Chef::REST::RESTRequest::ENCODING_GZIP_DEFLATE, - "Host" => host_header, - "X-REMOTE-REQUEST-ID"=> request_id, - "X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION, + expected_headers = { "Accept" => "*/*", + "X-Chef-Version" => Chef::VERSION, + "Accept-Encoding" => Chef::REST::RESTRequest::ENCODING_GZIP_DEFLATE, + "Host" => host_header, + "X-REMOTE-REQUEST-ID" => request_id, + "X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION, } expect(Net::HTTP::Get).to receive(:new).with("/?foo=bar", expected_headers).and_return(request_mock) rest.streaming_request(url, {}) end it "build a new HTTP GET request with the X-Remote-Request-Id header" do - expected_headers = {"Accept" => "*/*", - "X-Chef-Version" => Chef::VERSION, - "Accept-Encoding" => Chef::REST::RESTRequest::ENCODING_GZIP_DEFLATE, - "Host" => host_header, - "X-REMOTE-REQUEST-ID"=> request_id, - "X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION, + expected_headers = { "Accept" => "*/*", + "X-Chef-Version" => Chef::VERSION, + "Accept-Encoding" => Chef::REST::RESTRequest::ENCODING_GZIP_DEFLATE, + "Host" => host_header, + "X-REMOTE-REQUEST-ID" => request_id, + "X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION, } expect(Net::HTTP::Get).to receive(:new).with("/?foo=bar", expected_headers).and_return(request_mock) rest.streaming_request(url, {}) @@ -661,7 +657,7 @@ describe Chef::REST do path = tempfile.path expect(path).not_to be_nil allow(tempfile).to receive(:write).and_raise(IOError) - rest.fetch("cookbooks/a_cookbook") {|tmpfile| "shouldn't get here"} + rest.fetch("cookbooks/a_cookbook") { |tmpfile| "shouldn't get here" } expect(File.exists?(path)).to be_falsey end @@ -676,12 +672,12 @@ describe Chef::REST do expect(http_client).to receive(:request).and_yield(redirect).and_return(redirect) expect(http_client).to receive(:request).and_yield(http_response).and_return(http_response) - rest.fetch("cookbooks/a_cookbook") {|tmpfile| "shouldn't get here"} + rest.fetch("cookbooks/a_cookbook") { |tmpfile| "shouldn't get here" } end it "passes the original block to the redirected request" do http_redirect = Net::HTTPFound.new("1.1", "302", "bob is taking care of that one for me today") - http_redirect.add_field("location","/that-thing-is-here-now") + http_redirect.add_field("location", "/that-thing-is-here-now") allow(http_redirect).to receive(:read_body) block_called = false @@ -705,8 +701,8 @@ describe Chef::REST do end it "raises a RedirectLimitExceeded when redirected more than 10 times" do - redirected = lambda {rest.follow_redirect { redirected.call }} - expect {redirected.call}.to raise_error(Chef::Exceptions::RedirectLimitExceeded) + redirected = lambda { rest.follow_redirect { redirected.call } } + expect { redirected.call }.to raise_error(Chef::Exceptions::RedirectLimitExceeded) end it "does not count redirects from previous calls against the redirect limit" do @@ -717,9 +713,9 @@ describe Chef::REST do redirected.call unless total_redirects >= 9 end end - expect {redirected.call}.not_to raise_error + expect { redirected.call }.not_to raise_error total_redirects = 0 - expect {redirected.call}.not_to raise_error + expect { redirected.call }.not_to raise_error end it "does not sign the redirected request when sign_on_redirect is false" do @@ -743,12 +739,11 @@ describe Chef::REST do redirected.call unless total_redirects >= 9 end end - expect {redirected.call}.not_to raise_error + expect { redirected.call }.not_to raise_error total_redirects = 0 rest.redirect_limit = 3 - expect {redirected.call}.to raise_error(Chef::Exceptions::RedirectLimitExceeded) + expect { redirected.call }.to raise_error(Chef::Exceptions::RedirectLimitExceeded) end - end end diff --git a/spec/unit/role_spec.rb b/spec/unit/role_spec.rb index 6cdeaced47..744deb0067 100644 --- a/spec/unit/role_spec.rb +++ b/spec/unit/role_spec.rb @@ -39,12 +39,10 @@ describe Chef::Role do end describe "when a run list is set" do - before do @role.run_list(%w{ nginx recipe[ree] role[base]}) end - it "returns the run list" do expect(@role.run_list).to eq(%w{ nginx recipe[ree] role[base]}) end @@ -79,12 +77,10 @@ describe Chef::Role do it "env_run_lists can only be set with _default run list in it" do long_exception_name = Chef::Exceptions::InvalidEnvironmentRunListSpecification - expect {@role.env_run_lists({})}.to raise_error(long_exception_name) + expect { @role.env_run_lists({}) }.to raise_error(long_exception_name) end - end - describe "using the old #recipes API" do it "should let you set the recipe array" do expect(@role.recipes([ "one", "two" ])).to eq([ "one", "two" ]) @@ -99,13 +95,9 @@ describe Chef::Role do @role.run_list([ "one", "role[two]"]) expect(@role.recipes).to eq([ "recipe[one]", "role[two]" ]) end - end - end - - describe "default_attributes" do it "should let you set the default attributes hash explicitly" do expect(@role.default_attributes({ :one => "two" })).to eq({ :one => "two" }) @@ -214,7 +206,6 @@ describe Chef::Role do it "does not include the default environment in the per-environment run lists" do expect(@serialized_role["env_run_lists"]).not_to have_key("_default") end - end include_examples "to_json equivalent to Chef::JSONCompat.to_json" do @@ -249,7 +240,7 @@ describe Chef::Role do end end - ROLE_DSL=<<-EOR + ROLE_DSL = <<-EOR name "ceiling_cat" description "like Aliens, but furry" EOR @@ -293,25 +284,24 @@ EOR it "should raise an exception if the file does not exist" do expect(Dir).to receive(:glob).and_return(["#{Chef::Config[:role_path]}/meme.rb"]) expect(File).not_to receive(:exists?) - expect {@role.class.from_disk("lolcat")}.to raise_error(Chef::Exceptions::RoleNotFound) + expect { @role.class.from_disk("lolcat") }.to raise_error(Chef::Exceptions::RoleNotFound) end it "should raise an exception if two files exist with the same name" do expect(Dir).to receive(:glob).and_return(["#{Chef::Config[:role_path]}/memes/lolcat.rb", "#{Chef::Config[:role_path]}/lolcat.rb"]) expect(File).not_to receive(:exists?) - expect {@role.class.from_disk("lolcat")}.to raise_error(Chef::Exceptions::DuplicateRole) + expect { @role.class.from_disk("lolcat") }.to raise_error(Chef::Exceptions::DuplicateRole) end it "should not raise an exception if two files exist with a similar name" do expect(Dir).to receive(:glob).and_return(["#{Chef::Config[:role_path]}/memes/lolcat.rb", "#{Chef::Config[:role_path]}/super_lolcat.rb"]) expect(File).to receive(:exists?).with("#{Chef::Config[:role_path]}/memes/lolcat.rb").and_return(true) allow_any_instance_of(Chef::Role).to receive(:from_file).with("#{Chef::Config[:role_path]}/memes/lolcat.rb") - expect{ @role.class.from_disk("lolcat") }.not_to raise_error + expect { @role.class.from_disk("lolcat") }.not_to raise_error end end describe "when loading from disk and role_path is an array" do - before(:each) do Chef::Config[:role_path] = ["/path1", "/path/path2"] end @@ -355,8 +345,7 @@ EOR it "should raise an exception if the file does not exist" do expect(Dir).to receive(:glob).with(File.join("/path1", "**", "**")).exactly(1).times.and_return([]) expect(Dir).to receive(:glob).with(File.join("/path/path2", "**", "**")).exactly(1).times.and_return([]) - expect {@role.class.from_disk("lolcat")}.to raise_error(Chef::Exceptions::RoleNotFound) + expect { @role.class.from_disk("lolcat") }.to raise_error(Chef::Exceptions::RoleNotFound) end - end end diff --git a/spec/unit/run_context/cookbook_compiler_spec.rb b/spec/unit/run_context/cookbook_compiler_spec.rb index c53d10da47..4190261c57 100644 --- a/spec/unit/run_context/cookbook_compiler_spec.rb +++ b/spec/unit/run_context/cookbook_compiler_spec.rb @@ -27,7 +27,6 @@ require "support/lib/library_load_order" # Side effects used to verify the behavior are implemented as code in the various file types. # describe Chef::RunContext::CookbookCompiler do - let(:node) { Chef::Node.new } let(:events) { Chef::EventDispatch::Dispatcher.new } @@ -51,9 +50,7 @@ describe Chef::RunContext::CookbookCompiler do Chef::RunContext::CookbookCompiler.new(run_context, run_list_expansion, events) end - describe "loading attribute files" do - # Attribute files in the fixture data will append their # "cookbook_name::attribute_file_name" to the node's `:attr_load_order` # attribute when loaded. @@ -155,7 +152,6 @@ describe Chef::RunContext::CookbookCompiler do "circular-dep1-definition", "test-with-circular-deps-definition"]) end - end describe "loading recipes" do @@ -180,7 +176,5 @@ describe Chef::RunContext::CookbookCompiler do expect(compiler.unreachable_cookbook?(:'circular-dep1')).to be_truthy expect(compiler.unreachable_cookbook?(:'circular-dep2')).to be_truthy end - - end end diff --git a/spec/unit/run_context_spec.rb b/spec/unit/run_context_spec.rb index 3bc09c8bc3..4e50818ab2 100644 --- a/spec/unit/run_context_spec.rb +++ b/spec/unit/run_context_spec.rb @@ -93,7 +93,6 @@ describe Chef::RunContext do describe "loading cookbooks for a run list" do before do - # Each invocation reloads LWRPs, which triggers constant redefinition # warnings. In real usage this isn't an issue because of fork mode. if Chef::Provider.const_defined?(:TestProvider) @@ -202,7 +201,7 @@ describe Chef::RunContext do let(:notification) { Chef::Resource::Notification.new(nil, nil, notifying_resource) } shared_context "notifying resource is a Chef::Resource" do - let(:notifying_resource) { Chef::Resource.new("gerbil") } + let(:notifying_resource) { Chef::Resource.new("gerbil") } it "should be keyed off the resource name" do run_context.send(setter, notification) @@ -212,7 +211,7 @@ describe Chef::RunContext do shared_context "notifying resource is a subclass of Chef::Resource" do let(:declared_type) { :alpaca } - let(:notifying_resource) { + let(:notifying_resource) { r = Class.new(Chef::Resource).new("guinea pig") r.declared_type = declared_type r diff --git a/spec/unit/run_list/run_list_expansion_spec.rb b/spec/unit/run_list/run_list_expansion_spec.rb index b269c7923d..3ae59b4b85 100644 --- a/spec/unit/run_list/run_list_expansion_spec.rb +++ b/spec/unit/run_list/run_list_expansion_spec.rb @@ -61,7 +61,6 @@ describe Chef::RunList::RunListExpansion do it "has the correct list of recipes for the given environment" do expect(@expansion.recipes).to eq(["lobster::mastercookbook", "prod-only", "fist"]) end - end describe "after applying a role" do @@ -84,23 +83,22 @@ describe Chef::RunList::RunListExpansion do @first_role = Chef::Role.new @first_role.name("rage") @first_role.run_list("role[mollusk]") - @first_role.default_attributes({"foo" => "bar"}) - @first_role.override_attributes({"baz" => "qux"}) + @first_role.default_attributes({ "foo" => "bar" }) + @first_role.override_attributes({ "baz" => "qux" }) @second_role = Chef::Role.new @second_role.name("rage") @second_role.run_list("recipe[crabrevenge]") - @second_role.default_attributes({"foo" => "boo"}) - @second_role.override_attributes({"baz" => "bux"}) + @second_role.default_attributes({ "foo" => "boo" }) + @second_role.override_attributes({ "baz" => "bux" }) allow(@expansion).to receive(:fetch_role).and_return(@first_role, @second_role) @expansion.expand @json = '{"id":"_default","run_list":[{"type":"recipe","name":"lobster::mastercookbook","version":"0.1.0",' - .concat( + .concat( '"skipped":false},{"type":"role","name":"rage","children":[{"type":"role","name":"mollusk","children":[],"missing":null,' .concat( '"error":null,"skipped":null},{"type":"recipe","name":"crabrevenge","version":null,"skipped":false}],"missing":null,' .concat( '"error":null,"skipped":null},{"type":"recipe","name":"fist","version":"0.1","skipped":false}]}'))) - end it "produces json tree upon tracing expansion" do @@ -113,15 +111,14 @@ describe Chef::RunList::RunListExpansion do end it "has the merged attributes from the roles with outer roles overriding inner" do - expect(@expansion.default_attrs).to eq({"foo" => "bar"}) - expect(@expansion.override_attrs).to eq({"baz" => "qux"}) + expect(@expansion.default_attrs).to eq({ "foo" => "bar" }) + expect(@expansion.override_attrs).to eq({ "baz" => "qux" }) end it "has the list of all roles applied" do # this is the correct order, but 1.8 hash order is not stable expect(@expansion.roles).to match_array(["rage", "mollusk"]) end - end describe "after expanding a run list with a non existent role" do @@ -138,7 +135,5 @@ describe Chef::RunList::RunListExpansion do it "has a list of invalid role names" do expect(@expansion.errors).to include("crabrevenge") end - end - end diff --git a/spec/unit/run_list/run_list_item_spec.rb b/spec/unit/run_list/run_list_item_spec.rb index b4fe42f041..6d87d6a282 100644 --- a/spec/unit/run_list/run_list_item_spec.rb +++ b/spec/unit/run_list/run_list_item_spec.rb @@ -19,21 +19,19 @@ require "spec_helper" describe Chef::RunList::RunListItem do - describe "when creating from a Hash" do it "raises an exception when the hash doesn't have a :type key" do - expect {Chef::RunList::RunListItem.new(:name => "tatft")}.to raise_error(ArgumentError) + expect { Chef::RunList::RunListItem.new(:name => "tatft") }.to raise_error(ArgumentError) end it "raises an exception when the hash doesn't have an :name key" do - expect {Chef::RunList::RunListItem.new(:type => "R") }.to raise_error(ArgumentError) + expect { Chef::RunList::RunListItem.new(:type => "R") }.to raise_error(ArgumentError) end it "sets the name and type as given in the hash" do item = Chef::RunList::RunListItem.new(:type => "fuuu", :name => "uuuu") expect(item.to_s).to eq("fuuu[uuuu]") end - end describe "when creating an item from a string" do @@ -71,15 +69,15 @@ describe Chef::RunList::RunListItem do end it "raises an exception when the string has typo on the type part" do - expect {Chef::RunList::RunListItem.new("Recipe[lobster]") }.to raise_error(ArgumentError) + expect { Chef::RunList::RunListItem.new("Recipe[lobster]") }.to raise_error(ArgumentError) end it "raises an exception when the string has extra space between the type and the name" do - expect {Chef::RunList::RunListItem.new("recipe [lobster]") }.to raise_error(ArgumentError) + expect { Chef::RunList::RunListItem.new("recipe [lobster]") }.to raise_error(ArgumentError) end it "raises an exception when the string does not close the bracket" do - expect {Chef::RunList::RunListItem.new("recipe[lobster") }.to raise_error(ArgumentError) + expect { Chef::RunList::RunListItem.new("recipe[lobster") }.to raise_error(ArgumentError) 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 df9c8930ea..a529d5127f 100644 --- a/spec/unit/run_list/versioned_recipe_list_spec.rb +++ b/spec/unit/run_list/versioned_recipe_list_spec.rb @@ -18,7 +18,6 @@ require "spec_helper" describe Chef::RunList::VersionedRecipeList do - describe "initialize" do it "should create an empty array" do l = Chef::RunList::VersionedRecipeList.new @@ -34,11 +33,10 @@ describe Chef::RunList::VersionedRecipeList do before do recipes.each { |r| list << r } - versioned_recipes.each {|r| list.add_recipe r[:name], r[:version]} + versioned_recipes.each { |r| list.add_recipe r[:name], r[:version] } end describe "add_recipe" do - let(:recipes) { %w{ apt god apache2 } } it "should append the recipe to the end of the list" do @@ -54,40 +52,39 @@ describe Chef::RunList::VersionedRecipeList do it "should allow you to specify a version" do list.add_recipe "rails", "1.0.0" expect(list).to eq(["apt", "god", "apache2", "rails"]) - expect(list.with_versions).to include({:name => "rails", :version => "1.0.0"}) + expect(list.with_versions).to include({ :name => "rails", :version => "1.0.0" }) end it "should allow you to specify a version for a recipe that already exists" do list.add_recipe "apt", "1.2.3" expect(list).to eq(["apt", "god", "apache2"]) - expect(list.with_versions).to include({:name => "apt", :version => "1.2.3"}) + expect(list.with_versions).to include({ :name => "apt", :version => "1.2.3" }) end it "should allow you to specify the same version of a recipe twice" do list.add_recipe "rails", "1.0.0" list.add_recipe "rails", "1.0.0" - expect(list.with_versions).to include({:name => "rails", :version => "1.0.0"}) + expect(list.with_versions).to include({ :name => "rails", :version => "1.0.0" }) end it "should allow you to spcify no version, even when a version already exists" do list.add_recipe "rails", "1.0.0" list.add_recipe "rails" - expect(list.with_versions).to include({:name => "rails", :version => "1.0.0"}) + expect(list.with_versions).to include({ :name => "rails", :version => "1.0.0" }) end it "should not allow multiple versions of the same recipe" do list.add_recipe "rails", "1.0.0" - expect {list.add_recipe "rails", "0.1.0"}.to raise_error Chef::Exceptions::CookbookVersionConflict + expect { list.add_recipe "rails", "0.1.0" }.to raise_error Chef::Exceptions::CookbookVersionConflict end end describe "with_versions" do - let(:versioned_recipes) do [ - {:name => "apt", :version => "1.0.0"}, - {:name => "god", :version => nil}, - {:name => "apache2", :version => "0.0.1"}, + { :name => "apt", :version => "1.0.0" }, + { :name => "god", :version => nil }, + { :name => "apache2", :version => "0.0.1" }, ] end it "should return an array of hashes with :name and :version" do @@ -103,19 +100,16 @@ describe Chef::RunList::VersionedRecipeList do end describe "with_version_constraints" do - let(:versioned_recipes) do [ - {:name => "apt", :version => "~> 1.2.0"}, - {:name => "god", :version => nil}, - {:name => "apache2", :version => "0.0.1"}, + { :name => "apt", :version => "~> 1.2.0" }, + { :name => "god", :version => nil }, + { :name => "apache2", :version => "0.0.1" }, ] end - it "should return an array of hashes with :name and :version_constraint" do list.with_version_constraints.each_with_index do |recipe_spec, i| - expected_recipe = versioned_recipes[i] expect(recipe_spec[:name]).to eq(expected_recipe[:name]) @@ -125,34 +119,28 @@ describe Chef::RunList::VersionedRecipeList do end describe "with_fully_qualified_names_and_version_constraints" do - let(:fq_names) { list.with_fully_qualified_names_and_version_constraints } context "with bare cookbook names" do - let(:recipes) { %w{ apache2 } } it "gives $cookbook_name::default" do expect(fq_names).to eq( %w{ apache2::default } ) end - end context "with qualified recipe names but no versions" do - let(:recipes) { %w{ mysql::server } } it "returns the qualified recipe names" do expect(fq_names).to eq( %w{ mysql::server } ) end - end context "with unqualified names that have version constraints" do - let(:versioned_recipes) do [ - {:name => "apt", :version => "~> 1.2.0"}, + { :name => "apt", :version => "~> 1.2.0" }, ] end @@ -164,14 +152,12 @@ describe Chef::RunList::VersionedRecipeList do expect(fq_names).to eq([ "apt::default@~> 1.2.0" ]) expect(list).to eq( [ "apt" ] ) end - end context "with fully qualified names that have version constraints" do - let(:versioned_recipes) do [ - {:name => "apt::cacher", :version => "~> 1.2.0"}, + { :name => "apt::cacher", :version => "~> 1.2.0" }, ] end @@ -183,7 +169,6 @@ describe Chef::RunList::VersionedRecipeList do expect(fq_names).to eq([ "apt::cacher@~> 1.2.0" ]) expect(list).to eq( [ "apt::cacher" ] ) end - end end diff --git a/spec/unit/run_list_spec.rb b/spec/unit/run_list_spec.rb index 20de26ec78..b2dc3aeee0 100644 --- a/spec/unit/run_list_spec.rb +++ b/spec/unit/run_list_spec.rb @@ -223,7 +223,6 @@ describe Chef::RunList do @role_prod_base.name("prod-base") @role_prod_base.env_run_list["production"] = Chef::RunList.new("role[nested-deeper]") - @role_nested_deeper = Chef::Role.new @role_nested_deeper.name("nested-deeper") @role_nested_deeper.env_run_list["production"] = Chef::RunList.new("recipe[prod-secret-sauce]") @@ -238,11 +237,8 @@ describe Chef::RunList do expansion = @run_list.expand("production", "server") expect(expansion.recipes).to eq(%w{one two five prod-secret-sauce kitty}) end - end - end - end it "should return the list of expanded recipes" do @@ -307,7 +303,5 @@ describe Chef::RunList do include_examples "to_json equivalent to Chef::JSONCompat.to_json" do let(:jsonable) { @run_list } end - end - end diff --git a/spec/unit/run_lock_spec.rb b/spec/unit/run_lock_spec.rb index 937a6dc258..067e7d611a 100644 --- a/spec/unit/run_lock_spec.rb +++ b/spec/unit/run_lock_spec.rb @@ -19,7 +19,6 @@ require File.expand_path("../../spec_helper", __FILE__) require "chef/client" describe Chef::RunLock do - default_cache_path = windows? ? 'C:\chef' : "/var/chef" default_pid_location = windows? ? 'C:\chef\cache\chef-client-running.pid' : "/var/chef/cache/chef-client-running.pid" @@ -91,7 +90,7 @@ describe Chef::RunLock do it "should raise Chef::Exceptions::RunLockTimeout" do stub_blocked_run(0.001) expect(runlock).not_to receive(:wait) - expect{ runlock.acquire }.to raise_error(Chef::Exceptions::RunLockTimeout) + expect { runlock.acquire }.to raise_error(Chef::Exceptions::RunLockTimeout) end end end @@ -118,9 +117,9 @@ describe Chef::RunLock do describe "and the lockfile is locked by another client run" do describe "and the lock is released before the timeout expires" do it "should acquire the lock" do - stub_blocked_run(@timeout/2.0) + stub_blocked_run(@timeout / 2.0) expect(runlock).to receive(:wait) - expect{ runlock.acquire }.not_to raise_error + expect { runlock.acquire }.not_to raise_error end end @@ -128,7 +127,7 @@ describe Chef::RunLock do it "should raise a RunLockTimeout exception" do stub_blocked_run(2.0) expect(runlock).to receive(:wait) - expect{ runlock.acquire }.to raise_error(Chef::Exceptions::RunLockTimeout) + expect { runlock.acquire }.to raise_error(Chef::Exceptions::RunLockTimeout) end end end @@ -136,5 +135,4 @@ describe Chef::RunLock do end # See also: spec/functional/run_lock_spec - end diff --git a/spec/unit/run_status_spec.rb b/spec/unit/run_status_spec.rb index 016f5d608a..e6a011f774 100644 --- a/spec/unit/run_status_spec.rb +++ b/spec/unit/run_status_spec.rb @@ -16,7 +16,6 @@ # limitations under the License. # - require "spec_helper" describe Chef::RunStatus do @@ -77,7 +76,6 @@ describe Chef::RunStatus do expect(@run_status.to_hash[:end_time]).to eq(@end_time) expect(@run_status.to_hash[:elapsed_time]).to eq(23) end - end describe "with resources in the resource_collection" do diff --git a/spec/unit/runner_spec.rb b/spec/unit/runner_spec.rb index fe524e1cd3..4fd94c90e6 100644 --- a/spec/unit/runner_spec.rb +++ b/spec/unit/runner_spec.rb @@ -49,11 +49,9 @@ class SnitchyProvider < Chef::Provider @new_resource.updated_by_last_action(true) self.class.action_called(:third) end - end class FailureResource < Chef::Resource - attr_accessor :action def initialize(*args) @@ -67,7 +65,6 @@ class FailureResource < Chef::Resource end class FailureProvider < Chef::Provider - class ChefClientFail < StandardError; end def load_current_resource @@ -80,7 +77,6 @@ class FailureProvider < Chef::Provider end describe Chef::Runner do - let(:node) do node = Chef::Node.new node.name "latte" @@ -117,7 +113,6 @@ describe Chef::Runner do end context "when we are doing dynamic provider resolution" do - it "should pass each resource in the collection to a provider" do expect(run_context.resource_collection).to receive(:execute_each_resource).once runner.converge @@ -239,7 +234,7 @@ describe Chef::Runner do second_resource.notifies(:fail, third_resource, :delayed) second_resource.notifies(:purr, first_resource, :delayed) - expect {runner.converge}.to raise_error(FailureProvider::ChefClientFail) + expect { runner.converge }.to raise_error(FailureProvider::ChefClientFail) expect(first_resource).to be_updated end @@ -271,7 +266,7 @@ describe Chef::Runner do end expect(exception).to be_a(Chef::Exceptions::MultipleFailures) - expected_message =<<-E + expected_message = <<-E Multiple failures occurred: * FailureProvider::ChefClientFail occurred in delayed notification: [explode] (dynamically defined) had an error: FailureProvider::ChefClientFail: chef had an error of some sort * FailureProvider::ChefClientFail occurred in delayed notification: [explode again] (dynamically defined) had an error: FailureProvider::ChefClientFail: chef had an error of some sort @@ -372,10 +367,10 @@ Multiple failures occurred: first_resource.action = :buy only_if_called_times = 0 - first_resource.only_if {only_if_called_times += 1; true} + first_resource.only_if { only_if_called_times += 1; true } not_if_called_times = 0 - first_resource.not_if {not_if_called_times += 1; false} + first_resource.not_if { not_if_called_times += 1; false } second_resource = Chef::Resource::Cat.new("carmel", run_context) run_context.resource_collection << second_resource @@ -406,6 +401,5 @@ Multiple failures occurred: expect(first_resource).to be_updated end - end end diff --git a/spec/unit/scan_access_control_spec.rb b/spec/unit/scan_access_control_spec.rb index c48b92349f..b1639e26a9 100644 --- a/spec/unit/scan_access_control_spec.rb +++ b/spec/unit/scan_access_control_spec.rb @@ -19,7 +19,6 @@ require File.expand_path("../../spec_helper", __FILE__) require "chef/scan_access_control" describe Chef::ScanAccessControl do - before do @new_resource = Chef::Resource::File.new("/tmp/foo/bar/baz/link") @real_file = "/tmp/foo/bar/real/file" @@ -28,7 +27,6 @@ describe Chef::ScanAccessControl do end describe "when the fs entity does not exist" do - before do @new_resource.tap do |f| f.owner("root") @@ -43,11 +41,9 @@ describe Chef::ScanAccessControl do expect(@current_resource.group).to be_nil expect(@current_resource.mode).to be_nil end - end describe "when the fs entity exists" do - before do @stat = double("File::Stat for #{@new_resource.path}", :uid => 0, :gid => 0, :mode => 00100644) expect(File).to receive(:realpath).with(@new_resource.path).and_return(@real_file) @@ -106,11 +102,9 @@ describe Chef::ScanAccessControl do it "sets the mode of the current resource to the current mode as a String" do expect(@current_resource.mode).to eq("0644") end - end describe "when new_resource specifies the user with a UID" do - before do @new_resource.user(0) @scanner.set_all! @@ -122,7 +116,6 @@ describe Chef::ScanAccessControl do end describe "when new_resource specifies the user with a username" do - before do @new_resource.user("root") end @@ -145,7 +138,6 @@ describe Chef::ScanAccessControl do end describe "when new_resource specifies the group with a GID" do - before do @new_resource.group(0) @scanner.set_all! @@ -154,7 +146,6 @@ describe Chef::ScanAccessControl do it "sets the group of the current_resource to the gid of the current owner" do expect(@current_resource.group).to eq(0) end - end describe "when new_resource specifies the group with a group name" do @@ -177,8 +168,6 @@ describe Chef::ScanAccessControl do expect(@current_resource.group).to eq(0) end end - end end end - diff --git a/spec/unit/search/query_spec.rb b/spec/unit/search/query_spec.rb index 54c21944f0..6859672f1c 100644 --- a/spec/unit/search/query_spec.rb +++ b/spec/unit/search/query_spec.rb @@ -68,9 +68,9 @@ describe Chef::Search::Query do let(:response_rows) { [ { "env" => "elysium", "ruby_plat" => "nudibranch" }, - { "env" => "hades", "ruby_plat" => "i386-mingw32"}, - { "env" => "elysium", "ruby_plat" => "centos"}, - { "env" => "moon", "ruby_plat" => "solaris2"}, + { "env" => "hades", "ruby_plat" => "i386-mingw32" }, + { "env" => "elysium", "ruby_plat" => "centos" }, + { "env" => "moon", "ruby_plat" => "solaris2" }, ] } end @@ -263,7 +263,6 @@ describe Chef::Search::Query do filtered_rows = query.search(:node, "platform:rhel", args)[0] expect(filtered_rows).to match_array(response_rows) end - end end end diff --git a/spec/unit/shell/model_wrapper_spec.rb b/spec/unit/shell/model_wrapper_spec.rb index 311b90ecbe..e96400a9c4 100644 --- a/spec/unit/shell/model_wrapper_spec.rb +++ b/spec/unit/shell/model_wrapper_spec.rb @@ -21,13 +21,13 @@ require "ostruct" describe Shell::ModelWrapper do before do - @model = OpenStruct.new(:name=>"Chef::Node") + @model = OpenStruct.new(:name => "Chef::Node") @wrapper = Shell::ModelWrapper.new(@model) end describe "when created with an explicit model_symbol" do before do - @model = OpenStruct.new(:name=>"Chef::ApiClient") + @model = OpenStruct.new(:name => "Chef::ApiClient") @wrapper = Shell::ModelWrapper.new(@model, :client) end @@ -46,7 +46,7 @@ describe Shell::ModelWrapper do @node_1.name("sammich") @node_2 = Chef::Node.new @node_2.name("yummy") - @server_response = {:node_1 => @node_1, :node_2 => @node_2} + @server_response = { :node_1 => @node_1, :node_2 => @node_2 } @wrapper = Shell::ModelWrapper.new(Chef::Node) allow(Chef::Node).to receive(:list).and_return(@server_response) end @@ -57,7 +57,7 @@ describe Shell::ModelWrapper do end it "maps the listed nodes when given a block" do - expect(@wrapper.all {|n| n.name }.sort.reverse).to eq(%w{yummy sammich}) + expect(@wrapper.all { |n| n.name }.sort.reverse).to eq(%w{yummy sammich}) end end @@ -67,7 +67,7 @@ describe Shell::ModelWrapper do @node_1.name("sammich") @node_2 = Chef::Node.new @node_2.name("yummy") - @server_response = {:node_1 => @node_1, :node_2 => @node_2} + @server_response = { :node_1 => @node_1, :node_2 => @node_2 } @wrapper = Shell::ModelWrapper.new(Chef::Node) # Creating a Chef::Search::Query object tries to read the private key... @@ -88,10 +88,7 @@ describe Shell::ModelWrapper do it "creates a 'AND'-joined query string from a HASH" do # Hash order woes expect(@searcher).to receive(:search).with(:node, "name:app* AND name:app*").and_yield(@node_1).and_yield(@node_2) - expect(@wrapper.find(:name=>"app*","name"=>"app*")).to include(@node_1, @node_2) + expect(@wrapper.find(:name => "app*", "name" => "app*")).to include(@node_1, @node_2) end - end - - end diff --git a/spec/unit/shell/shell_ext_spec.rb b/spec/unit/shell/shell_ext_spec.rb index a418eba217..dabacd4a0a 100644 --- a/spec/unit/shell/shell_ext_spec.rb +++ b/spec/unit/shell/shell_ext_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" describe Shell::Extensions do describe "extending object for top level methods" do - before do @shell_client = TestableShellSession.instance allow(Shell).to receive(:session).and_return(@shell_client) @@ -92,9 +91,9 @@ describe Shell::Extensions do end it "prints node attributes" do - node = double("node", :attribute => {:foo => :bar}) + node = double("node", :attribute => { :foo => :bar }) @shell_client.node = node - expect(@root_context).to receive(:pp).with({:foo => :bar}) + expect(@root_context).to receive(:pp).with({ :foo => :bar }) @root_context.ohai expect(@root_context).to receive(:pp).with(:bar) @root_context.ohai(:foo) @@ -131,11 +130,9 @@ describe Shell::Extensions do expect(Dir).to receive(:entries).with("/tmp").and_return(entries) @root_context.ls "/tmp" end - end describe "extending the recipe object" do - before do @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(Chef::Node.new, {}, @events) @@ -148,6 +145,5 @@ describe Shell::Extensions do expect(@recipe_object).to receive(:pp).with(["file[foo]"]) @recipe_object.resources end - end end diff --git a/spec/unit/shell/shell_session_spec.rb b/spec/unit/shell/shell_session_spec.rb index 289bf35313..c286f12cd8 100644 --- a/spec/unit/shell/shell_session_spec.rb +++ b/spec/unit/shell/shell_session_spec.rb @@ -18,9 +18,7 @@ require "spec_helper" require "ostruct" - class TestableShellSession < Shell::ShellSession - def rebuild_node nil end @@ -36,15 +34,12 @@ class TestableShellSession < Shell::ShellSession def loading_complete nil end - end describe Shell::ShellSession do - it "is a singleton object" do expect(Shell::ShellSession).to include(Singleton) end - end describe Shell::ClientSession do @@ -75,7 +70,6 @@ describe Shell::ClientSession do expect(Chef::Client).to receive(:new).with(nil, Chef::Config[:shell_config]).and_return(@client) @session.send(:rebuild_node) end - end describe Shell::StandAloneSession do @@ -126,7 +120,6 @@ describe Shell::StandAloneSession do expect(Chef::Client).to receive(:new).with(nil, Chef::Config[:shell_config]).and_return(@client) @session.send(:rebuild_node) end - end describe Shell::SoloSession do @@ -158,7 +151,7 @@ describe Shell::SoloSession do end it "keeps json attribs and passes them to the node for consumption" do - @session.node_attributes = {"besnard_lakes" => "are_the_dark_horse"} + @session.node_attributes = { "besnard_lakes" => "are_the_dark_horse" } expect(@session.node.besnard_lakes).to eq("are_the_dark_horse") #pending "1) keep attribs in an ivar 2) pass them to the node 3) feed them to the node on reset" end @@ -192,5 +185,4 @@ describe Shell::SoloSession do expect(Chef::Client).to receive(:new).with(nil, Chef::Config[:shell_config]).and_return(@client) @session.send(:rebuild_node) end - end diff --git a/spec/unit/shell_out_spec.rb b/spec/unit/shell_out_spec.rb index 35844f4961..4704484f3b 100644 --- a/spec/unit/shell_out_spec.rb +++ b/spec/unit/shell_out_spec.rb @@ -9,7 +9,6 @@ describe "Chef::ShellOut deprecation notices" do end describe "Chef::Exceptions::ShellCommandFailed deprecation notices" do - it "logs a warning when referencing the constant Chef::Exceptions::ShellCommandFailed" do expect(Chef::Log).to receive(:warn).with("Chef::Exceptions::ShellCommandFailed is deprecated, use Mixlib::ShellOut::ShellCommandFailed") expect(Chef::Log).to receive(:warn).with(/Called from\:/) diff --git a/spec/unit/shell_spec.rb b/spec/unit/shell_spec.rb index cebd7b0389..4c226b94a1 100644 --- a/spec/unit/shell_spec.rb +++ b/spec/unit/shell_spec.rb @@ -39,7 +39,6 @@ class TestJobManager end describe Shell do - before do Shell.irb_conf = {} allow(Shell::ShellSession.instance).to receive(:reset!) @@ -48,11 +47,9 @@ describe Shell do end describe "reporting its status" do - it "always says it is running" do expect(Shell).to be_running end - end describe "configuring IRB" do @@ -82,7 +79,7 @@ describe Shell do conf = OpenStruct.new events = Chef::EventDispatch::Dispatcher.new - conf.main = Chef::Recipe.new(nil,nil,Chef::RunContext.new(Chef::Node.new, {}, events)) + conf.main = Chef::Recipe.new(nil, nil, Chef::RunContext.new(Chef::Node.new, {}, events)) Shell.irb_conf[:IRB_RC].call(conf) expect(conf.prompt_c).to eq("chef:recipe > ") expect(conf.prompt_i).to eq("chef:recipe (#{Chef::VERSION})> ") @@ -101,11 +98,9 @@ describe Shell do expect(conf.prompt_n).to eq("chef:attributes ?> ") expect(conf.prompt_s).to eq("chef:attributes%l> ") end - end describe "convenience macros for creating the chef object" do - before do @chef_object = Object.new @chef_object.instance_eval(&ObjectTestHarness) @@ -116,7 +111,7 @@ describe Shell do end it "adds help text when a new method is described then defined" do - describe_define =<<-EVAL + describe_define = <<-EVAL desc "foo2the Bar" def baz end @@ -127,7 +122,7 @@ describe Shell do end it "adds help text for subcommands" do - describe_define =<<-EVAL + describe_define = <<-EVAL subcommands :baz_obj_command => "something you can do with baz.baz_obj_command" def baz end @@ -139,7 +134,7 @@ describe Shell do end it "doesn't add previous subcommand help to commands defined afterward" do - describe_define =<<-EVAL + describe_define = <<-EVAL desc "swingFromTree" def monkey_time end @@ -150,7 +145,7 @@ describe Shell do EVAL @chef_object.instance_eval describe_define expect(@chef_object.help_descriptions.size).to eq(2) - expect(@chef_object.help_descriptions.select {|h| h.cmd == "super_monkey_time" }).to be_empty + expect(@chef_object.help_descriptions.select { |h| h.cmd == "super_monkey_time" }).to be_empty end it "creates a help banner with the command descriptions" do @@ -158,5 +153,4 @@ describe Shell do expect(@chef_object.help_banner).to match(/^\|\ rspec_method[\s]+\|\ rspecin\'[\s]*$/) end end - end diff --git a/spec/unit/user_spec.rb b/spec/unit/user_spec.rb index a4f1dff721..9b7b41b270 100644 --- a/spec/unit/user_spec.rb +++ b/spec/unit/user_spec.rb @@ -60,7 +60,6 @@ describe Chef::User do expect { @user.name "foo&" }.to raise_error(ArgumentError) end - it "should not accept spaces" do expect { @user.name "ops master" }.to raise_error(ArgumentError) end @@ -168,10 +167,10 @@ describe Chef::User do describe "when deserializing from JSON" do before(:each) do user = { "name" => "mr_spinks", - "public_key" => "turtles", - "private_key" => "pandas", - "password" => "password", - "admin" => true } + "public_key" => "turtles", + "private_key" => "pandas", + "password" => "password", + "admin" => true } @user = Chef::User.from_json(Chef::JSONCompat.to_json(user)) end @@ -198,7 +197,6 @@ describe Chef::User do it "includes the password if present" do expect(@user.password).to eq("password") end - end describe "API Interactions" do @@ -212,8 +210,8 @@ describe Chef::User do describe "list" do before(:each) do Chef::Config[:chef_server_url] = "http://www.example.com" - @osc_response = { "admin" => "http://www.example.com/users/admin"} - @ohc_response = [ { "user" => { "username" => "admin" }} ] + @osc_response = { "admin" => "http://www.example.com/users/admin" } + @ohc_response = [ { "user" => { "username" => "admin" } } ] allow(Chef::User).to receive(:load).with("admin").and_return(@user) @osc_inflated_response = { "admin" => @user } end @@ -244,14 +242,14 @@ describe Chef::User do describe "create" do it "creates a new user via the API" do @user.password "password" - expect(@http_client).to receive(:post).with("users", {:name => "foobar", :admin => false, :password => "password"}).and_return({}) + expect(@http_client).to receive(:post).with("users", { :name => "foobar", :admin => false, :password => "password" }).and_return({}) @user.create end end describe "read" do it "loads a named user from the API" do - expect(@http_client).to receive(:get).with("users/foobar").and_return({"name" => "foobar", "admin" => true, "public_key" => "pubkey"}) + expect(@http_client).to receive(:get).with("users/foobar").and_return({ "name" => "foobar", "admin" => true, "public_key" => "pubkey" }) user = Chef::User.load("foobar") expect(user.name).to eq("foobar") expect(user.admin).to eq(true) @@ -261,7 +259,7 @@ describe Chef::User do describe "update" do it "updates an existing user on via the API" do - expect(@http_client).to receive(:put).with("users/foobar", {:name => "foobar", :admin => false}).and_return({}) + expect(@http_client).to receive(:put).with("users/foobar", { :name => "foobar", :admin => false }).and_return({}) @user.update end end diff --git a/spec/unit/user_v1_spec.rb b/spec/unit/user_v1_spec.rb index 165437d350..eaa966debc 100644 --- a/spec/unit/user_v1_spec.rb +++ b/spec/unit/user_v1_spec.rb @@ -90,7 +90,6 @@ describe Chef::UserV1 do expect { @user.username "foo&" }.to raise_error(ArgumentError) end - it "should not accept spaces" do expect { @user.username "ops master" }.to raise_error(ArgumentError) end @@ -413,7 +412,6 @@ describe Chef::UserV1 do it "raises the original error" do expect { @user.update }.to raise_error(exception_400) end - end end # when the server returns a 400 @@ -438,7 +436,6 @@ describe Chef::UserV1 do end end # when the server supports API V0 end # when the server returns a 406 - end # when server API V1 is not valid on the Chef Server receiving the request end # update @@ -474,7 +471,7 @@ describe Chef::UserV1 do context "when handling API V1" do it "creates a new user via the API with a middle_name when it exists" do @user.middle_name "some_middle_name" - expect(@user.chef_root_rest_v1).to receive(:post).with("users", payload.merge({:middle_name => "some_middle_name"})).and_return({}) + expect(@user.chef_root_rest_v1).to receive(:post).with("users", payload.merge({ :middle_name => "some_middle_name" })).and_return({}) @user.create end end # when server API V1 is valid on the Chef Server receiving the request @@ -497,11 +494,10 @@ describe Chef::UserV1 do it "creates a new user via the API with a middle_name when it exists" do @user.middle_name "some_middle_name" - expect(@user.chef_root_rest_v0).to receive(:post).with("users", payload.merge({:middle_name => "some_middle_name"})).and_return({}) + expect(@user.chef_root_rest_v0).to receive(:post).with("users", payload.merge({ :middle_name => "some_middle_name" })).and_return({}) @user.create end end # when server API V1 is not valid on the Chef Server receiving the request - end # create # DEPRECATION @@ -519,7 +515,7 @@ describe Chef::UserV1 do context "when server API V0 is valid on the Chef Server receiving the request" do it "creates a new object via the API" do - expect(@user.chef_root_rest_v0).to receive(:put).with("users/#{@user.username}", payload.merge({"private_key" => true})).and_return({}) + expect(@user.chef_root_rest_v0).to receive(:put).with("users/#{@user.username}", payload.merge({ "private_key" => true })).and_return({}) @user.reregister end end # when server API V0 is valid on the Chef Server receiving the request @@ -532,7 +528,6 @@ describe Chef::UserV1 do end end # when server API V0 is not supported by the Chef Server end # reregister - end # Versioned API Interactions describe "API Interactions" do @@ -546,8 +541,8 @@ describe Chef::UserV1 do describe "list" do before(:each) do Chef::Config[:chef_server_url] = "http://www.example.com" - @osc_response = { "admin" => "http://www.example.com/users/admin"} - @ohc_response = [ { "user" => { "username" => "admin" }} ] + @osc_response = { "admin" => "http://www.example.com/users/admin" } + @ohc_response = [ { "user" => { "username" => "admin" } } ] allow(Chef::UserV1).to receive(:load).with("admin").and_return(@user) @osc_inflated_response = { "admin" => @user } end @@ -567,7 +562,7 @@ describe Chef::UserV1 do describe "read" do it "loads a named user from the API" do - expect(@http_client).to receive(:get).with("users/foobar").and_return({"username" => "foobar", "admin" => true, "public_key" => "pubkey"}) + expect(@http_client).to receive(:get).with("users/foobar").and_return({ "username" => "foobar", "admin" => true, "public_key" => "pubkey" }) user = Chef::UserV1.load("foobar") expect(user.username).to eq("foobar") expect(user.public_key).to eq("pubkey") diff --git a/spec/unit/util/backup_spec.rb b/spec/unit/util/backup_spec.rb index 8d7caff8d6..30dde51bc7 100644 --- a/spec/unit/util/backup_spec.rb +++ b/spec/unit/util/backup_spec.rb @@ -16,12 +16,10 @@ # limitations under the License. # - require "spec_helper" require "tmpdir" describe Chef::Util::Backup do - let (:tempfile) do Tempfile.new("chef-util-backup-spec-test") end @@ -37,7 +35,6 @@ describe Chef::Util::Backup do end describe "for cases when we don't want to back anything up" do - before(:each) do expect(@backup).not_to receive(:do_backup) end @@ -57,7 +54,6 @@ describe Chef::Util::Backup do expect(File).to receive(:exist?).with(tempfile.path).at_least(:once).and_return(false) @backup.backup! end - end describe "for cases when we want to back things up" do @@ -138,5 +134,4 @@ describe Chef::Util::Backup do expect(@backup.send(:backup_path)).to match(%r|^c:\\backupdir[\\/]+a\\b\\c.txt.chef-\d{14}.\d{6}$|) end end - end diff --git a/spec/unit/util/diff_spec.rb b/spec/unit/util/diff_spec.rb index 8a2bef2858..4b5ac9c8b8 100644 --- a/spec/unit/util/diff_spec.rb +++ b/spec/unit/util/diff_spec.rb @@ -16,7 +16,6 @@ # limitations under the License. # - require "spec_helper" require "tmpdir" @@ -106,7 +105,6 @@ shared_examples_for "a diff util" do end describe "when the default external encoding is UTF-8" do - before do @saved_default_external = Encoding.default_external Encoding.default_external = Encoding::UTF_8 @@ -167,11 +165,9 @@ shared_examples_for "a diff util" do expect(differ.for_reporting).to be_nil end end - end describe "when the default external encoding is Latin-1" do - before do @saved_default_external = Encoding.default_external Encoding.default_external = Encoding::ISO_8859_1 @@ -232,10 +228,8 @@ shared_examples_for "a diff util" do expect(differ.for_reporting).to be_nil end end - end describe "when the default external encoding is Shift_JIS" do - before do @saved_default_external = Encoding.default_external Encoding.default_external = Encoding::Shift_JIS @@ -296,7 +290,6 @@ shared_examples_for "a diff util" do expect(differ.for_reporting.encoding).to equal(Encoding::UTF_8) end end - end describe "when testing the diff_filesize_threshold" do @@ -358,7 +351,6 @@ shared_examples_for "a diff util" do end describe "when the diff output is too long" do - before do @diff_output_threshold_saved = Chef::Config[:diff_output_threshold] Chef::Config[:diff_output_threshold] = 10 @@ -379,7 +371,6 @@ shared_examples_for "a diff util" do end describe "when checking if files are binary or text" do - it "should identify zero-length files as text" do Tempfile.open("chef-util-diff-spec") do |file| file.close @@ -412,7 +403,6 @@ shared_examples_for "a diff util" do end describe "when the default external encoding is UTF-8" do - before do @saved_default_external = Encoding.default_external Encoding.default_external = Encoding::UTF_8 @@ -453,11 +443,9 @@ shared_examples_for "a diff util" do expect(differ.send(:is_binary?, file.path)).to be_truthy end end - end describe "when the default external encoding is Latin-1" do - before do @saved_default_external = Encoding.default_external Encoding.default_external = Encoding::ISO_8859_1 @@ -501,7 +489,6 @@ shared_examples_for "a diff util" do end describe "when the default external encoding is Shift-JIS" do - before do @saved_default_external = Encoding.default_external Encoding.default_external = Encoding::Shift_JIS @@ -541,10 +528,8 @@ shared_examples_for "a diff util" do expect(differ.send(:is_binary?, file.path)).to be_falsey end end - end end - end describe Chef::Util::Diff, :uses_diff => true do @@ -553,11 +538,11 @@ describe Chef::Util::Diff, :uses_diff => true do let(:plain_ascii) { "This is a text file.\nWith more than one line.\nAnd a \tTab.\nAnd lets make sure that other printable chars work too: ~!@\#$%^&*()`:\"<>?{}|_+,./;'[]\\-=\n" } # these are all byte sequences that are illegal in the other encodings... (but they may legally transcode) - let(:utf_8) { "testing utf-8 unicode...\n\n\non a new line: \xE2\x80\x93\n" } # unicode em-dash + let(:utf_8) { "testing utf-8 unicode...\n\n\non a new line: \xE2\x80\x93\n" } # unicode em-dash let(:latin_1) { "It is more metal.\nif you have an \xFDmlaut.\n" } # NB: changed to y-with-diaresis, but i'm American so I don't know the difference let(:shift_jis) { "I have no idea what this character is:\n \x83\x80.\n" } # seriously, no clue, but \x80 is nice and illegal in other encodings - let(:differ) do # subject + let(:differ) do # subject differ = Chef::Util::Diff.new differ.diff(old_file, new_file) differ @@ -569,11 +554,9 @@ describe Chef::Util::Diff, :uses_diff => true do it_behaves_like "a diff util" end - describe "when file path doesn't have spaces" do include_context "using file paths without spaces" it_behaves_like "a diff util" end end - diff --git a/spec/unit/util/dsc/configuration_generator_spec.rb b/spec/unit/util/dsc/configuration_generator_spec.rb index 7b39404c4d..d59423e1e5 100644 --- a/spec/unit/util/dsc/configuration_generator_spec.rb +++ b/spec/unit/util/dsc/configuration_generator_spec.rb @@ -50,7 +50,7 @@ describe Chef::Util::DSC::ConfigurationGenerator do describe "#get_merged_configuration_flags" do context "when strings are used as switches" do it "should merge the hash if there are no restricted switches" do - merged = conf_man.send(:get_merged_configuration_flags!, {"flag" => "a"}, "hello") + merged = conf_man.send(:get_merged_configuration_flags!, { "flag" => "a" }, "hello") expect(merged).to include(:flag) expect(merged[:flag]).to eql("a") expect(merged).to include(:outputpath) @@ -58,25 +58,25 @@ describe Chef::Util::DSC::ConfigurationGenerator do it "should raise an ArgumentError if you try to override outputpath" do expect { - conf_man.send(:get_merged_configuration_flags!, {"outputpath" => "a"}, "hello") + conf_man.send(:get_merged_configuration_flags!, { "outputpath" => "a" }, "hello") }.to raise_error(ArgumentError) end it "should be case insensitive for switches that are not allowed" do expect { - conf_man.send(:get_merged_configuration_flags!, {"OutputPath" => "a"}, "hello") + conf_man.send(:get_merged_configuration_flags!, { "OutputPath" => "a" }, "hello") }.to raise_error(ArgumentError) end it "should be case insensitive to switches that are allowed" do - merged = conf_man.send(:get_merged_configuration_flags!, {"FLAG" => "a"}, "hello") + merged = conf_man.send(:get_merged_configuration_flags!, { "FLAG" => "a" }, "hello") expect(merged).to include(:flag) end end context "when symbols are used as switches" do it "should merge the hash if there are no restricted switches" do - merged = conf_man.send(:get_merged_configuration_flags!, {:flag => "a"}, "hello") + merged = conf_man.send(:get_merged_configuration_flags!, { :flag => "a" }, "hello") expect(merged).to include(:flag) expect(merged[:flag]).to eql("a") expect(merged).to include(:outputpath) @@ -84,18 +84,18 @@ describe Chef::Util::DSC::ConfigurationGenerator do it "should raise an ArgumentError if you try to override outputpath" do expect { - conf_man.send(:get_merged_configuration_flags!, {:outputpath => "a"}, "hello") + conf_man.send(:get_merged_configuration_flags!, { :outputpath => "a" }, "hello") }.to raise_error(ArgumentError) end it "should be case insensitive for switches that are not allowed" do expect { - conf_man.send(:get_merged_configuration_flags!, {:OutputPath => "a"}, "hello") + conf_man.send(:get_merged_configuration_flags!, { :OutputPath => "a" }, "hello") }.to raise_error(ArgumentError) end it "should be case insensitive to switches that are allowed" do - merged = conf_man.send(:get_merged_configuration_flags!, {:FLAG => "a"}, "hello") + merged = conf_man.send(:get_merged_configuration_flags!, { :FLAG => "a" }, "hello") expect(merged).to include(:flag) end end @@ -127,7 +127,7 @@ describe Chef::Util::DSC::ConfigurationGenerator do it "should write the input to a file" do allow(File).to receive(:open).and_yield(file_like_object) allow(File).to receive(:join) do |a, b| - [a,b].join("++") + [a, b].join("++") end allow(file_like_object).to receive(:write) conf_man.send(:write_document_generation_script, "file", "hello", {}) @@ -140,18 +140,18 @@ describe Chef::Util::DSC::ConfigurationGenerator do # These tests seem way too implementation specific. Unfortunately, File and Dir # need to be mocked because they are OS specific allow(File).to receive(:join) do |a, b| - [a,b].join("++") + [a, b].join("++") end - allow(Dir).to receive(:entries).with("tmp++hello") {["f1", "f2", "hello.mof", "f3"]} + allow(Dir).to receive(:entries).with("tmp++hello") { ["f1", "f2", "hello.mof", "f3"] } expect(conf_man.send(:find_configuration_document, "hello")).to eql("tmp++hello++hello.mof") end it "should return nil if the mof file is not found" do allow(File).to receive(:join) do |a, b| - [a,b].join("++") + [a, b].join("++") end - allow(Dir).to receive(:entries).with("tmp++hello") {["f1", "f2", "f3"]} + allow(Dir).to receive(:entries).with("tmp++hello") { ["f1", "f2", "f3"] } expect(conf_man.send(:find_configuration_document, "hello")).to be_nil end end @@ -169,25 +169,25 @@ describe Chef::Util::DSC::ConfigurationGenerator do end context "with imports" do it "should import all resources when a module has an empty list" do - dsc = conf_man.send(:configuration_code, "archive{}", "hello", {"FooModule" => []}) + dsc = conf_man.send(:configuration_code, "archive{}", "hello", { "FooModule" => [] }) expect(dsc).to match(/Import-DscResource -ModuleName FooModule\s*\n/) end it "should import all resources when a module has a list with *" do - dsc = conf_man.send(:configuration_code, "archive{}", "hello", {"FooModule" => ["FooResource", "*", "BarResource"]}) + dsc = conf_man.send(:configuration_code, "archive{}", "hello", { "FooModule" => ["FooResource", "*", "BarResource"] }) expect(dsc).to match(/Import-DscResource -ModuleName FooModule\s*\n/) end it "should import specific resources when a module has list without * that is not empty" do - dsc = conf_man.send(:configuration_code, "archive{}", "hello", {"FooModule" => ["FooResource", "BarResource"]}) + dsc = conf_man.send(:configuration_code, "archive{}", "hello", { "FooModule" => ["FooResource", "BarResource"] }) expect(dsc).to match(/Import-DscResource -ModuleName FooModule -Name FooResource,BarResource/) end it "should import multiple modules with multiple import statements" do - dsc = conf_man.send(:configuration_code, "archive{}", "hello", {"FooModule" => ["FooResource", "BarResource"], "BazModule" => []}) + dsc = conf_man.send(:configuration_code, "archive{}", "hello", { "FooModule" => ["FooResource", "BarResource"], "BazModule" => [] }) expect(dsc).to match(/Import-DscResource -ModuleName FooModule -Name FooResource,BarResource/) expect(dsc).to match(/Import-DscResource -ModuleName BazModule\s*\n/) - end + end end end end diff --git a/spec/unit/util/dsc/lcm_output_parser_spec.rb b/spec/unit/util/dsc/lcm_output_parser_spec.rb index 06f2a9288a..69eb8724ea 100644 --- a/spec/unit/util/dsc/lcm_output_parser_spec.rb +++ b/spec/unit/util/dsc/lcm_output_parser_spec.rb @@ -22,13 +22,13 @@ describe Chef::Util::DSC::LocalConfigurationManager::Parser do context "empty input parameter" do it "raises an exception when there are no valid lines" do str = <<-EOF - + EOF - expect {Chef::Util::DSC::LocalConfigurationManager::Parser::parse(str)}.to raise_error(Chef::Exceptions::LCMParser) + expect { Chef::Util::DSC::LocalConfigurationManager::Parser::parse(str) }.to raise_error(Chef::Exceptions::LCMParser) end it "raises an exception for a nil input" do - expect {Chef::Util::DSC::LocalConfigurationManager::Parser::parse(nil)}.to raise_error(Chef::Exceptions::LCMParser) + expect { Chef::Util::DSC::LocalConfigurationManager::Parser::parse(nil) }.to raise_error(Chef::Exceptions::LCMParser) end end @@ -69,7 +69,7 @@ logtype: [machinename]: LCM: [ End Resource ] [name] logtype: [machinename]: LCM: [ End Set ] EOF resources = Chef::Util::DSC::LocalConfigurationManager::Parser::parse(str) - expect(resources[0].change_log).to match_array(["[name]","[message]","[name]"]) + expect(resources[0].change_log).to match_array(["[name]", "[message]", "[name]"]) end it "should return false for changes_state?" do diff --git a/spec/unit/util/dsc/local_configuration_manager_spec.rb b/spec/unit/util/dsc/local_configuration_manager_spec.rb index 0ea544d839..f72c72b340 100644 --- a/spec/unit/util/dsc/local_configuration_manager_spec.rb +++ b/spec/unit/util/dsc/local_configuration_manager_spec.rb @@ -20,7 +20,6 @@ require "chef" require "chef/util/dsc/local_configuration_manager" describe Chef::Util::DSC::LocalConfigurationManager do - let(:lcm) { Chef::Util::DSC::LocalConfigurationManager.new(nil, "tmp") } let(:normal_lcm_output) { <<-EOH @@ -85,7 +84,7 @@ EOH expect(Chef::Log).to receive(:warn).at_least(:once) expect(lcm).to receive(:whatif_not_supported?).and_call_original test_configuration_result = nil - expect {test_configuration_result = lcm.test_configuration("config", {})}.not_to raise_error + expect { test_configuration_result = lcm.test_configuration("config", {}) }.not_to raise_error expect(test_configuration_result.class).to be(Array) end end @@ -99,13 +98,13 @@ EOH expect(Chef::Log).to receive(:warn).at_least(:once) expect(lcm).to receive(:dsc_module_import_failure?).and_call_original test_configuration_result = nil - expect {test_configuration_result = lcm.test_configuration("config", {})}.not_to raise_error + expect { test_configuration_result = lcm.test_configuration("config", {}) }.not_to raise_error end it "should return a (possibly empty) array of ResourceInfo instances" do expect(Chef::Log).to receive(:warn).at_least(:once) test_configuration_result = nil - expect {test_configuration_result = lcm.test_configuration("config", {})}.not_to raise_error + expect { test_configuration_result = lcm.test_configuration("config", {}) }.not_to raise_error expect(test_configuration_result.class).to be(Array) end end @@ -118,7 +117,7 @@ EOH it "should log a warning" do expect(Chef::Log).to receive(:warn).at_least(:once) expect(lcm).to receive(:dsc_module_import_failure?).and_call_original - expect {lcm.test_configuration("config", {})}.not_to raise_error + expect { lcm.test_configuration("config", {}) }.not_to raise_error end end end @@ -136,4 +135,3 @@ EOH end end end - diff --git a/spec/unit/util/dsc/resource_store.rb b/spec/unit/util/dsc/resource_store.rb index 5adcd378c0..b441cc7b94 100644 --- a/spec/unit/util/dsc/resource_store.rb +++ b/spec/unit/util/dsc/resource_store.rb @@ -24,15 +24,15 @@ describe Chef::Util::DSC::ResourceStore do let(:resource_a) { { "ResourceType" => "AFoo", "Name" => "Foo", - "Module" => {"Name" => "ModuleA"}, - } + "Module" => { "Name" => "ModuleA" }, + } } let(:resource_b) { { "ResourceType" => "BFoo", "Name" => "Foo", - "Module" => {"Name" => "ModuleB"}, - } + "Module" => { "Name" => "ModuleB" }, + } } context "when resources are not cached" do diff --git a/spec/unit/util/file_edit_spec.rb b/spec/unit/util/file_edit_spec.rb index af8dd4907d..71b55fd4ac 100644 --- a/spec/unit/util/file_edit_spec.rb +++ b/spec/unit/util/file_edit_spec.rb @@ -20,7 +20,6 @@ require "spec_helper" require "tempfile" describe Chef::Util::FileEdit do - let(:starting_content) do <<-EOF 127.0.0.1 localhost @@ -111,7 +110,7 @@ twice end it "should throw an exception if the input file does not exist" do - expect{Chef::Util::FileEdit.new("nonexistfile")}.to raise_error(ArgumentError) + expect { Chef::Util::FileEdit.new("nonexistfile") }.to raise_error(ArgumentError) end # CHEF-5018: people have monkey patched this and it has accidentally been broken @@ -124,7 +123,7 @@ twice let(:hosts_content) { "" } it "should not throw an exception" do - expect{ fedit }.not_to raise_error + expect { fedit }.not_to raise_error end end diff --git a/spec/unit/util/powershell/cmdlet_spec.rb b/spec/unit/util/powershell/cmdlet_spec.rb index 2d6b34ded8..5c0e66aee2 100644 --- a/spec/unit/util/powershell/cmdlet_spec.rb +++ b/spec/unit/util/powershell/cmdlet_spec.rb @@ -69,38 +69,38 @@ describe Chef::Util::Powershell::Cmdlet do describe '#command_switches_string' do it "raises an ArgumentError if the key is not a symbol" do expect { - @cmdlet.send(:command_switches_string, {"foo" => "bar"}) + @cmdlet.send(:command_switches_string, { "foo" => "bar" }) }.to raise_error(ArgumentError) end it "does not allow invalid switch names" do expect { - @cmdlet.send(:command_switches_string, {:foo! => "bar"}) + @cmdlet.send(:command_switches_string, { :foo! => "bar" }) }.to raise_error(ArgumentError) end it "ignores switches with a false value" do - expect(@cmdlet.send(:command_switches_string, {foo: false})).to eql("") + expect(@cmdlet.send(:command_switches_string, { foo: false })).to eql("") end it "should correctly handle a value type of string" do - expect(@cmdlet.send(:command_switches_string, {foo: "bar"})).to eql("-foo 'bar'") + expect(@cmdlet.send(:command_switches_string, { foo: "bar" })).to eql("-foo 'bar'") end it "should correctly handle a value type of string even when it is 0 length" do - expect(@cmdlet.send(:command_switches_string, {foo: ""})).to eql("-foo ''") + expect(@cmdlet.send(:command_switches_string, { foo: "" })).to eql("-foo ''") end it "should not quote integers" do - expect(@cmdlet.send(:command_switches_string, {foo: 1})).to eql("-foo 1") + expect(@cmdlet.send(:command_switches_string, { foo: 1 })).to eql("-foo 1") end it "should not quote floats" do - expect(@cmdlet.send(:command_switches_string, {foo: 1.0})).to eql("-foo 1.0") + expect(@cmdlet.send(:command_switches_string, { foo: 1.0 })).to eql("-foo 1.0") end it "has just the switch when the value is true" do - expect(@cmdlet.send(:command_switches_string, {foo: true})).to eql("-foo") + expect(@cmdlet.send(:command_switches_string, { foo: true })).to eql("-foo") end end end diff --git a/spec/unit/util/powershell/ps_credential_spec.rb b/spec/unit/util/powershell/ps_credential_spec.rb index 88e772c4e6..6f65174d15 100644 --- a/spec/unit/util/powershell/ps_credential_spec.rb +++ b/spec/unit/util/powershell/ps_credential_spec.rb @@ -24,7 +24,7 @@ describe Chef::Util::Powershell::PSCredential do let (:password) { "ThIsIsThEpAsSwOrD" } context "when username and password are provided" do - let(:ps_credential) { Chef::Util::Powershell::PSCredential.new(username, password)} + let(:ps_credential) { Chef::Util::Powershell::PSCredential.new(username, password) } context "when calling to_psobject" do it "should create the script to create a PSCredential when calling" do allow(ps_credential).to receive(:encrypt).with(password).and_return("encrypted") diff --git a/spec/unit/util/selinux_spec.rb b/spec/unit/util/selinux_spec.rb index 205553aa0c..609ff02215 100644 --- a/spec/unit/util/selinux_spec.rb +++ b/spec/unit/util/selinux_spec.rb @@ -16,7 +16,6 @@ # limitations under the License. # - require "spec_helper" describe Chef::Util::Selinux do @@ -62,7 +61,7 @@ describe Chef::Util::Selinux do describe "when selinux is enabled" do before do cmd_result = double("Cmd Result", :exitstatus => 0) - expect(@test_instance).to receive(:shell_out!).once.with(@selinux_enabled_path, {:returns=>[0, 1]}).and_return(cmd_result) + expect(@test_instance).to receive(:shell_out!).once.with(@selinux_enabled_path, { :returns => [0, 1] }).and_return(cmd_result) end it "should report selinux is enabled" do @@ -75,7 +74,7 @@ describe Chef::Util::Selinux do describe "when selinux is disabled" do before do cmd_result = double("Cmd Result", :exitstatus => 1) - expect(@test_instance).to receive(:shell_out!).once.with(@selinux_enabled_path, {:returns=>[0, 1]}).and_return(cmd_result) + expect(@test_instance).to receive(:shell_out!).once.with(@selinux_enabled_path, { :returns => [0, 1] }).and_return(cmd_result) end it "should report selinux is disabled" do @@ -88,11 +87,11 @@ describe Chef::Util::Selinux do describe "when selinux gives an unexpected status" do before do cmd_result = double("Cmd Result", :exitstatus => 101) - expect(@test_instance).to receive(:shell_out!).once.with(@selinux_enabled_path, {:returns=>[0, 1]}).and_return(cmd_result) + expect(@test_instance).to receive(:shell_out!).once.with(@selinux_enabled_path, { :returns => [0, 1] }).and_return(cmd_result) end it "should throw an error" do - expect {@test_instance.selinux_enabled?}.to raise_error(RuntimeError) + expect { @test_instance.selinux_enabled? }.to raise_error(RuntimeError) end end end diff --git a/spec/unit/version/platform_spec.rb b/spec/unit/version/platform_spec.rb index 698339164a..a053ef46c4 100644 --- a/spec/unit/version/platform_spec.rb +++ b/spec/unit/version/platform_spec.rb @@ -18,7 +18,6 @@ require "spec_helper" require "chef/version/platform" describe Chef::Version::Platform do - it "is a subclass of Chef::Version" do v = Chef::Version::Platform.new("1.1") expect(v).to be_an_instance_of(Chef::Version::Platform) @@ -50,12 +49,8 @@ describe Chef::Version::Platform do end describe "<=>" do - it "should equate versions 1 and 1.0.0" do expect(Chef::Version::Platform.new("1")).to eq(Chef::Version::Platform.new("1.0.0")) end - end - end - diff --git a/spec/unit/version_class_spec.rb b/spec/unit/version_class_spec.rb index 4cbd09ce53..2b150bcfbd 100644 --- a/spec/unit/version_class_spec.rb +++ b/spec/unit/version_class_spec.rb @@ -64,7 +64,6 @@ describe Chef::Version do end describe "<=>" do - it "should equate versions 1.2 and 1.2.0" do expect(Chef::Version.new("1.2")).to eq(Chef::Version.new("1.2.0")) end @@ -105,7 +104,7 @@ describe Chef::Version 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| Chef::Version.new(s) end - got = a.sort.map {|v| v.to_s } + got = a.sort.map { |v| v.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 @@ -169,4 +168,3 @@ describe Chef::Version do end end end - diff --git a/spec/unit/version_constraint/platform_spec.rb b/spec/unit/version_constraint/platform_spec.rb index 96edbf46cc..0a01b9a393 100644 --- a/spec/unit/version_constraint/platform_spec.rb +++ b/spec/unit/version_constraint/platform_spec.rb @@ -18,7 +18,6 @@ require "spec_helper" require "chef/version_constraint/platform" describe Chef::VersionConstraint::Platform do - it "is a subclass of Chef::VersionConstraint" do v = Chef::VersionConstraint::Platform.new expect(v).to be_an_instance_of(Chef::VersionConstraint::Platform) @@ -31,7 +30,6 @@ describe Chef::VersionConstraint::Platform do end describe "include?" do - it "pessimistic ~> x" do vc = Chef::VersionConstraint::Platform.new "~> 1" expect(vc).to include "1.3.3" @@ -40,7 +38,5 @@ describe Chef::VersionConstraint::Platform do expect(vc).not_to include "2.2" expect(vc).not_to include "0.3.0" end - end end - diff --git a/spec/unit/version_constraint_spec.rb b/spec/unit/version_constraint_spec.rb index f83af03fb7..0325ea730e 100644 --- a/spec/unit/version_constraint_spec.rb +++ b/spec/unit/version_constraint_spec.rb @@ -47,7 +47,6 @@ describe Chef::VersionConstraint do it "should allow initialization with ['1.2.3'] for back compatibility" do Chef::VersionConstraint.new(["1.2"]) == Chef::VersionConstraint.new("1.2") end - end it "should default to >= 0.0.0" do diff --git a/spec/unit/win32/registry_spec.rb b/spec/unit/win32/registry_spec.rb index 63ab520611..1523ac1919 100644 --- a/spec/unit/win32/registry_spec.rb +++ b/spec/unit/win32/registry_spec.rb @@ -22,13 +22,13 @@ describe Chef::Win32::Registry do include_context "Win32" let(:value1) { { :name => "one", :type => :string, :data => "1" } } - let(:value1_upcase_name) { {:name => "ONE", :type => :string, :data => "1"} } + let(:value1_upcase_name) { { :name => "ONE", :type => :string, :data => "1" } } let(:key_path) { 'HKCU\Software\OpscodeNumbers' } let(:key) { 'Software\OpscodeNumbers' } let(:key_parent) { "Software" } let(:key_to_delete) { "OpscodeNumbers" } - let(:sub_key) {"OpscodePrimes"} - let(:missing_key_path) {'HKCU\Software'} + let(:sub_key) { "OpscodePrimes" } + let(:missing_key_path) { 'HKCU\Software' } let(:registry) { Chef::Win32::Registry.new() } let(:hive_mock) { double("::Win32::Registry::KHKEY_CURRENT_USER") } let(:reg_mock) { double("reg") } @@ -40,7 +40,7 @@ describe Chef::Win32::Registry do before(:each) do allow_any_instance_of(Chef::Win32::Registry).to receive(:machine_architecture).and_return(:x86_64) - + #Making the values for registry constants available on unix Win32::Registry::KEY_SET_VALUE = 0x0002 Win32::Registry::KEY_QUERY_VALUE = 0x0001 @@ -67,7 +67,7 @@ describe Chef::Win32::Registry do it "throws an exception if key does not exist" do expect(registry).to receive(:get_hive_and_key).with(key_path).and_return([hive_mock, key]) expect(registry).to receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) - expect{registry.get_values(key_path)}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { registry.get_values(key_path) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end end @@ -116,7 +116,7 @@ describe Chef::Win32::Registry do it "should raise an exception if the key does not exist" do expect(registry).to receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) - expect {registry.set_value(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { registry.set_value(key_path, value1) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end end @@ -153,7 +153,7 @@ describe Chef::Win32::Registry do it "raises an exception if intermediate keys are missing and recursive is set to false" do expect(registry).to receive(:keys_missing?).with(key_path).and_return(true) - expect{registry.create_key(key_path, false)}.to raise_error(Chef::Exceptions::Win32RegNoRecursive) + expect { registry.create_key(key_path, false) }.to raise_error(Chef::Exceptions::Win32RegNoRecursive) end it "does nothing if the key exists" do @@ -193,7 +193,7 @@ describe Chef::Win32::Registry do it "raises an exception if it has subkeys but recursive is set to false" do expect(registry).to receive(:key_exists?).with(key_path).and_return(true) expect(registry).to receive(:has_subkeys?).with(key_path).and_return(true) - expect{registry.delete_key(key_path, false)}.to raise_error(Chef::Exceptions::Win32RegNoRecursive) + expect { registry.delete_key(key_path, false) }.to raise_error(Chef::Exceptions::Win32RegNoRecursive) end it "deletes key if the key exists and has no subkeys" do @@ -223,7 +223,7 @@ describe Chef::Win32::Registry do describe "key_exists!" do it "throws an exception if the key_parent does not exist" do expect(registry).to receive(:key_exists?).with(key_path).and_return(false) - expect{registry.key_exists!(key_path)}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { registry.key_exists!(key_path) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end end @@ -258,7 +258,7 @@ describe Chef::Win32::Registry do it "throws an exception if the key does not exist" do expect(registry).to receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) - expect {registry.set_value(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { registry.set_value(key_path, value1) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end end @@ -275,7 +275,7 @@ describe Chef::Win32::Registry do describe "value_exists?" do it "throws an exception if the key does not exist" do expect(registry).to receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) - expect {registry.value_exists?(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { registry.value_exists?(key_path, value1) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "returns true if the value exists" do @@ -298,7 +298,7 @@ describe Chef::Win32::Registry do describe "data_exists?" do it "throws an exception if the key does not exist" do expect(registry).to receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) - expect {registry.data_exists?(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect { registry.data_exists?(key_path, value1) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "returns true if the data exists" do @@ -328,7 +328,7 @@ describe Chef::Win32::Registry do it "throws an exception if the value does not exist" do expect(registry).to receive(:value_exists?).with(key_path, value1).and_return(false) - expect{registry.value_exists!(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegValueMissing) + expect { registry.value_exists!(key_path, value1) }.to raise_error(Chef::Exceptions::Win32RegValueMissing) end end @@ -340,7 +340,7 @@ describe Chef::Win32::Registry do it "throws an exception if the data does not exist" do expect(registry).to receive(:data_exists?).with(key_path, value1).and_return(false) - expect{registry.data_exists!(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegDataMissing) + expect { registry.data_exists!(key_path, value1) }.to raise_error(Chef::Exceptions::Win32RegDataMissing) end end @@ -364,7 +364,7 @@ describe Chef::Win32::Registry do it "throws an exception if value does not exist" do expect(registry).to receive(:value_exists?).with(key_path, value1).and_return(false) - expect{registry.type_matches?(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegValueMissing) + expect { registry.type_matches?(key_path, value1) }.to raise_error(Chef::Exceptions::Win32RegValueMissing) end end @@ -376,7 +376,7 @@ describe Chef::Win32::Registry do it "throws an exception if the type does not match" do expect(registry).to receive(:type_matches?).with(key_path, value1).and_return(false) - expect{registry.type_matches!(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegTypesMismatch) + expect { registry.type_matches!(key_path, value1) }.to raise_error(Chef::Exceptions::Win32RegTypesMismatch) end end diff --git a/tasks/cbgb.rb b/tasks/cbgb.rb index f95a251885..9aa6700137 100644 --- a/tasks/cbgb.rb +++ b/tasks/cbgb.rb @@ -34,7 +34,7 @@ begin out = "\n" out << "\n\n" out << "# " + cbgb["Preamble"]["title"] + "\n\n" - out << cbgb["Preamble"]["text"] + "\n" + out << cbgb["Preamble"]["text"] + "\n" out << "# Board of Governors\n\n" out << "## " + cbgb["Org"]["Lead"]["title"] + "\n\n" out << person(cbgb["people"], cbgb["Org"]["Lead"]["person"]) + "\n\n" @@ -52,8 +52,8 @@ begin def components(list, cmp) out = "" - cmp.each do |k,v| - out << "\n#### #{v['title'].gsub('#','\\#')}\n" + cmp.each do |k, v| + out << "\n#### #{v['title'].gsub('#', '\\#')}\n" out << cbgb(list, v["cbgb"]) end out diff --git a/tasks/external_tests.rb b/tasks/external_tests.rb index f3a0da062f..f6fd79c86b 100644 --- a/tasks/external_tests.rb +++ b/tasks/external_tests.rb @@ -55,10 +55,10 @@ EXTERNAL_PROJECTS = { "knife-windows" => "rake unit_spec", } -task :external_specs => EXTERNAL_PROJECTS.keys.map { |g| :"#{g.sub("-","_")}_spec" } +task :external_specs => EXTERNAL_PROJECTS.keys.map { |g| :"#{g.sub("-", "_")}_spec" } EXTERNAL_PROJECTS.each do |test_gem, commands| - task :"#{test_gem.gsub("-","_")}_spec" do + task :"#{test_gem.gsub("-", "_")}_spec" do bundle_exec_with_chef(test_gem, commands) end end diff --git a/tasks/maintainers.rb b/tasks/maintainers.rb index 6c5eb18ad2..535edda248 100644 --- a/tasks/maintainers.rb +++ b/tasks/maintainers.rb @@ -38,7 +38,7 @@ begin task :generate do out = "\n\n" out << "# " + source["Preamble"]["title"] + "\n\n" - out << source["Preamble"]["text"] + "\n" + out << source["Preamble"]["text"] + "\n" # The project lead is a special case out << "# " + source["Org"]["Lead"]["title"] + "\n\n" @@ -70,7 +70,7 @@ begin end def teams - @teams ||= {"client-maintainers" => {"title" => "Client Maintainers"}} + @teams ||= { "client-maintainers" => { "title" => "Client Maintainers" } } end def add_members(team, name) @@ -94,7 +94,7 @@ begin # setting, so we know whether we need to update it def get_github_teams github.org_teams("chef").each do |team| - gh_teams[team[:slug]] = {"id" => team[:id], "privacy" => team[:privacy]} + gh_teams[team[:slug]] = { "id" => team[:id], "privacy" => team[:privacy] } end end @@ -109,8 +109,8 @@ begin def create_team(team) puts "creating new github team: #{team} with title: #{teams[team]["title"]} " t = github.create_team("chef", name: team, description: teams[team]["title"], - privacy: "closed", repo_names: REPOSITORIES, - accept: "application/vnd.github.ironman-preview+json") + privacy: "closed", repo_names: REPOSITORIES, + accept: "application/vnd.github.ironman-preview+json") gh_teams[team] = { "id" => t[:id], "privacy" => t[:privacy] } end @@ -146,14 +146,14 @@ begin return if gh_teams[team]["privacy"] == "closed" puts "Setting #{team} privacy to closed from #{gh_teams[team]["privacy"]}" github.update_team(gh_teams[team]["id"], privacy: "closed", - accept: "application/vnd.github.ironman-preview+json") + accept: "application/vnd.github.ironman-preview+json") end def add_team_members(team, additions) additions.each do |member| puts "Adding #{member} to #{team}" github.add_team_membership(gh_teams[team]["id"], member, role: "member", - accept: "application/vnd.github.ironman-preview+json") + accept: "application/vnd.github.ironman-preview+json") end end @@ -188,7 +188,7 @@ begin end out << format_maintainers(cmp.delete("maintainers")) + "\n" if cmp.has_key?("maintainers") cmp.delete("paths") - cmp.each {|k,v| out << format_components(v) } + cmp.each { |k, v| out << format_components(v) } out end diff --git a/tasks/rspec.rb b/tasks/rspec.rb index 72c783038f..a52960f165 100644 --- a/tasks/rspec.rb +++ b/tasks/rspec.rb @@ -25,7 +25,6 @@ CHEF_ROOT = File.join(File.dirname(__FILE__), "..") begin require "rspec/core/rake_task" - desc "Run specs for Chef's Components" task :component_specs do Dir.chdir("chef-config") do @@ -55,7 +54,7 @@ begin t.pattern = FileList["spec/**/*_spec.rb"] t.rcov = true t.rcov_opts = lambda do - IO.readlines("#{CHEF_ROOT}/spec/rcov.opts").map {|l| l.chomp.split " "}.flatten + IO.readlines("#{CHEF_ROOT}/spec/rcov.opts").map { |l| l.chomp.split " " }.flatten end end -- cgit v1.2.1